diff --git a/scripts/eval/eval_mscoco7.sh b/scripts/eval/eval_mscoco7.sh new file mode 100644 index 0000000000000000000000000000000000000000..de913f3656f7bdd194d68fdfb89c87db384b565c --- /dev/null +++ b/scripts/eval/eval_mscoco7.sh @@ -0,0 +1,15 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/captions_val2017.json +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Emu3/MSCOCO2017Val/sjd/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --coco_gt_path /mnt/petrelfs/leihaodong/local_dataset/val2017 \ + --dataset_name coco \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_pp.sh b/scripts/eval/eval_pp.sh new file mode 100644 index 0000000000000000000000000000000000000000..fb48cb671d86d04696b7e83b33a908708c96f6d8 --- /dev/null +++ b/scripts/eval/eval_pp.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/PartiPrompts.tsv +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_PartiPrompts/mscr_sjd_0.005/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name parti_cocoformat \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_pp1.sh b/scripts/eval/eval_pp1.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd00d3abfce7695d6a569f10fb0d2de64b2326d0 --- /dev/null +++ b/scripts/eval/eval_pp1.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/PartiPrompts.tsv +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_PartiPrompts/mscr_sjd_0.01/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name parti_cocoformat \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_pp5.sh b/scripts/eval/eval_pp5.sh new file mode 100644 index 0000000000000000000000000000000000000000..b6e6497bd4966ef5e067caede22a3a0d48fb71d8 --- /dev/null +++ b/scripts/eval/eval_pp5.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/PartiPrompts.tsv +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Emu3/PartiPrompts/mscr_sjd_0.05/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name parti_cocoformat \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_pp6.sh b/scripts/eval/eval_pp6.sh new file mode 100644 index 0000000000000000000000000000000000000000..fa9c7411486ec14f4f9e4c12ca9f229f3ebc2696 --- /dev/null +++ b/scripts/eval/eval_pp6.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/PartiPrompts.tsv +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Emu3/PartiPrompts/sjd/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name parti_cocoformat \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_t2i.sh b/scripts/eval/eval_t2i.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b31c11377e50e13dc72c2040696d46091fe57ff --- /dev/null +++ b/scripts/eval/eval_t2i.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/T2I-CompBench_val.json +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_T2ICompBenchVal/mscr_gsd/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name T2I-CompBench \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_t2i1.sh b/scripts/eval/eval_t2i1.sh new file mode 100644 index 0000000000000000000000000000000000000000..112c1d06554b1c4544764aeccc89115c1434e748 --- /dev/null +++ b/scripts/eval/eval_t2i1.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/T2I-CompBench_val.json +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_T2ICompBenchVal/ms_gsd/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name T2I-CompBench \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_t2i2.sh b/scripts/eval/eval_t2i2.sh new file mode 100644 index 0000000000000000000000000000000000000000..d380f7b7225ef54d26ac1e3923aad8ecfbec5f06 --- /dev/null +++ b/scripts/eval/eval_t2i2.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/T2I-CompBench_val.json +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_T2ICompBenchVal/base/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name T2I-CompBench \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_t2i3.sh b/scripts/eval/eval_t2i3.sh new file mode 100644 index 0000000000000000000000000000000000000000..6e467fe2202a13131c80470121952feb0a9407da --- /dev/null +++ b/scripts/eval/eval_t2i3.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/T2I-CompBench_val.json +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Emu3/T2ICompBenchVal/ms_sjd/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name T2I-CompBench \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_t2i4.sh b/scripts/eval/eval_t2i4.sh new file mode 100644 index 0000000000000000000000000000000000000000..8e2e6f9d81c73cd97c72da104840b67579c2ef87 --- /dev/null +++ b/scripts/eval/eval_t2i4.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/T2I-CompBench_val.json +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Emu3/T2ICompBenchVal/mscr_gsd/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name T2I-CompBench \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_t2i5.sh b/scripts/eval/eval_t2i5.sh new file mode 100644 index 0000000000000000000000000000000000000000..06be333b57a809a1fc7b3e50b157dd4af9e47571 --- /dev/null +++ b/scripts/eval/eval_t2i5.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/T2I-CompBench_val.json +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Emu3/T2ICompBenchVal/mscr_sjd_0.05/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name T2I-CompBench \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_t2i6.sh b/scripts/eval/eval_t2i6.sh new file mode 100644 index 0000000000000000000000000000000000000000..e5e2443c03e3467f4718d968adf700593086713c --- /dev/null +++ b/scripts/eval/eval_t2i6.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/T2I-CompBench_val.json +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Emu3/T2ICompBenchVal/sjd/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name T2I-CompBench \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/eval_t2i7.sh b/scripts/eval/eval_t2i7.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff4657b00c0279ed2bd3d55fe5a82efc922794f1 --- /dev/null +++ b/scripts/eval/eval_t2i7.sh @@ -0,0 +1,14 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/eval +# HF_ENDPOINT=https://hf-mirror.com +dataset_anno_file=/mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/T2I-CompBench_val.json +workdir=/mnt/petrelfs/leihaodong/ICLR25/exp/Emu3/T2ICompBenchVal/base/img + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python evaluation_metrics.py \ + --workdir $workdir \ + --dataset_anno_file $dataset_anno_file \ + --dataset_name T2I-CompBench \ + --n_images 0 \ No newline at end of file diff --git a/scripts/eval/slurm-6226567.out b/scripts/eval/slurm-6226567.out new file mode 100644 index 0000000000000000000000000000000000000000..2a86d6f1323467b8cee3da97b49f175412ba5aec --- /dev/null +++ b/scripts/eval/slurm-6226567.out @@ -0,0 +1,17 @@ +loading annotations into memory... +Done (t=0.03s) +creating index... +index created! +一共2182 张 +loading annotations into memory... +Done (t=0.03s) +creating index... +index created! +/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_MSCOCO2017Val/base/img/gt +/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_MSCOCO2017Val/base/img + 0%| | 0/2183 [00:00 + results = evaluate_quantitative_scores_text2img( + File "/mnt/petrelfs/leihaodong/ICLR25/eval/evaluation_metrics.py", line 309, in evaluate_quantitative_scores_text2img + image = Image.open(image_file) + File "/mnt/petrelfs/leihaodong/anaconda3/envs/eval_xx/lib/python3.10/site-packages/PIL/Image.py", line 3560, in open + raise UnidentifiedImageError(msg) +PIL.UnidentifiedImageError: cannot identify image file '/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_PartiPrompts/mscr_sjd_0.05/img/695.png' +srun: error: SH-IDC1-10-140-37-43: task 0: Exited with exit code 1 diff --git a/scripts/eval/slurm-6234590.out b/scripts/eval/slurm-6234590.out new file mode 100644 index 0000000000000000000000000000000000000000..4f0221a78fd638644f49d39d85003b8467bb3748 --- /dev/null +++ b/scripts/eval/slurm-6234590.out @@ -0,0 +1,22 @@ +/mnt/petrelfs/leihaodong/anaconda3/envs/eval_xx/lib/python3.10/site-packages/torchmetrics/utilities/prints.py:43: UserWarning: Metric `InceptionScore` will save all extracted features in buffer. For large datasets this may lead to large memory footprint. + warnings.warn(*args, **kwargs) +/mnt/petrelfs/leihaodong/anaconda3/envs/eval_xx/lib/python3.10/site-packages/open_clip/factory.py:450: UserWarning: QuickGELU mismatch between final model config (quick_gelu=False) and pretrained tag 'openai' (quick_gelu=True). + warnings.warn( +Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`. +Loading PartiPrompts from /mnt/petrelfs/leihaodong/ICLR25/sjdtree/data/prompts/PartiPrompts.tsv for GPU 0, Node 0 +Number of unique prompts: 1632 | Max prompt length: 389 +一共172 张 + Evaluating images: 0%| | 0/172 [00:00 ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/MSCOCO/caccl+sjd++.sh b/scripts/lumina_gpt/MSCOCO/caccl+sjd++.sh new file mode 100644 index 0000000000000000000000000000000000000000..c189bab38df72ed501641911ccbb616f7dd40e60 --- /dev/null +++ b/scripts/lumina_gpt/MSCOCO/caccl+sjd++.sh @@ -0,0 +1,58 @@ +#!/bin/bash +#SBATCH -N 1 # 节点数(可改成多节点) +#SBATCH --job-name=MSCOCO2017Val # 可选:任务名,便于查看 + +# ==================== 环境变量 ==================== +export PARTITION=DataFrontier_Knowledge +export CFSCTL=/mnt/petrelfs/leihaodong/app/cfs/bin/cfsctl +export NNODES=$SLURM_NNODES # 实际分配到的节点数 +export MASTER_ADDR=$(scontrol show hostname $SLURM_NODELIST | head -n1) +echo "Job started at $(date)" +echo "Nodes: $SLURM_NODELIST" +echo "Master node: $MASTER_ADDR" +echo "Total nodes: $NNODES" +# ==================== CFS 预加载(启动 + preload + 停止) ==================== +echo "Starting CFS preload..." +# 取主节点(和你们原来脚本保持一致) +MAIN_SERVER=$(scontrol show hostname $SLURM_NODELIST | head -n1) +# 停止可能残留的旧 CFS 实例 +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER stop || true +# 启动 CFS +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER start +# 开始预加载(这一步会卡住直到所有节点 preload 完成) +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER -a preload +# ==================== 真正要跑的程序 ==================== +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='caccl' +num_init_new_token=96 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768/${prompt}/caccl +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=/nvme/leihaodong/mnt/local_model/models--Alpha-VLLM--Lumina-mGPT-7B-768/snapshots/755e7e40530a8edf4eea6078cbc484d2bfda091f +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --sjd_pp_threshold=0.5 \ + --slice=$slice \ + --target_size=768 > ${output_path}.log 2>&1 + +# ==================== 清理 CFS ==================== +echo "Python script finished, stopping CFS..." +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER stop +echo "Job finished at $(date)" \ No newline at end of file diff --git a/scripts/lumina_gpt/MSCOCO/ms_gsd.sh b/scripts/lumina_gpt/MSCOCO/ms_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..142ef3de3bd3865f3f2103ca111eb930dd28c100 --- /dev/null +++ b/scripts/lumina_gpt/MSCOCO/ms_gsd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/MSCOCO/ms_lantern.sh b/scripts/lumina_gpt/MSCOCO/ms_lantern.sh new file mode 100644 index 0000000000000000000000000000000000000000..a838fefa52964bacff0a80075f6d9b2c4959ce6c --- /dev/null +++ b/scripts/lumina_gpt/MSCOCO/ms_lantern.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='lantern' +num_init_new_token=16 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_lantern +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/MSCOCO/ms_sjd.sh b/scripts/lumina_gpt/MSCOCO/ms_sjd.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab6b05459e27c5ef10574500906547dfe47dc709 --- /dev/null +++ b/scripts/lumina_gpt/MSCOCO/ms_sjd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_sjd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/MSCOCO/mscr_gsd.sh b/scripts/lumina_gpt/MSCOCO/mscr_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..88254dca8850287efc0d6360b77a2431d0125edf --- /dev/null +++ b/scripts/lumina_gpt/MSCOCO/mscr_gsd.sh @@ -0,0 +1,33 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi_groupsum' +num_init_new_token=16 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +groupsum_delta=0.008 +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/mscr_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --groupsum_delta=$groupsum_delta \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/MSCOCO/mscr_sjd.sh b/scripts/lumina_gpt/MSCOCO/mscr_sjd.sh new file mode 100644 index 0000000000000000000000000000000000000000..4fb2214df99ace24211068f8271ea3549b0e2d99 --- /dev/null +++ b/scripts/lumina_gpt/MSCOCO/mscr_sjd.sh @@ -0,0 +1,33 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='speculative_jacobi_groupsum' +num_init_new_token=16 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +groupsum_delta=0.05 +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/mscr_sjd_${groupsum_delta} +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --groupsum_delta=$groupsum_delta \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/MSCOCO/sjd++.sh b/scripts/lumina_gpt/MSCOCO/sjd++.sh new file mode 100644 index 0000000000000000000000000000000000000000..2bfc756077fe8b1543a5e135d819780c37f8789d --- /dev/null +++ b/scripts/lumina_gpt/MSCOCO/sjd++.sh @@ -0,0 +1,57 @@ +#!/bin/bash +#SBATCH -N 1 # 节点数(可改成多节点) +#SBATCH --job-name=MSCOCO2017Val # 可选:任务名,便于查看 + +# ==================== 环境变量 ==================== +export PARTITION=DataFrontier_Knowledge +export CFSCTL=/mnt/petrelfs/leihaodong/app/cfs/bin/cfsctl +export NNODES=$SLURM_NNODES # 实际分配到的节点数 +export MASTER_ADDR=$(scontrol show hostname $SLURM_NODELIST | head -n1) +echo "Job started at $(date)" +echo "Nodes: $SLURM_NODELIST" +echo "Master node: $MASTER_ADDR" +echo "Total nodes: $NNODES" +# ==================== CFS 预加载(启动 + preload + 停止) ==================== +echo "Starting CFS preload..." +# 取主节点(和你们原来脚本保持一致) +MAIN_SERVER=$(scontrol show hostname $SLURM_NODELIST | head -n1) +# 停止可能残留的旧 CFS 实例 +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER stop || true +# 启动 CFS +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER start +# 开始预加载(这一步会卡住直到所有节点 preload 完成) +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER -a preload +# ==================== 真正要跑的程序 ==================== +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='sjd++' +num_init_new_token=96 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768/${prompt}/sjd++ +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=/nvme/leihaodong/mnt/local_model/models--Alpha-VLLM--Lumina-mGPT-7B-768/snapshots/755e7e40530a8edf4eea6078cbc484d2bfda091f +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --target_size=768 > ${output_path}.log 2>&1 + +# ==================== 清理 CFS ==================== +echo "Python script finished, stopping CFS..." +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER stop +echo "Job finished at $(date)" \ No newline at end of file diff --git a/scripts/lumina_gpt/PP/base.sh b/scripts/lumina_gpt/PP/base.sh new file mode 100644 index 0000000000000000000000000000000000000000..fe04b2832579be1c486474b6fe5322de3dd3e8bf --- /dev/null +++ b/scripts/lumina_gpt/PP/base.sh @@ -0,0 +1,27 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +isp='random' +method='speculative_jacobi' +num_init_new_token=1 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/base +mkdir -p ${output_path} + + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/PP/ms_gsd.sh b/scripts/lumina_gpt/PP/ms_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..79008f9dfd9f07e929be5eee77652227fdb9eef1 --- /dev/null +++ b/scripts/lumina_gpt/PP/ms_gsd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/PP/ms_lantern.sh b/scripts/lumina_gpt/PP/ms_lantern.sh new file mode 100644 index 0000000000000000000000000000000000000000..a55a090a4da35283b830ef9cc1c300d62a94e097 --- /dev/null +++ b/scripts/lumina_gpt/PP/ms_lantern.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='lantern' +num_init_new_token=16 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_lantern +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/PP/ms_sjd.sh b/scripts/lumina_gpt/PP/ms_sjd.sh new file mode 100644 index 0000000000000000000000000000000000000000..25ca90b3a749580fa7d603100afc5a32363dbc90 --- /dev/null +++ b/scripts/lumina_gpt/PP/ms_sjd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_sjd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/PP/mscr_gsd.sh b/scripts/lumina_gpt/PP/mscr_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..04ee04f26d819e73ab70ab95301c97d76575056e --- /dev/null +++ b/scripts/lumina_gpt/PP/mscr_gsd.sh @@ -0,0 +1,33 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi_groupsum' +num_init_new_token=16 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +groupsum_delta=0.008 +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/mscr_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --groupsum_delta=$groupsum_delta \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/PP/mscr_sjd.sh b/scripts/lumina_gpt/PP/mscr_sjd.sh new file mode 100644 index 0000000000000000000000000000000000000000..1edbf0ec50076d9cbd4c02309872a7f9608e9f84 --- /dev/null +++ b/scripts/lumina_gpt/PP/mscr_sjd.sh @@ -0,0 +1,33 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='speculative_jacobi_groupsum' +num_init_new_token=16 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +groupsum_delta=0.5 +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/mscr_sjd_${groupsum_delta} +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --groupsum_delta=$groupsum_delta \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/PP/sjd++.sh b/scripts/lumina_gpt/PP/sjd++.sh new file mode 100644 index 0000000000000000000000000000000000000000..aeb60545c40c18b05eaeebf1967c19cbf786bbab --- /dev/null +++ b/scripts/lumina_gpt/PP/sjd++.sh @@ -0,0 +1,57 @@ +#!/bin/bash +#SBATCH -N 1 # 节点数(可改成多节点) +#SBATCH --job-name=sciQA_test # 可选:任务名,便于查看 + +# ==================== 环境变量 ==================== +export PARTITION=DataFrontier_Knowledge +export CFSCTL=/mnt/petrelfs/leihaodong/app/cfs/bin/cfsctl +export NNODES=$SLURM_NNODES # 实际分配到的节点数 +export MASTER_ADDR=$(scontrol show hostname $SLURM_NODELIST | head -n1) +echo "Job started at $(date)" +echo "Nodes: $SLURM_NODELIST" +echo "Master node: $MASTER_ADDR" +echo "Total nodes: $NNODES" +# ==================== CFS 预加载(启动 + preload + 停止) ==================== +echo "Starting CFS preload..." +# 取主节点(和你们原来脚本保持一致) +MAIN_SERVER=$(scontrol show hostname $SLURM_NODELIST | head -n1) +# 停止可能残留的旧 CFS 实例 +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER stop || true +# 启动 CFS +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER start +# 开始预加载(这一步会卡住直到所有节点 preload 完成) +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER -a preload +# ==================== 真正要跑的程序 ==================== +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='sjd++' +num_init_new_token=96 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768/${prompt}/sjd++ +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=/nvme/leihaodong/mnt/local_model/models--Alpha-VLLM--Lumina-mGPT-7B-768/snapshots/755e7e40530a8edf4eea6078cbc484d2bfda091f +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --target_size=768 > ${output_path}.log 2>&1 + +# ==================== 清理 CFS ==================== +echo "Python script finished, stopping CFS..." +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER stop +echo "Job finished at $(date)" \ No newline at end of file diff --git a/scripts/lumina_gpt/T2ICompBench/base.sh b/scripts/lumina_gpt/T2ICompBench/base.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d1f514e5c4b7e83579c7d4fff20c496e8b14bb0 --- /dev/null +++ b/scripts/lumina_gpt/T2ICompBench/base.sh @@ -0,0 +1,24 @@ +#!/bin/bash +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +isp='random' +method='speculative_jacobi' +num_init_new_token=1 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/base +mkdir -p ${output_path} + +# nohup +python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/T2ICompBench/jd.sh b/scripts/lumina_gpt/T2ICompBench/jd.sh new file mode 100644 index 0000000000000000000000000000000000000000..46075a4ce610ba54d73a48d991367dbe280f123c --- /dev/null +++ b/scripts/lumina_gpt/T2ICompBench/jd.sh @@ -0,0 +1,24 @@ +#!/bin/bash +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +isp='random' +method='jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/base +mkdir -p ${output_path} + +# nohup +python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/T2ICompBench/ms_gsd.sh b/scripts/lumina_gpt/T2ICompBench/ms_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..098d66bc239fc0e43caececa29213b25a7424c61 --- /dev/null +++ b/scripts/lumina_gpt/T2ICompBench/ms_gsd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/T2ICompBench/ms_lantern.sh b/scripts/lumina_gpt/T2ICompBench/ms_lantern.sh new file mode 100644 index 0000000000000000000000000000000000000000..45b2bda84d558262d9dee16f2a4b3eac6be3cf17 --- /dev/null +++ b/scripts/lumina_gpt/T2ICompBench/ms_lantern.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='lantern' +num_init_new_token=16 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_lantern +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/T2ICompBench/ms_sjd.sh b/scripts/lumina_gpt/T2ICompBench/ms_sjd.sh new file mode 100644 index 0000000000000000000000000000000000000000..3b0d542e6070f94d7af134f0d9641f42d14f3482 --- /dev/null +++ b/scripts/lumina_gpt/T2ICompBench/ms_sjd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_sjd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/T2ICompBench/mscr_gsd.sh b/scripts/lumina_gpt/T2ICompBench/mscr_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..73714c7d0b5fa1f1e1eab2c5d987641bb8f7d2f7 --- /dev/null +++ b/scripts/lumina_gpt/T2ICompBench/mscr_gsd.sh @@ -0,0 +1,33 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi_groupsum' +num_init_new_token=16 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +groupsum_delta=0.008 +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/mscr_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --groupsum_delta=$groupsum_delta \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/T2ICompBench/mscr_sjd.sh b/scripts/lumina_gpt/T2ICompBench/mscr_sjd.sh new file mode 100644 index 0000000000000000000000000000000000000000..1404f1b01c28e5c2441339a8fd824b404d241dbc --- /dev/null +++ b/scripts/lumina_gpt/T2ICompBench/mscr_sjd.sh @@ -0,0 +1,33 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='speculative_jacobi_groupsum' +num_init_new_token=16 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='683-684' +groupsum_delta=0.5 +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/mscr_sjd_${groupsum_delta} +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --groupsum_delta=$groupsum_delta \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}_${slice}.log 2>&1 \ No newline at end of file diff --git a/scripts/lumina_gpt/T2ICompBench/sjd++.sh b/scripts/lumina_gpt/T2ICompBench/sjd++.sh new file mode 100644 index 0000000000000000000000000000000000000000..85c6614833150682c0acb4e6ef5867145b8438d5 --- /dev/null +++ b/scripts/lumina_gpt/T2ICompBench/sjd++.sh @@ -0,0 +1,57 @@ +#!/bin/bash +#SBATCH -N 1 # 节点数(可改成多节点) +#SBATCH --job-name=sciQA_test # 可选:任务名,便于查看 + +# ==================== 环境变量 ==================== +export PARTITION=DataFrontier_Knowledge +export CFSCTL=/mnt/petrelfs/leihaodong/app/cfs/bin/cfsctl +export NNODES=$SLURM_NNODES # 实际分配到的节点数 +export MASTER_ADDR=$(scontrol show hostname $SLURM_NODELIST | head -n1) +echo "Job started at $(date)" +echo "Nodes: $SLURM_NODELIST" +echo "Master node: $MASTER_ADDR" +echo "Total nodes: $NNODES" +# ==================== CFS 预加载(启动 + preload + 停止) ==================== +echo "Starting CFS preload..." +# 取主节点(和你们原来脚本保持一致) +MAIN_SERVER=$(scontrol show hostname $SLURM_NODELIST | head -n1) +# 停止可能残留的旧 CFS 实例 +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER stop || true +# 启动 CFS +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER start +# 开始预加载(这一步会卡住直到所有节点 preload 完成) +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER -a preload +# ==================== 真正要跑的程序 ==================== +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='sjd++' +num_init_new_token=96 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768/${prompt}/sjd++ +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=/nvme/leihaodong/mnt/local_model/models--Alpha-VLLM--Lumina-mGPT-7B-768/snapshots/755e7e40530a8edf4eea6078cbc484d2bfda091f +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --target_size=768 > ${output_path}.log 2>&1 + +# ==================== 清理 CFS ==================== +echo "Python script finished, stopping CFS..." +$CFSCTL -p $PARTITION -n $NNODES -X $MAIN_SERVER stop +echo "Job finished at $(date)" \ No newline at end of file diff --git a/scripts/pic/pic.ipynb b/scripts/pic/pic.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5c93cd577b54172fe28c4ce12889d7d77518182e --- /dev/null +++ b/scripts/pic/pic.ipynb @@ -0,0 +1,79 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "ename": "", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1;31mRunning cells with 'mgpt' requires the ipykernel package.\n", + "\u001b[1;31mRun the following command to install 'ipykernel' into the Python environment. \n", + "\u001b[1;31mCommand: 'conda install -n mgpt ipykernel --update-deps --force-reinstall'" + ] + } + ], + "source": [ + "import matplotlib.pyplot as plt\n", + "import seaborn as sns # For professional styling\n", + "\n", + "# Set seaborn style for scientific aesthetics\n", + "plt.style.use('seaborn-v0_8') # Use seaborn for clean, professional look\n", + "plt.rcParams['font.family'] = 'Arial' # Set font to Arial for publication\n", + "plt.rcParams['font.size'] = 14 # Larger font size for readability\n", + "plt.rcParams['axes.linewidth'] = 1.2 # Thicker axes for clarity\n", + "plt.rcParams['lines.linewidth'] = 2 # Thicker plot lines\n", + "plt.rcParams['legend.fontsize'] = 12 # Legend font size\n", + "plt.rcParams['xtick.labelsize'] = 12 # X-axis tick label size\n", + "plt.rcParams['ytick.labelsize'] = 12 # Y-axis tick label size\n", + "\n", + "# Data from the table\n", + "K = [2, 4, 6, 8, 12]\n", + "L = [3.21, 3.89, 4.57, 4.96, 5.38]\n", + "SR = [2.73, 3.01, 3.44, 3.30, 2.89]\n", + "\n", + "# Plot K vs L\n", + "plt.figure(figsize=(8, 6))\n", + "plt.scatter(K, L, color='#1f77b4', s=100, label='L', alpha=0.8, edgecolors='w') # Tableau blue, larger markers\n", + "plt.plot(K, L, color='#1f77b4', linestyle='--', alpha=0.6) # Dashed line, slightly transparent\n", + "plt.xlabel('K', fontsize=16, weight='bold')\n", + "plt.ylabel('L', fontsize=16, weight='bold')\n", + "plt.title('K vs L', fontsize=18, weight='bold')\n", + "plt.grid(True, linestyle='--', alpha=0.7)\n", + "plt.legend()\n", + "plt.tight_layout()\n", + "plt.savefig('K_vs_L.png', dpi=600, bbox_inches='tight') # High DPI for publication\n", + "plt.show()\n", + "\n", + "# Plot K vs SR\n", + "plt.figure(figsize=(8, 6))\n", + "plt.scatter(K, SR, color='#ff7f0e', s=100, label='SR', alpha=0.8, edgecolors='w') # Tableau orange\n", + "plt.plot(K, SR, color='#ff7f0e', linestyle='--', alpha=0.6) # Dashed line, slightly transparent\n", + "plt.xlabel('K', fontsize=16, weight='bold')\n", + "plt.ylabel('SR', fontsize=16, weight='bold')\n", + "plt.title('K vs SR', fontsize=18, weight='bold')\n", + "plt.grid(True, linestyle='--', alpha=0.7)\n", + "plt.legend()\n", + "plt.tight_layout()\n", + "plt.savefig('K_vs_SR.png', dpi=600, bbox_inches='tight') # High DPI for publication\n", + "plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "mgpt", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.16" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/scripts/pic/pic.py b/scripts/pic/pic.py new file mode 100644 index 0000000000000000000000000000000000000000..efd52ca01147bd23e462c38442ba69bd9708c980 --- /dev/null +++ b/scripts/pic/pic.py @@ -0,0 +1,43 @@ +import matplotlib.pyplot as plt +# import seaborn as sns # For professional styling + +# Set seaborn style for scientific aesthetics +plt.style.use('seaborn-v0_8') # Use seaborn for clean, professional look +plt.rcParams['font.family'] = 'Arial' # Set font to Arial for publication +plt.rcParams['font.size'] = 14 # Larger font size for readability +plt.rcParams['axes.linewidth'] = 1.2 # Thicker axes for clarity +plt.rcParams['lines.linewidth'] = 2 # Thicker plot lines +plt.rcParams['legend.fontsize'] = 12 # Legend font size +plt.rcParams['xtick.labelsize'] = 12 # X-axis tick label size +plt.rcParams['ytick.labelsize'] = 12 # Y-axis tick label size + +# Data from the table +K = [2, 4, 6, 8, 12] +L = [3.21, 3.89, 4.57, 4.96, 5.38] +SR = [2.73, 3.01, 3.44, 3.30, 2.89] + +# Plot K vs L +plt.figure(figsize=(8, 6)) +plt.scatter(K, L, color='#1f77b4', s=100, alpha=0.8, edgecolors='w') # Tableau blue, larger markers +plt.plot(K, L, color='#1f77b4', linestyle='--', alpha=0.6) # Dashed line, slightly transparent +plt.xlabel('K', fontsize=16, weight='bold') +plt.ylabel(r'$\tau$', fontsize=16, weight='bold') +# plt.title('K vs L', fontsize=18, weight='bold') +plt.grid(True, linestyle='--', alpha=0.7) +plt.legend() +plt.tight_layout() +plt.savefig('K_vs_L.png', dpi=600, bbox_inches='tight') # High DPI for publication +# plt.show() + +# Plot K vs SR +plt.figure(figsize=(8, 6)) +plt.scatter(K, SR, color='#ff7f0e', s=100, alpha=0.8, edgecolors='w') # Tableau orange +plt.plot(K, SR, color='#ff7f0e', linestyle='--', alpha=0.6) # Dashed line, slightly transparent +plt.xlabel('K', fontsize=16, weight='bold') +plt.ylabel('SR', fontsize=16, weight='bold') +# plt.title('K vs SR', fontsize=18, weight='bold') +plt.grid(True, linestyle='--', alpha=0.7) +plt.legend() +plt.tight_layout() +plt.savefig('K_vs_SR.png', dpi=600, bbox_inches='tight') # High DPI for publication +# plt.show() \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/MSCOCO/base.sh b/scripts/trash/lumina_gpt_1024/MSCOCO/base.sh new file mode 100644 index 0000000000000000000000000000000000000000..45a465c865191e044c4518d2aaf92532a45e0b93 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/MSCOCO/base.sh @@ -0,0 +1,24 @@ +#!/bin/bash +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +isp='random' +method='speculative_jacobi' +num_init_new_token=1 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/base +mkdir -p ${output_path} + +# nohup +python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/MSCOCO/ms_gsd.sh b/scripts/trash/lumina_gpt_1024/MSCOCO/ms_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..142ef3de3bd3865f3f2103ca111eb930dd28c100 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/MSCOCO/ms_gsd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/MSCOCO/ms_lantern.sh b/scripts/trash/lumina_gpt_1024/MSCOCO/ms_lantern.sh new file mode 100644 index 0000000000000000000000000000000000000000..a838fefa52964bacff0a80075f6d9b2c4959ce6c --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/MSCOCO/ms_lantern.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='lantern' +num_init_new_token=16 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_lantern +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/MSCOCO/ms_sjd.sh b/scripts/trash/lumina_gpt_1024/MSCOCO/ms_sjd.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab6b05459e27c5ef10574500906547dfe47dc709 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/MSCOCO/ms_sjd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="MSCOCO2017Val" +num_images=4000 +slice='0-4000' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_sjd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/PP/base.sh b/scripts/trash/lumina_gpt_1024/PP/base.sh new file mode 100644 index 0000000000000000000000000000000000000000..6c5c6654be8ae6fe04679470a4d3adc8fd626877 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/PP/base.sh @@ -0,0 +1,23 @@ +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +isp='random' +method='speculative_jacobi' +num_init_new_token=1 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/base +mkdir -p ${output_path} + +# nohup +python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/PP/ms_gsd.sh b/scripts/trash/lumina_gpt_1024/PP/ms_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..79008f9dfd9f07e929be5eee77652227fdb9eef1 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/PP/ms_gsd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/PP/ms_lantern.sh b/scripts/trash/lumina_gpt_1024/PP/ms_lantern.sh new file mode 100644 index 0000000000000000000000000000000000000000..a55a090a4da35283b830ef9cc1c300d62a94e097 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/PP/ms_lantern.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='lantern' +num_init_new_token=16 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_lantern +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/PP/ms_sjd.sh b/scripts/trash/lumina_gpt_1024/PP/ms_sjd.sh new file mode 100644 index 0000000000000000000000000000000000000000..25ca90b3a749580fa7d603100afc5a32363dbc90 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/PP/ms_sjd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_sjd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/PP/mscr_gsd.sh b/scripts/trash/lumina_gpt_1024/PP/mscr_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..a23194238d467d6a329335963685afc06c60ed8d --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/PP/mscr_gsd.sh @@ -0,0 +1,33 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi_groupsum' +num_init_new_token=16 +benchmark_way='order' +prompt="PartiPrompts" +num_images=1600 +slice='0-1600' +groupsum_delta=0.01 +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/mscr_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --groupsum_delta=$groupsum_delta \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/T2ICompBench/base.sh b/scripts/trash/lumina_gpt_1024/T2ICompBench/base.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d1f514e5c4b7e83579c7d4fff20c496e8b14bb0 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/T2ICompBench/base.sh @@ -0,0 +1,24 @@ +#!/bin/bash +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +isp='random' +method='speculative_jacobi' +num_init_new_token=1 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/base +mkdir -p ${output_path} + +# nohup +python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/T2ICompBench/ms_gsd.sh b/scripts/trash/lumina_gpt_1024/T2ICompBench/ms_gsd.sh new file mode 100644 index 0000000000000000000000000000000000000000..098d66bc239fc0e43caececa29213b25a7424c61 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/T2ICompBench/ms_gsd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='group_speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_gsd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/T2ICompBench/ms_lantern.sh b/scripts/trash/lumina_gpt_1024/T2ICompBench/ms_lantern.sh new file mode 100644 index 0000000000000000000000000000000000000000..45b2bda84d558262d9dee16f2a4b3eac6be3cf17 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/T2ICompBench/ms_lantern.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='lantern' +num_init_new_token=16 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_lantern +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/scripts/trash/lumina_gpt_1024/T2ICompBench/ms_sjd.sh b/scripts/trash/lumina_gpt_1024/T2ICompBench/ms_sjd.sh new file mode 100644 index 0000000000000000000000000000000000000000..3b0d542e6070f94d7af134f0d9641f42d14f3482 --- /dev/null +++ b/scripts/trash/lumina_gpt_1024/T2ICompBench/ms_sjd.sh @@ -0,0 +1,31 @@ +#!/bin/sh +cd /mnt/petrelfs/leihaodong/ICLR25/sjdtree +isp='random' +method='speculative_jacobi' +num_init_new_token=16 +benchmark_way='order' +prompt="T2ICompBenchVal" +num_images=2400 +slice='0-2400' +output_path=/mnt/petrelfs/leihaodong/ICLR25/exp/Lumina-mGPT-7B-768_${prompt}/ms_sjd +tokenizer_path=/mnt/petrelfs/leihaodong/local_model/chameleon/tokenizer +model_path=Alpha-VLLM/Lumina-mGPT-7B-768 +mkdir -p ${output_path} + +srun \ + -N 1 \ + --ntasks-per-node 1 \ + python /mnt/petrelfs/leihaodong/ICLR25/sjdtree/main.py \ + --tokenizer_path=$tokenizer_path \ + --output_path=$output_path \ + --model_path=$model_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice \ + --static_tree \ + --target_size=768 \ + --tree_choices=Grouped_Tree_6 > ${output_path}.log 2>&1 \ No newline at end of file diff --git a/sjdtree/.gitignore b/sjdtree/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b7faf403d915ca307532bb0eb9cceaf0214e8e5b --- /dev/null +++ b/sjdtree/.gitignore @@ -0,0 +1,207 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock +#poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +#pdm.lock +#pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +#pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ diff --git a/sjdtree/LICENSE b/sjdtree/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2617bf49d69af19ce9d8dae38329fd2fed21bc31 --- /dev/null +++ b/sjdtree/LICENSE @@ -0,0 +1,18 @@ +MIT No Attribution + +Copyright 2025 雷浩东 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/sjdtree/README.md b/sjdtree/README.md new file mode 100644 index 0000000000000000000000000000000000000000..80d69e72b505964138c5b02ab75c3e84b71fd906 --- /dev/null +++ b/sjdtree/README.md @@ -0,0 +1,125 @@ +# FSJD: Accelerating Auto-regressive Text-to-Image Generation with Training-free
Speculative Jacobi Decoding + + +## 🚩 注意事项 +如果你把workdir生成在了本地,不要把workdir的内容push到仓库!!!! + +## 🚩 New Features/Updates + +- ✅ Apr, 2025. 💥 **SJD** has been integrated into [Lumina-mGPT2](https://github.com/Alpha-VLLM/Lumina-mGPT-2.0) and [SimpleAR](https://github.com/wdrink/SimpleAR). +- ✅ Jan, 2025. 💥 **SJD** is accepted to ICLR 2025. +- ✅ Oct, 2024. Release **SJD**'s code. + +## 🚩 TODO List + +- □ Integrating SJD into vLLM framework for further acceleration. + +## Installing the dependencies + +##### Environment: + +- Python 3.10 +- CUDA 12.5 +- Pytorch 2.5.1+cu124 +- Transformers 4.47.1 + +##### Install from `yaml`: + +```bash +conda env create -f environment.yaml +``` + +## 🚩 如果你想完成完整的数据集测试? + +### target model: lumina-gpt + +``` +cd ./fsjd +isp='random' #init的填充方式 +method='speculative_jacobi' #sjd +num_init_new_token=16 #填充数量 +benchmark_way='order' #测试集的载入方式 +prompt="MSCOCO2017Val" #测试集的名字 +num_images=2 #测试集的图片数量 +slice='0-1000' #测试集的区间 +output_path=/home/leihaodong/AAAI25/exp/FSJD/${prompt}/${method}# 测试结果的输出文件夹 + +python /home/leihaodong/AAAI25/fsjd/main.py \ + --output_path=$output_path \ + --isp=$isp \ + --method=$method \ + --num_init_new_token=$num_init_new_token \ + --benchmark_way=$benchmark_way \ + --prompt=$prompt \ + --num_images=$num_images \ + --slice=$slice +``` +### target model: lumina-gpt + +benchmark 为 parti-prompt + +``` +cd /home/leihaodong/AAAI25/fsjd +gpu_ids=0,3 +dataset_name=parti +dataset_anno_file=/home/leihaodong/AAAI25/fsjd/data/prompts/PartiPrompts.tsv +model_name=leloy/Anole-7b-v0.1-hf +max_num_new_tokens=16 +multi_token_init_scheme=random +seed=42 +target_size=1024 +prefix_token_sampler_scheme=speculative_jacobi +temperature=1.0 + +output_path=/home/leihaodong/AAAI25/exp/SJD/${dataset_name}_anole_${temperature}/${prefix_token_sampler_scheme} +mkdir -p ${output_path} + +nohup python eval_model.py \ + --gpu_ids $gpu_ids \ + --dataset_name $dataset_name \ + --dataset_anno_file $dataset_anno_file \ + --model_name $model_name \ + --max_num_new_tokens $max_num_new_tokens \ + --multi_token_init_scheme $multi_token_init_scheme \ + --seed $seed \ + --target_size $target_size \ + --prefix_token_sampler_scheme $prefix_token_sampler_scheme \ + --temperature $temperature \ + --output_dir $output_path \ + --return_accl True \ + --num_images 0 > ${output_path}.log 2>&1 & +``` + +#### Lumina-mGPT + +```bash +CUDA_VISIBLE_DEVICES=0 python test_lumina_mgpt.py +``` + +#### Emu3 + +```bash +CUDA_VISIBLE_DEVICES=0 python test_emu3.py +``` + +#### LlamaGen + +```bash +CUDA_VISIBLE_DEVICES=0 python test_llamagen.py +``` + +## Acknowledge + +Our code is based on [Lumina-mGPT](https://github.com/Alpha-VLLM/Lumina-mGPT), [Emu3](https://github.com/Alpha-VLLM/Lumina-mGPT), [LlamaGen](https://github.com/FoundationVision/LlamaGen), [Anole](https://github.com/GAIR-NLP/anole), and [CLLM](https://github.com/hao-ai-lab/Consistency_LLM). We would like to express our gratitude to [Tianwei Xiong](https://github.com/SilentView) for his assistance. + +## Citation + +```bibtex +@article{teng2024accelerating, + title={Accelerating auto-regressive text-to-image generation with training-free speculative jacobi decoding}, + author={Teng, Yao and Shi, Han and Liu, Xian and Ning, Xuefei and Dai, Guohao and Wang, Yu and Li, Zhenguo and Liu, Xihui}, + journal={arXiv preprint arXiv:2410.01699}, + year={2024} +} +``` + diff --git a/sjdtree/anole/__init__.py b/sjdtree/anole/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sjdtree/anole/modeling_chameleon.py b/sjdtree/anole/modeling_chameleon.py new file mode 100644 index 0000000000000000000000000000000000000000..4ed69924cf1a85b91c810920857d3ea59480c939 --- /dev/null +++ b/sjdtree/anole/modeling_chameleon.py @@ -0,0 +1,2043 @@ +# coding=utf-8 +# Copyright 2024 Meta Inc. and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch Chameleon model.""" + +import math +import warnings +from functools import cached_property +from typing import Dict, Literal, Optional, Tuple, Union, List + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import nn +from torch.nn import CrossEntropyLoss + +from transformers.activations import ACT2FN +from transformers.cache_utils import Cache, StaticCache +from transformers.generation.configuration_utils import GenerationConfig + +from transformers.modeling_attn_mask_utils import AttentionMaskConverter +from transformers.modeling_flash_attention_utils import _flash_attention_forward +from transformers.modeling_outputs import ( + BaseModelOutputWithPast, + CausalLMOutputWithPast, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS +from transformers.utils import ( + add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + is_flash_attn_2_available, + is_flash_attn_greater_or_equal_2_10, + logging, + replace_return_docstrings, +) +from transformers.models.chameleon.configuration_chameleon import ChameleonConfig, PretrainedConfig + + +if is_flash_attn_2_available(): + from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa + +class ChameleonVQVAEConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`ChameleonVQModel`]. It is used to instantiate a + `ChameleonVQModel` according to the specified arguments, defining the model architecture. + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. Instantiating a + configuration with the defaults will yield a similar configuration to the VQModel of the + [meta/chameleon-7B](https://huggingface.co/meta/chameleon-7B). + + Args: + embed_dim (`int`, *optional*, defaults to 256): + Dimensionality of each embedding vector. + num_embeddings (`int`, *optional*, defaults to 8192): + Number of codebook embeddings. + double_latent (`bool`, *optional*, defaults to `False`): + Whether to use double z channels. + latent_channels (`int`, *optional*, defaults to 256): + Number of channels for the latent space. + resolution (`int`, *optional*, defaults to 512): + Resolution of the input images. + in_channels (`int`, *optional*, defaults to 3): + Number of input channels. + out_channels (`int`, *optional*, defaults to 3): + Number of output channels. + base_channels (`int`, *optional*, defaults to 128): + Base channel count. + channel_multiplier (`List[int]`, *optional*, defaults to `[1, 1, 2, 2, 4]`): + Channel multipliers for each resolution. + num_res_blocks (`int`, *optional*, defaults to 2): + Number of residual blocks. + attn_resolutions (`List[int]`, *optional*): + Resolutions to apply attention. + dropout (`float`, *optional*, defaults to 0.0): + Dropout rate. + attn_type (`str`, *optional*, defaults to `"vanilla"`): + Attention type used in VQ-GAN encoder. Can be "vanilla" or None. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + """ + + model_type = "chameleon_vqgan" + + def __init__( + self, + embed_dim: int = 256, + num_embeddings: int = 8192, + double_latent: bool = False, + latent_channels: int = 256, + resolution: int = 512, + in_channels: int = 3, + out_channels: int = 3, + base_channels: int = 128, + channel_multiplier: List[int] = [1, 1, 2, 2, 4], + num_res_blocks: int = 2, + attn_resolutions: List[int] = None, + dropout: float = 0.0, + attn_type: str = "vanilla", + initializer_range=0.02, + **kwargs, + ): + super().__init__(**kwargs) + self.embed_dim = embed_dim + self.num_embeddings = num_embeddings + self.double_latent = double_latent + self.latent_channels = latent_channels + self.resolution = resolution + self.in_channels = in_channels + self.out_channels = out_channels + self.base_channels = base_channels + self.channel_multiplier = channel_multiplier + self.num_res_blocks = num_res_blocks + self.attn_resolutions = attn_resolutions + self.dropout = dropout + self.attn_type = attn_type + self.initializer_range = initializer_range + +# Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position +def _prepare_4d_causal_attention_mask_with_cache_position( + attention_mask: torch.Tensor, + sequence_length: int, + target_length: int, + dtype: torch.dtype, + device: torch.device, + min_dtype: float, + cache_position: torch.Tensor, + batch_size: int, +): + """ + Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape + `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. + + Args: + attention_mask (`torch.Tensor`): + A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`. + sequence_length (`int`): + The sequence length being processed. + target_length (`int`): + The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet. + dtype (`torch.dtype`): + The dtype to use for the 4D attention mask. + device (`torch.device`): + The device to plcae the 4D attention mask on. + min_dtype (`float`): + The minimum value representable with the dtype `dtype`. + cache_position (`torch.Tensor`): + Indices depicting the position of the input sequence tokens in the sequence. + batch_size (`torch.Tensor`): + Batch size. + """ + if attention_mask is not None and attention_mask.dim() == 4: + # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. + causal_mask = attention_mask + else: + causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device) + if sequence_length != 1: + causal_mask = torch.triu(causal_mask, diagonal=1) + causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) + causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) + if attention_mask is not None: + causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit + mask_length = attention_mask.shape[-1] + padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :] + padding_mask = padding_mask == 0 + causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( + padding_mask, min_dtype + ) + + return causal_mask + + +logger = logging.get_logger(__name__) + +_CONFIG_FOR_DOC = "ChameleonConfig" +_CHECKPOINT_FOR_DOC = "meta/chameleon-7b" +_EXPECTED_OUTPUT_SHAPE = [1, 7, 4096] +_SEQ_CLASS_EXPECTED_LOSS = 1.03 +_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_0'" + + +# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Chameleon +class ChameleonRMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + ChameleonRMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return self.weight * hidden_states.to(input_dtype) + + def extra_repr(self): + return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + + +ALL_LAYERNORM_LAYERS.append(ChameleonRMSNorm) + + +# copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Chameleon +# TODO(joao): add me back asap :) +class ChameleonRotaryEmbedding(nn.Module): + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): + super().__init__() + self.scaling_factor = scaling_factor + self.dim = dim + self.max_position_embeddings = max_position_embeddings + self.base = base + inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + # For BC we register cos and sin cached + self.max_seq_len_cached = max_position_embeddings + + @torch.no_grad() + def forward(self, x, position_ids): + # x: [bs, num_attention_heads, seq_len, head_size] + inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) + position_ids_expanded = position_ids[:, None, :].float() + # Force float32 since bfloat16 loses precision on long contexts + # See https://github.com/huggingface/transformers/pull/29285 + device_type = x.device.type + device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu" + with torch.autocast(device_type=device_type, enabled=False): + freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) + emb = torch.cat((freqs, freqs), dim=-1) + cos = emb.cos() + sin = emb.sin() + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + + +# copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Chameleon +# TODO(joao): add me back asap :) +class ChameleonLinearScalingRotaryEmbedding(ChameleonRotaryEmbedding): + """ChameleonRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" + + def forward(self, x, position_ids): + # difference to the original RoPE: a scaling factor is aplied to the position ids + position_ids = position_ids.float() / self.scaling_factor + cos, sin = super().forward(x, position_ids) + return cos, sin + + +# copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Chameleon +# TODO(joao): add me back asap :) +class ChameleonDynamicNTKScalingRotaryEmbedding(ChameleonRotaryEmbedding): + """ChameleonRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla""" + + def forward(self, x, position_ids): + # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length + seq_len = torch.max(position_ids) + 1 + if seq_len > self.max_position_embeddings: + base = self.base * ( + (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) + ) ** (self.dim / (self.dim - 2)) + inv_freq = 1.0 / ( + base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim) + ) + self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation + + cos, sin = super().forward(x, position_ids) + return cos, sin + + +# Copied from transformers.models.llama.modeling_llama.rotate_half +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) + + +# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb +def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. + + Args: + q (`torch.Tensor`): The query tensor. + k (`torch.Tensor`): The key tensor. + cos (`torch.Tensor`): The cosine part of the rotary embedding. + sin (`torch.Tensor`): The sine part of the rotary embedding. + position_ids (`torch.Tensor`, *optional*): + Deprecated and unused. + unsqueeze_dim (`int`, *optional*, defaults to 1): + The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note + that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and + k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes + cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have + the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + Returns: + `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. + """ + 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 + + +# Copied from transformers.models.llama.modeling_llama.LlamaMLP with Llama->Chameleon +class ChameleonMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias) + self.act_fn = ACT2FN[config.hidden_act] + + # Ignore copy + def forward(self, x): + down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + return down_proj + + +class ChameleonLayerNorm(nn.LayerNorm): + """ + LayerNorm but computes stats only over the last dim because Chameleon applies gamma and beta + from each shard separately to each head, instead of reducing. We can apply each head's own + gamma/beta by repeat-interleaving weights from each shard, but the stats have to be computed + in the last dimension. This module applies gamma/beta manually to fulfill this requirement. + """ + + def __init__(self, hidden_size, *args, **kwargs): + super().__init__(hidden_size, *args, **kwargs) + self.normalized_shape = (hidden_size[-1],) + + def forward(self, hidden_states): + hidden_states = F.layer_norm(hidden_states, self.normalized_shape, None, None, eps=1e-5) + hidden_states = hidden_states * self.weight + self.bias + return hidden_states + + +# Copied from transformers.models.llama.modeling_llama.repeat_kv +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + 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) + + +class ChameleonAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: ChameleonConfig, layer_idx: Optional[int] = None): + super().__init__() + self.config = config + self.layer_idx = layer_idx + if layer_idx is None: + logger.warning_once( + f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will " + "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` " + "when creating this class." + ) + + self.attention_dropout = config.attention_dropout + self.hidden_size = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.hidden_size // self.num_heads + self.num_key_value_heads = config.num_key_value_heads + self.num_key_value_groups = self.num_heads // self.num_key_value_heads + self.max_position_embeddings = config.max_position_embeddings + self.rope_theta = config.rope_theta + self.is_causal = True + self.model_parallel_size = config.model_parallel_size + + if (self.head_dim * self.num_heads) != self.hidden_size: + raise ValueError( + f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" + f" and `num_heads`: {self.num_heads})." + ) + + self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias) + self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) + self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) + self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias) + self.q_norm = ChameleonLayerNorm((self.num_heads, self.head_dim)) + self.k_norm = ChameleonLayerNorm((self.num_key_value_heads, self.head_dim)) + self._init_rope() + + # copied from transformers.models.llama.modeling_llama.LlamaAttention._init_rope with Llama->Chameleon + # TODO(joao): add me back asap :) + def _init_rope(self): + if self.config.rope_scaling is None: + self.rotary_emb = ChameleonRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + base=self.rope_theta, + ) + else: + scaling_type = self.config.rope_scaling["type"] + scaling_factor = self.config.rope_scaling["factor"] + if scaling_type == "linear": + self.rotary_emb = ChameleonLinearScalingRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + scaling_factor=scaling_factor, + base=self.rope_theta, + ) + elif scaling_type == "dynamic": + self.rotary_emb = ChameleonDynamicNTKScalingRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + scaling_factor=scaling_factor, + base=self.rope_theta, + ) + else: + raise ValueError(f"Unknown RoPE scaling type {scaling_type}") + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.reshape(-1, self.num_heads, self.head_dim) + query_states = self.q_norm(query_states) + + key_states = key_states.reshape(-1, self.num_key_value_heads, self.head_dim) + key_states = self.k_norm(key_states) + + query_states = query_states.reshape(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.reshape(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + cos, sin = self.rotary_emb(value_states, position_ids) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + if past_key_value is not None: + # sin and cos are specific to RoPE models; position_ids needed for the static cache + cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) + + if attention_mask is not None: # no matter the length, we just slice it + causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] + attn_weights = attn_weights + causal_mask + + # upcast attention to fp32 + attn_weights = nn.functional.softmax(attn_weights, dim=-1).to(query_states.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) + attn_output = torch.matmul(attn_weights, value_states) + + if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.transpose(1, 2).contiguous() + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + +# copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Chameleon +# TODO(joao): add me back asap :) +class ChameleonFlashAttention2(ChameleonAttention): + """ + Chameleon flash attention module. This module inherits from `ChameleonAttention` as the weights of the module stays + untouched. The only required change would be on the forward pass where it needs to correctly call the public API of + flash attention and deal with padding tokens in case the input contains any of them. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. + # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. + # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). + self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() + + # Ignore copy + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if isinstance(past_key_value, StaticCache): + raise ValueError( + "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` " + "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers" + ) + + output_attentions = False + + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.reshape(-1, self.num_heads, self.head_dim) + query_states = self.q_norm(query_states) + + key_states = key_states.reshape(-1, self.num_key_value_heads, self.head_dim) + key_states = self.k_norm(key_states) + + # Flash attention requires the input to have the shape + # batch_size x seq_length x head_dim x hidden_dim + # therefore we just need to keep the original shape + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + cos, sin = self.rotary_emb(value_states, position_ids) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + if past_key_value is not None: + # sin and cos are specific to RoPE models; position_ids needed for the static cache + cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. + # We would need to refactor the KV cache to be able to avoid many of these transpose/reshape/view. + query_states = query_states.transpose(1, 2) + key_states = key_states.transpose(1, 2) + value_states = value_states.transpose(1, 2) + + dropout_rate = self.attention_dropout if self.training else 0.0 + + # In PEFT, usually we cast the layer norms in float32 for training stability reasons + # therefore the input hidden states gets silently casted in float32. Hence, we need + # cast them back in the correct dtype just to be sure everything works as expected. + # This might slowdown training & inference so it is recommended to not cast the LayerNorms + # in fp32. (ChameleonRMSNorm handles it correctly) + + input_dtype = query_states.dtype + if input_dtype == torch.float32: + if torch.is_autocast_enabled(): + target_dtype = torch.get_autocast_gpu_dtype() + # Handle the case where the model is quantized + elif hasattr(self.config, "_pre_quantization_dtype"): + target_dtype = self.config._pre_quantization_dtype + else: + target_dtype = self.q_proj.weight.dtype + + logger.warning_once( + f"The input hidden states seems to be silently casted in float32, this might be related to" + f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" + f" {target_dtype}." + ) + + query_states = query_states.to(target_dtype) + key_states = key_states.to(target_dtype) + value_states = value_states.to(target_dtype) + + attn_output = _flash_attention_forward( + query_states, + key_states, + value_states, + attention_mask, + q_len, + dropout=dropout_rate, + sliding_window=getattr(self, "sliding_window", None), + use_top_left_mask=self._flash_attn_uses_top_left_mask, + is_causal=self.is_causal, + ) + + attn_output = attn_output.reshape(bsz, q_len, -1).contiguous() + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + +class ChameleonSdpaAttention(ChameleonAttention): + """ + Chameleon attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from + `ChameleonAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to + SDPA API. + """ + + # Adapted from ChameleonAttention.forward + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + cache_position: Optional[torch.LongTensor] = None, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if output_attentions: + # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented. + logger.warning_once( + "ChameleonModel is using ChameleonSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, " + 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' + ) + return super().forward( + 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, + ) + + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.reshape(-1, self.num_heads, self.head_dim) + query_states = self.q_norm(query_states) + + key_states = key_states.reshape(-1, self.num_key_value_heads, self.head_dim) + key_states = self.k_norm(key_states) + + query_states = query_states.reshape(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.reshape(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + cos, sin = self.rotary_emb(value_states, position_ids) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None) + + if past_key_value is not None: + # sin and cos are specific to RoPE models; position_ids needed for the static cache + cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + causal_mask = attention_mask + if attention_mask is not None and cache_position is not None: + causal_mask = causal_mask[:, :, :, : key_states.shape[-2]] + + # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask, + # Reference: https://github.com/pytorch/pytorch/issues/112577. + 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() + + # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment + # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling. + is_causal = True if causal_mask is None and q_len > 1 else False + + attn_output = torch.nn.functional.scaled_dot_product_attention( + query_states, + key_states, + value_states, + attn_mask=causal_mask, + dropout_p=self.attention_dropout if self.training else 0.0, + is_causal=is_causal, + ) + + attn_output = attn_output.transpose(1, 2).contiguous() + attn_output = attn_output.view(bsz, q_len, self.hidden_size) + + attn_output = self.o_proj(attn_output) + + return attn_output, None, past_key_value + + +CHAMELEON_ATTENTION_CLASSES = { + "eager": ChameleonAttention, + "flash_attention_2": ChameleonFlashAttention2, + "sdpa": ChameleonSdpaAttention, +} + + +# copied from transformers.models.llama.modeling_llama.LlamaDecoderLayer with Llama->Chameleon, LLAMA->CHAMELEON +# TODO(joao): add me back asap :) +class ChameleonDecoderLayer(nn.Module): + def __init__(self, config: ChameleonConfig, layer_idx: int): + super().__init__() + self.hidden_size = config.hidden_size + + self.self_attn = CHAMELEON_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx) + + self.mlp = ChameleonMLP(config) + self.input_layernorm = ChameleonRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = ChameleonRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): + attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, + query_sequence_length, key_sequence_length)` if default attention is used. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): + Indices depicting the position of the input sequence tokens in the sequence + kwargs (`dict`, *optional*): + Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code + into the model + """ + residual = hidden_states + + hidden_states = self.input_layernorm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + 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, + ) + hidden_states = residual + hidden_states + + # Fully Connected + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +class ChameleonSwinDecoderLayer(nn.Module): + def __init__(self, config: ChameleonConfig, layer_idx: int): + super().__init__() + self.hidden_size = config.hidden_size + + self.self_attn = CHAMELEON_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx) + + self.mlp = ChameleonMLP(config) + self.input_layernorm = ChameleonRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = ChameleonRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): + input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): + attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, + query_sequence_length, key_sequence_length)` if default attention is used. + position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): + Indices depicting the position of the input sequence tokens in the sequence. + """ + + residual = hidden_states + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + 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, + ) + hidden_states = self.input_layernorm(hidden_states) + hidden_states = residual + hidden_states + # Fully Connected + residual = hidden_states + hidden_states = self.mlp(hidden_states) + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states = residual + hidden_states + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +class ChameleonVQVAEVectorQuantizer(nn.Module): + """ + A module for vector quantization using learned embedding vectors. + + This module implements the quantization process similar to te one described in + the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous + input vectors into discrete codebook vectors, which are learned during training. + Current implementation improves over previous ones by avoiding costly matrix multiplications + and allowing for post-hoc remapping of indices. + """ + + def __init__(self, config): + super().__init__() + self.num_embeddings = config.num_embeddings + self.embedding_dim = config.embed_dim + self.quant_state_dims = [config.resolution // 2 ** (len(config.channel_multiplier) - 1)] * 2 + self.beta = getattr(config, "beta", 0.25) + + self.embedding = nn.Embedding(self.num_embeddings, self.embedding_dim) + self.re_embed = self.num_embeddings + + def forward(self, hidden_state: torch.FloatTensor): + batch_size = hidden_state.shape[0] + hidden_state = hidden_state.permute(0, 2, 3, 1).contiguous() + hidden_state_flattened = hidden_state.view(-1, self.embedding_dim) + + # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z + distances = ( + torch.sum(hidden_state_flattened**2, dim=1, keepdim=True) + + torch.sum(self.embedding.weight**2, dim=1) + - 2 * torch.einsum("bd,dn->bn", hidden_state_flattened, self.embedding.weight.transpose(0, 1)) + ) + + min_encoding_indices = torch.argmin(distances, dim=1) + hidden_state_quant = self.embedding(min_encoding_indices).view(hidden_state.shape) + + # compute loss for embedding + loss = torch.mean((hidden_state_quant.detach() - hidden_state) ** 2) + self.beta * torch.mean( + (hidden_state_quant - hidden_state.detach()) ** 2 + ) + + # preserve gradients + hidden_state_quant = hidden_state + (hidden_state_quant - hidden_state).detach() + + # reshape back to match original input shape + hidden_state_quant = hidden_state_quant.permute(0, 3, 1, 2).contiguous() + + return hidden_state_quant, loss, min_encoding_indices.view(batch_size, -1) + + def get_codebook_entry(self, image_tokens: torch.LongTensor) -> torch.FloatTensor: + batch_size = image_tokens.shape[0] + emb_dim: int = self.embedding.weight.shape[-1] + # get quantized latent vectors + hidden_state_quant = self.embedding(image_tokens) + + # reshape back to match original input shape + hidden_state_quant = hidden_state_quant.view((batch_size, *self.quant_state_dims, emb_dim)) + hidden_state_quant = hidden_state_quant.permute(0, 3, 1, 2).contiguous() + + return hidden_state_quant + + +class ChameleonVQVAEDecoderConvUpsample(nn.Module): + def __init__(self, in_channels): + super().__init__() + self.conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1) + + def forward(self, hidden_states): + hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest") + hidden_states = self.conv(hidden_states) + return hidden_states + + +class ChameleonVQVAEEncoderConvDownsample(nn.Module): + def __init__(self, in_channels): + super().__init__() + self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0) + + def forward(self, hidden_states): + # no asymmetric padding in torch conv, must do it ourselves + hidden_states = F.pad(hidden_states, pad=(0, 1, 0, 1), mode="constant", value=0) + hidden_states = self.conv(hidden_states) + return hidden_states + + +class ChameleonVQVAEResnetBlock(nn.Module): + def __init__( + self, + config, + in_channels, + out_channels=None, + conv_shortcut=False, + ): + super().__init__() + self.in_channels = in_channels + self.out_channels = in_channels if out_channels is None else out_channels + self.use_conv_shortcut = conv_shortcut + + self.norm1 = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True) + self.conv1 = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) + self.norm2 = torch.nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True) + self.dropout = torch.nn.Dropout(config.dropout) + self.conv2 = torch.nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1) + if self.in_channels != self.out_channels: + if self.use_conv_shortcut: + self.conv_shortcut = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) + else: + self.nin_shortcut = torch.nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0) + + def forward(self, hidden_states): + residual = hidden_states + hidden_states = self.norm1(hidden_states) + hidden_states *= torch.sigmoid(hidden_states) + hidden_states = self.conv1(hidden_states) + + hidden_states = self.norm2(hidden_states) + hidden_states *= torch.sigmoid(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.conv2(hidden_states) + + if self.in_channels != self.out_channels: + if self.use_conv_shortcut: + residual = self.conv_shortcut(residual) + else: + residual = self.nin_shortcut(residual) + + return residual + hidden_states + + +class ChameleonVQVAEAttnBlock(nn.Module): + def __init__(self, in_channels): + super().__init__() + self.in_channels = in_channels + + self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True) + self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) + self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) + self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) + self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) + + def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor: + residual = hidden_states + hidden_states = self.norm(hidden_states) + query_states = self.q(hidden_states) + key_states = self.k(hidden_states) + value_states = self.v(hidden_states) + + # compute attention + batch_size, channels, height, width = query_states.shape + query_states = query_states.reshape(batch_size, channels, height * width).permute(0, 2, 1) + key_states = key_states.reshape(batch_size, channels, height * width) + attn_weights = torch.bmm(query_states, key_states) + attn_weights = attn_weights * (int(channels) ** (-0.5)) + attn_weights = F.softmax(attn_weights, dim=2) + + # attend to values + value_states = value_states.reshape(batch_size, channels, height * width) + attn_weights = attn_weights.permute(0, 2, 1) + attn_output = torch.bmm(value_states, attn_weights).reshape(batch_size, channels, height, width) + + attn_output = self.proj_out(attn_output) + return residual + attn_output + + +class ChameleonVQVAEEncoder(nn.Module): + def __init__(self, config): + super().__init__() + + self.num_resolutions = len(config.channel_multiplier) + self.num_res_blocks = config.num_res_blocks + base_channels = config.base_channels + resolution = config.resolution + in_channels = config.in_channels + double_latent = config.double_latent + latent_channels = config.latent_channels + channel_multiplier = config.channel_multiplier + + self.conv_in = torch.nn.Conv2d(in_channels, base_channels, kernel_size=3, stride=1, padding=1) + + curr_res = resolution + in_channel_multiplier = (1,) + tuple(channel_multiplier) + self.in_channel_multiplier = in_channel_multiplier + self.down = nn.ModuleList() + for i_level in range(self.num_resolutions): + block = nn.ModuleList() + attn = nn.ModuleList() + block_in = base_channels * in_channel_multiplier[i_level] + block_out = base_channels * channel_multiplier[i_level] + for i_block in range(self.num_res_blocks): + block.append( + ChameleonVQVAEResnetBlock( + config=config, + in_channels=block_in, + out_channels=block_out, + ) + ) + block_in = block_out + if ( + config.attn_resolutions is not None + and curr_res in config.attn_resolutions + and config.attn_type == "vanilla" + ): + attn.append(ChameleonVQVAEAttnBlock(block_in)) + + down = nn.Module() + down.block = block + down.attn = attn + if i_level != self.num_resolutions - 1: + down.downsample = ChameleonVQVAEEncoderConvDownsample(block_in) + curr_res = curr_res // 2 + self.down.append(down) + + self.mid = nn.Module() + self.mid.block_1 = ChameleonVQVAEResnetBlock( + config=config, + in_channels=block_in, + out_channels=block_in, + ) + self.mid.attn_1 = ChameleonVQVAEAttnBlock(block_in) if config.attn_type == "vanilla" else nn.Identity() + self.mid.block_2 = ChameleonVQVAEResnetBlock( + config=config, + in_channels=block_in, + out_channels=block_in, + ) + + self.norm_out = torch.nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True) + self.conv_out = torch.nn.Conv2d( + block_in, + 2 * latent_channels if double_latent else latent_channels, + kernel_size=3, + stride=1, + padding=1, + ) + + def forward(self, pixel_values: torch.FloatTensor) -> torch.FloatTensor: + # downsampling + hidden_states = [self.conv_in(pixel_values)] + for i_level in range(self.num_resolutions): + for i_block in range(self.num_res_blocks): + hidden_state = self.down[i_level].block[i_block]( + hidden_states[-1], + ) + if len(self.down[i_level].attn) > 0: + hidden_state = self.down[i_level].attn[i_block](hidden_state) + hidden_states.append(hidden_state) + if i_level != self.num_resolutions - 1: + hidden_states.append(self.down[i_level].downsample(hidden_states[-1])) + + # middle + last_hidden_state = hidden_states[-1] + last_hidden_state = self.mid.block_1(last_hidden_state) + last_hidden_state = self.mid.attn_1(last_hidden_state) + last_hidden_state = self.mid.block_2(last_hidden_state) + + # end + last_hidden_state = self.norm_out(last_hidden_state) + last_hidden_state *= torch.sigmoid(last_hidden_state) + last_hidden_state = self.conv_out(last_hidden_state) + return last_hidden_state + + +class ChameleonVQVAEDecoder(nn.Module): + def __init__(self, config): + super().__init__() + + self.num_resolutions = len(config.channel_multiplier) + self.num_res_blocks = config.num_res_blocks + base_channels = config.base_channels + resolution = config.resolution + latent_channels = config.latent_channels + out_channels = config.in_channels # 没有用 + + # compute in_ch_mult, block_in and curr_res at lowest res + block_in = base_channels * config.channel_multiplier[self.num_resolutions - 1] + curr_res = resolution // 2 ** (self.num_resolutions - 1) + self.z_shape = (1, latent_channels, curr_res, curr_res) + + # z to block_in + self.conv_in = torch.nn.Conv2d(latent_channels, block_in, kernel_size=3, stride=1, padding=1) + + # middle + self.mid = nn.Module() + self.mid.block_1 = ChameleonVQVAEResnetBlock( + config=config, + in_channels=block_in, + out_channels=block_in, + ) + self.mid.attn_1 = ChameleonVQVAEAttnBlock(block_in) if config.attn_type == "vanilla" else nn.Identity() + self.mid.block_2 = ChameleonVQVAEResnetBlock( + config=config, + in_channels=block_in, + out_channels=block_in, + ) + + # upsampling + self.up = nn.ModuleList() + for i_level in reversed(range(self.num_resolutions)): + block = nn.ModuleList() + attn = nn.ModuleList() + block_out = base_channels * config.channel_multiplier[i_level] + for i_block in range(self.num_res_blocks + 1): + block.append( + ChameleonVQVAEResnetBlock( + config=config, + in_channels=block_in, + out_channels=block_out, + ) + ) + block_in = block_out + if ( + config.attn_resolutions is not None + and curr_res in config.attn_resolutions + and config.attn_type == "vanilla" + ): + attn.append(ChameleonVQVAEAttnBlock(block_in)) + up = nn.Module() + up.block = block + up.attn = attn + if i_level != 0: + up.upsample = ChameleonVQVAEDecoderConvUpsample(block_in) + curr_res = curr_res * 2 + self.up.insert(0, up) # prepend to get consistent order + + # end + self.norm_out = torch.nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True) + self.conv_out = torch.nn.Conv2d(block_in, out_channels, kernel_size=3, stride=1, padding=1) + + def forward(self, hidden_state: torch.FloatTensor) -> torch.FloatTensor: + hidden_state = self.conv_in(hidden_state) + + # middle + hidden_state = self.mid.block_1(hidden_state) + hidden_state = self.mid.attn_1(hidden_state) + hidden_state = self.mid.block_2(hidden_state) + + # upsampling + for i_level in reversed(range(self.num_resolutions)): + for i_block in range(self.num_res_blocks + 1): + hidden_state = self.up[i_level].block[i_block](hidden_state) + if len(self.up[i_level].attn) > 0: + hidden_state = self.up[i_level].attn[i_block](hidden_state) + if i_level != 0: + hidden_state = self.up[i_level].upsample(hidden_state) + + hidden_state = self.norm_out(hidden_state) + hidden_state *= torch.sigmoid(hidden_state) + hidden_state = self.conv_out(hidden_state) + return hidden_state + + +CHAMELEON_VQ_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`ChameleonVQVAEConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + """The VQ-VAE model used in Chameleon for encoding/decoding images into discrete tokens. + This model follows the "Make-a-scene: Scene-based text-to-image generation with human priors" paper from + [ Oran Gafni, Adam Polyak, Oron Ashual, Shelly Sheynin, Devi Parikh, and Yaniv Taigman](https://arxiv.org/abs/2203.13131). + """, + CHAMELEON_VQ_START_DOCSTRING, +) +class ChameleonVQVAE(PreTrainedModel): + config_class = ChameleonVQVAEConfig + _no_split_modules = ["ChameleonVQVAEVectorQuantizer"] + + def _init_weights(self, module): + std = self.config.initializer_range + if isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + elif isinstance(module, nn.GroupNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) + elif isinstance(module, (nn.Linear, nn.Conv2d)): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + + def __init__(self, config: ChameleonVQVAEConfig): + super().__init__(config) + + self.encoder = ChameleonVQVAEEncoder(config) + self.decoder = ChameleonVQVAEDecoder(config) + self.quantize = ChameleonVQVAEVectorQuantizer(config) + self.quant_conv = torch.nn.Conv2d(config.latent_channels, config.embed_dim, 1) + self.post_quant_conv = torch.nn.Conv2d(config.embed_dim, config.latent_channels, 1) + self.eval() # Chameleon's VQ model is frozen + + def encode(self, pixel_values: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.LongTensor]: + """ + Encodes pixel values into quantized tokens. + + Args: + pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)): + The tensors corresponding to the input images. + + Returns: + quant (`torch.FloatTensor` of shape `(batch_size, embed_dim, quantize.quant_state_dims[0], quantize.quant_state_dims[1])`): + Embeddings of quantized tokens. + emb_loss (`torch.FloatTensor`): + Embedding loss. + indices (`torch.LongTensor` of shape `(batch_size, quantize.quant_state_dims[0] * quantize.quant_state_dims[1])`): + Token IDs + """ + hidden_states = self.encoder(pixel_values) + hidden_states = self.quant_conv(hidden_states) + quant, emb_loss, indices = self.quantize(hidden_states) + return quant, emb_loss, indices + + def decode(self, image_tokens: torch.LongTensor) -> torch.FloatTensor: + """ + Decodes quantized token IDs into pixel values. + + Args: + image_tokens (`torch.LongTensor` of shape `(batch_size, quantize.quant_state_dims[0] * quantize.quant_state_dims[1])`): + Batch of token IDs. + + Returns: + (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): + Pixel values decoded from the token IDs. + """ + if image_tokens.shape[1] != self.quantize.quant_state_dims[0] * self.quantize.quant_state_dims[1]: + raise ValueError( + f"Expected `image_tokens` to have shape `(batch_size, {self.quantize.quant_state_dims[0] * self.quantize.quant_state_dims[1]})`, " + f"but got shape `{image_tokens.shape}`." + ) + codebook_entry = self.quantize.get_codebook_entry(image_tokens) + hidden_states = self.post_quant_conv(codebook_entry) + pixel_values = self.decoder(hidden_states) + return pixel_values + + +class ChameleonImageVocabularyMapping: + """ + A class for mapping discrete image tokens from VQGAN to BPE tokens. + """ + + def __init__( + self, + vocab_map: Dict[str, int], + image_token_id: int, + boi_token_id: int, + eoi_token_id: int, + ): + self.vocab_map = vocab_map + self.image_token_id = image_token_id + self.boi_token_id = boi_token_id + self.eoi_token_id = eoi_token_id + + @cached_property + def val2name(self): + return {v: k for k, v in self.vocab_map.items()} + + @cached_property + def image_token_ids(self): + return sorted([val for name, val in self.vocab_map.items() if name.startswith("IMGIMG")]) + + @cached_property + def bpe2img(self): + img_tkn_chr_mapping = {chr(ord("A") + i): str(i) for i in range(10)} + + def remap(old_name: str) -> str: + return "".join(img_tkn_chr_mapping.get(c, c) for c in old_name[len("IMGIMG") : -1]) + + return {tok: int(remap(self.val2name[tok])) for tok in self.image_token_ids} + + @cached_property + def img2bpe(self): + return {v: k for k, v in self.bpe2img.items()} + + @cached_property + def bpe2img_mapping_tensor(self): + mapping = torch.zeros(max(self.bpe2img.keys()) + 1, dtype=torch.int) + for k, v in self.bpe2img.items(): + mapping[k] = v + return mapping + + @cached_property + def img2bpe_mapping_tensor(self): + mapping = torch.zeros(max(self.img2bpe.keys()) + 1, dtype=torch.int) + for k, v in self.img2bpe.items(): + mapping[k] = v + return mapping + + +CHAMELEON_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`ChameleonConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare chameleon Model outputting raw hidden-states without any specific head on top.", + CHAMELEON_START_DOCSTRING, +) +class ChameleonPreTrainedModel(PreTrainedModel): + config_class = ChameleonConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["ChameleonDecoderLayer", "ChameleonSwinDecoderLayer", "ChameleonVQVAE"] + _skip_keys_device_placement = ["past_key_values", "causal_mask"] + _supports_flash_attn_2 = True + _supports_sdpa = True + _supports_quantized_cache = True + _supports_cache_class = True + _supports_static_cache = True + _supports_param_buffer_assignment = False + + def _init_weights(self, module): + std = self.config.initializer_range + if isinstance(module, ChameleonVQVAE): + module.apply(module._init_weights) + elif isinstance(module, (nn.Linear, nn.Conv2d)): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + +CHAMELEON_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)): + The tensors corresponding to the input images. Pixel values can be obtained using + [`AutoImageProcessor`]. See [`ChameleonImageProcessor.__call__`] for details. + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.n_positions - 1]`. + + [What are position IDs?](../glossary#position-ids) + past_key_values (`Cache`, *optional*): + Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` + returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. + + Should always be a [`~cache_utils.Cache`] instance and the model will output the same cache instance. + If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't + have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` + of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): + Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`, + this tensor is not affected by padding. It is used to update the cache in the correct position and to infer + the complete sequence length. +""" + + +@add_start_docstrings( + "The bare chameleon Model outputting raw hidden-states without any specific head on top.", + CHAMELEON_START_DOCSTRING, +) +class ChameleonModel(ChameleonPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ChameleonDecoderLayer`] + + Args: + config: ChameleonConfig + """ + + def __init__(self, config: ChameleonConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.vocabulary_mapping = ChameleonImageVocabularyMapping( + config.vocabulary_map, + config.image_token_id, + config.boi_token_id, + config.eoi_token_id, + ) + self.register_buffer( + "img2bpe_mapping_tensor", + self.vocabulary_mapping.img2bpe_mapping_tensor, + persistent=False, + ) + self.register_buffer( + "bpe2img_mapping_tensor", + self.vocabulary_mapping.bpe2img_mapping_tensor, + persistent=False, + ) + decoder_layer = ChameleonDecoderLayer if not self.config.swin_norm else ChameleonSwinDecoderLayer + self.layers = nn.ModuleList( + [decoder_layer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + ) + self.norm = ChameleonRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.vqmodel = ChameleonVQVAE(config.vq_config) + self.gradient_checkpointing = False + + # Initialize weights and apply final processing + self.post_init() + + @property + def image_seq_length(self) -> int: + return self.vqmodel.quantize.quant_state_dims[0] * self.vqmodel.quantize.quant_state_dims[1] + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + def convert_img2bpe_tokens(self, img_batch: torch.LongTensor) -> torch.LongTensor: + """ + Converts image tokens generated by the VQVAE model into BPE tokens compatible with the text tokenizer. + + Notes: + - It is important to move the `img_batch` tensor to the same device as the `img2bpe_mapping_tensor` buffer + as Accelerate may move the buffer to a different device when loading the model with `device_map="auto"`. + - Accelerate up to version 0.33.0 (and also maybe later versions) has a bug where buffers in downstream modules + may be ignored when inferring the proper device map. See: https://github.com/huggingface/accelerate/blob/79ca85c27df292dbf64cfa2bcc12dbb62fbe9267/src/accelerate/utils/modeling.py#L1273 + This causes the `img2bpe_mapping_tensor` buffer to be placed on the CPU by default, which may cause a performance + loss--especially with prompts that contain many images. No action needs to be done when this bug is fixed. + + Args: + img_batch (`torch.Tensor` of shape `(batch_size, image_seq_length)`): + The image tokens generated by the VQVAE model. + + Returns: + `torch.Tensor` of shape `(batch_size, image_seq_length)`: + The image tokens converted to be compatible with the text tokenizer's BPE tokens. + """ + device = img_batch.device + img_tokens = self.img2bpe_mapping_tensor[img_batch.to(self.img2bpe_mapping_tensor.device)] + return img_tokens.to(device) + + def convert_bpe2img_tokens(self, bpe_batch: torch.LongTensor) -> torch.LongTensor: + """ + Converts image tokens that are compatible with the text tokenizer into image tokens compatible with the VQVAE + model. + + Notes: + - It is important to move the `img_batch` tensor to the same device as the `img2bpe_mapping_tensor` buffer + as Accelerate may move the buffer to a different device when loading the model with `device_map="auto"`. + - Accelerate up to version 0.33.0 (and also maybe later versions) has a bug where buffers in downstream modules + may be ignored when inferring the proper device map. See: https://github.com/huggingface/accelerate/blob/79ca85c27df292dbf64cfa2bcc12dbb62fbe9267/src/accelerate/utils/modeling.py#L1273 + This causes the `img2bpe_mapping_tensor` buffer to be placed on the CPU by default, which may cause a performance + loss--especially when generating interleaved text & images. No action needs to be done when this bug is fixed. + + Args: + bpe_batch (`torch.Tensor` of shape `(batch_size, image_seq_length)`): + The image tokens compatible with the text tokenizer. + + Returns: + `torch.Tensor` of shape `(batch_size, image_seq_length)`: + The image tokens converted to be compatible with the VQVAE model. + """ + device = bpe_batch.device + img_tokens = self.bpe2img_mapping_tensor[bpe_batch.to(self.bpe2img_mapping_tensor.device)] + return img_tokens.to(device) + + def get_image_tokens(self, pixel_values: torch.FloatTensor): + """ + Tokenizes images into discrete tokens with VQGAN module. Converts + obtained image tokens into BPE tokens and wraps with "boi" and "eoi" + special tokens. + + Args: + pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)): + The tensors corresponding to the input images. + + Returns: + `torch.Tensor` of shape `(batch_size, image_seq_length)`: + The BPE tokens generated by the model. + """ + _, _, image_toks = self.vqmodel.encode(pixel_values) + return self.convert_img2bpe_tokens(image_toks) + + def decode_image_tokens(self, bpe_tokens: torch.LongTensor) -> torch.LongTensor: + """ + Converts BPE tokens generated by the model into discrete image tokens + compatible with the VQGAN module, then decodes them into pixel values. + + Args: + bpe_tokens (`torch.tensor` of shape `(batch, image_seq_length)`): + The BPE tokens generated by the model. + + Returns: + `torch.Tensor` of shape `(batch, num_channels, 512, 512)`: + """ + if bpe_tokens.shape[1] != self.image_seq_length: + raise ValueError(f"All batches must have {self.image_seq_length} tokens.") + image_tensor = self.convert_bpe2img_tokens(bpe_tokens) + return self.vqmodel.decode(image_tensor) + + @add_start_docstrings_to_model_forward(CHAMELEON_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_EXPECTED_OUTPUT_SHAPE, + ) + def forward( + self, + input_ids: torch.LongTensor = None, + pixel_values: torch.FloatTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if self.gradient_checkpointing and self.training and use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." + ) + use_cache = False + + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError( + "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one" + ) + + if pixel_values is not None and inputs_embeds is not None: + raise ValueError( + "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one" + ) + + if pixel_values is not None: + image_tokens = self.get_image_tokens(pixel_values) + special_image_mask = input_ids == self.vocabulary_mapping.image_token_id + image_tokens = image_tokens.to(input_ids.device, input_ids.dtype) + input_ids = input_ids.masked_scatter(special_image_mask, image_tokens) + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + if cache_position is None: + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + cache_position = torch.arange( + past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device + ) + + if position_ids is None: + position_ids = cache_position.unsqueeze(0) + + causal_mask = self._update_causal_mask( + attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions + ) + + # embed positions + hidden_states = inputs_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = None + + for decoder_layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + decoder_layer.__call__, + hidden_states, + causal_mask, + position_ids, + past_key_values, + output_attentions, + use_cache, + cache_position, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=causal_mask, + position_ids=position_ids, + past_key_value=past_key_values, + output_attentions=output_attentions, + use_cache=use_cache, + cache_position=cache_position, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache = layer_outputs[2 if output_attentions else 1] + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = None + if use_cache: + next_cache = next_decoder_cache + + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask + def _update_causal_mask( + self, + attention_mask: torch.Tensor, + input_tensor: torch.Tensor, + cache_position: torch.Tensor, + past_key_values: Cache, + output_attentions: bool, + ): + # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static + # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes. + # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using + # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114 + + if self.config._attn_implementation == "flash_attention_2": + if attention_mask is not None and 0.0 in attention_mask: + return attention_mask + return None + + # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in + # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail + # to infer the attention mask. + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + using_static_cache = isinstance(past_key_values, StaticCache) + + # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward + if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions: + if AttentionMaskConverter._ignore_causal_mask_sdpa( + attention_mask, + inputs_embeds=input_tensor, + past_key_values_length=past_seen_tokens, + is_training=self.training, + ): + return None + + dtype, device = input_tensor.dtype, input_tensor.device + min_dtype = torch.finfo(dtype).min + sequence_length = input_tensor.shape[1] + if using_static_cache: + target_length = past_key_values.get_max_length() + else: + target_length = ( + attention_mask.shape[-1] + if isinstance(attention_mask, torch.Tensor) + else past_seen_tokens + sequence_length + 1 + ) + + # In case the provided `attention` mask is 2D, we generate a causal mask here (4D). + causal_mask = _prepare_4d_causal_attention_mask_with_cache_position( + attention_mask, + sequence_length=sequence_length, + target_length=target_length, + dtype=dtype, + device=device, + min_dtype=min_dtype, + cache_position=cache_position, + batch_size=input_tensor.shape[0], + ) + + if ( + self.config._attn_implementation == "sdpa" + and attention_mask is not None + and attention_mask.device.type == "cuda" + and not output_attentions + ): + # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when + # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. + # Details: https://github.com/pytorch/pytorch/issues/110213 + causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) + + return causal_mask + + +@add_start_docstrings( + "Chameleon Model with a head on top used for outputting logits for next token prediction.", + CHAMELEON_START_DOCSTRING, +) +class ChameleonForConditionalGeneration(ChameleonPreTrainedModel): + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config: ChameleonConfig): + super().__init__(config) + self.model = ChameleonModel(config) + self.vocabulary_mapping = self.model.vocabulary_mapping + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + def _prepare_generation_config( + self, + generation_config: Optional[GenerationConfig] = None, + multimodal_generation_mode: Optional[ + Literal["text-only", "image-only", "interleaved-text-image", "unrestricted"] + ] = None, + **kwargs, + ): + if ( + multimodal_generation_mode == "image-only" + and kwargs.get("max_length") is None + and kwargs.get("max_new_tokens") is None + and ( + generation_config is None + or (generation_config.max_length is None and generation_config.max_new_tokens is None) + ) + ): + kwargs["max_new_tokens"] = self.model.image_seq_length + 2 + generation_config, model_kwargs = super()._prepare_generation_config(generation_config, **kwargs) + if multimodal_generation_mode is not None: + generation_config.multimodal_generation_mode = multimodal_generation_mode + if ( + not hasattr(generation_config, "multimodal_generation_mode") + or generation_config.multimodal_generation_mode is None + ): + generation_config.multimodal_generation_mode = "text-only" + return generation_config, model_kwargs + + @add_start_docstrings_to_model_forward(CHAMELEON_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + pixel_values: torch.FloatTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + Returns: + + Example: + + ```python + >>> from transformers import ChameleonProcessor, ChameleonForConditionalGeneration + >>> import torch + >>> import requests + >>> from PIL import Image + + >>> model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", torch_dtype=torch.bfloat16) + >>> processor = ChameleonProcessor.from_pretrained("facebook/chameleon-7b") + + >>> prompt = "I used to know a lot about constellations when I was younger, but as I grew older, I forgot most of what I knew. These are the only two constellations that I really remember now.I would like for you to tell me about 3 more constellations and give me a little bit of history about the constellation." + >>> image = Image.open(requests.get("https://nineplanets.org/wp-content/uploads/2020/12/the-big-dipper-1.jpg", stream=True).raw) + >>> image_2 = Image.open(requests.get("https://www.kxan.com/wp-content/uploads/sites/40/2020/10/ORION.jpg", stream=True).raw) + + >>> inputs = processor(prompt, images=[image, image_2], return_tensors="pt").to(model.device, torch.bfloat16) + + >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False) + >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + ```""" + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model( + input_ids=input_ids, + pixel_values=pixel_values, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + cache_position=cache_position, + ) + + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + logits = logits.float() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + shift_logits = shift_logits.view(-1, self.config.vocab_size) + shift_labels = shift_labels.view(-1) + # Enable model parallelism + shift_labels = shift_labels.to(shift_logits.device) + loss = loss_fct(shift_logits, shift_labels) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, + input_ids, + pixel_values=None, + past_key_values=None, + attention_mask=None, + inputs_embeds=None, + cache_position=None, + position_ids=None, + use_cache=True, + **kwargs, + ): + # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens + # Exception 1: when passing input_embeds, input_ids may be missing entries + # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here + if past_key_values is not None: + if inputs_embeds is not None: # Exception 1 + input_ids = input_ids[:, -cache_position.shape[0] :] + elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2) + input_ids = input_ids[:, cache_position] + + if attention_mask is not None and position_ids is None: + # create position_ids on the fly for batch generation + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + if past_key_values: + position_ids = position_ids[:, -input_ids.shape[1] :] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and cache_position[0] == 0: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases + + if cache_position[0] == 0: + # If we're in cached decoding stage, pixel values should be `None` because input ids do not contain special image token anymore + # Otherwise we need pixel values to be passed to model + model_inputs["pixel_values"] = pixel_values + + model_inputs.update( + { + "position_ids": position_ids, + "cache_position": cache_position, + "past_key_values": past_key_values, + "use_cache": use_cache, + "attention_mask": attention_mask, + } + ) + return model_inputs + + def decode_image_tokens(self, bpe_tokens: torch.Tensor): + """ + Converts BPE tokens generated by the model into discrete image tokens + compatible with the VQGAN module, then decodes them into pixel values. + + Args: + bpe_tokens (`torch.tensor` of shape `(batch, image_seq_length)`): + The BPE tokens generated by the model. + + Returns: + `torch.Tensor` of shape `(batch, num_channels, 512, 512)`: + """ + return self.model.decode_image_tokens(bpe_tokens) diff --git a/sjdtree/assets/.DS_Store b/sjdtree/assets/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..54110604828fbfdf604b90c4f88ce15f3991d0f0 Binary files /dev/null and b/sjdtree/assets/.DS_Store differ diff --git a/sjdtree/data/configs/anole_config.json b/sjdtree/data/configs/anole_config.json new file mode 100644 index 0000000000000000000000000000000000000000..c945ad1e306a0ecac6f696eef42c363f1c8eada8 --- /dev/null +++ b/sjdtree/data/configs/anole_config.json @@ -0,0 +1,48 @@ +{ + "architectures": [ + "ChameleonForConditionalGeneration" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "boi_token_id": 8197, + "bos_token_id": 1, + "eoi_token_id": 8196, + "eos_token_id": 2, + "hidden_act": "silu", + "hidden_size": 4096, + "image_token_id": 8711, + "initializer_range": 0.02, + "intermediate_size": 11008, + "max_position_embeddings": 4096, + "mlp_bias": false, + "model_parallel_size": 1, + "model_type": "chameleon", + "num_attention_heads": 32, + "num_hidden_layers": 1, + "num_key_value_heads": 32, + "rms_norm_eps": 1e-05, + "rope_scaling": null, + "rope_theta": 10000.0, + "swin_norm": false, + "tie_word_embeddings": false, + "torch_dtype": "bfloat16", + "transformers_version": "4.43.0.dev0", + "use_cache": true, + "vocab_size": 65536, + "vq_config": { + "attn_resolutions": [], + "ch": 128, + "ch_mult": [ + 1, + 1, + 2, + 2, + 4 + ], + "double_z": false, + "model_type": "chameleon_vqgan", + "n_embed": 8192, + "out_ch": 3, + "z_channels": 256 + } +} diff --git a/sjdtree/data/configs/llamagen_t2i2_config.json b/sjdtree/data/configs/llamagen_t2i2_config.json new file mode 100644 index 0000000000000000000000000000000000000000..8485f743b99a3f3f9ae483f76e6a0e69ecc5dc05 --- /dev/null +++ b/sjdtree/data/configs/llamagen_t2i2_config.json @@ -0,0 +1,27 @@ +{ + "architectures": [ + "LlamaForCausalLM" + ], + "bos_token_id": 1, + "eos_token_id": 2, + "hidden_act": "silu", + "hidden_size": 1280, + "caption_dim": 2048, + "class_dropout_p": 0.0, + "initializer_range": 0.02, + "intermediate_size": 3584, + "max_position_embeddings": 2048, + "model_type": "llama", + "num_attention_heads": 20, + "num_hidden_layers": 1, + "num_key_value_heads": 20, + "pretraining_tp": 1, + "rms_norm_eps": 1e-06, + "rope_scaling": null, + "tie_word_embeddings": false, + "torch_dtype": "float16", + "transformers_version": "4.32.0.dev0", + "use_cache": true, + "vocab_size": 16384, + "input_type": "t2i2" +} diff --git a/sjdtree/data/configs/llamagen_t2i_config.json b/sjdtree/data/configs/llamagen_t2i_config.json new file mode 100644 index 0000000000000000000000000000000000000000..dc2c30eec661f5a5028b11e1e86b85c05c6b11f7 --- /dev/null +++ b/sjdtree/data/configs/llamagen_t2i_config.json @@ -0,0 +1,27 @@ +{ + "architectures": [ + "LlamaForCausalLM" + ], + "bos_token_id": 1, + "eos_token_id": 2, + "hidden_act": "silu", + "hidden_size": 1280, + "caption_dim": 2048, + "class_dropout_p": 0.0, + "initializer_range": 0.02, + "intermediate_size": 3584, + "max_position_embeddings": 2048, + "model_type": "llama", + "num_attention_heads": 20, + "num_hidden_layers": 1, + "num_key_value_heads": 20, + "pretraining_tp": 1, + "rms_norm_eps": 1e-06, + "rope_scaling": null, + "tie_word_embeddings": false, + "torch_dtype": "float16", + "transformers_version": "4.32.0.dev0", + "use_cache": true, + "vocab_size": 16384, + "input_type": "t2i" +} diff --git a/sjdtree/data/configs/lumina_mgpt_config.json b/sjdtree/data/configs/lumina_mgpt_config.json new file mode 100644 index 0000000000000000000000000000000000000000..951d25e2895769ed3bca9f09cffe62618b0f67ef --- /dev/null +++ b/sjdtree/data/configs/lumina_mgpt_config.json @@ -0,0 +1,49 @@ +{ + "architectures": [ + "ChameleonForConditionalGeneration" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "dropout": 0.05, + "boi_token_id": 8197, + "bos_token_id": 1, + "eoi_token_id": 8196, + "eos_token_id": 2, + "hidden_act": "silu", + "hidden_size": 4096, + "image_token_id": 8711, + "initializer_range": 0.02, + "intermediate_size": 11008, + "max_position_embeddings": 4096, + "mlp_bias": false, + "model_parallel_size": 1, + "model_type": "chameleon", + "num_attention_heads": 32, + "num_hidden_layers": 1, + "num_key_value_heads": 32, + "rms_norm_eps": 1e-05, + "rope_scaling": null, + "rope_theta": 10000.0, + "swin_norm": false, + "tie_word_embeddings": false, + "torch_dtype": "bfloat16", + "transformers_version": "4.43.3", + "use_cache": true, + "vocab_size": 65536, + "vq_config": { + "attn_resolutions": [], + "ch": 128, + "ch_mult": [ + 1, + 1, + 2, + 2, + 4 + ], + "double_z": false, + "model_type": "chameleon_vqgan", + "n_embed": 8192, + "out_ch": 3, + "z_channels": 256 + } + } \ No newline at end of file diff --git a/sjdtree/data/prompts/PartiPrompts.tsv b/sjdtree/data/prompts/PartiPrompts.tsv new file mode 100644 index 0000000000000000000000000000000000000000..f96e7125a02e48976736179a667b080ba81539fb --- /dev/null +++ b/sjdtree/data/prompts/PartiPrompts.tsv @@ -0,0 +1,1633 @@ +Prompt Category Challenge Note +bond Abstract Basic Biology-inspired concepts with multiple meanings +element Abstract Basic Biology-inspired concepts with multiple meanings +molecule Abstract Basic Biology-inspired concepts with multiple meanings +life Abstract Basic Biology-inspired concepts with multiple meanings +protein Abstract Basic Biology-inspired concepts with multiple meanings +yin-yang Abstract Basic Related to five elements +wood Abstract Basic Related to five elements +metal Abstract Basic Related to five elements +space Abstract Basic Related to five elements +air Abstract Basic Related to five elements +fire Abstract Basic Related to five elements +water Abstract Basic Related to five elements +earth Abstract Basic Related to five elements +force Abstract Basic Physics concepts +motion Abstract Basic Physics concepts +inertia Abstract Basic Physics concepts +energy Abstract Basic Physics concepts +black hole Abstract Basic Physics concepts +gravity Abstract Basic Physics concepts +peace Abstract Basic +fairness Abstract Basic +gender Abstract Basic +intelligence Abstract Basic +bias Abstract Basic +hate Abstract Basic +anger Abstract Basic +emotion Abstract Basic +feeling Abstract Basic +love Abstract Basic +artificial intelligence Abstract Basic +meaning of life Abstract Basic +42 Abstract Basic Simple numbers but challenging +0 Abstract Basic Simple numbers but challenging +infinity Abstract Basic Math concepts +imaginary numbers Abstract Basic Math concepts +Fibonacci number Abstract Basic Math concepts +golden ratio Abstract Basic Math concepts +an F1 Vehicles Basic +parallel lines Illustrations Basic Math concepts +concentric circles Illustrations Basic Math concepts +concurrent lines Illustrations Basic Math concepts +congruent triangles Illustrations Basic Math concepts +a hot air balloon Vehicles Basic +The Starry Night Arts Basic +300 Abstract Basic Simple numbers but challenging +101 Abstract Basic Simple numbers but challenging +U.S. 101 World Knowledge Basic Simple numbers but challenging +commonsense Abstract Basic +happiness Abstract Basic +hope Abstract Basic +insight Abstract Basic +inspiration Abstract Basic +derision Abstract Basic +Salvador Dalí People Basic +a shiba inu Animals Basic +a handpalm People Basic +an espresso machine Artifacts Basic +a propaganda poster Artifacts Basic +The Oriental Pearl World Knowledge Basic CogView +Ha Long Bay World Knowledge Basic +A Vietnam map World Knowledge Basic +A bowl of Pho Food & Beverage Basic +a snail Animals Basic +brain coral Animals Basic +a walnut Produce & Plants Basic +a capybara Animals Basic +a baby penguin Animals Basic +a cup of boba Food & Beverage Basic +a photo of san francisco's golden gate bridge World Knowledge Basic DALL-E +A picture of some food in the plate Food & Beverage Basic VQ-Diffusion +a chair Artifacts Basic +the Empire State Building World Knowledge Basic +the Sydney Opera House World Knowledge Basic +a hedgehog Animals Basic +a corgi Animals Basic +a robot Artifacts Basic +robots Artifacts Basic +a fall landscape Outdoor Scenes Basic +a sunset Outdoor Scenes Basic +a boat Vehicles Basic +a fox Animals Basic +a red cube Illustrations Basic +a panda Animals Basic +a space elevator Artifacts Basic GLIDE +a city Outdoor Scenes Basic +a fog Outdoor Scenes Basic +a clock Artifacts Basic +a phone Artifacts Basic +food Food & Beverage Basic +a store front Outdoor Scenes Basic +an armchair Artifacts Basic +a teapot Artifacts Basic +an illustration of a teapot Artifacts Basic DALL-E +a tiger Animals Basic +a bench Artifacts Basic +an orange Produce & Plants Basic +a laptop Artifacts Basic +an owl Animals Basic +a train Vehicles Basic +a cow Animals Basic +a submarine Vehicles Basic +a whale Animals Basic +a t-shirt Artifacts Basic +a bowl Artifacts Basic +a flag Artifacts Basic +a cat Animals Basic +a towel Artifacts Basic +a wall Artifacts Basic +a car Vehicles Basic +a giraffe Animals Basic +an eagle Animals Basic +a kangaroo Animals Basic +a canal Outdoor Scenes Basic +the grand canyon World Knowledge Basic +lily pads Produce & Plants Basic +a street Outdoor Scenes Basic +a house Outdoor Scenes Basic +a fish Animals Basic +a city intersection Outdoor Scenes Basic +a circle Illustrations Basic +a red circle Illustrations Basic +a box Illustrations Basic +a yellow box Illustrations Basic +a red box Illustrations Basic +a sphere Illustrations Basic +a red sphere Illustrations Basic +a large blue box Illustrations Basic +a blue metallic sphere Illustrations Basic +a horse Animals Basic +a pumpkin Produce & Plants Basic +a sword Artifacts Basic +a statue Artifacts Basic +a logo Illustrations Basic +a circular logo Illustrations Basic +a coffee mug Artifacts Basic +a pig Animals Basic +a squirrel Animals Basic +a hammer Artifacts Basic +a screwdriver Artifacts Basic +a handsaw Artifacts Basic +a power drill Artifacts Basic +a cocktail Food & Beverage Basic +a margarita Food & Beverage Basic +an avocado Produce & Plants Basic +a kitchen Indoor Scenes Basic +an iPhone case Artifacts Basic +a coffee maker Artifacts Basic +a banana Produce & Plants Basic +a violin Artifacts Basic +a room Indoor Scenes Basic +a mountain Outdoor Scenes Basic +a bird Animals Basic +a TV Artifacts Basic +a Christmas tree Artifacts Basic +The Statue of Liberty World Knowledge Basic +the Eiffel Tower World Knowledge Basic +a zebra Animals Basic +the city of London World Knowledge Basic +a koi fish Animals Basic +a pineapple Produce & Plants Basic +a toaster Artifacts Basic +a sign Artifacts Basic +a red lego block Artifacts Basic +teacup Artifacts Basic +chair Artifacts Basic +waterfall Outdoor Scenes Basic +a pirate ship Vehicles Basic +a dragon Animals Basic +a present Artifacts Basic +a bottle Artifacts Basic +a book cover Illustrations Basic +a sweatshirt Artifacts Basic +matching socks Artifacts Basic +cash Artifacts Basic +a wood cabin Indoor Scenes Basic +a clock tower Artifacts Basic +a chimpanzee Animals Basic +a hat Artifacts Basic +sneakers Artifacts Basic +a roast turkey Food & Beverage Basic +a turkey Animals Basic +a plate Artifacts Basic +a ladder Artifacts Basic +a Tyrannosaurus Rex Animals Basic +a Stegasaurus Animals Basic +a Triceratops Animals Basic +a Styracosaurus Animals Basic +a Diplodocus Animals Basic +a yellow sticky note Artifacts Basic +a ball Artifacts Basic +red balls Artifacts Basic +an ostrich Animals Basic +a stone path Outdoor Scenes Basic +a wooden deck Outdoor Scenes Basic +an F1 race car Vehicles Basic +a taxi Vehicles Basic +a road Outdoor Scenes Basic +a volcano Outdoor Scenes Basic +a large open book Artifacts Basic +a living room Indoor Scenes Basic +an elephant Animals Basic +a tree Produce & Plants Basic +a dolphin Animals Basic +a rowboat Vehicles Basic +a crown Artifacts Basic +a pick-up truck Vehicles Basic +a key Artifacts Basic +a goat Animals Basic +a chest Artifacts Basic +a coffee table Artifacts Basic +toy cars Artifacts Basic +a bookshelf Artifacts Basic +the moon Outdoor Scenes Basic +the Earth Outdoor Scenes Basic +the International Space Station World Knowledge Basic +the planet Jupiter Outdoor Scenes Basic +a tornado Outdoor Scenes Basic +a tidal wave Outdoor Scenes Basic +a laptop screen Artifacts Basic +an airplane Vehicles Basic +a butterfly Animals Basic +a lizard Animals Basic +a turtle Animals Basic +an octopus Animals Basic +a book Artifacts Basic +a moose Animals Basic +a kachina doll World Knowledge Basic +a doorknocker Artifacts Basic +a rabbit Animals Basic +orange juice Food & Beverage Basic +a green pepper Food & Beverage Basic +beer Food & Beverage Basic +Times Square World Knowledge Basic +the Great Wall World Knowledge Basic +the Kremlin World Knowledge Basic +a pickup truck Vehicles Basic +a shoe Artifacts Basic +a plant Produce & Plants Basic +a flower Produce & Plants Basic +a pair of headphones Artifacts Basic +a chemtrail Outdoor Scenes Basic +a tennis court Outdoor Scenes Basic +a ceiling fan Indoor Scenes Basic +a fire hydrant Artifacts Basic +a wooden post Artifacts Basic +a trash bin Artifacts Basic +a piano Artifacts Basic +a musical note Illustrations Basic +a harp Artifacts Basic +a tuba Artifacts Basic +The Alamo World Knowledge Basic +a windmill Outdoor Scenes Basic +the geyser Old Faithful World Knowledge Basic +a motorcycle Vehicles Basic +a painting of black and white Illustrations Basic +the Great Pyramid World Knowledge Basic +the Parthenon World Knowledge Basic +the Millennium Wheel World Knowledge Basic +a marina Outdoor Scenes Basic +a team People Basic +a child People Basic +a man People Basic +a woman People Basic +a girl People Basic +a person People Basic +a boy People Basic +a boy and a tiger People Basic +a family People Basic +a father and a son People Basic +a portrait of an old man People Basic +a portrait of young girl People Basic +a scientist People Basic +A dignified beaver wearing glasses, a vest, and colorful neck tie. He stands next to a tall stack of books in a library. Animals Complex +A solitary figure shrouded in mists peers up from the cobble stone street at the imposing and dark gothic buildings surrounding it. an old-fashioned lamp shines nearby. oil painting. Arts Complex +A punk rock squirrel in a studded leather jacket shouting into a microphone while standing on a stump and holding a beer on dark stage. Animals Complex +Horses pulling a carriage on the moon's surface, with the Statue of Liberty and Great Pyramid in the background. The Planet Earth can be seen in the sky. World Knowledge Complex +A robot painted as graffiti on a brick wall. The words "Fly an airplane" are written on the wall. A sidewalk is in front of the wall, and grass is growing out of cracks in the concrete. Outdoor Scenes Complex +A warrior wombat holding a sword and shield in a fighting stance. The wombat stands in front of the Arc de Triomphe on a day shrouded mist with the sun high in the sky. World Knowledge Complex +A set of 2x2 emoji icons with happy, angry, surprised and sobbing faces. The emoji icons look like dogs. All of the dogs are wearing blue turtlenecks. Illustrations Complex +A set of 2x2 emoji icons with happy, angry, surprised and sobbing faces. The emoji icons look like macaroons. All of the macaroons are wearing cowboy hats. Illustrations Complex +A set of 2x2 emoji icons with happy, angry, surprised and sobbing faces. The emoji icons look like colorful macarons. All of the macarons are wearing cowboy hats. Illustrations Complex +A set of 2x2 emoji icons with happy, angry, surprised and sobbing faces. The emoji icons look like pandas. All of the pandas are wearing colorful sunglasses. Illustrations Complex +A set of 2x2 emoji icons with happy, angry, surprised and sobbing faces. The emoji icons look like pigs. All of the pigs are wearing crowns. Illustrations Complex +A richly textured oil painting of a young badger delicately sniffing a yellow rose next to a tree trunk. A small waterfall can be seen in the background. Arts Complex +A portrait of a metal statue of a pharaoh wearing steampunk glasses and a leather jacket over a white t-shirt that has a drawing of a space shuttle on it. World Knowledge Complex +A photograph of the inside of a subway train. There are frogs sitting on the seats. One of them is reading a newspaper. The window shows the river in the background. Vehicles Complex +A photograph of the inside of a subway train. There are lobsters sitting on the seats. One of them is reading a newspaper. The window shows the ocean in the background. Vehicles Complex +A photograph of the inside of a subway train. There are raccoons sitting on the seats. One of them is reading a newspaper. The window shows the city in the background. Vehicles Complex +A photograph of the inside of a subway train. There are red pandas sitting on the seats. One of them is reading a newspaper. The window shows the jungle in the background. Vehicles Complex +A raccoon wearing formal clothes, wearing a tophat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of abstract cubism. Arts Complex +A raccoon wearing formal clothes, wearing a tophat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of Egyptian tomp hieroglyphics. Arts Complex +A raccoon wearing formal clothes, wearing a tophat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of Hokusai. Arts Complex +A raccoon wearing formal clothes, wearing a tophat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of Madhubani art. Arts Complex +A raccoon wearing formal clothes, wearing a tophat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of pixel art. Arts Complex +A raccoon wearing formal clothes, wearing a tophat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of pointilism. Arts Complex +A raccoon wearing formal clothes, wearing a tophat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of Rembrandt. Arts Complex +A raccoon wearing formal clothes, wearing a tophat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of traditional Chinese painting. Arts Complex +A raccoon wearing formal clothes, wearing a tophat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of Vincent Van Gogh. Arts Complex +A raccoon wearing formal clothes, wearing a top hat and holding a cane. The raccoon is holding a garbage bag. Oil painting in the style of Vincent Van Gogh. Arts Complex +a statue of Abraham Lincoln wearing an opaque and shiny astronaut's helmet. The statue sits on the moon, with the planet Earth in the sky. World Knowledge Complex +a portrait of a statue of the Egyptian god Anubis wearing aviator goggles, white t-shirt and leather jacket. The city of Los Angeles is in the background. World Knowledge Complex +A smiling sloth wearing a leather jacket, a cowboy hat, a kilt and a bowtie. The sloth is holding a quarterstaff and a big book. A shiny VW van with a cityscape painted on it and parked on grass. World Knowledge Complex +A smiling sloth wearing a leather jacket, a cowboy hat, a kilt and a bowtie. The sloth is holding a quarterstaff and a big book. The sloth stands a few feet in front of a shiny VW van. The van has a cityscape painted on it and parked on grass. World Knowledge Complex +A DSLR photo of a shiny VW van that has a cityscape painted on it. A smiling sloth stands on grass in front of the van and is wearing a leather jacket, a cowboy hat, a kilt and a bowtie. The sloth is holding a quarterstaff and a big book. World Knowledge Complex +a poodle wearing a baseball cap holding a dictionary in hand and writing bonez on a chalkboard Animals Complex +a portrait of a statue of anubis with a crown and wearing a yellow t-shirt that has a space shuttle drawn on it World Knowledge Complex +an oil surrealist painting of a dreamworld on a seashore where clocks and watches appear to be inexplicably limp and melting in the desolate landscape. a table on the left, with a golden watch swarmed by ants. a strange fleshy creature in the center of the painting Arts Complex Description of The Persistence of Memory +a portrait of a statue of the Egyptian god Anubis wearing aviator goggles, white t-shirt and leather jacket. A full moon over the city of Los Angeles is in the background at night. World Knowledge Complex +a portrait of a statue of the Egyptian god Anubis wearing aviator goggles, white t-shirt and leather jacket. the skyline of Los Angeles at night can be seen in the background. World Knowledge Complex +a portrait of a statue of the Egyptian god Anubis wearing aviator goggles, white t-shirt and leather jacket, flying over the city of Mars. World Knowledge Complex +A photo of the Space Shuttle Endeavor painted yellow and flying over the Earth. The continent of South America is visible. World Knowledge Complex +A close-up photo of a wombat wearing a red backpack and raising both arms in the air. Mount Rushmore is in the background. World Knowledge Complex +A penguin wearing aviator goggles and flying confidently next to a bemused eagle. Animals Complex +A donkey is playing tug-of-war against an octopus. The donkey holds the rope in its mouth. A cat is jumping over the rope. Animals Complex +A wall in a royal castle. There are two paintings on the wall. The one on the left a detailed oil painting of the royal raccoon king. The one on the right a detailed oil painting of the royal raccoon queen. A cute dog looking at the two paintings, holding a sign saying 'plz conserve' Indoor Scenes Complex +A single beam of light enter the room from the ceiling. The beam of light is illuminating an easel. On the easel there is a Rembrandt painting of a raccoon Indoor Scenes Complex +The Millennium Wheel next to the Statue of Liberty. The Sagrada Familia church is also visible. World Knowledge Complex +A train ride in the monsoon rain in Kerala. With a Koala bear wearing a hat looking out of the window. There is a lot of coconut trees out of the window. World Knowledge Complex +A photograph of a portrait of a statue of a pharaoh wearing steampunk glasses, white t-shirt and leather jacket. World Knowledge Complex +An oil painting of two rabbits in the style of American Gothic, wearing the same clothes as in the original. Arts Complex +a blue cow is standing next to a tree with red leaves and yellow fruit. the cow is standing in a field with white flowers. impressionistic painting Animals Complex +A wombat sits in a yellow beach chair, while sipping a martini that is on his laptop keyboard. The wombat is wearing a white panama hat and a floral Hawaiian shirt. Out-of-focus palm trees in the background. Animals Complex +A high-contrast photo of a panda riding a horse. The panda is wearing a wizard hat and is reading a book. The horse is standing on a street against a gray concrete wall. Colorful flowers and the word "PEACE" are painted on the wall. Green grass grows from cracks in the street. Animals Complex +The buildings of downtown Manhattan situated at below Mount Everest. The Great Pyramid is in the foreground. World Knowledge Complex +Anime illustration of the Great Pyramid sitting next to the Parthenon under a blue night sky of roiling energy, exploding yellow stars, and chromatic blue swirls World Knowledge Complex +An anime illustration of Sydney Opera House sitting next to Eiffel tower, under a blue night sky of roiling energy, exploding yellow stars, and radiating swirls of blu World Knowledge Complex +A close-up high-contrast photo of Sydney Opera House sitting next to Eiffel tower, under a blue night sky of roiling energy, exploding yellow stars, and radiating swirls of blue World Knowledge Complex +the Sydney Opera House with the Eiffel tower sitting on the right, and Mount Everest rising above World Knowledge Complex +Greek statue of a man comforting a cat. The cat has a big head. The man looks angry. People Complex +a robot painted as graffiti on a brick wall. a sidewalk is in front of the wall, and grass is growing out of cracks in the concrete. Outdoor Scenes Complex +a portrait of a statue of a pharaoh wearing steampunk glasses, white t-shirt and leather jacket. dslr photograph. People Complex +a real flamingo reading a large open book. a big stack of books is piled up next to it. dslr photograph. Animals Complex +A photo of a hamburger fighting a hot dog in a boxing ring. The hot dog is tired and up against the ropes. Food & Beverage Complex +a blue cow is standing next to a tree with red leaves and yellow fruit. the cow is standing in a field with white flowers. impressionistic painting. Animals Complex +A cozy living room with a painting of a corgi on the wall above a couch and a round coffee table in front of a couch and a vase of flowers on a coffee table Indoor Scenes Complex +Photograph of a wall along a city street with a watercolor mural of foxes in a jazz band. Outdoor Scenes Complex +A high resolution photo of a donkey in a clown costume giving a lecture at the front of a lecture hall. The blackboard has mathematical equations on it. There are many students in the lecture hall. Indoor Scenes Complex +A black dog sitting on a wooden chair. A white cat with black ears is standing up with its paws on the chair. Animals Complex +a Saint Bernard standing up with its paws in the air. A young girl is seated on the dog's shoulders. People Complex +a photograph of a squirrel holding an arrow above its head and holding a longbow in its left hand Animals Complex +An empty fireplace with a television above it. The TV shows a lion hugging a giraffe. Indoor Scenes Complex +an invisible man wearing horn-rimmed glasses and a pearl bead necklase while looking at his phone People Complex +a blue semi-truck and its trailer jumping over a row of motorcycles. there are metal ramps on either side of the motorcycles. Vehicles Complex +a white rabbit in blue jogging clothes doubled over in pain while a turtle wearing a red tank top dashes confidently through the finish line Animals Complex +a hot air balloon with a yin-yang symbol, with the moon visible in the daytime sky Vehicles Complex +a photograph of a fiddle next to a basketball on a ping pong table Artifacts Complex +a racoon detective using a microscope while riding in a train Animals Complex +a photograph of an ostrich wearing a fedora and singing soulfully into a microphone Animals Complex +a cream-colored labradoodle wearing glasses and black beret teaching calculus at a blackboard Animals Complex +a basketball to the left of two soccer balls on a gravel driveway Artifacts Complex +a cat patting a crystal ball with the number 7 written on it in black marker Animals Complex +a cat licking a large felt ball with a drawing of the Eiffel Tower on it World Knowledge Complex +a giraffe wearing a white bathing suit and carefully stepping to the edge of a diving board and preparing to dive Animals Complex +a paranoid android freaking out and jumping into the air because it is surrounded by colorful Easter eggs Artifacts Complex +a mixed media image with a photograph of a woman with long orange hair over a background that is a sketch of a city skyline People Complex +a black and orange yin-yang symbol with tiger's heads instead of circles Illustrations Complex +a painting of an ornate treasure chest with a broad sword propped up against it, glowing in a dark cave Arts Complex +Renaissance portrayals of the Virgin Mary, seated in a loggia. Behind her is a hazy and seemingly isolated landscape imagined by the artist and painted using sfumato. People Complex Description of Mona Lisa +Oil-on-canvas painting of a blue night sky with roiling energy. A fuzzy and bright yellow crescent moon shining at the top. Below the exploding yellow stars and radiating swirls of blue, a distant village sits quietly on the right. Connecting earth and sky is a flame-like cypress tree with curling and swaying branches on the left. A church spire rises as a beacon over rolling blue hills Arts Complex Description of The Starry Night +Painting of a panic-stricken creature, simultaneously corpselike and reminiscent of a sperm or fetus, whose contours are echoed in the swirling lines of the blood-red sky Arts Complex Description of The Scream +a propaganda poster depicting a cat dressed as french emperor napoleon holding a piece of cheese Artifacts Complex DALL-E 2 +a white bird in front of a dinosaur standing by some trees Outdoor Scenes Complex +Snow mountain and tree reflection in the lake Outdoor Scenes Complex VQ-Diffusion +a white robot, a red robot and a black robot standing together Artifacts Complex +a tree reflected in the hood of a blue car Produce & Plants Complex +a tree reflected in the sunroof of a blue car Produce & Plants Complex +a monarch butterfly hatching from its chrysalis Animals Complex +a glass of orange juice to the right of a plate with buttered toast on it Food & Beverage Complex +a bottle of beer next to an ashtray with a half-smoked cigarrette Food & Beverage Complex +a pineapple with one beer to its left and two beers on its right Food & Beverage Complex +a pickup truck with a horse on its left and two dogs on its right Vehicles Complex +a brown trash bin with a green compost bin on its left and a blue recycling bin on its right Artifacts Complex +a woman with long hair next to a luminescent bird People Complex +a tall man stooping down to enter a low red sports car People Complex +a black dog jumping up to hug a woman wearing a red sweater People Complex +a man and a woman standing in the back up an old pickup truck People Complex +a boy sitting on the shoulders of a woman who is wearing an elegant dress People Complex +a girl with curly black hair jumping off a boulder People Complex +a grandmother reading a book to her grandson and granddaughter People Complex +a young woman with glasses reading a thick book at a mahogany desk People Complex +a man in a business suit on a ladder that is leaning up against the side of a white house People Complex +a man pouring milk into a coffee cup to make a latte with a beatiful design People Complex +a woman using a sledgehammer to smash an ice sculpture of a goose People Complex +a painting of the mona lisa on a white wall World Knowledge Complex +a man eating a glazed donut and a woman eating a chocolate cake People Complex +A teddy bear wearing a motorcycle helmet and cape is standing in front of Loch Awe with Kilchurn Castle behind him World Knowledge Fine-grained Detail +A teddy bear wearing a motorcycle helmet and cape is driving a speed boat near the Golden Gate Bridge World Knowledge Fine-grained Detail +A teddy bear wearing a motorcycle helmet and cape is car surfing on a taxi cab in New York City World Knowledge Fine-grained Detail +A teddy bear wearing a motorcycle helmet and cape is riding a motorcycle in Rio de Janeiro with Dois Irmãos in the background World Knowledge Fine-grained Detail +A punk rock squirrel in a studded leather jacket shouting into a microphone while standing on a stump Animals Fine-grained Detail +A punk rock squirrel in a studded leather jacket shouting into a microphone while standing on a lily pad Animals Fine-grained Detail +A punk rock squirrel in a studded leather jacket shouting into a microphone while standing on a boulder Animals Fine-grained Detail +A punk rock frog in a studded leather jacket shouting into a microphone while standing on a stump Animals Fine-grained Detail +A punk rock frog in a studded leather jacket shouting into a microphone while standing on a lily pad Animals Fine-grained Detail +A punk rock frog in a studded leather jacket shouting into a microphone while standing on a boulder Animals Fine-grained Detail +A punk rock platstumppus in a studded leather jacket shouting into a microphone while standing on a stump Animals Fine-grained Detail +A punk rock platypus in a studded leather jacket shouting into a microphone while standing on a lily pad Animals Fine-grained Detail +A punk rock platypus in a studded leather jacket shouting into a microphone while standing on a boulder Animals Fine-grained Detail +A map of the United States made out sushi. It is on a table next to a glass of red wine. World Knowledge Fine-grained Detail +A blue Porsche 356 parked in front of a yellow brick wall World Knowledge Fine-grained Detail +A helicopter flies over the Arches National Park. World Knowledge Fine-grained Detail +A helicopter flies over the Grand Canyon. World Knowledge Fine-grained Detail +A helicopter flies over Yosemite. World Knowledge Fine-grained Detail +A sunken ship becomes the homeland of fish. Vehicles Fine-grained Detail + A sloth in a go kart on a race track. The sloth is holding a banana in one hand. There is a banana peel on the track in the background. Animals Fine-grained Detail +a photograph of a bird wearing headphones and speaking into a microphone in a recording studio Animals Fine-grained Detail +A teddybear on a skateboard in Times Square, doing tricks on a cardboard box ramp. World Knowledge Fine-grained Detail +A smiling sloth wearing a bowtie and holding a quarterstaff and a big book. A shiny VW van parked on grass. World Knowledge Fine-grained Detail +A smiling sloth wearing a bowtie and holding a quarterstaff and a big book. Animals Fine-grained Detail +A smiling sloth wearing a leather jacket, a cowboy hat, a kilt and a bowtie. The sloth is holding a quarterstaff and a big book. Animals Fine-grained Detail +A smiling sloth wearing a leather jacket, a cowboy hat and a kilt. Animals Fine-grained Detail +A shiny VW van with a cityscape painted on it and parked on grass. World Knowledge Fine-grained Detail +The Statue of Liberty with the Manhattan skyline in the background. World Knowledge Fine-grained Detail +a cream colored labradoodle next to a white cat with black-tipped ears Animals Fine-grained Detail +The Great Pyramid of Giza situated in front of Mount Everest World Knowledge Fine-grained Detail +A photo of a Ming Dynasty vase on a leather topped table. World Knowledge Fine-grained Detail +A table full of food. There is a plate of chicken rice, a bowl of bak chor mee, and a bowl of laksa. Food & Beverage Fine-grained Detail +A map of the United States with a pin on San Francisco World Knowledge Fine-grained Detail +A map of the United States made out of sushi on the table. World Knowledge Fine-grained Detail +a cute wooden owl statue holding a large globe of the Earth above its head Animals Fine-grained Detail +a photograph of the mona lisa drinking coffee as she has her breakfast. her plate has an omelette and croissant. People Fine-grained Detail +the mona lisa wearing a cowboy hat and screaming a punk song into a microphone People Fine-grained Detail +a young badger delicately sniffing a yellow rose, richly textured oil painting Arts Fine-grained Detail +a photograph of a blue porsche 356 coming around a bend in the road Vehicles Fine-grained Detail +fairy cottage with smoke coming up chimney and a squirrel looking from the window Outdoor Scenes Fine-grained Detail +purple lego dollhouse with a pool and a swing Artifacts Fine-grained Detail +black bearded dog with an injured leg wearing a cone Animals Fine-grained Detail +brown white and black white guinea pigs eating parsley handed to them Animals Fine-grained Detail +The Rosetta Stone lying on the ground, covered in snow. World Knowledge Fine-grained Detail +a high-quality photograph of an armadillo playing a bagpipe while standing on one leg Animals Fine-grained Detail +a white robot with a red mohawk painted as graffiti on a red brick wall Artifacts Fine-grained Detail +a panda bear playing ping pong using a blue paddle against an ostrich using a red paddle Animals Fine-grained Detail +Anubis wearing sunglasses and sitting astride a hog motorcyle World Knowledge Fine-grained Detail +a photograph of sand with a bucket, lots of scattered shells but no sandpipers Outdoor Scenes Fine-grained Detail +a shiba inu wearing a beret and black turtleneck Animals Fine-grained Detail DALL-E 2 +a handpalm with leaves growing from it People Fine-grained Detail DALL-E 2 +panda mad scientist mixing sparkling chemicals Animals Fine-grained Detail DALL-E 2 +a corgi’s head depicted as an explosion of a nebula Animals Fine-grained Detail DALL-E 2 +a dolphin in an astronaut suit on saturn Animals Fine-grained Detail DALL-E 2 +a teddy bear on a skateboard in times square World Knowledge Fine-grained Detail DALL-E 2 +A Big Ben clock towering over the city of London World Knowledge Fine-grained Detail CogView +A Vietnam map showing Ha Long Bay World Knowledge Fine-grained Detail +A bowl of Pho served with bean sprouts on top Food & Beverage Fine-grained Detail +a capybara sitting in a field Animals Fine-grained Detail DALL-E +a baby penguin wearing a blue hat, red gloves, green shirt, and yellow pants Animals Fine-grained Detail DALL-E +a collection of glasses is sitting on a table Artifacts Fine-grained Detail DALL-E +A bare kitchen has wood cabinets and white appliances Indoor Scenes Fine-grained Detail VQ-Diffusion +A black and white landscape photograph of a black tree Outdoor Scenes Fine-grained Detail VQ-Diffusion +an ornate, high-backed mahogany chair with a red cushion Artifacts Fine-grained Detail +a whale breaching in front of the Sydney Opera House World Knowledge Fine-grained Detail +a white country home with a wrap-around porch Outdoor Scenes Fine-grained Detail +a corgi wearing a red bowtie and a purple party hat Animals Fine-grained Detail GLIDE +robots meditating in a vipassana retreat Artifacts Fine-grained Detail GLIDE +a white robot passing a soccer ball to a red robot Artifacts Fine-grained Detail +a fall landscape with a small cottage next to a lake Outdoor Scenes Fine-grained Detail GLIDE +a cat looking out of a window at a squirrel on a fence Animals Fine-grained Detail +a white cat with black ears and markings Animals Fine-grained Detail +a white cat and a tabby cat looking at each other Animals Fine-grained Detail +a cat sitting on a stairway railing Animals Fine-grained Detail +a professional photo of a sunset behind the grand canyon Outdoor Scenes Fine-grained Detail GLIDE +a large white yacht in a calm bay on a sunny day Vehicles Fine-grained Detail +a large white yacht tossed about in a stormy sea Vehicles Fine-grained Detail +a baby daikon radish in a tutu walking a dog Produce & Plants Fine-grained Detail DALL-E +an illustration of a baby daikon radish in a tutu walking a dog Produce & Plants Fine-grained Detail DALL-E +a long wooden bench in front of a brick wall Artifacts Fine-grained Detail +an ornate metal bench by a nature path Outdoor Scenes Fine-grained Detail +a white plastic bench with a high arched back Artifacts Fine-grained Detail +a tall horse next to a red car Animals Fine-grained Detail +an owl standing on a wire Animals Fine-grained Detail +an owl standing on a telephone wire Animals Fine-grained Detail +the skyline of New York City World Knowledge Fine-grained Detail +beautiful fireworks in the sky with red, white and blue Outdoor Scenes Fine-grained Detail +a steam locomotive speeding through a desert Vehicles Fine-grained Detail +a submarine floating past a shark Vehicles Fine-grained Detail +a whale breaching near a mountain Animals Fine-grained Detail +the United States flag next to the flag of Texas World Knowledge Fine-grained Detail +a giraffe with an owl on its head Animals Fine-grained Detail +an owl on top of an elephant's back Animals Fine-grained Detail +an eagle swooping down to catch a mouse Animals Fine-grained Detail +an owl with its wings spread out swooping over a tree Animals Fine-grained Detail +a giraffe eating the bark of a tree Animals Fine-grained Detail +a car and a truck on the road next to a traffic light Vehicles Fine-grained Detail +a cityscape at night with a full moon Outdoor Scenes Fine-grained Detail +an owl gripping a squirrel in its talons Animals Fine-grained Detail +a bloody mary cocktail next to a napkin Food & Beverage Fine-grained Detail +an old-fashioned cocktail next to a napkin Food & Beverage Fine-grained Detail +a long-island ice tea cocktail next to a napkin Food & Beverage Fine-grained Detail +a margarita next to a napkin Food & Beverage Fine-grained Detail +a room with two chairs and a painting of the Statue of Liberty Indoor Scenes Fine-grained Detail +a mountain and its reflection in a lake Outdoor Scenes Fine-grained Detail +a bird and its reflection in a fountain Outdoor Scenes Fine-grained Detail +The Statue of Liberty on a cloudy day World Knowledge Fine-grained Detail +The Statue of Liberty surrounded by helicopters World Knowledge Fine-grained Detail +the Eiffel Tower in winter World Knowledge Fine-grained Detail +a sunken ship at the bottom of the ocean Vehicles Fine-grained Detail +a sunken submarine at the bottom of the ocean Vehicles Fine-grained Detail +the Eiffel Tower in a desert World Knowledge Fine-grained Detail +Golden Gate bridge on the surface of Mars World Knowledge Fine-grained Detail +the city of London on Mars World Knowledge Fine-grained Detail +the city of London on the moon World Knowledge Fine-grained Detail +a stop sign with a large tree behind it Artifacts Fine-grained Detail +a stop sign knocked over on a sidewalk Artifacts Fine-grained Detail +teacups surounding a kettle Artifacts Fine-grained Detail +a dragon breathing fire Animals Fine-grained Detail +a dragon breathing fire on a castle Animals Fine-grained Detail +a dragon breathing fire onto a knight Animals Fine-grained Detail +a view of the Big Dipper in the night sky World Knowledge Fine-grained Detail +a view of the Orion constellation in the night sky World Knowledge Fine-grained Detail +a teddy bear to the right of a toy car Artifacts Fine-grained Detail +a toy car in front of a teddy bear Artifacts Fine-grained Detail +a large present with a red ribbon Artifacts Fine-grained Detail +a large present with a red ribbon to the left of a Christmas tree Indoor Scenes Fine-grained Detail +a half empty bottle of red wine Food & Beverage Fine-grained Detail +a wine bottle with a lit candle stuck in its spout Food & Beverage Fine-grained Detail +a wine bottle with a red ribbon wrapped around it Food & Beverage Fine-grained Detail +a kids' book cover with an illustration of white dog driving a red pickup truck Illustrations Fine-grained Detail +milk pouring into a large glass Food & Beverage Fine-grained Detail +milk pouring from a glass into a bowl Food & Beverage Fine-grained Detail +matching socks with cute cats on them Artifacts Fine-grained Detail +cash on a wooden table Artifacts Fine-grained Detail +a wood cabin with a fire pit in front of it Indoor Scenes Fine-grained Detail +view of a clock tower on a cloudy day Artifacts Fine-grained Detail +a chimpanzee wearing a bowtie and playing a piano Animals Fine-grained Detail +a black baseball hat with a flame decal on it Artifacts Fine-grained Detail +black hi-top sneakers with the Nike swoosh Artifacts Fine-grained Detail +a roast turkey being taken out of the oven Food & Beverage Fine-grained Detail +a bamboo ladder propped up against an oak tree Artifacts Fine-grained Detail +a Tyrannosaurus Rex roaring in front of a palm tree Animals Fine-grained Detail +a Stegasaurus eating ferns Animals Fine-grained Detail +a Triceratops charging down a hill Animals Fine-grained Detail +a Styracosaurus displaying its horns Animals Fine-grained Detail +a Diplodocus standing in a lake Animals Fine-grained Detail +a tabby cat coming through a door Animals Fine-grained Detail +a cat's tail showing under a couch Animals Fine-grained Detail +a light shining on a giraffe in a street Animals Fine-grained Detail +a barred owl peeking out from dense tree branches Animals Fine-grained Detail +a great gray owl with a mouse in its beak Animals Fine-grained Detail +a snowy owl standing in a grassy field Animals Fine-grained Detail +a stone path leading away from a fountain Outdoor Scenes Fine-grained Detail +a wooden deck overlooking a mountain valley Outdoor Scenes Fine-grained Detail +a mouse sitting next to a computer mouse Animals Fine-grained Detail +a tiny dragon landing on a knight's shield Animals Fine-grained Detail +an F1 race car in a Manhattan street World Knowledge Fine-grained Detail +a chess queen to the right of a chess knight Artifacts Fine-grained Detail +a white pawn attacking a black bishop Artifacts Fine-grained Detail +a mountain stream with salmon leaping out of it Outdoor Scenes Fine-grained Detail +a living room with a large Egyptian statue in the corner Indoor Scenes Fine-grained Detail +a stone bust next to an egg and an eggplant Artifacts Fine-grained Detail +scraps of paper drifting in the wind Outdoor Scenes Fine-grained Detail +the silhouette of an elephant on the full moon Animals Fine-grained Detail +a tree growing out of the middle of an intersection Outdoor Scenes Fine-grained Detail +a can of Spam on an elegant plate Food & Beverage Fine-grained Detail +a dolphin jumping over a rowboat Animals Fine-grained Detail +a pick-up truck rolling over a grassy field Vehicles Fine-grained Detail +a drop-top sports car coming around a bend in the road Vehicles Fine-grained Detail +the Taj Mahal at sunrise World Knowledge Fine-grained Detail +a small garden with an apple tree behind it Produce & Plants Fine-grained Detail +a old-time car with a large front grille Vehicles Fine-grained Detail +a blue wall with a large framed watercolor painting of a mountain Indoor Scenes Fine-grained Detail +a yellow wall with a large framed oil painting of a car Indoor Scenes Fine-grained Detail +an old-fashioned phone next to a sleek laptop Artifacts Fine-grained Detail +a motorcycle parked in an ornate bank lobby Vehicles Fine-grained Detail +a hot air balloon landing in a corn field Vehicles Fine-grained Detail +a wooden toy horse with a mane made of rope Artifacts Fine-grained Detail +a beach with a cruise ship passing by Outdoor Scenes Fine-grained Detail +a group of penguins in a snowstorm Animals Fine-grained Detail +a Scottish castle next to a loch World Knowledge Fine-grained Detail +a full moon peeking through clouds at night Outdoor Scenes Fine-grained Detail +a crescent moon viewed between tree branches at night Outdoor Scenes Fine-grained Detail +a full moon rising above a mountain at night Outdoor Scenes Fine-grained Detail +the International Space Station flying in front of the moon World Knowledge Fine-grained Detail +a tornado passing over a corn field Outdoor Scenes Fine-grained Detail +a tidal wave approaching a coastal road Outdoor Scenes Fine-grained Detail +an antique car by a beach Vehicles Fine-grained Detail +a water tower next to a deserted road Outdoor Scenes Fine-grained Detail +a small airplane flying over rolling hills Vehicles Fine-grained Detail +an airplane flying into a cloud that looks like monster Vehicles Fine-grained Detail +a blue airplane taxiing on a runway with the sun behind it Vehicles Fine-grained Detail +a car with tires that have yellow rims Vehicles Fine-grained Detail +a turtle upside down and spinning on its shell Animals Fine-grained Detail +an octopus fleeing and squirting black ink Animals Fine-grained Detail +a moose by a mountain stream Animals Fine-grained Detail +a kachina doll with feathers on its head and wearing a white dress and brown boots. World Knowledge Fine-grained Detail +a kachina doll standing in sand World Knowledge Fine-grained Detail +a doorknocker shaped like a lion's head Artifacts Fine-grained Detail +a silver doorknocker on a mahoghany door Artifacts Fine-grained Detail +a rabbit with white fur and black-tipped ears Animals Fine-grained Detail +a glass of orange juice next to an empty pitcher Food & Beverage Fine-grained Detail +a glass of orange juice with an orange peel stuck on the rim Food & Beverage Fine-grained Detail +a bottle of light beer with a lemon slice wedged in the rim Food & Beverage Fine-grained Detail +a helicopter hovering over Times Square World Knowledge Fine-grained Detail +a traffic jam at Times Square World Knowledge Fine-grained Detail +a prop plane flying low over the Great Wall World Knowledge Fine-grained Detail +a view of the Kremlin on a sunny day World Knowledge Fine-grained Detail +a view of the Kremlin with snow falling World Knowledge Fine-grained Detail +a palm tree forest in front of the Kremlin World Knowledge Fine-grained Detail +a Ferrari Testarossa in front of the Kremlin World Knowledge Fine-grained Detail +a rusty red pickup truck with white wheel rims Vehicles Fine-grained Detail +a blue pickup truck with a rhinoceros in its flatbed Vehicles Fine-grained Detail +an orange pickup truck next to a yellow Porsche 911 Vehicles Fine-grained Detail +a pickup truck kicking up dust on a back road Vehicles Fine-grained Detail +a pickup truck going up a mountain switchback Vehicles Fine-grained Detail +a pickup truck at the beach at sunrise Vehicles Fine-grained Detail +a pickup truck under street lights at night Vehicles Fine-grained Detail +a pair of shoes on a tennis racquet Artifacts Fine-grained Detail +a shoe with a sock draped over it Artifacts Fine-grained Detail +a plant growing on the side of a brick wall Produce & Plants Fine-grained Detail +a plant at the bottom of a shallow stream Produce & Plants Fine-grained Detail +a cow eating a green leafy plant Animals Fine-grained Detail +a bundle of blue and yellow flowers in a vase Produce & Plants Fine-grained Detail +a horse chewing a large blue flower Animals Fine-grained Detail +a yellow diamond-shaped sign with a deer silhouette Artifacts Fine-grained Detail +a yellow diamond-shaped sign with a turtle silhouette Artifacts Fine-grained Detail +a yellow diamond-shaped sign with a puma silhouette Artifacts Fine-grained Detail +a yellow diamond-shaped sign with a wooly mammoth silhouette Artifacts Fine-grained Detail +a pair of headphones on a pumpkin Artifacts Fine-grained Detail +a pair of headphones on a guitar Artifacts Fine-grained Detail +a pair of headphones on a statue of a horse Artifacts Fine-grained Detail +a pair of headphones dangling from a tree branch Artifacts Fine-grained Detail +a car's wheel crushing a pair of headphones Vehicles Fine-grained Detail +a chemtrail passing between two clouds Outdoor Scenes Fine-grained Detail +a long chemtrail trailing an airplane in a blue sky Outdoor Scenes Fine-grained Detail +a tennis court with a basketball hoop in one corner Outdoor Scenes Fine-grained Detail +a tennis court that is very wet from lots of rain Outdoor Scenes Fine-grained Detail +a rocking chair next to the net of a tennis court Outdoor Scenes Fine-grained Detail +a ceiling fan with an ornate light fixture Indoor Scenes Fine-grained Detail +red and yellow balloons hanging from a ceiling fan Indoor Scenes Fine-grained Detail +a sidewalk next to a wooden post with a blue '5' painted on top Outdoor Scenes Fine-grained Detail +a harp with a carved eagle figure at the top Artifacts Fine-grained Detail +a tuba with red flowers protruding from its bell Artifacts Fine-grained Detail +an elephant using its trunk to blow into a tuba Animals Fine-grained Detail +The Alamo with bright white clouds above it World Knowledge Fine-grained Detail +a flock of geese in front of The Alamo World Knowledge Fine-grained Detail +an old-fashioned windmill surrounded by flowers Outdoor Scenes Fine-grained Detail +a windmill farm next to a country road Outdoor Scenes Fine-grained Detail +a family of bears passing by the geyser Old Faithful World Knowledge Fine-grained Detail +an old red truck parked by the geyser Old Faithful World Knowledge Fine-grained Detail +an inflatable rabbit held up in the air by the geyser Old Faithful World Knowledge Fine-grained Detail +a Harley-Davidson motorcycle with a flame decal Vehicles Fine-grained Detail +a motorcycle in front of an rhinoceros Vehicles Fine-grained Detail +a chopper decorated with the Stars and Stripes Vehicles Fine-grained Detail +a painting of black and white with a red flower in the right corner Illustrations Fine-grained Detail +a gorilla climbing up the side of the Great Pyramid World Knowledge Fine-grained Detail +a beat-up truck at the base of the Great Pyramid World Knowledge Fine-grained Detail +snow covering the Great Pyramid World Knowledge Fine-grained Detail +the sun setting behind the Parthenon World Knowledge Fine-grained Detail +fireworks above the Parthenon World Knowledge Fine-grained Detail +the Millennium Wheel in a snow storm World Knowledge Fine-grained Detail +a marina with a herd of dolphins playing in it Outdoor Scenes Fine-grained Detail +a volcano exploding next to a marina Outdoor Scenes Fine-grained Detail +a team playing baseball at the beach People Fine-grained Detail +a man standing on a street corner People Fine-grained Detail +a crowd of people watching fireworks by a park People Fine-grained Detail +a crowd of people watching fireworks by a city People Fine-grained Detail +a smiling man with wavy brown hair and trimmed beard People Fine-grained Detail +a woman with long black hair and dark skin People Fine-grained Detail +a woman with long black hair and dark skin in a long white dress People Fine-grained Detail +a man with long blonde hair, brown eyes and blue jeans People Fine-grained Detail +an elderly woman with straight hair and metal-rimmed glasses People Fine-grained Detail +a man wearing sunglasses and business suit People Fine-grained Detail +a girl with long curly blonde hair and sunglasses People Fine-grained Detail +an old man with a long grey beard and green eyes People Fine-grained Detail +a woman with tan skin in blue jeans and yellow shirt People Fine-grained Detail +a woman with a dog puppet and a cat puppet People Fine-grained Detail +a group of skiers are preparing to walk up a sand dune People Fine-grained Detail +a child eating a birthday cake near some palm trees People Fine-grained Detail +a man with wild hair looking into a crystal ball People Fine-grained Detail +Gandalf saying you shall not pass World Knowledge Fine-grained Detail +a mosquito biting a man People Fine-grained Detail +a witch riding a broom People Fine-grained Detail +a knight holding a long sword People Fine-grained Detail +a man reading a book with a prism on its cover People Fine-grained Detail +a cricket team walking on to the pitch People Fine-grained Detail +a cricketer standing next to a wicket People Fine-grained Detail +an elder politician giving a campaign speech People Fine-grained Detail +a young girl playing piano People Fine-grained Detail +a girl getting a kite out of a tree People Fine-grained Detail +a politician giving a speech at a podium People Fine-grained Detail +a politician speaking to a large crowd People Fine-grained Detail +a child in the air while jumping on a trampoline People Fine-grained Detail +the Beatles crossing Abbey road People Fine-grained Detail +a girl riding an ostrich People Fine-grained Detail +a river with people swimming in it as a boat goes by People Fine-grained Detail +a selfie of an old man with a white beard People Fine-grained Detail +a young girl wearing a tiara and frilly dress People Fine-grained Detail +a ballet dancer next to a waterfall People Fine-grained Detail +a judge delivering a sentence to the defendant People Fine-grained Detail +people packed on a double-decker bus People Fine-grained Detail +a man riding a camel on the beach People Fine-grained Detail +a woman singing into a microphone People Fine-grained Detail +a child unraveling a roll of toilet paper People Fine-grained Detail +a girl examining an ammonite fossil People Fine-grained Detail +a fairy flying over a girl's shoulder People Fine-grained Detail +Tibetan priests ringing a bell People Fine-grained Detail +a man sleeping in a hammock People Fine-grained Detail +a library filled with kids reading books People Fine-grained Detail +a scientist accepting an award People Fine-grained Detail +A tornado made of sharks crashing into a skyscraper. painting in the style of Hokusai. Arts Imagination +A tornado made of sharks crashing into a skyscraper. painting in the style of abstract cubism. Arts Imagination +A tornado made of sharks crashing into a skyscraper. painting in the style of watercolor. Arts Imagination +A tornado made of tigers crashing into a skyscraper. painting in the style of Hokusai. Arts Imagination +A tornado made of tigers crashing into a skyscraper. painting in the style of abstract cubism. Arts Imagination +A tornado made of tigers crashing into a skyscraper. painting in the style of watercolor. Arts Imagination +A tornado made of bees crashing into a skyscraper. painting in the style of Hokusai. Arts Imagination +A tornado made of bees crashing into a skyscraper. painting in the style of abstract cubism. Arts Imagination +A tornado made of bees crashing into a skyscraper. painting in the style of watercolor. Arts Imagination +A television made of water that displays an image of a cityscape at night. Artifacts Imagination +A photo of a light bulb in outer space traveling the galaxy with a sailing boat inside the light bulb. Artifacts Imagination +A shiny robot wearing a race car suit and black visor stands proudly in front of an F1 race car. The sun is setting on a cityscape in the background. comic book illustration. Illustrations Imagination +A horse sitting on an astronaut's shoulders. People Imagination +The collision of two black holes in the center of a galaxy. Abstract Imagination +a super math wizard cat, richly textured oil painting Arts Imagination +A group of farm animals (cows, sheep, and pigs) made out of cheese and ham, on a wooden board. There is a dog in the background eyeing the board hungrily. Food & Beverage Imagination +A giant cobra snake made from corn Animals Imagination +A giant cobra snake made from sushi Animals Imagination +A giant cobra snake made from pancakes Animals Imagination +A giant cobra snake made from salad Animals Imagination +A photo of an astronaut riding a horse in the forest. There is a river in front of them with water lilies. People Imagination +A rhino beetle this size of a tank grapples a real life passenger airplane on the tarmac Animals Imagination +a massive robot with a coffee cup head. it is standing in the street with one foot smashing a car. Artifacts Imagination +A large city fountain that has milk instead of water. Several cats are leaning into the fountain. Outdoor Scenes Imagination +A bowl of soup that looks like a monster knitted out of wool Food & Beverage Imagination +A bowl of soup that looks like a monster made out of plasticine Food & Beverage Imagination +A bowl of soup that looks like a monster spray-painted on a wall Food & Beverage Imagination +A bowl of soup that looks like a monster with tofu says deep learning Food & Beverage Imagination +The 1970s logo for a london-area football club called "The Rumbury Wanderers" World Knowledge Imagination +a swordfish and a narwhal fencing in an underwater sandy arena. a crap and a lobster are cheering. Animals Imagination +A castle made of tortilla chips, in a river made of salsa. There are tiny burritos walking around the castle Food & Beverage Imagination +A city in 4-dimensional space-time Abstract Imagination +A high resolution photo of a rat working out in a gym. Animals Imagination +A high resolution photo of a chicken working out in a gym. Animals Imagination +a dump truck filled with soccer balls scuba diving in a coral reef. Vehicles Imagination +a yellow dump truck filled with soccer balls driving in a coral reef. a blue whale looms in the background. Vehicles Imagination +A photo of llama wearing sunglasses standing on the deck of a spaceship with the Earth in the background. Animals Imagination +A high resolution photo of a large bowl of ramen. There are several origami boats in the ramen of different colors. Food & Beverage Imagination +an elf drinking orange juice through a straw of a giant orange next to a squirrel and an owl watching from above Animals Imagination Concept from an old children's book +An alien octopus floats through a portal reading a newspaper. DSLR photo. Animals Imagination +A photo of an astronaut riding a horse in the forest. People Imagination +A photograph of a bird made of wheat bread and an egg. Animals Imagination +a horse corral with tigers standing in each stall Animals Imagination +a bike rack with some bike locks attached to it but no bicycles Vehicles Imagination +A red dragon dressed in a tuxedo and playing chess. The chess pieces are fashioned after robots. Animals Imagination +An oil painting of a two-story house lifting off the ground like a rocket. Arts Imagination +a portrait of a postal worker who has forgotten their mailbag People Imagination +a politician wearing a soccer jersey and holding a volleyball while giving a speech on a stage People Imagination +a kangaroo hopping in the air between two identical large statues of warrior rabbits Animals Imagination +a impressionistic painting of a scholarly badger reading the Rosetta Stone World Knowledge Imagination +A black dragon perched on top of a tall Egyptian obelisk and breathing flames at a knight on the ground Animals Imagination +a photograph of a knight in shining armor holding a basketball People Imagination +Dogs playing poker Animals Imagination Description of "Dogs Playing Poker" +Dogs sitting around a poker table Animals Imagination Description of "Dogs Playing Poker" +Dogs sitting around a poker table with beer bottles and chips. Their hands are holding cards. Animals Imagination Description of "Dogs Playing Poker" +Salvador Dalí with a robotic half face People Imagination DALL-E 2 +an espresso machine that makes coffee from human souls Artifacts Imagination DALL-E 2 +panda mad scientist Animals Imagination DALL-E 2 +a snail made of harp Animals Imagination DALL-E +a giraffe made of turtle Animals Imagination DALL-E +a giraffe imitating a turtle Animals Imagination DALL-E +a cube made of porcupine Illustrations Imagination DALL-E +a watermelon chair Artifacts Imagination +a giant gorilla at the top of the Empire State Building World Knowledge Imagination +a spaceship that looks like the Sydney Opera House Vehicles Imagination +a hedgehog using a calculator Animals Imagination GLIDE +a cat playing checkers Animals Imagination +a hamster dragon Animals Imagination +a futuristic city Outdoor Scenes Imagination GLIDE +corgi pizza Animals Imagination +a clock with no hands Artifacts Imagination +a baby daikon radish in a tutu Produce & Plants Imagination DALL-E +a chimpanzee sitting on a wooden bench Animals Imagination +a smiling banana wearing a bandana Produce & Plants Imagination +an orange wearing a cowboy hat Produce & Plants Imagination +a cat drinking a pint of beer Animals Imagination +a train going to the moon Vehicles Imagination +a subway train in an empty station Vehicles Imagination +a cow jumping over the moon Animals Imagination +a cat sitting in a car seat Animals Imagination +a friendly car Vehicles Imagination +two cats doing research Animals Imagination +a red train is coming down the beach Vehicles Imagination +a small kitchen with a white goat in it Indoor Scenes Imagination +a giraffe with a funny face Animals Imagination +a peaceful lakeside landscape with migrating herd of sauropods Outdoor Scenes Imagination +a cat standing on a horse Animals Imagination +a horse standing on an elephant Animals Imagination +a cat chasing a horse Animals Imagination +a horse chasing a cat Animals Imagination +a cat with four eyes Animals Imagination +a sword slicing through a loaf of bread Artifacts Imagination +a sword slicing through pouring milk Artifacts Imagination +a coffee mug floating in the sky Artifacts Imagination +a pig face with an eye patch Animals Imagination +a stork playing a violin Animals Imagination +a TV on a horse Artifacts Imagination +a Christmas tree on a toy train Artifacts Imagination +The Statue of Liberty with the face of an owl World Knowledge Imagination +a zebra with blue stripes Animals Imagination +a zebra with alternating blue and red stripes Animals Imagination +a yellow tiger with blue stripes Animals Imagination +a tiger wearing a tuxedo Animals Imagination +the statue of Liberty next to the Washington Monument World Knowledge Imagination +a koi fish flying in the sky Animals Imagination +a pineapple surfing on a wave Produce & Plants Imagination +a toaster shaking hands with a microwave Artifacts Imagination +blue apples on a tree with yellow leaves Produce & Plants Imagination +square blue apples on a tree with circular yellow leaves Produce & Plants Imagination +square red apples on a tree with circular green leaves Produce & Plants Imagination +a pirate ship landing on the moon Vehicles Imagination +a turkey walking in the kitchen Animals Imagination +a horned owl with a graduation cap and diploma Animals Imagination +a panda bear with aviator glasses on its head Animals Imagination +a nerdy bear wearing glasses and a bowtie Animals Imagination +a volcano spewing fish into the sky Outdoor Scenes Imagination +a tree with leaves that look like purple balloons Produce & Plants Imagination +a pony with a shooting star on its flank Animals Imagination +a half moon in the day sky Outdoor Scenes Imagination +the moon with a smiling face Outdoor Scenes Imagination +a tornado with a house carried along at its top Outdoor Scenes Imagination +a penguin that is a car Animals Imagination +a bicycle wheel that is made of red yarn Vehicles Imagination +a rabbit sitting on a turtle's back Animals Imagination +a rabbit wearing a black tophat and monocle Animals Imagination +a full pitcher of beer with an elephant's trunk in it Food & Beverage Imagination +an elephant walking on the Great Wall World Knowledge Imagination +a spaceship landing on the Great Wall World Knowledge Imagination +an ocean at the base of the Great Wall World Knowledge Imagination +a herd of buffalo stampeding at the Kremlin World Knowledge Imagination +a pickup truck missing its wheels Vehicles Imagination +a flower with a cat's face in the middle Produce & Plants Imagination +a flower with large red petals growing on the moon's surface Produce & Plants Imagination +a grand piano next to the net of a tennis court Outdoor Scenes Imagination +a piano tumbling down a hill Artifacts Imagination +a drawing of a series of musical notes wrapped around the Earth Illustrations Imagination +a tuba made of flower petals Artifacts Imagination +a spaceship hovering over The Alamo World Knowledge Imagination +a motorcycle hanging on a garage wall Vehicles Imagination +a dragon perched on top of the Great Pyramid World Knowledge Imagination +a flying boat gliding past the Parthenon Vehicles Imagination +the Parthenon in front of the Great Pyramid World Knowledge Imagination +a diplodocus standing in front of the Millennium Wheel World Knowledge Imagination +a child and a penguin sitting on the moon People Imagination +Superman shaking hands with Spiderman People Imagination +a man with puppet that looks like a king People Imagination +a person with arms like a tree branch People Imagination +a man riding a cat People Imagination +a triangle with a smiling face Illustrations Imagination +a square with an angry face Illustrations Imagination +a concert without any fans People Linguistic Structures Negation +a summer tree without any leaves Produce & Plants Linguistic Structures Negation +a classroom without any students People Linguistic Structures Negation +a bookshelf without any books on it Artifacts Linguistic Structures Negation +a shoe rack without any pairs of shoes on it Artifacts Linguistic Structures Negation +a closet without clothes Artifacts Linguistic Structures Negation +a plate that has no bananas on it. there is a glass without orange juice next to it. Food & Beverage Linguistic Structures Negation +A bird gives an apple to a squirrel Animals Linguistic Structures Ditransitive verbs +A squirrel gives an apple to a bird Animals Linguistic Structures Ditransitive verbs +A dog gives an apple to a squirrel Animals Linguistic Structures Ditransitive verbs +The sculpture rolled off the shelf because it wasn't level Artifacts Linguistic Structures Winograd Schema Challenge +The sculpture rolled off the shelf because it wasn't anchored Artifacts Linguistic Structures Winograd Schema Challenge +The large ball crashed right through the table because it was made of styrofoam Artifacts Linguistic Structures Winograd Schema Challenge +The large ball crashed right through the table because it was made of steel Artifacts Linguistic Structures Winograd Schema Challenge +The trophy doesn't fit into the brown suitcase because it's too small Artifacts Linguistic Structures Winograd Schema Challenge +The trophy doesn't fit into the brown suitcase because it's too large Artifacts Linguistic Structures Winograd Schema Challenge +The coach smiled at the player tossed the frisbee People Linguistic Structures https://en.wikipedia.org/wiki/List_of_linguistic_example_sentences +The rat the cat the dog bit chased escaped. Animals Linguistic Structures https://en.wikipedia.org/wiki/List_of_linguistic_example_sentences +To a squirrel, a dog gives an apple. Animals Linguistic Structures Ditransitive verbs +A man gives a woman a laptop and a boy a book. People Linguistic Structures Ditransitive verbs +A robot gives a wombat an orange and a lemur a banana. Animals Linguistic Structures Ditransitive verbs +A man sips a latte and a woman a beer. Food & Beverage Linguistic Structures +A rabbit checks its watch, and so does a gecko. Animals Linguistic Structures +A boy holds and a girl paints a piece of wood. People Linguistic Structures +A cat that has black fur bats a red Christmas ornament that has silver sparkles. Animals Linguistic Structures +The mouse the cat watches is jumping in the air. Animals Linguistic Structures +Four deer surrounding a moose. Animals Linguistic Structures +supercalifragilisticexpialidocious Abstract Linguistic Structures Mary Poppins described it as the word to use “when you have nothing to say.” +Incomprehensibilities Abstract Linguistic Structures +Pneumonoultramicroscopicsilicovolcanoconiosis Abstract Linguistic Structures Longest word: "a lung disease caused by inhalation of very fine silicate or quartz dust." +a large stone pedestal without a statue of a horse on it Artifacts Linguistic Structures Negation +a brown mouse laughing at a gray cat because a 16 ton weight is about to fall on its head Animals Linguistic Structures +a black dog sitting between a bush and a pair of green pants standing up with nobody inside them Animals Linguistic Structures +The horse raced past the barn fell Animals Linguistic Structures Garden-path sentences +The old man the boat. People Linguistic Structures Garden-path sentences +We painted the wall with cracks. People Linguistic Structures Garden-path sentences +The raft floated down the river sank. Vehicles Linguistic Structures Garden-path sentences +Mary gave the child the dog bit a Band-Aid. People Linguistic Structures Garden-path sentences +The man who whistles tunes pianos. People Linguistic Structures Garden-path sentences +One morning I chased an elephant in my pajamas People Linguistic Structures Syntactic Ambiguities +A tourist is looking at a whale using a binocular People Linguistic Structures Syntactic Ambiguities +The dog chased the cat, which ran up a tree. It waited at the top. Animals Linguistic Structures Winograd Schema Challenge +The dog chased the cat, which ran up a tree. It waited at the bottom. Animals Linguistic Structures Winograd Schema Challenge +An aerial view of Ha Long Bay without any boats World Knowledge Linguistic Structures Negation +a bench without any cats on it Artifacts Linguistic Structures Negation +a laptop no letters on its keyboard Artifacts Linguistic Structures Negation +a subway train with no cows in it Vehicles Linguistic Structures Negation +a kitchen without a refrigerator Indoor Scenes Linguistic Structures Negation +several lily pads without frogs Produce & Plants Linguistic Structures Negation +a street without vehicles Outdoor Scenes Linguistic Structures Negation +a house with no windows Outdoor Scenes Linguistic Structures Negation +a car with no windows Vehicles Linguistic Structures Negation +a fish without eyes Animals Linguistic Structures Negation +a city intersection without cars Outdoor Scenes Linguistic Structures Negation +a horse without a rider Animals Linguistic Structures Negation +a banana without its peel Produce & Plants Linguistic Structures Negation +a bat landing on a baseball bat Animals Linguistic Structures +a bird landing on a bat Animals Linguistic Structures +a rowboat without paddles Vehicles Linguistic Structures Negation +a harp without any strings Artifacts Linguistic Structures Negation +a marina without any boats in it Outdoor Scenes Linguistic Structures Negation +Zoomed out view of a giraffe and a zebra in the middle of a field covered with colorful flowers Animals Perspective +Three-quarters front view of a blue 1977 Corvette coming around a curve in a mountain road and looking over a green valley on a cloudy day. Vehicles Perspective +Three-quarters front view of a blue 1977 Ford F-150 coming around a curve in a mountain road and looking over a green valley on a cloudy day. Vehicles Perspective +Three-quarters front view of a blue 1977 Porsche 911 coming around a curve in a mountain road and looking over a green valley on a cloudy day. Vehicles Perspective +Three-quarters front view of a red 1997 Corvette coming around a curve in a mountain road and looking over a green valley on a cloudy day. Vehicles Perspective +Three-quarters front view of a red 1997 Ford F-150 coming around a curve in a mountain road and looking over a green valley on a cloudy day. Vehicles Perspective +Three-quarters front view of a red 1997 Porsche 911 coming around a curve in a mountain road and looking over a green valley on a cloudy day. Vehicles Perspective +Three-quarters front view of a yellow 2017 Corvette coming around a curve in a mountain road and looking over a green valley on a cloudy day. Vehicles Perspective +Three-quarters front view of a yellow 2017 Ford F-150 coming around a curve in a mountain road and looking over a green valley on a cloudy day. Vehicles Perspective +Three-quarters front view of a yellow 2017 Porsche 911 coming around a curve in a mountain road and looking over a green valley on a cloudy day. Vehicles Perspective +A photo of a frog reading the newspaper named "Toaday" written on it. There is a frog printed on the newspaper too. Animals Perspective +The frog found itself in the newspaper Animals Perspective +A cat dreaming about becoming a tiger Animals Perspective +A close-up of two chameleons wearing karate uniforms and fighting, jumping over a waterfall. Animals Perspective +A close-up of two mantis wearing karate uniforms and fighting, jumping over a waterfall. Animals Perspective +A close-up of two beetles wearing karate uniforms and fighting, jumping over a waterfall. Animals Perspective +A robot with a black visor and the number 42 on its chest. It stands proudly in front of an F1 race car. The sun is setting on a cityscape in the background. wide-angle view. comic book illustration. Illustrations Perspective +A smiling sloth is wearing a leather jacket, a cowboy hat, a kilt and a bowtie. The sloth is holding a quarterstaff and a big book. The sloth is standing on grass a few feet in front of a shiny VW van with flowers painted on it. wide-angle lens from below. World Knowledge Perspective +A smiling sloth wearing a leather jacket, bowtie, kilt and cowboy hat. The sloth is holding a quarterstaff and a big book. The sloth is standing on grass a few feet in front of a rusty old VW van with flowers painted on it. wide-angle lens from below. World Knowledge Perspective +view of a giraffe and a zebra in the middle of a field Animals Perspective +Aerial view of downtown Manhattan, but with Millennium Wheel next to the Statue of Liberty. The Great Pyramid is on a sandy island near the buildings. World Knowledge Perspective +Ground view of the Great Pyramids and Sphinx on the moon's surface. The back of an astronaut is in the foreground. The planet Earth looms in the sky. World Knowledge Perspective +Saturn rises on the horizon. Outdoor Scenes Perspective +Mars rises on the horizon. Outdoor Scenes Perspective +Jupiter rises on the horizon. Outdoor Scenes Perspective +a close-up of a blue dragonfly on a daffodil Animals Perspective +long shards of a broken mirror reflecting the eyes of a great horned owl Artifacts Perspective +side view of a brown horse wearing a saddle. the number 55 is stamped in white on its rear flank. Animals Perspective +three quarters view of a rusty old red pickup truck with white doors and a smashed windshield Vehicles Perspective +view from below of a tall white ladder with just one rung leaning up against a yellow brick wall Artifacts Perspective +a photo of the back of a covered wagon. a polar bear is sticking it's head out of the wagon. Vehicles Perspective +a close up of a handpalm with leaves growing from it People Perspective DALL-E 2 +a corgi’s head Animals Perspective +An aerial view of Ha Long Bay World Knowledge Perspective +a macro photograph of brain coral Animals Perspective DALL-E +a cross-section view of a walnut Produce & Plants Perspective DALL-E +an extreme close-up view of a capybara sitting in a field Animals Perspective DALL-E +an overhead view of the Empire State Building World Knowledge Perspective +a pig face Animals Perspective +a close-up of a bloody mary cocktail Food & Beverage Perspective +a close-up of an old-fashioned cocktail Food & Beverage Perspective +a close-up of a long-island ice tea cocktail Food & Beverage Perspective +a close-up of a margarita Food & Beverage Perspective +the back of a violin Artifacts Perspective +view of a clock tower from above Artifacts Perspective +view of a clock tower from below Artifacts Perspective +an aerial photo of a carnival at night Outdoor Scenes Perspective +an aerial photo of a baseball stadium Outdoor Scenes Perspective +an aerial photo of a sandy island in the ocean Outdoor Scenes Perspective +an ostrich's face Animals Perspective +a close-up of an ostrich's face Animals Perspective +the eyes of an owl Animals Perspective +a close-up of the eyes of an owl Animals Perspective +a top down view of a horse running in a field Animals Perspective +tall buildings seen through a window with rain on it Outdoor Scenes Perspective +trees seen through a car window on a rainy day Outdoor Scenes Perspective +a view of the Earth from the moon Outdoor Scenes Perspective +an image of the moons of the planet Jupiter Outdoor Scenes Perspective +the eye of the planet Jupiter Outdoor Scenes Perspective +a close-up of the eye of the planet Jupiter Outdoor Scenes Perspective +an aerial view of the Great Wall World Knowledge Perspective +view of the Great Wall from its base World Knowledge Perspective +an overhead view of a pickup truck with boxes in its flatbed Vehicles Perspective +a close-up of the keys of a piano Artifacts Perspective +an aerial view of the Great Pyramid World Knowledge Perspective +a view of the Milllenium Wheel from the Thames World Knowledge Perspective +overhead view of three people looking down at the street from the top of a tall building People Perspective +two people facing each other People Perspective +two people facing the viewer People Perspective +a three quarters view of a man getting into a car People Perspective +a stack of three red cubes with a blue sphere on the right and two green cones on the left Illustrations Properties & Positioning +A photo of a Persian Metal Engraving vase sitting to the left of a bunch of orange flowers. World Knowledge Properties & Positioning +A photo of a Japanese Porcelain Imari vase on the ground below a wooden chair. World Knowledge Properties & Positioning +a pen-and-ink crosshatched drawing of a sphere with dark square on it Illustrations Properties & Positioning +a metallic blue sphere to the left of a yellow box made of felt Illustrations Properties & Positioning +a blue wooden pyramid on top of a red plastic box Illustrations Properties & Positioning +concentric squares fading from yellow on the outside to deep orange on the inside Illustrations Properties & Positioning +A green heart with shadow Illustrations Properties & Positioning VQ-Diffusion +a red cube on top of a blue cube Illustrations Properties & Positioning GLIDE +a white flag with a red circle next to a solid blue flag Artifacts Properties & Positioning +a red circle on top of a blue square Illustrations Properties & Positioning +a yellow box to the right of a blue sphere Illustrations Properties & Positioning +a red box to the right of a green sphere Illustrations Properties & Positioning +a red box next to a blue box Illustrations Properties & Positioning +a red sphere on top of a yellow box Illustrations Properties & Positioning +a large blue box with three small yellow boxes on it Illustrations Properties & Positioning +several red lego blocks and one blue one Artifacts Properties & Positioning +a red block to the left of a blue pyramid Illustrations Properties & Positioning +three small yellow boxes on a large blue box Illustrations Properties & Positioning +a black background with a large yellow circle Illustrations Properties & Positioning +a white background with a large blue circle Illustrations Properties & Positioning +a black background with a large yellow square Illustrations Properties & Positioning +a white background with a large blue square Illustrations Properties & Positioning +a black background with a large yellow circle and a small red square Illustrations Properties & Positioning +a white background with a large blue circle and a small green square Illustrations Properties & Positioning +a large yellow triangle above a green square and red rectangle Illustrations Properties & Positioning +two small circles to the left of a red triangle that is on a green rectangle Illustrations Properties & Positioning +a green pyramid in front of a blue box Illustrations Properties & Positioning +a large yellow sphere behind a small purple pyramid Illustrations Properties & Positioning +a metallic blue sphere to the left of a brown cardboard box Illustrations Properties & Positioning +a yellow swirl next to a blue dashed line. Illustrations Properties & Positioning +a red swirl above a black dashed line. Illustrations Properties & Positioning +a green pepper to the left of a red pepper Food & Beverage Properties & Positioning +a brown trash bin to the left of a blue recycling bin Artifacts Properties & Positioning +a circular brown trash bin in front of a brick wall Artifacts Properties & Positioning +ten red apples Produce & Plants Quantity +Four dragons surrounding a dinosaur Animals Quantity +Four cats surrounding a dog Animals Quantity +two baseballs to the left of three tennis balls Artifacts Quantity +a group of not more than five meerkats standing with the sun setting behind them Animals Quantity +a basketball game between a team of four cats and a team of three dogs Animals Quantity +the hands of a single person holding a basketball People Quantity +several people putting their hands on a basketball People Quantity +a tiny football in front of three yellow tennis balls Artifacts Quantity +two beat-up baseballs on either side of a yellow basketball Artifacts Quantity +two baseballs next to three tennis balls Artifacts Quantity +7 dogs sitting around a poker table Animals Quantity Description of "Dogs Playing Poker" +7 dogs sitting around a poker table, two of which are turning away. Animals Quantity Description of "Dogs Playing Poker" +300 movie titles Artifacts Quantity Simple numbers but challenging +a collection of glasses Artifacts Quantity +two chairs Artifacts Quantity +three chairs Artifacts Quantity +five chairs Artifacts Quantity +two wooden chairs and three metal chairs Artifacts Quantity +three black cats standing next to two orange cats Animals Quantity +a bunch of laptops piled on a sofa Indoor Scenes Quantity +four owls standing on a telephone wire Animals Quantity +an owl family Animals Quantity +a comic about an owl family in the forest Artifacts Quantity +two cats Animals Quantity +a comic about two cats doing research Artifacts Quantity +three elephants standing on top of each other Animals Quantity +two red boxes Illustrations Quantity +two violins standing up Artifacts Quantity +two violins standing up with their bows on the ground in front of them Artifacts Quantity +three violins lying on the floor Indoor Scenes Quantity +three red lego blocks Artifacts Quantity +four teacups surounding a kettle Artifacts Quantity +three small yellow boxes Illustrations Quantity +bottles Artifacts Quantity +two frosted glass bottles Artifacts Quantity +five frosted glass bottles Artifacts Quantity +three green glass bottles Artifacts Quantity +four green glass bottles Artifacts Quantity +two wine bottles Artifacts Quantity +three wine bottles Artifacts Quantity +four wine bottles Artifacts Quantity +ten wine bottles Artifacts Quantity +two wine bottles and three beer cans Artifacts Quantity +a pair of matching socks with cute cats on them Artifacts Quantity +a pile of cash on a wooden table Artifacts Quantity +a pile of cash on a stone floor Artifacts Quantity +two red balls Artifacts Quantity +two red balls on a table Artifacts Quantity +five red balls Artifacts Quantity +five red balls on a table Artifacts Quantity +three yellow balls and two red boxes on a table Artifacts Quantity +an antique chest with three drawers Artifacts Quantity +ten triangles and five squares on a black background Illustrations Quantity +a pile of toy cars Artifacts Quantity +a full bookshelf with three shelves Artifacts Quantity +a bookshelf with ten books stacked vertically Artifacts Quantity +three airplanes parked in a row at a terminal Vehicles Quantity +three green peppers Food & Beverage Quantity +five green peppers to the right of two red onions Food & Beverage Quantity +Times Square with thousands of dogs running around World Knowledge Quantity +three pickup trucks piled on top of each other Vehicles Quantity +a pair of brown suede shoes Artifacts Quantity +two red flowers and three white flowers Produce & Plants Quantity +two parallel chemtrails in blue sky Outdoor Scenes Quantity +two chemtrails forming an X in blue sky Outdoor Scenes Quantity +a tennis court with three yellow cones on it Outdoor Scenes Quantity +a tennis court with tennis balls scattered all over it Outdoor Scenes Quantity +a ceiling fan with four white blades Indoor Scenes Quantity +a ceiling fan with five brown blades Indoor Scenes Quantity +two pianos next to each other Indoor Scenes Quantity +a series of musical notes Illustrations Quantity +a field with ten massive modern windmills Outdoor Scenes Quantity +two motorcycles facing each other Vehicles Quantity +children People Quantity +one child on a couch People Quantity +three children on a couch People Quantity +ten children on a couch People Quantity +a crowd of people watching fireworks People Quantity +a parade with cars and people waving People Quantity +a family of four posing in front of a house People Quantity +a family of four posing at the Grand Canyon People Quantity +a family of four posing at Mount Rushmore People Quantity +a family of four posing on the moon People Quantity +a family of four walking at the beach with waves covering their feet People Quantity +a jungle gym with three kids on it People Quantity +four people riding in a convertible car People Quantity +two runners crossing the finish line together People Quantity +a four-piece band on a stage in front of a small crowd People Quantity +two sets of identical twins People Quantity +Siberian husky playing the piano. Animals Simple Detail +A van parked on grass Vehicles Simple Detail +a smiling sloth Animals Simple Detail +A shiny VW van parked on grass. World Knowledge Simple Detail +a farm scene with cows, ducks and a tractor. Outdoor Scenes Simple Detail +a lavender backpack with a triceratops stuffed animal head on top Artifacts Simple Detail +a dolphin in an astronaut suit Animals Simple Detail DALL-E 2 +a teddy bear on a skateboard Artifacts Simple Detail DALL-E 2 +A tiger is playing football Animals Simple Detail CogView +A Google map highlighting Vietnam World Knowledge Simple Detail +A bowl of Chicken Pho Food & Beverage Simple Detail +A bowl of Beef Pho Food & Beverage Simple Detail +a lovestruck cup of boba Food & Beverage Simple Detail DALL-E +a horse in a field of flowers Outdoor Scenes Simple Detail +A green heart Illustrations Simple Detail +The sunset on the beach is wonderful Outdoor Scenes Simple Detail VQ-Diffusion +A red bus is driving on the road Vehicles Simple Detail VQ-Diffusion +A picture of a very tall stop sign Outdoor Scenes Simple Detail VQ-Diffusion +A movie poster of mountain and sea Artifacts Simple Detail VQ-Diffusion +A giraffe walking through a green grass covered field Animals Simple Detail VQ-Diffusion +A green train is coming down the tracks Vehicles Simple Detail VQ-Diffusion +A living area with a television and a table Indoor Scenes Simple Detail VQ-Diffusion +A red hydrant on the grass Outdoor Scenes Simple Detail VQ-Diffusion +Sunset over the sea Outdoor Scenes Simple Detail VQ-Diffusion +A small house in the wilderness Outdoor Scenes Simple Detail VQ-Diffusion +Sunset over the skyline of a city Outdoor Scenes Simple Detail VQ-Diffusion +A heart made of chocolate Illustrations Simple Detail VQ-Diffusion +A heart made of water Illustrations Simple Detail VQ-Diffusion +A heart made of wood Illustrations Simple Detail VQ-Diffusion +A heart made of cookie Illustrations Simple Detail VQ-Diffusion +a white country home Outdoor Scenes Simple Detail +robots meditating Artifacts Simple Detail +a robot kicking a soccer ball Artifacts Simple Detail +a cat looking out of a window Animals Simple Detail +a cat coming through a cat door Animals Simple Detail +a cat jumping in the air Animals Simple Detail +a cat jumping in the air to catch a bird Animals Simple Detail +a cat jumping in the air to get onto a table Animals Simple Detail +a sunset behind the grand canyon World Knowledge Simple Detail GLIDE +a boat in the canals of venice World Knowledge Simple Detail GLIDE +a large white yacht Vehicles Simple Detail +a panda eating bamboo Animals Simple Detail GLIDE +a fog rolling into new york World Knowledge Simple Detail GLIDE +a green clock Artifacts Simple Detail +a photo of a phone from the 20s Artifacts Simple Detail DALL-E +a photo of the food of china Food & Beverage Simple Detail DALL-E +a baby daikon radish Produce & Plants Simple Detail DALL-E +a very fancy French restaurant Indoor Scenes Simple Detail +a tiger standing by some flowers Animals Simple Detail +a bench next to a flower pot Artifacts Simple Detail +a bird standing on a stick Animals Simple Detail +a blue sports car on the road Vehicles Simple Detail +a red sports car on the road Vehicles Simple Detail +a soccer ball flying over a car Outdoor Scenes Simple Detail +the finale of a fireworks display Outdoor Scenes Simple Detail +beautiful fireworks in the sky Outdoor Scenes Simple Detail +a subway train Vehicles Simple Detail +a subway train coming out of a tunnel Vehicles Simple Detail +orange jello Food & Beverage Simple Detail +a yellow t-shirt Artifacts Simple Detail +a blue t-shirt Artifacts Simple Detail +a flag furling in the wind Artifacts Simple Detail +a white towel Artifacts Simple Detail +a white towel with a cat on it Artifacts Simple Detail +a black towel Artifacts Simple Detail +a black towel with a dog on it Artifacts Simple Detail +a yellow wall Artifacts Simple Detail +a friendly car in the city Vehicles Simple Detail +an owl family in the forest Animals Simple Detail +a kangaroo jumping through the park Animals Simple Detail +a street in Paris World Knowledge Simple Detail +a canal in Venice World Knowledge Simple Detail +a small house Outdoor Scenes Simple Detail +a small house on a mountain top Outdoor Scenes Simple Detail +the grand canyon on a cloudy day World Knowledge Simple Detail +a house on a mountain Outdoor Scenes Simple Detail +a photograph of a house on a mountain Outdoor Scenes Simple Detail +a peaceful lakeside landscape Outdoor Scenes Simple Detail +a cat reading a book Animals Simple Detail +a cat reading a newspaper Animals Simple Detail +a cat reading a comic book Animals Simple Detail +a horse reading a book Animals Simple Detail +a horse reading a newspaper Animals Simple Detail +a horse reading a comic book Animals Simple Detail +a cat jumping down from a wall Animals Simple Detail +a pumpkin with a candle in it Produce & Plants Simple Detail +a sword in a stone Artifacts Simple Detail +an Egyptian statue World Knowledge Simple Detail +an Egyptian statue in the desert World Knowledge Simple Detail +a massive statue in a temple Artifacts Simple Detail +a circular logo on a coffee mug Illustrations Simple Detail +a pig in a field Animals Simple Detail +a horse in a field Animals Simple Detail +a squirrel in a field Animals Simple Detail +a tiger in a field Animals Simple Detail +a pig in a forest Animals Simple Detail +a horse in a forest Animals Simple Detail +a squirrel in a forest Animals Simple Detail +a tiger in a forest Animals Simple Detail +a hammer on a table Artifacts Simple Detail +a screwdriver on a table Artifacts Simple Detail +a handsaw on a table Artifacts Simple Detail +a power drill on a table Artifacts Simple Detail +a bloody mary cocktail Food & Beverage Simple Detail +an old-fashioned cocktail Food & Beverage Simple Detail +a long-island ice tea cocktail Food & Beverage Simple Detail +a tree surrounded by flowers Produce & Plants Simple Detail +a street with several cars on it Outdoor Scenes Simple Detail +an avocado on a table Produce & Plants Simple Detail +a kitchen with a large refrigerator Indoor Scenes Simple Detail +weeds in the cracks of a sidewalk Artifacts Simple Detail +a wood treehouse in an oak tree Artifacts Simple Detail +a metal treehouse in an oak tree Artifacts Simple Detail +a violin next to an apple Artifacts Simple Detail +a room with two chairs and a painting Indoor Scenes Simple Detail +a canal in Amsterdam World Knowledge Simple Detail +red apples on a tree with green leaves Produce & Plants Simple Detail +a stop sign Artifacts Simple Detail +a yield sign Artifacts Simple Detail +a mountain with a cloud hanging over it Outdoor Scenes Simple Detail +a bottle of red wine Food & Beverage Simple Detail +wine bottles Food & Beverage Simple Detail +the cover of a book about gardening Illustrations Simple Detail +a milk container on a table Artifacts Simple Detail +a milk container in a refrigerator Artifacts Simple Detail +a marine iguana crossing the street Animals Simple Detail +cash on a stone floor Artifacts Simple Detail +a half-peeled banana Produce & Plants Simple Detail +a black baseball hat Artifacts Simple Detail +black hi-top sneakers Artifacts Simple Detail +a roast turkey on the table Food & Beverage Simple Detail +a plate with white rice topped by cooked vegetables Food & Beverage Simple Detail +slices of avocado on a piece of toast Food & Beverage Simple Detail +slices of mango on a piece of toast Food & Beverage Simple Detail +a bamboo ladder Artifacts Simple Detail +a cat jumps over a baby gate Animals Simple Detail +an ostrich standing on a couch Animals Simple Detail +a taxi driving in the countryside Vehicles Simple Detail +a two lane road with a bright yellow line Outdoor Scenes Simple Detail +a road ruined by an earthquake Outdoor Scenes Simple Detail +a volcano erupting near a small town Outdoor Scenes Simple Detail +a volcano with lava pouring down its slopes Outdoor Scenes Simple Detail +a horse running in a field Animals Simple Detail +a robot cooking Artifacts Simple Detail +a robot cooking in the kitchen Indoor Scenes Simple Detail +a compass next to a piece of fruit Artifacts Simple Detail +the silhouette of an elephant Animals Simple Detail +a tree growing through a fence Produce & Plants Simple Detail +a butterfly kite stuck high in a tree Produce & Plants Simple Detail +a unicorn with a multicolored mane Animals Simple Detail +a crown with a ruby in its center Artifacts Simple Detail +an ornate jewel-encrusted key Artifacts Simple Detail +a goat wearing headphones Animals Simple Detail +a small tree covered in white blossoms Produce & Plants Simple Detail +an antique chest Artifacts Simple Detail +a coffee table with a magazine on it Indoor Scenes Simple Detail +a yellow wall with two framed sketches Indoor Scenes Simple Detail +a squirrell driving a toy car Animals Simple Detail +a penguin standing on a sidewalk Animals Simple Detail +a basketball hoop with a large blue ball stuck in it Outdoor Scenes Simple Detail +a racoon holding a shiny red apple over its head Animals Simple Detail +a pair of glasses under a computer monitor Artifacts Simple Detail +a throw rug on a stone floor Artifacts Simple Detail +a beach with apartment buildings next to it Outdoor Scenes Simple Detail +a moose standing over a fox Animals Simple Detail +a massive statue of Hanuman World Knowledge Simple Detail +a black t-shirt Artifacts Simple Detail +a small airplane Vehicles Simple Detail +an airplane taking off of a runway Vehicles Simple Detail +a monarch butterfly Animals Simple Detail +a lizard that just lost its tail Animals Simple Detail +a golden doorknocker on a red door Artifacts Simple Detail +a pitcher of orange juice Food & Beverage Simple Detail +a glass of orange juice Food & Beverage Simple Detail +a green pepper cut in half on a plate Food & Beverage Simple Detail +a green pepper sliced into many pieces Food & Beverage Simple Detail +a full pint of IPA Food & Beverage Simple Detail +a half-full pitcher of stout Food & Beverage Simple Detail +Times Square during the day World Knowledge Simple Detail +Times Square at night World Knowledge Simple Detail +the Kremlin at night World Knowledge Simple Detail +a hot air balloon floating by the Kremlin World Knowledge Simple Detail +a black shoe with a lightning bolt on it Artifacts Simple Detail +a plant with small flowers with purple petals Produce & Plants Simple Detail +a plant with orange flowers shaped like stars Produce & Plants Simple Detail +a flower with large yellow petals Produce & Plants Simple Detail +a yellow diamond-shaped sign Artifacts Simple Detail +an elephant in a tennis court Animals Simple Detail +a silver fire hydrant next to a sidewalk Artifacts Simple Detail +a yellow fire hydrant in grass Artifacts Simple Detail +a red fire hydrant by a brick wall Artifacts Simple Detail +a rusty fire hydrant surrounded by dirt Artifacts Simple Detail +a fire hydrant with graffiti on it Artifacts Simple Detail +a snake curled around a wooden post Animals Simple Detail +a grand piano with a white bench Indoor Scenes Simple Detail +a piano with Christmas lights all over it Indoor Scenes Simple Detail +a piano with an open song book above the keys Indoor Scenes Simple Detail +an ornate gold harp Artifacts Simple Detail +a massive modern windmill Outdoor Scenes Simple Detail +a red sport bike Vehicles Simple Detail +a painting of black and white vertical stripes Illustrations Simple Detail +a painting of black and white checkerboard Illustrations Simple Detail +a painting of black and white with a red border Illustrations Simple Detail +a team playing baseball People Simple Detail +children on a couch People Simple Detail +a woman with long hair People Simple Detail +a man standing under a tree People Simple Detail +a smiling man People Simple Detail +an elderly woman People Simple Detail +an old man People Simple Detail +a man with puppet People Simple Detail +a boy going to school People Simple Detail +a girl going to a farm People Simple Detail +a family on a road trip People Simple Detail +a father and a son playing tennis People Simple Detail +a man heading a soccer ball People Simple Detail +a sad man with green hair People Simple Detail +a woman with sunglasses and red hair People Simple Detail +a man looking at a distant mountain People Simple Detail +a woman looking at a house People Simple Detail +a man riding a horse People Simple Detail +a man chasing a cat People Simple Detail +a man chasing a horse People Simple Detail +a pumpkin on a man's head People Simple Detail +an angry man People Simple Detail +a frustrated child People Simple Detail +a laughing woman People Simple Detail +a woman running on a trail People Simple Detail +a boy jumping off a wall People Simple Detail +a girl diving into a pool People Simple Detail +a man banging on a door People Simple Detail +a comic book supervillian Artifacts Simple Detail +Downtown Istanbul at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown Seattle at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown Beijing at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown Rio de Janeiro at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown LA at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown Sydney at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown Sanfrancisco at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown Singapore at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown NYC at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown Austin at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown Shanghai at sunrise. detailed ink wash. World Knowledge Style & Format +Downtown Saigon at sunrise. detailed ink wash. World Knowledge Style & Format +A section of the Great Wall in the mountains. detailed charcoal sketch. World Knowledge Style & Format +The Great Hypostyle Hall of Karnak. detailed charcoal sketch. World Knowledge Style & Format +A Mesoamerican pyramid surrounded by jungle. detailed charcoal sketch. World Knowledge Style & Format +Taj Mahal with its reflection. detailed charcoal sketch. World Knowledge Style & Format +A spaceship made of cardboard. Artifacts Style & Format +A old phonograph made of cardboard. Artifacts Style & Format +A castle made of cardboard. Artifacts Style & Format +A photo of a dragonfly made of water. Animals Style & Format +A photo of a panda made of water. Animals Style & Format +A photo of a teddy bear made of water. Animals Style & Format +A photo of a crocodile made of water. Animals Style & Format +A photo of a lotus flower made of water. Produce & Plants Style & Format +A photo of a maple leaf made of water. Produce & Plants Style & Format +A photo of a palm tree made of water. Produce & Plants Style & Format +A photo of a four-leaf clover made of water. Produce & Plants Style & Format +an abstract oil painting in deep red and black with a thick patches of white Arts Style & Format +light and happiness throughout and finding its way to every corner of the world, abstract oil painting Arts Style & Format +trying to find my way in a big confusing world, abstract oil painting Arts Style & Format +the door of knowing, a portal brightly opening the way through darkness. abstract anime landscape oil painting. Arts Style & Format +A soft beam of light shines down on an armored granite wombat warrior statue holding a broad sword. The statue stands an ornate pedestal in the cella of a temple. wide-angle lens. anime oil painting. Animals Style & Format +Oil painting generated by artificial intelligence Abstract Style & Format +A heavy metal tiger standing on a rooftop while singing and jamming on an electric guitar under a spotlight. anime illustration. Animals Style & Format +A funny Rube Goldberg machine made out of metal World Knowledge Style & Format +A funny Rube Goldberg machine made out of paper World Knowledge Style & Format +A funny Rube Goldberg machine made out of wood World Knowledge Style & Format +Oil painting of a giant robot made of sushi, holding chopsticks. Artifacts Style & Format +Portrait of a gecko wearing a train conductor’s hat and holding a flag that has a yin-yang symbol on it. Charcoal. Animals Style & Format +Portrait of a gecko wearing a train conductor’s hat and holding a flag that has a yin-yang symbol on it. Child's crayon drawing. Animals Style & Format +Portrait of a gecko wearing a train conductor’s hat and holding a flag that has a yin-yang symbol on it. Chinese ink. Animals Style & Format +Portrait of a gecko wearing a train conductor’s hat and holding a flag that has a yin-yang symbol on it. Comic. Animals Style & Format +Portrait of a gecko wearing a train conductor’s hat and holding a flag that has a yin-yang symbol on it. Marble statue. Animals Style & Format +Portrait of a gecko wearing a train conductor’s hat and holding a flag that has a yin-yang symbol on it. Oil on canvas. Animals Style & Format +Portrait of a gecko wearing a train conductor’s hat and holding a flag that has a yin-yang symbol on it. Photograph. Animals Style & Format +Portrait of a gecko wearing a train conductor’s hat and holding a flag that has a yin-yang symbol on it. Watercolor. Animals Style & Format +Portrait of a gecko wearing a train conductor’s hat and holding a flag that has a yin-yang symbol on it. Woodcut. Animals Style & Format +A rusty spaceship blasts off in the foreground. A city with tall skyscrapers is in the distance, with a mountain and ocean in the background. A dark moon is in the sky. realistic high-contrast anime illustration. Vehicles Style & Format +A photo of an Athenian vase with a painting of pandas playing basketball in the style of Egyptian hieroglyphics World Knowledge Style & Format +A photo of an Athenian vase with a painting of pandas playing soccer in the style of Egyptian hieroglyphics World Knowledge Style & Format +A photo of an Athenian vase with a painting of pandas playing tennis in the style of Egyptian hieroglyphics World Knowledge Style & Format +A photo of an Athenian vase with a painting of pangolins playing basketball in the style of Egyptian hieroglyphics World Knowledge Style & Format +A photo of an Athenian vase with a painting of pangolins playing soccer in the style of Egyptian hieroglyphics World Knowledge Style & Format +A photo of an Athenian vase with a painting of pangolins playing tennis in the style of Egyptian hieroglyphics World Knowledge Style & Format +A photo of an Athenian vase with a painting of toucans playing basketball in the style of Egyptian hieroglyphics World Knowledge Style & Format +A photo of an Athenian vase with a painting of toucans playing soccer in the style of Egyptian hieroglyphics World Knowledge Style & Format +A photo of an Athenian vase with a painting of toucans playing tennis in the style of Egyptian hieroglyphics World Knowledge Style & Format +A shiny VW van in front of a cityscape. A smiling sloth stands on grass in front of the van and is wearing a leather jacket, a cowboy hat, a kilt and a bowtie. The sloth is holding a quarterstaff and a big book. High-contrast oil painting. World Knowledge Style & Format +A shiny VW van that has flowers painted on it. A smiling sloth stands on grass in front of the van and is wearing a leather jacket, a cowboy hat, a kilt and a bowtie. The sloth is holding a quarterstaff and a big book. ink sketch. World Knowledge Style & Format +Wood engraving of the Greek letter Omega World Knowledge Style & Format +a satellite image of a costal french city there is a large park on the west side and a mountain to the north. There is a cloud covering part of the image Illustrations Style & Format +A gundam stands tall with its sword raised. A city with tall skyscrapers is in the distance, with a mountain and ocean in the background. A dark moon is in the sky. realistic high-contrast anime illustration. World Knowledge Style & Format +Hokusai's version of Animal Farm Arts Style & Format +A photograph in a temple of a wall painting depicting pandas playing tennis, in the style of Egyptian tomb hieroglyphics World Knowledge Style & Format +an old raccoon wearing a top hat and holding an apple, oil painting in the style of van gogh Arts Style & Format +portrait of a well-dressed raccoon, oil painting in the style of Rembrandt Arts Style & Format +close-up portrait of a smiling businesswoman holding a cell phone, oil painting in the style of Rembrandt People Style & Format +a portrait of a man wearing sunglasses and a business suit, painting in pop art style People Style & Format +a sport car melting into a clock, surrealist painting in the style of Salvador Dali Arts Style & Format +a stained glass window depicting a calm tyrannosaurus rex Illustrations Style & Format +a tennis match in the style of Egyptian hieroglyphic tomb paintings World Knowledge Style & Format +vibrant portrait painting of Salvador Dalí with a robotic half face People Style & Format DALL-E 2 +an espresso machine that makes coffee from human souls, high-contrast painting Artifacts Style & Format DALL-E 2 +panda mad scientist mixing sparkling chemicals, high-contrast painting Animals Style & Format DALL-E 2 +a dolphin in an astronaut suit on saturn, high-contrast painting Animals Style & Format DALL-E 2 +The Oriental Pearl in sketch style World Knowledge Style & Format CogView +The Oriental Pearl in Chinese painting World Knowledge Style & Format CogView +The Oriental Pearl in oil painting World Knowledge Style & Format CogView +a capybara made of voxels sitting in a field Animals Style & Format DALL-E +an emoji of a baby penguin wearing a blue hat, red gloves, green shirt, and yellow pants Illustrations Style & Format DALL-E +a professional high quality emoji of a lovestruck cup of boba Illustrations Style & Format DALL-E +a dutch baroque painting of a horse in a field of flowers Arts Style & Format +Icon of a red heart Illustrations Style & Format VQ-Diffusion +A cartoon house with red roof Illustrations Style & Format VQ-Diffusion +A cartoon tiger face Animals Style & Format VQ-Diffusion +Face of an orange frog in cartoon style Animals Style & Format VQ-Diffusion +A vector illustration of a tree Illustrations Style & Format VQ-Diffusion +an abstract painting of the Empire State Building World Knowledge Style & Format +an abstract painting of the Sydney Opera House World Knowledge Style & Format +a painting of a white country home with a wrap-around porch Outdoor Scenes Style & Format +an oil painting of a cat playing checkers Arts Style & Format +a surrealist dream-like oil painting by salvador dalí of a cat playing checkers Arts Style & Format GLIDE +an oil painting of a hamster dragon Arts Style & Format GLIDE +a high-quality oil painting of a psychedelic hamster dragon Arts Style & Format GLIDE +a painting of a fox in the style of starry night Arts Style & Format GLIDE +a stained glass window of a panda eating bamboo Artifacts Style & Format GLIDE +a crayon drawing of a space elevator Vehicles Style & Format GLIDE +a futuristic city in synthwave style Outdoor Scenes Style & Format GLIDE +a pixel art corgi pizza Illustrations Style & Format GLIDE +a green clock in the shape of a pentagon Artifacts Style & Format DALL-E +a painting of a phone from the 20s Artifacts Style & Format DALL-E +a painting of the food of china Food & Beverage Style & Format DALL-E +a photograph of a bust of homer People Style & Format DALL-E +a drawing of a bust of homer People Style & Format DALL-E +an armchair in the shape of an avocado Artifacts Style & Format DALL-E +a painting of the skyline of New York City World Knowledge Style & Format +a drawing of the skyline of New York City World Knowledge Style & Format +a cartoon of a train going to the moon Vehicles Style & Format +a cartoon of a cow jumping over the moon Animals Style & Format +orange jello in the shape of a man Food & Beverage Style & Format +a comic about a friendly car in the city Artifacts Style & Format +a painting of street in Paris World Knowledge Style & Format +a painting of a canal in Venice World Knowledge Style & Format +an abstract painting with blue, red and black Arts Style & Format +an abstract painting of a waterfall Arts Style & Format +an abstract painting of a spaceship Arts Style & Format +an abstract painting of a pond with a bridge Arts Style & Format +a cartoon of an angry shark Animals Style & Format +a cartoon of a happy car on the road Vehicles Style & Format +a cartoon of a bear birthday party Animals Style & Format +a drawing of a house on a mountain Arts Style & Format +a cartoon of a house on a mountain Illustrations Style & Format +a painting of a house on a mountain Arts Style & Format +an abstract painting of a house on a mountain Arts Style & Format +a painting of a peaceful lakeside landscape Arts Style & Format +a drawing of a peaceful lakeside landscape Arts Style & Format +a map of Australia World Knowledge Style & Format +a map of Italy World Knowledge Style & Format +a map of South America World Knowledge Style & Format +a map of Texas World Knowledge Style & Format +a map of Manhattan World Knowledge Style & Format +an impressionistic painting of tree and a building Arts Style & Format +an abstract painting of a tree and a building Arts Style & Format +a watercolor painting of a tree and a building Arts Style & Format +an oil painting of a tree and a building Arts Style & Format +an abstract painting of three triangles in blue, red and white Arts Style & Format +an abstract painting of three triangles in blue, yellow and red Arts Style & Format +an abstract painting of three squares in blue, red and white Arts Style & Format +an abstract painting of three squares in blue, yellow and red Arts Style & Format +a painting of a cute owl on a box Arts Style & Format +a horse in a field in Minecraft style Animals Style & Format +a drawing of a pig face with an eye patch Illustrations Style & Format +a drawing of a hammer Illustrations Style & Format +a drawing of a screwdriver Illustrations Style & Format +a drawing of a handsaw Illustrations Style & Format +a drawing of a power drill Illustrations Style & Format +a cloud in the shape of a teacup Outdoor Scenes Style & Format +a cloud in the shape of a elephant Outdoor Scenes Style & Format +a cloud in the shape of a castle Outdoor Scenes Style & Format +a footprint shaped like a peanut Artifacts Style & Format +a drawing of a stork playing a violin Illustrations Style & Format +The Statue of Liberty in Minecraft World Knowledge Style & Format +An oil painting of the Statue of Liberty World Knowledge Style & Format +An abstract painting of the Statue of Liberty World Knowledge Style & Format +a diagram of brain function Illustrations Style & Format +a diagram of the human digestive system Illustrations Style & Format +a diagram of a suburban house Illustrations Style & Format +a stop sign with a blue background Artifacts Style & Format +a painting of a sport car in the style of Monet Arts Style & Format +a painting of a sport car in the style of Dali Arts Style & Format +a drawing of a space shuttle in the style of da Vinci Arts Style & Format +a coloring book page of a horse next to a stream Artifacts Style & Format +a sketch of a horse Illustrations Style & Format +a sketch of a skyscraper Illustrations Style & Format +a sketch of a train Illustrations Style & Format +a sketch of a camel next to a stream Illustrations Style & Format +a diagram of the star constellations Illustrations Style & Format +a thumbnail image of an ice cream cone Illustrations Style & Format +a thumbnail image of a horse and cart Illustrations Style & Format +background pattern with alternating roses and skulls Illustrations Style & Format +graffiti of a funny dog on a street wall Illustrations Style & Format +graffiti of a rocket ship on a brick wall Illustrations Style & Format +a watercolor painting of a snowy owl standing in a grassy field Arts Style & Format +a cute illustration of a horned owl with a graduation cap and diploma Illustrations Style & Format +a cardboard spaceship Vehicles Style & Format +the flag of the United Kingdom painted in rusty corrugated iron World Knowledge Style & Format +a diagram of the solar system Illustrations Style & Format +a drawing of a pint of beer on a brick wall Illustrations Style & Format +an abstract painting of the lights at Times Square World Knowledge Style & Format +an abstract drawing of the Great Wall World Knowledge Style & Format +a diagram of the Great Wall World Knowledge Style & Format +a map showing the Great Wall World Knowledge Style & Format +a still life painting of a pair of shoes Artifacts Style & Format +an impressionist painting of the geyser Old Faithful World Knowledge Style & Format +a diagram of how the geyser Old Faithful works World Knowledge Style & Format +an abstract painting of the Great Pyramid World Knowledge Style & Format +a diagram of the inside of the Great Pyramid World Knowledge Style & Format +the silhouette of the Milllenium Wheel at dusk World Knowledge Style & Format +a painting of ten children on a couch People Style & Format +a painting of a man standing on a street corner People Style & Format +a painting of a man standing under a tree People Style & Format +a drawing of a man standing under a tree People Style & Format +a cartoon of a man standing under a tree People Style & Format +a comic about a boy going to school People Style & Format +a comic about a girl going to a farm People Style & Format +a comic about a boy and a tiger People Style & Format +a comic about a family on a road trip People Style & Format +a comic about a father and a son playing tennis People Style & Format +a cartoon of a boy playing with a tiger People Style & Format +the mona lisa People Style & Format +a painting of the Mona Lisa with a frown People Style & Format +a painting of the Mona Lisa with New York City behind her People Style & Format +the Mona Lisa in the style of Minecraft People Style & Format +a thumbnail image of a person skiing People Style & Format +a thumbnail image of a gingerbread man Illustrations Style & Format +the cover of The Beatle's album Revolver World Knowledge Style & Format +the saying "BE EXCELLENT TO EACH OTHER" on a rough wall with a graffiti image of a green alien wearing a tuxedo. Outdoor Scenes Writing & Symbols +A green sign that says "Very Deep Learning" and is at the edge of the Grand Canyon. World Knowledge Writing & Symbols +Portrait of a tiger wearing a train conductor's hat and holding a skateboard that has a yin-yang symbol on it. charcoal sketch Animals Writing & Symbols +Portrait of a tiger wearing a train conductor's hat and holding a skateboard that has a yin-yang symbol on it. child's crayon drawing Animals Writing & Symbols +Portrait of a tiger wearing a train conductor's hat and holding a skateboard that has a yin-yang symbol on it. Chinese ink and wash painting Animals Writing & Symbols +Portrait of a tiger wearing a train conductor's hat and holding a skateboard that has a yin-yang symbol on it. color ink-and-wash drawing Animals Writing & Symbols +Portrait of a tiger wearing a train conductor's hat and holding a skateboard that has a yin-yang symbol on it. comic book illustration Animals Writing & Symbols +Portrait of a tiger wearing a train conductor's hat and holding a skateboard that has a yin-yang symbol on it. marble statue Animals Writing & Symbols +Portrait of a tiger wearing a train conductor's hat and holding a skateboard that has a yin-yang symbol on it. oil painting Animals Writing & Symbols +Portrait of a tiger wearing a train conductor's hat and holding a skateboard that has a yin-yang symbol on it. photograph Animals Writing & Symbols +Portrait of a tiger wearing a train conductor's hat and holding a skateboard that has a yin-yang symbol on it. woodcut Animals Writing & Symbols +Two cups of coffee, one with latte art of a map of United States. The other has latte art of a map of Africa. World Knowledge Writing & Symbols +Two cups of coffee, one with latte art of a lovely princess. The other has latte art of a frog. Food & Beverage Writing & Symbols +Two cups of coffee, one with latte art of a heart. The other has latte art of stars. Food & Beverage Writing & Symbols +Two cups of coffee, one with latte art of the Eiffel tower. The other has latte art of the Statue of Liberty. Food & Beverage Writing & Symbols +A sign that says Deep Learning Artifacts Writing & Symbols +A bar of chocolate without a wrapper that has the word "WRAPPER" printed on it. Artifacts Writing & Symbols +A glass of red wine tipped over on a couch, with a stain that writes "OOPS" on the couch. Indoor Scenes Writing & Symbols +Two cups of coffee, one with latte art of yin yang symbol. The other has latte art of a heart. Food & Beverage Writing & Symbols +"G I G G L E" painted in thick colorful lettering as graffiti on a faded red brick wall with a splotch of exploding white paint. Illustrations Writing & Symbols +high-contrast image of the word "WOMBAT" written with thick colored graffiti letters on a white wall with dramatic splashes of paint Illustrations Writing & Symbols +A plush monkey fording the Charles River on a log while wearing a Boston Red Sox hat with MIT in the background. World Knowledge Writing & Symbols +the letters P A X forming a very simple outline of an elephant's shape. the elephant is facing left. vector art, orange logo. Illustrations Writing & Symbols +A burger patty, with the bottom bun and lettuce and tomatoes. "COFFEE" written on it in mustard Food & Beverage Writing & Symbols +Two cups of coffee, one with latte art of the words "LOVE" written in one. The other has latte art of the words "PEACE" written in the other. Artifacts Writing & Symbols +The saying "BE EXCELLENT TO EACH OTHER" written in a stained glass window. Illustrations Writing & Symbols +The saying "BE EXCELLENT TO EACH OTHER" written in faded paint on the hull of an old wooden boat and reflected in the water. Wide-angle lens. Illustrations Writing & Symbols +The saying "BE EXCELLENT TO EACH OTHER" written on a red brick wall with a graffiti image of a green alien wearing a tuxedo. A yellow fire hydrant is on a sidewalk in the foreground. Illustrations Writing & Symbols +The saying "BE EXCELLENT TO EACH OTHER" written with carved letters on driftwood. Illustrations Writing & Symbols +a hot air balloon with chameleon logo. the sun is shining and puffy white clouds are in the background. Vehicles Writing & Symbols +A portrait photo of a kangaroo wearing an orange hoodie and blue sunglasses standing on the grassin front of the Sydney Opera House holding a sign on the chest that says Welcome Friends! World Knowledge Writing & Symbols +Anime illustration of a kangaroo holding a sign that says "Starry Night", in front of the Sydney Opera House sitting next to the Eiffel Tower under a blue night sky of roiling energy, exploding yellow stars, and radiating swirls of blu World Knowledge Writing & Symbols +a group of cats in a meeting. there is a whiteboard with "stack more layers" written on it. Indoor Scenes Writing & Symbols +A high contrast portrait photo of a fluffy hamster wearing an orange beanie and sunglasses holding a sign that says "Let's PAINT!" Animals Writing & Symbols +a cartoon of a dog saying "I see what you did there" Animals Writing & Symbols +a robot holding a sign with "Let's PAINT!" written on it Artifacts Writing & Symbols +a dog wearing a baseball cap backwards and writing BONEZ on a chalkboard Animals Writing & Symbols +graffiti spelling BE KIND on white subway tile Illustrations Writing & Symbols +a grumpy porcupine handing a check for $10,000 to a smiling peacock Animals Writing & Symbols +a boat with 'BLUE GROOVE' written on its hull Vehicles Writing & Symbols +a store front that has the word ‘openai’ written on it. Outdoor Scenes Writing & Symbols DALL-E +a laptop with a maze sticker on it Artifacts Writing & Symbols +a yellow t-shirt with a dog on it Artifacts Writing & Symbols +a blue t-shirt with a dinosaur on it Artifacts Writing & Symbols +a bowl with a dinosaur on it Artifacts Writing & Symbols +a bowl with a cartoon dinosaur on it Artifacts Writing & Symbols +a flag with a dinosaur on it Illustrations Writing & Symbols +a flag with a drawing of a dinosaur on it Artifacts Writing & Symbols +a flag with three vertical stripes Illustrations Writing & Symbols +a flag with three vertical stripes that are blue, white and red Illustrations Writing & Symbols +a white towel with a cartoon of a cat on it Artifacts Writing & Symbols +a black towel with a cartoon of a dog on it Artifacts Writing & Symbols +a yellow wall with the word KA-BOOM on it Artifacts Writing & Symbols +a cat sitting on a box with a drawing of an elephant on it Animals Writing & Symbols +the word 'mardefly' on a coffee mug Artifacts Writing & Symbols +a stop sigh with 'ALL WAY' written below it Artifacts Writing & Symbols +a sticker stuck in the middle of a stop sign Artifacts Writing & Symbols +world's best brother t-shirt Artifacts Writing & Symbols +the cover of a book called 'Backpropaganda' by I.C. Gradients Illustrations Writing & Symbols +the saying 'do unto others as they would do unto you' written on a white background Artifacts Writing & Symbols +a t-shirt with Carpe Diem written on it Artifacts Writing & Symbols +a sweatshirt with 'Batch Norm' written on it Artifacts Writing & Symbols +a yellow sticky note with 'BUY MILK' written on it Artifacts Writing & Symbols +a large open book showing text and an illustration of a cat Artifacts Writing & Symbols +a yellow wall with 'Hello, world.' written on it Indoor Scenes Writing & Symbols +a motorcycle parked in an ornate bank lobby with "BUZZ" written on its body Vehicles Writing & Symbols +a logo of a wombat on a coffee mug Artifacts Writing & Symbols +a coffee mug with an ankh symbol on it Artifacts Writing & Symbols +a t-shirt with 'ANKH' written on it Artifacts Writing & Symbols +a t-shirt with 'Archaelogy Rocks!' written on it Artifacts Writing & Symbols +a black t-shirt with the peace sign on it Artifacts Writing & Symbols +a store front with 'Grassy Meadow' written on it Outdoor Scenes Writing & Symbols +a store front with 'AwesomePurchase' written on it Outdoor Scenes Writing & Symbols +a laptop screen showing an internet search Artifacts Writing & Symbols +a laptop screen showing a bunch of photographs Artifacts Writing & Symbols +a laptop screen showing a document being edited Artifacts Writing & Symbols +a book with the words 'Don't Panic!' written on it Artifacts Writing & Symbols +the words 'KEEP OFF THE GRASS' Illustrations Writing & Symbols +the words 'KEEP OFF THE GRASS' written on a brick wall Indoor Scenes Writing & Symbols +the words 'KEEP OFF THE GRASS' on a black sticker Illustrations Writing & Symbols +the words 'KEEP OFF THE GRASS' on a sign next to a lawn Outdoor Scenes Writing & Symbols +the word 'START' Illustrations Writing & Symbols +the word 'START' written on a street surface Illustrations Writing & Symbols +the word 'START' on a blue t-shirt Artifacts Writing & Symbols +the word 'START' written above the word 'SMILING' Illustrations Writing & Symbols +the word 'START' written in chalk on a sidewalk Outdoor Scenes Writing & Symbols +a wooden post with a yellow '3' painted on top Outdoor Scenes Writing & Symbols +a wooden post in front of a patch of tall grass Outdoor Scenes Writing & Symbols +a wooden post with a blue '5' painted on top Outdoor Scenes Writing & Symbols +a series of musical notes on a black t-shirt Artifacts Writing & Symbols +a series of musical notes on a computer screen Artifacts Writing & Symbols diff --git a/sjdtree/data/prompts/SJDPrompts.tsv b/sjdtree/data/prompts/SJDPrompts.tsv new file mode 100644 index 0000000000000000000000000000000000000000..acc3c7e54596fbe96bac55629f41c55f794ad0e7 --- /dev/null +++ b/sjdtree/data/prompts/SJDPrompts.tsv @@ -0,0 +1,11 @@ +Prompt +A hawk-man with a red head +A masterpiece of oil painting about the starry sky +Macro photography of a transparent water drop in the shape of a cat. +A Corgi dog in 2D logo style, simple texture, clean background, facial- and eye-symmetry. +Most beautiful anime artwork, a most cute anime girl, double exposure, iridescent nebula galaxy, black background, ethereal glow, bloom, hdr, high-quality, 8K +A cool furry black monkey meditates on the clean wet ground, in the dusk, the golden sunset is shining on the ground on one side and the other side, high-quality, 8K, facial-symmetry +a cool man with a beautiful face wearing a yellow suit stands in the Mountain, the most Professional high-quality 8K photograph +Most beautiful girl (with deep red iris, short white hair, and a sly smile) wearing purple clothes and a hood. eye-symmetry, facial-symmetry, 8K, high quality, realistic +a giant golden flying saucer firing lasers from the bottom, scorching the ground, the most Fantasy high-quality photos +one typical zebra's upper body in the grassland, not occluded by grass, the zebra has only two ears, clear striped pattern, the most Professional high-quality 8K photograph, clear texture, sharp-focus, Exquisite details \ No newline at end of file diff --git a/sjdtree/environment.yaml b/sjdtree/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3dc1f3d94f5f5f14b0cfdebbfec4a867626906e5 --- /dev/null +++ b/sjdtree/environment.yaml @@ -0,0 +1,98 @@ +name: mgpt +channels: + - pytorch + - defaults +dependencies: + - pip=24.2=py310h06a4308_0 + - python=3.10.16=he870216_1 + - pip: + - absl-py==2.1.0 + - accelerate==1.2.1 + - args==0.1.0 + - attrs==25.1.0 + - braceexpand==0.1.7 + - certifi==2024.12.14 + - charset-normalizer==3.4.0 + - clint==0.5.1 + - contourpy==1.3.1 + - cycler==0.12.1 + - diffusers==0.31.0 + - einops==0.8.0 + - exceptiongroup==1.2.2 + - filelock==3.13.1 + - fonttools==4.55.7 + - fsspec==2024.2.0 + - ftfy==6.3.1 + - grpcio==1.70.0 + - hpsv2==1.2.0 + - huggingface-hub==0.27.0 + - idna==3.10 + - importlib-metadata==8.5.0 + - iniconfig==2.0.0 + - jinja2==3.1.3 + - kiwisolver==1.4.8 + - lightning-utilities==0.11.9 + - markdown==3.7 + - markupsafe==2.1.5 + - matplotlib==3.10.0 + - ml-collections==1.0.0 + - mpmath==1.3.0 + - networkx==3.2.1 + - numpy==1.26.3 + - nvidia-cublas-cu12==12.4.5.8 + - nvidia-cuda-cupti-cu12==12.4.127 + - nvidia-cuda-nvrtc-cu12==12.4.127 + - nvidia-cuda-runtime-cu12==12.4.127 + - nvidia-cudnn-cu12==9.1.0.70 + - nvidia-cufft-cu12==11.2.1.3 + - nvidia-curand-cu12==10.3.5.147 + - nvidia-cusolver-cu12==11.6.1.9 + - nvidia-cusparse-cu12==12.3.1.170 + - nvidia-nccl-cu12==2.21.5 + - nvidia-nvjitlink-cu12==12.4.127 + - nvidia-nvtx-cu12==12.4.127 + - packaging==24.2 + - pandas==2.2.3 + - pillow==10.2.0 + - pluggy==1.5.0 + - protobuf==3.20.3 + - psutil==6.1.0 + - pyarrow==19.0.0 + - pycocotools==2.0.8 + - pyparsing==3.2.1 + - pytest==7.2.0 + - pytest-split==0.8.0 + - python-dateutil==2.9.0.post0 + - pytorch-fid==0.3.0 + - pytz==2024.2 + - pyyaml==6.0.2 + - regex==2024.11.6 + - requests==2.32.3 + - safetensors==0.4.5 + - scipy==1.15.1 + - sentencepiece==0.2.0 + - six==1.17.0 + - sympy==1.13.1 + - tensorboard==2.18.0 + - tensorboard-data-server==0.7.2 + - tensorboardx==2.6.2.2 + - tiktoken==0.9.0 + - timm==1.0.14 + - tokenizers==0.21.0 + - tomli==2.2.1 + - torch==2.5.1+cu124 + - torch-fidelity==0.3.0 + - torchaudio==2.5.1+cu124 + - torchmetrics==1.6.1 + - torchvision==0.20.1+cu124 + - tqdm==4.67.1 + - transformers==4.47.1 + - triton==3.1.0 + - typing-extensions==4.9.0 + - tzdata==2025.1 + - urllib3==2.2.3 + - wcwidth==0.2.13 + - webdataset==0.2.100 + - werkzeug==3.1.3 + - zipp==3.21.0 + - tiktoken==0.9.0 \ No newline at end of file diff --git a/sjdtree/eval_model.py b/sjdtree/eval_model.py new file mode 100644 index 0000000000000000000000000000000000000000..50ed230b07aac03c1c81dd0a40987c29d15565a7 --- /dev/null +++ b/sjdtree/eval_model.py @@ -0,0 +1,195 @@ +import os +from torch import multiprocessing as mp + +from torchvision.utils import save_image + +from argparse import ArgumentParser +import time +import multiprocessing + +from dataset_tools.multi_gpu_infer_with_prompt import _run_on_multiple_gpus + +from absl import logging +from utils import set_logger + +if __name__ == "__main__": + + # set start method as 'spawn' to avoid CUDA re-initialization issues + multiprocessing.set_start_method('spawn') + + parser = ArgumentParser() + parser.add_argument("-v", "--verbose", action="store_true") + + parser.add_argument("--multiprocess", action="store_true") + parser.add_argument("--gpu_ids", type=lambda x: [int(i) for i in x.split(",")], default=[0]) + + parser.add_argument( + "--cache_dir", + type=str, + default=None, + help="The directory to store the cache files." + ) + + parser.add_argument( + "--node_id", + type=int, + default=0, + help="Node ID for distributed inference." + ) + + parser.add_argument( + "--node_ids", + type=lambda x: [int(i) for i in x.split(",")], + default=[0], + help="Node IDs for distributed inference, separated by commas." + ) + + parser.add_argument( + "--dataset_name", + type=str, + default="coco", + ) + parser.add_argument( + "--dataset_anno_file", + type=str, + default="./data/prompts/captions_val2017.json", + ) + + parser.add_argument( + "--model_name", + type=str, + default="leloy/Anole-7b-v0.1-hf", + ) + + parser.add_argument( + "--max_num_new_tokens", + type=int, + default=16, + ) + + parser.add_argument( + "--multi_token_init_scheme", + type=str, + default='random', # sample_horizon sample_vertical # '2d_repeat' 'random' #'2d_extrapolation', #'repeat_last' # '1d_extrapolation' + ) + + parser.add_argument( + "--seed", + type=int, + default=42, + ) + + parser.add_argument( + "--image_top_k", + type=int, + default=2000, + ) + + parser.add_argument( + "--target_size", + type=int, + default=1024, + ) + + parser.add_argument( + "--prefix_token_sampler_scheme", + type=str, + default='speculative_jacobi', + ) + + parser.add_argument( + "--guidance_scale", + type=float, + default=3.0, + ) + + parser.add_argument( + "--output_dir", + type=str, + default="/home/leihaodong/AAAI25/exp/SJD", + ) + + parser.add_argument( + "--temperature", + type=float, + default=1.0, + ) + + parser.add_argument( + "--num_images", + type=int, + default=1, + ) + + parser.add_argument( + "--tokenizer_path", + default='/data/lei/localmodel/lumina_mgpt/chameleon/tokenizer', + type=str, help="location of the reference images for evaluation" + ) + + parser.add_argument("--return_accl",default=True,type=bool) + + args = parser.parse_args() + + start_time = time.time() + + max_num_new_tokens = args.max_num_new_tokens + multi_token_init_scheme = args.multi_token_init_scheme + seed = args.seed if args.seed >=0 else None + model_name = args.model_name + dataset_name = args.dataset_name + guidance_scale = args.guidance_scale #3.0 + image_top_k = args.image_top_k + prefix_token_sampler_scheme = args.prefix_token_sampler_scheme + + num_images = args.num_images + + if args.target_size > 0: + target_size = args.target_size + else: + potential_target_size = model_name.split("-")[-1] + if potential_target_size.isdigit(): + target_size = int(potential_target_size) + else: + target_size = 512 + + workdir = args.output_dir + if not os.path.exists(workdir): + os.makedirs(workdir) + + set_logger(log_level='info', fname=os.path.join(workdir, 'gen_img_output.log')) + + + logging.info(f"cache dir: {args.cache_dir}") + logging.info(f"gpu_ids: {args.gpu_ids}") + logging.info(f"node_ids: {args.node_ids}") + logging.info(f"target_size: {target_size}") + + _run_on_multiple_gpus( + gpu_ids=args.gpu_ids, + node_ids=args.node_ids, + node_id=args.node_id, + \ + dataset_params = dict( + name = args.dataset_name, + annFile = args.dataset_anno_file, + data_len = num_images + ), + model_name = args.model_name, + \ + cache_dir = args.cache_dir, + target_size = target_size, + seed = seed, + max_num_new_tokens = max_num_new_tokens, + multi_token_init_scheme = multi_token_init_scheme, + guidance_scale = guidance_scale, + image_top_k=image_top_k, + max_gen_len=8192, + temperature=args.temperature, + output_dir = workdir, + prefix_token_sampler_scheme = prefix_token_sampler_scheme, + local_chameleon_tokenizer_path = args.tokenizer_path, + return_accl = args.return_accl + ) + end_time = time.time() + logging.info(f"Total Time taken: {end_time - start_time}") \ No newline at end of file diff --git a/sjdtree/main.py b/sjdtree/main.py new file mode 100644 index 0000000000000000000000000000000000000000..fbca5ce7bf64d70e159c241a7c43679af470cb4d --- /dev/null +++ b/sjdtree/main.py @@ -0,0 +1,306 @@ +import argparse +import os +import sys +sys.path.append("./lumina_mgpt/") +sys.path.append("./") +# print(sys.path) + +import gc + +from lumina_mgpt.inference_solver import FlexARInferenceSolver +from PIL import Image +import torch +import time + +import random +import numpy as np + +import json, csv +import re + +import lumina_mgpt.data.drafters.choices as choices + +def set_seed(seed: int): + """ + Args: + Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch`. + seed (`int`): The seed to set. + """ + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + +def load_prompts(args): + prompts = [] + output_file_name_list = [] + if args.prompt == "PartiPrompts": + with open('data/prompts/PartiPrompts.tsv', 'r') as f: + tsv_reader = csv.DictReader(f, delimiter='\t') + ids = 0 + for row in tsv_reader: + prompts.append(row['Prompt']) + output_file_name_list.append(ids) + ids += 1 + elif args.prompt == "MSCOCO2017Val": + from pycocotools.coco import COCO + coco = COCO("data/prompts/captions_val2017.json") + top_k = 0 + for i in range(args.num_images): + img_id = coco.getImgIds()[i] + img_name = coco.loadImgs(img_id)[0] + ann_ids = coco.getAnnIds(imgIds=img_id) + anns = coco.loadAnns(ann_ids) + for j, ann in enumerate(anns): + ann_id = ann['id'] + caption = ann["caption"] + prompts.append(caption) + output_file_name_list.append(ann_id) + if j == top_k: + break + elif args.prompt == "MSCOCO2014Val": + with open('data/prompts/captions_val_2014.json', 'r') as f: + captions = json.load(f) + for caption in captions: + prompts.append(caption) + elif args.prompt == "MSCOCO2017Train": + with open('data/prompts/captions_train2017_extracted.json', 'r') as f: + captions = json.load(f) + for caption in captions: + prompts.append(caption['caption']) + elif args.prompt == "SJDPrompts": + with open('data/prompts/SJDPrompts.tsv', 'r') as f: + tsv_reader = csv.DictReader(f, delimiter='\t') + for row in tsv_reader: + prompts.append(row['Prompt']) + elif args.prompt == "T2ICompBenchVal": + with open("data/prompts/T2I-CompBench_val.json", "r", encoding="utf-8") as f: + data = json.load(f) + for line in data: + # 每行是一个独立的JSON对象,逐行解析 + prompts.append(line['caption']) + output_file_name_list.append(line['image_id']) + else: + # Single prompt input + prompts = [args.prompt] * args.num_images + + if args.slice is not None: + assert re.match(r'^\d+-\d+$', args.slice), f"Invalid format: '{args.slice}'. Expected format is 'start-end'." + + start, end = map(int, args.slice.split('-')) + assert start < end, f"Invalid range: '{args.slice}'. Start value must be less than end value." + assert start >= 0 and end >= 0, "Slice values must be non-negative." + + prompts = prompts[start:end] + output_file_name_list = output_file_name_list[start:end] + + if args.num_images < len(prompts): + print(f"Number of images to generate is less than the number of prompts. Sampling {args.num_images} prompts.") + if args.benchmark_way == "random": + prompts = random.sample(prompts, args.num_images) + else: + prompts = prompts[:args.num_images] + output_file_name_list = output_file_name_list[:args.num_images] + else: + print(f"Number of images to generate is greater than the number of prompts. Generating only {len(prompts)} images and no sampling.") + pass + + return prompts,output_file_name_list + +def main(args): + static_tree = args.static_tree + tree_choices = args.tree_choices + lantern_delta = args.lantern_delta + groupsum_delta = args.groupsum_delta + threshold = args.sjd_pp_threshold + try: + tree_choices = getattr(choices, args.tree_choices) + except AttributeError: + print(f"Tree choices {args.tree_choices} is not a valid choice") + return + # ******************** Args Initation ******************** + model_path = args.model_path + target_size = args.target_size + target_size_h, target_size_w = target_size, target_size + device = "cuda:0" + # TODO: 修改你的本地chameleon + local_chameleon_tokenizer_path=args.tokenizer_path + # TODO: 修改你的本地输出地址 + output_path = args.output_path + output_img_path = os.path.join(output_path,"img") + if not os.path.exists(output_path): + os.makedirs(output_path) + if not os.path.exists(output_img_path): + os.makedirs(output_img_path) + + # ******************** Input Initation ******************** + inference_solver = FlexARInferenceSolver( + model_path=model_path, + precision="bf16", + target_size=target_size, + device = device, + local_chameleon_tokenizer_path = local_chameleon_tokenizer_path + ) + + seeds = [None, ] #[_ for _ in range(124, 200) ] + max_num_new_tokens = args.num_init_new_token # 16 + multi_token_init_scheme = args.isp # 'repeat_horizon' random + image_top_k = 2000 + text_top_k = 10 + guidance_scale = 3.0 + prefix_token_sampler_scheme = args.method # 'jacobi', 'speculative_jacobi' + + # ******************** Load Benchmark ******************** + + prompts,output_file_name_list = load_prompts(args) + + template_condition_sentences = [ + f"Generate an image of {target_size_w}x{target_size_h} according to the following prompt:\n", + ] * len(prompts) + + # ******************** Image Generation ******************** + from scheduler.jacobi_iteration_lumina_mgpt import renew_pipeline_sampler + inference_solver = renew_pipeline_sampler( + inference_solver, + jacobi_loop_interval_l = 3, + jacobi_loop_interval_r = (target_size // 16)**2 + target_size // 16 - 10, + max_num_new_tokens = max_num_new_tokens, + guidance_scale = guidance_scale, + seed = seeds[0], + multi_token_init_scheme = multi_token_init_scheme, + do_cfg= True, + image_top_k=image_top_k, + text_top_k=text_top_k, + prefix_token_sampler_scheme = prefix_token_sampler_scheme, + local_chameleon_tokenizer_path = local_chameleon_tokenizer_path, + static_tree = static_tree, + ) + time_avg = 0 + time_avg_forward = 0 + avg_acceptance_length = 0 + gen_count = 0 + with open(f"{output_path}/generation_configs.json", "w") as f: + json.dump(vars(args), f, indent=4) + + global_statistics = {} + + for seed in seeds: + inference_solver.model.seed = seed + for i, q_image_content_condition in enumerate(prompts): + q1 = template_condition_sentences[i] + q_image_content_condition + + output_file_name = str(output_file_name_list[i]) + ".png" + + time_start = time.time() + t1 = torch.cuda.Event(enable_timing=True) + t2 = torch.cuda.Event(enable_timing=True) + torch.cuda.synchronize() + t1.record() + + result = inference_solver.generate( + images=[], + qas=[[q1, None]], + max_gen_len=8192, + temperature=1.0, + logits_processor=inference_solver.create_logits_processor(cfg=guidance_scale, image_top_k=image_top_k, static_tree = static_tree), + return_accl=True, + # for static tree + static_tree = static_tree, + tree_choices = tree_choices, + lantern_delta = lantern_delta, + groupsum_delta = groupsum_delta, + threshold = threshold + ) + generated = result.input_ids + + t2.record() + torch.cuda.synchronize() + + t = t1.elapsed_time(t2) / 1000 + time_end = time.time() + + a1, new_image = generated[0], generated[1][0] + + result_image = inference_solver.create_image_grid([new_image], 1, 1) + result_image.save(os.path.join(output_img_path,output_file_name)) + + time_forward = result.time_forward + token_gen_len = result.token_gen_len + loop_num = result.loop_num + acceptance_length = token_gen_len / loop_num + avg_acceptance_length += acceptance_length + statistics = { + "prompt": q_image_content_condition, + "time": time_forward, + "acceptance_length": acceptance_length, + "loop_num": loop_num, + "Time elapsed cuda": t, + "Time elapsed": time_end - time_start, + "ann_id": output_file_name_list[i] + } + + global_statistics[f"prompt_{i}"] = statistics + time_avg += t / len(seeds) + time_avg_forward += time_forward + with open(f"{args.output_path}/result_{args.slice}.json", "w") as f: + json.dump(global_statistics, f, indent=4) + gen_count += 1 + avg_acceptance_length = avg_acceptance_length/gen_count + time_avg = time_avg/gen_count + time_avg_forward = time_avg_forward/gen_count + statistics = { + "method":f"{prefix_token_sampler_scheme}_{multi_token_init_scheme}_{max_num_new_tokens}", + "avg_acceptance_length":avg_acceptance_length, + "time_forward_avg":time_avg_forward, + "time_avg":time_avg, + } + global_statistics[f"summary"] = statistics + with open(f"{args.output_path}/result_{args.slice}.json", "w") as f: + json.dump(global_statistics, f, indent=4) + print("Average time per generation: ", time_avg) + del inference_solver + gc.collect() + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--model_path", default="Alpha-VLLM/Lumina-mGPT-7B-768",type=str, help="location of fake images for evaluation") + parser.add_argument("--tokenizer_path", default='/data/lei/localmodel/lumina_mgpt/chameleon/tokenizer',type=str, help="location of the reference images for evaluation") + parser.add_argument("--output_path", default='/home/leihaodong/AAAI25/exp/FSJD',type=str) + parser.add_argument("--target_size", type=int, default=768) + + parser.add_argument("--isp", default='random', type=str,help="repeat_horizon, random") + parser.add_argument("--method", default='speculative_jacobi', type=str,help="'jacobi', 'speculative_jacobi'") + parser.add_argument("--num_init_new_token", type=int, default=16) + + parser.add_argument("--benchmark_way", default='order', type=str, help="order or sample",) + parser.add_argument("--prompt", type=str, help="Prompt for image generation", + default="Atlantis, the most Fantasy high-quality photos") + parser.add_argument("--num_images", type=int, help="Number of images to generate", + default=2) + parser.add_argument("--slice", type=str, help="Slice of prompts to use; format: 'start-end'", + default=None) + + #Tree + parser.add_argument("--static_tree", action="store_true", help="Enable static tree structure for draft token generation") + # Experimental arguments + parser.add_argument("--tree_choices", type=str, help="Tree choice for LANTERN", + default="mc_sim_7b_63") + + #lantern + parser.add_argument("--lantern_delta", type=int, help="Delta for LANTERN", + default=3) + + #groupsum + parser.add_argument("--groupsum_delta", type=float, help="Delta for groupsum", + default=0.01) + + #sjd++ + parser.add_argument("--sjd_pp_threshold", type=float, help="Threshold for sjd++", + default=0.5) + + return parser + +if __name__ == "__main__": + parser = parse_args() + args = parser.parse_args() + main(args) \ No newline at end of file diff --git a/sjdtree/main_emu3.py b/sjdtree/main_emu3.py new file mode 100644 index 0000000000000000000000000000000000000000..993637a2087f633799aeed7e2ff26757b2d38502 --- /dev/null +++ b/sjdtree/main_emu3.py @@ -0,0 +1,329 @@ +import sys +sys.path.append("./lumina_mgpt/") +sys.path.append("./") +import gc + +import os +import time + +from PIL import Image +from transformers import AutoTokenizer, AutoModel, AutoImageProcessor, AutoModelForCausalLM +from transformers.generation.configuration_utils import GenerationConfig +from transformers.generation import LogitsProcessorList, PrefixConstrainedLogitsProcessor, UnbatchedClassifierFreeGuidanceLogitsProcessor +import torch + +from emu3.mllm.processing_emu3 import Emu3Processor + +import argparse + +import random +import numpy as np + +import json, csv +import re + +import lumina_mgpt.data.drafters.choices as choices +def load_prompts(args): + prompts = [] + output_file_name_list = [] + if args.prompt == "PartiPrompts": + with open('data/prompts/PartiPrompts.tsv', 'r') as f: + tsv_reader = csv.DictReader(f, delimiter='\t') + ids = 0 + for row in tsv_reader: + prompts.append(row['Prompt']) + output_file_name_list.append(ids) + ids += 1 + elif args.prompt == "MSCOCO2017Val":# + # with open('data/prompts/captions_val2017_longest.json', 'r') as f: + # captions = json.load(f) + # for caption in captions: + # prompts.append(caption) + from pycocotools.coco import COCO + coco = COCO("data/prompts/captions_val2017.json") + top_k = 0 + for i in range(args.num_images): + img_id = coco.getImgIds()[i] + img_name = coco.loadImgs(img_id)[0] + ann_ids = coco.getAnnIds(imgIds=img_id) + anns = coco.loadAnns(ann_ids) + for j, ann in enumerate(anns): + ann_id = ann['id'] + caption = ann["caption"] + prompts.append(caption) + output_file_name_list.append(ann_id) + if j == top_k: + break + elif args.prompt == "MSCOCO2014Val": + with open('data/prompts/captions_val_2014.json', 'r') as f: + captions = json.load(f) + for caption in captions: + prompts.append(caption) + elif args.prompt == "MSCOCO2017Train": + with open('data/prompts/captions_train2017_extracted.json', 'r') as f: + captions = json.load(f) + for caption in captions: + prompts.append(caption['caption']) + elif args.prompt == "SJDPrompts": + with open('data/prompts/SJDPrompts.tsv', 'r') as f: + tsv_reader = csv.DictReader(f, delimiter='\t') + for row in tsv_reader: + prompts.append(row['Prompt']) + elif args.prompt == "T2ICompBenchVal": + with open("data/prompts/T2I-CompBench_val.json", "r", encoding="utf-8") as f: + data = json.load(f) + for line in data: + # 每行是一个独立的JSON对象,逐行解析 + prompts.append(line['caption']) + output_file_name_list.append(line['image_id']) + else: + # Single prompt input + prompts = [args.prompt] * args.num_images + output_file_name_list = [i for i in range(len(prompts))] + + if args.slice is not None: + assert re.match(r'^\d+-\d+$', args.slice), f"Invalid format: '{args.slice}'. Expected format is 'start-end'." + + start, end = map(int, args.slice.split('-')) + assert start < end, f"Invalid range: '{args.slice}'. Start value must be less than end value." + assert start >= 0 and end >= 0, "Slice values must be non-negative." + + prompts = prompts[start:end] + output_file_name_list = output_file_name_list[start:end] + + if args.num_images < len(prompts): + print(f"Number of images to generate is less than the number of prompts. Sampling {args.num_images} prompts.") + if args.benchmark_way == "random": + prompts = random.sample(prompts, args.num_images) + else: + prompts = prompts[:args.num_images] + output_file_name_list = output_file_name_list[:args.num_images] + else: + print(f"Number of images to generate is greater than the number of prompts. Generating only {len(prompts)} images and no sampling.") + pass + + return prompts,output_file_name_list + +def get_jacobi_param_dict(target_size, max_num_new_tokens, guidance_scale, + seeds, image_top_k, text_top_k, prefix_token_sampler_scheme, + local_chameleon_tokenizer_path, static_tree, multi_token_init_scheme): + jacobi_param_dict = dict( + jacobi_loop_interval_l = 1, + jacobi_loop_interval_r = (target_size // 8)**2 -1, + max_num_new_tokens = max_num_new_tokens, + guidance_scale = guidance_scale, + seed = seeds[0], + multi_token_init_scheme = multi_token_init_scheme, + do_cfg= True, #True, + image_top_k=image_top_k, + text_top_k=text_top_k, + prefix_token_sampler_scheme = prefix_token_sampler_scheme, + local_chameleon_tokenizer_path = local_chameleon_tokenizer_path, + static_tree = static_tree, + ) + return jacobi_param_dict + +def main(args): + static_tree = args.static_tree + tree_choices = args.tree_choices + lantern_delta = args.lantern_delta + groupsum_delta = args.groupsum_delta + try: + tree_choices = getattr(choices, args.tree_choices) + except AttributeError: + print(f"Tree choices {args.tree_choices} is not a valid choice") + return + # ******************** Args Initation ******************** + EMU_HUB = args.model_path + target_size = args.target_size + device = "cuda:0" + local_chameleon_tokenizer_path=args.tokenizer_path + output_path = args.output_path + output_img_path = os.path.join(output_path,"img") + if not os.path.exists(output_path): + os.makedirs(output_path) + if not os.path.exists(output_img_path): + os.makedirs(output_img_path) + + # model path + VQ_HUB = "BAAI/Emu3-VisionTokenizer" + + dtype = torch.bfloat16 + + # ******************** Model Initation ******************** + # prepare model and processor + model = AutoModelForCausalLM.from_pretrained( + EMU_HUB, + device_map=device, + torch_dtype=dtype, + attn_implementation="sdpa", # "sdpa" , "flash_attention_2" + trust_remote_code=True, + ) + tokenizer = AutoTokenizer.from_pretrained(EMU_HUB, trust_remote_code=True) + image_processor = AutoImageProcessor.from_pretrained(VQ_HUB, trust_remote_code=True) + image_tokenizer = AutoModel.from_pretrained(VQ_HUB, device_map=device, trust_remote_code=True).eval() + image_tokenizer = image_tokenizer.to(dtype) + + # ******************** Input Initation ******************** + processor = Emu3Processor(image_processor, image_tokenizer, tokenizer) + + seeds = [None, ] + max_num_new_tokens = args.num_init_new_token + multi_token_init_scheme = args.isp # 'repeat_horizon' random + image_top_k = 2048 + text_top_k = 10 + guidance_scale = 3.0 + prefix_token_sampler_scheme = args.method + # ******************** Load Benchmark ******************** + # image_area=model.config.image_area + image_area = target_size **2 + assert image_area == target_size **2, f"Image area {image_area} does not match target size {target_size}" + kwargs = dict( + mode='G', + ratio="1:1", + image_area=image_area, + return_tensors="pt", + ) + # prepare hyper parameters + GENERATION_CONFIG = GenerationConfig( + use_cache=True, + eos_token_id=model.config.eos_token_id, + pad_token_id=model.config.pad_token_id, + max_new_tokens=40960, + do_sample=True, + top_k=image_top_k, + return_accl=True, + # for static tree + static_tree = static_tree, + tree_choices = tree_choices, + lantern_delta = lantern_delta, + groupsum_delta = groupsum_delta, + ) + POSITIVE_PROMPT = " masterpiece, film grained, best quality." + NEGATIVE_PROMPT = "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry." + prompts,output_file_name_list = load_prompts(args) + neg_inputs = processor(text=NEGATIVE_PROMPT, **kwargs) + + time_avg_forward = 0 + avg_acceptance_length = 0 + gen_count = 0 + with open(f"{output_path}/generation_configs.json", "w") as f: + json.dump(vars(args), f, indent=4) + + global_statistics = {} + + # ******************** Generation Begin ******************** + for i, prompt in enumerate(prompts): + # ******************** Input Begin ******************** + prompt += POSITIVE_PROMPT + pos_inputs = processor(text=prompt, **kwargs) + + h, w = pos_inputs.image_size[0] + + pos_input_ids = pos_inputs.input_ids.to(device) + neg_input_ids = neg_inputs.input_ids.to(device) + + jacobi_param_dict = get_jacobi_param_dict(target_size, max_num_new_tokens, guidance_scale, + seeds, image_top_k, text_top_k, prefix_token_sampler_scheme, + local_chameleon_tokenizer_path, static_tree,multi_token_init_scheme) + jacobi_param_dict['h'] = h + jacobi_param_dict['w'] = w + jacobi_param_dict['neg_inputs'] = neg_input_ids + jacobi_param_dict['classifier_free_guidance'] = guidance_scale + + from scheduler.jacobi_iteration_emu3 import renew_solver + model, logits_processor = renew_solver(model, processor, **jacobi_param_dict) + + # generate + model_inputs = model.prepare_batch_cfg_model_inputs( + pos_input_ids, + neg_input_ids=neg_input_ids, + attention_mask=None, + ) + pos_input_ids = model_inputs['pos_input_ids'] + attention_mask = model_inputs['attention_mask'] + # ******************** Generate Begin ******************** + with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=torch.bfloat16): + result = model.generate( + pos_input_ids, + GENERATION_CONFIG, + logits_processor=logits_processor, + attention_mask=attention_mask, + neg_input_ids=neg_input_ids, + ) + + outputs = result.input_ids[0] + time_forward = result.time_forward + token_gen_len = result.token_gen_len + loop_num = result.loop_num + acceptance_length = token_gen_len / loop_num + avg_acceptance_length += acceptance_length + # ******************** Generate Saving ******************** + + with torch.no_grad(): + mm_list = processor.decode(outputs) + mm_list[1].save(os.path.join(output_img_path, f"{output_file_name_list[i]}.png")) + statistics = { + "prompt": prompt, + "time": time_forward, + "acceptance_length": acceptance_length, + "loop_num": loop_num, + "ann_id": output_file_name_list[i] + } + global_statistics[f"prompt_{i}"] = statistics + time_avg_forward += time_forward + with open(f"{args.output_path}/result_{args.slice}.json", "w") as f: + json.dump(global_statistics, f, indent=4) + gen_count += 1 + avg_acceptance_length = avg_acceptance_length/gen_count + time_avg_forward = time_avg_forward/gen_count + statistics = { + "method":f"{prefix_token_sampler_scheme}_{multi_token_init_scheme}_{max_num_new_tokens}", + "avg_acceptance_length":avg_acceptance_length, + "time_forward_avg":time_avg_forward, + } + global_statistics[f"summary"] = statistics + with open(f"{args.output_path}/result_{args.slice}.json", "w") as f: + json.dump(global_statistics, f, indent=4) + print("Average time per generation: ", time_avg_forward) + gc.collect() + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--model_path", default="BAAI/Emu3-Gen",type=str, help="location of fake images for evaluation") + parser.add_argument("--tokenizer_path", default='/data/lei/localmodel/lumina_mgpt/chameleon/tokenizer',type=str, help="location of the reference images for evaluation") + parser.add_argument("--output_path", default='/home/leihaodong/ICLR25/exp/ablation',type=str) + parser.add_argument("--target_size", type=int, default=720) + + parser.add_argument("--isp", default='random', type=str,help="repeat_horizon, random") + parser.add_argument("--method", default='speculative_jacobi', type=str,help="'jacobi', 'speculative_jacobi'") + parser.add_argument("--num_init_new_token", type=int, default=16) + #Benchmark + parser.add_argument("--benchmark_way", default='order', type=str, help="order or sample",) + parser.add_argument("--prompt", type=str, help="Prompt for image generation", + default="Atlantis, the most Fantasy high-quality photos") + parser.add_argument("--num_images", type=int, help="Number of images to generate", + default=2) + parser.add_argument("--slice", type=str, help="Slice of prompts to use; format: 'start-end'", + default=None) + #Tree + parser.add_argument("--static_tree", action="store_true", help="Enable static tree structure for draft token generation") + # Experimental arguments + parser.add_argument("--tree_choices", type=str, help="Tree choice for LANTERN", + default="mc_sim_7b_63") + + #lantern + parser.add_argument("--lantern_delta", type=int, help="Delta for LANTERN", + default=3) + + #groupsum + parser.add_argument("--groupsum_delta", type=float, help="Delta for groupsum", + default=0.01) + + return parser + +if __name__ == "__main__": + parser = parse_args() + args = parser.parse_args() + main(args) \ No newline at end of file diff --git a/sjdtree/main_llamagen.py b/sjdtree/main_llamagen.py new file mode 100644 index 0000000000000000000000000000000000000000..c01104b7e54c33723137718b997ba3103f6e9380 --- /dev/null +++ b/sjdtree/main_llamagen.py @@ -0,0 +1,365 @@ +import os +import sys +sys.path.append("./lumina_mgpt/") +sys.path.append("./") + +import torch +torch.backends.cuda.matmul.allow_tf32 = True +torch.backends.cudnn.allow_tf32 = True +torch.set_float32_matmul_precision('high') +setattr(torch.nn.Linear, 'reset_parameters', lambda self: None) # disable default parameter init for faster speed +setattr(torch.nn.LayerNorm, 'reset_parameters', lambda self: None) # disable default parameter init for faster speed + +import time +import argparse + +from llamagen.tokenizer.tokenizer_image.vq_model import VQ_models +from llamagen.language.t5 import T5Embedder +from llamagen.llamagen import GPT_models +from llamagen.llamagen_solver import LlamaGenSolver, renew_llamagen, generate +from scheduler.jacobi_iteration_lumina_mgpt import renew_sampler + +from PIL import Image + +import json +# Prompt +import random +import numpy as np + +import json, csv +import re + + + +os.environ["TOKENIZERS_PARALLELISM"] = "false" + +def get_jacobi_param_dict(args): + target_size = 512 + + seeds = [None, ] + max_num_new_tokens = args.num_init_new_token # 16 + multi_token_init_scheme = args.isp + image_top_k = 1000 + text_top_k = 10 + guidance_scale = 7.5 + prefix_token_sampler_scheme = args.method + + jacobi_param_dict = dict( + jacobi_loop_interval_l = 1, + jacobi_loop_interval_r = (target_size // 16)**2 - max_num_new_tokens - 2, + max_num_new_tokens = max_num_new_tokens, + guidance_scale = guidance_scale, + seed = seeds[0], + multi_token_init_scheme = multi_token_init_scheme, + do_cfg= True, + image_top_k=image_top_k, + text_top_k=text_top_k, + prefix_token_sampler_scheme = prefix_token_sampler_scheme, + local_chameleon_tokenizer_path=args.tokenizer_path + ) + return jacobi_param_dict + + +def load_prompts(args): + prompts = [] + output_file_name_list = [] + if args.prompt == "PartiPrompts": + with open('data/prompts/PartiPrompts.tsv', 'r') as f: + tsv_reader = csv.DictReader(f, delimiter='\t') + ids = 0 + for row in tsv_reader: + prompts.append(row['Prompt']) + output_file_name_list.append(ids) + ids += 1 + elif args.prompt == "MSCOCO2017Val":# + # with open('data/prompts/captions_val2017_longest.json', 'r') as f: + # captions = json.load(f) + # for caption in captions: + # prompts.append(caption) + from pycocotools.coco import COCO + coco = COCO("/data/lei/dataset/mscoco/annotations/captions_val2017.json") + top_k = 0 + for i in range(args.num_images): + img_id = coco.getImgIds()[i] + img_name = coco.loadImgs(img_id)[0] + ann_ids = coco.getAnnIds(imgIds=img_id) + anns = coco.loadAnns(ann_ids) + for j, ann in enumerate(anns): + ann_id = ann['id'] + caption = ann["caption"] + prompts.append(caption) + output_file_name_list.append(ann_id) + if j == top_k: + break + elif args.prompt == "MSCOCO2014Val": + with open('data/prompts/captions_val_2014.json', 'r') as f: + captions = json.load(f) + for caption in captions: + prompts.append(caption) + elif args.prompt == "MSCOCO2017Train": + with open('data/prompts/captions_train2017_extracted.json', 'r') as f: + captions = json.load(f) + for caption in captions: + prompts.append(caption['caption']) + elif args.prompt == "SJDPrompts": + with open('data/prompts/SJDPrompts.tsv', 'r') as f: + tsv_reader = csv.DictReader(f, delimiter='\t') + for row in tsv_reader: + prompts.append(row['Prompt']) + elif args.prompt == "T2ICompBenchVal": + with open("data/prompts/T2I-CompBench_val.json", "r", encoding="utf-8") as f: + data = json.load(f) + for line in data: + # 每行是一个独立的JSON对象,逐行解析 + prompts.append(line['caption']) + output_file_name_list.append(line['image_id']) + else: + # Single prompt input + prompts = [args.prompt] * args.num_images + + if args.slice is not None: + assert re.match(r'^\d+-\d+$', args.slice), f"Invalid format: '{args.slice}'. Expected format is 'start-end'." + + start, end = map(int, args.slice.split('-')) + assert start < end, f"Invalid range: '{args.slice}'. Start value must be less than end value." + assert start >= 0 and end >= 0, "Slice values must be non-negative." + + prompts = prompts[start:end] + output_file_name_list = output_file_name_list[start:end] + + if args.num_images < len(prompts): + print(f"Number of images to generate is less than the number of prompts. Sampling {args.num_images} prompts.") + if args.benchmark_way == "random": + prompts = random.sample(prompts, args.num_images) + else: + prompts = prompts[:args.num_images] + output_file_name_list = output_file_name_list[:args.num_images] + else: + print(f"Number of images to generate is greater than the number of prompts. Generating only {len(prompts)} images and no sampling.") + pass + + return prompts,output_file_name_list + +def main(args): + # ******************** Input Initation ******************** + max_num_new_tokens = args.num_init_new_token # 16 + prefix_token_sampler_scheme = args.method # 'jacobi', 'speculative_jacobi' + multi_token_init_scheme = args.isp + + torch.set_grad_enabled(False) + device = "cuda" if torch.cuda.is_available() else "cpu" + + # create and load model + vq_model = VQ_models[args.vq_model]( + codebook_size=args.codebook_size, + codebook_embed_dim=args.codebook_embed_dim) + vq_model.to(device) + vq_model.eval() + checkpoint = torch.load(args.vq_ckpt, map_location="cpu") + vq_model.load_state_dict(checkpoint["model"]) + del checkpoint + print(f"image tokenizer is loaded") + + # create and load gpt model + precision = {'none': torch.float32, 'bf16': torch.bfloat16, 'fp16': torch.float16}[args.precision] + latent_size = args.image_size // args.downsample_size + gpt_model = GPT_models[args.gpt_model]( + block_size=latent_size ** 2, + cls_token_num=args.cls_token_num, + model_type=args.gpt_type, + ).to(device=device, dtype=precision) + + print(gpt_model.__class__) + + jacobi_param_dict = get_jacobi_param_dict(args) + image_top_k = jacobi_param_dict['image_top_k'] + + gpt_model.__class__ = renew_llamagen(gpt_model.__class__) + gpt_model._init_new_params(**jacobi_param_dict) + gpt_model.__class__ = renew_sampler(gpt_model.__class__) + gpt_model._init_new_params(**jacobi_param_dict) + + checkpoint = torch.load(args.gpt_ckpt, map_location="cpu") + + if "model" in checkpoint: # ddp + model_weight = checkpoint["model"] + elif "module" in checkpoint: # deepspeed + model_weight = checkpoint["module"] + elif "state_dict" in checkpoint: + model_weight = checkpoint["state_dict"] + else: + raise Exception("please check model weight") + gpt_model.load_state_dict(model_weight, strict=False) + gpt_model.eval() + del checkpoint + print(f"gpt model is loaded") + + if args.compile: + print(f"compiling the model...") + gpt_model = torch.compile( + gpt_model, + mode="reduce-overhead", + fullgraph=True + ) # requires PyTorch 2.0 (optional) + else: + print(f"no need to compile model in demo") + + if not os.path.exists(args.t5_path): + os.makedirs(args.t5_path) + + assert os.path.exists(args.t5_path), f"t5 model path {args.t5_path} does not exist" + t5_model = T5Embedder( + device=device, + local_cache=True, + cache_dir=args.t5_path, + dir_or_name=args.t5_model_type, + torch_dtype=precision, + model_max_length=args.t5_feature_max_len, + ) + + # ******************** Load Benchmark ******************** + prompts, output_file_name_list = load_prompts(args) + + global_statistics = {} + caption_embs, emb_masks = t5_model.get_text_embeddings(prompts) + + if not args.no_left_padding: + print(f"processing left-padding...") + # a naive way to implement left-padding + new_emb_masks = torch.flip(emb_masks, dims=[-1]) + new_caption_embs = [] + for idx, (caption_emb, emb_mask) in enumerate(zip(caption_embs, emb_masks)): + valid_num = int(emb_mask.sum().item()) + print(f' prompt {idx} token len: {valid_num}') + new_caption_emb = torch.cat([caption_emb[valid_num:], caption_emb[:valid_num]]) + new_caption_embs.append(new_caption_emb) + new_caption_embs = torch.stack(new_caption_embs) + else: + new_caption_embs, new_emb_masks = caption_embs, emb_masks + c_indices = new_caption_embs * new_emb_masks[:,:, None] + c_emb_masks = new_emb_masks + + solver = LlamaGenSolver( + model = gpt_model, + image_top_k=image_top_k, + image_top_p=args.top_p + ) + print(f"start sampling...") + qzshape = [len(c_indices), args.codebook_embed_dim, latent_size, latent_size] + qzshape = [1, args.codebook_embed_dim, latent_size, latent_size] + + time_avg = 0 + avg_acceptance_length = 0 + index_sample = None + samples = None + gen_count = 0 + for i in range(len(c_indices)): + t1 = time.time() + result = solver.generate( + c_indices[i:i+1], latent_size ** 2, + c_emb_masks[i:i+1], + cfg_scale=args.cfg_scale, + temperature=args.temperature, top_k=image_top_k, + top_p=args.top_p, sample_logits=True, + return_accl=True + ) + sampling_time = time.time() - t1 + if index_sample == None: + index_sample = result.input_ids + else: + index_sample = torch.concat([index_sample,result.input_ids], dim=0) + token_gen_len = result.token_gen_len + loop_num = result.loop_num + acceptance_length = token_gen_len / loop_num + avg_acceptance_length += acceptance_length + time_avg += sampling_time + print(f"Full sampling takes about {sampling_time:.2f} seconds.") + statistics = { + "prompt": prompts[i], + "time": sampling_time, + "acceptance_length": acceptance_length, + "loop_num": loop_num, + "ann_id": output_file_name_list[i] + } + global_statistics[f"prompt_{i}"] = statistics + gen_count += 1 + + t2 = time.time() + samples = vq_model.decode_code(index_sample, qzshape) # output value is between [-1, 1] + decoder_time = time.time() - t2 + print(f"decoder takes about {decoder_time:.2f} seconds.") + + images = samples + images = images.clamp(min=-1, max=1) + images_sum = (images - images.min()) / (images.max() - images.min()) * 255 + + # TODO: 修改你的本地输出地址 + output_path = args.output_path + output_img_path = os.path.join(output_path,"img") + if not os.path.exists(output_path): + os.makedirs(output_path) + if not os.path.exists(output_img_path): + os.makedirs(output_img_path) + + for i in range(len(c_indices)): + images = images_sum[i].permute(1, 2, 0).cpu().numpy() + result_image = Image.fromarray((images).astype("uint8")) + output_file_name = str(output_file_name_list[i]) + ".png" + result_image.save(os.path.join(output_img_path,output_file_name)) + print(f"image is saved to sample_{os.path.join(output_img_path,output_file_name)}.png") + avg_acceptance_length = avg_acceptance_length/gen_count + time_avg_forward = time_avg/gen_count + statistics = { + "method":f"{prefix_token_sampler_scheme}_{multi_token_init_scheme}_{max_num_new_tokens}", + "avg_acceptance_length":avg_acceptance_length, + "time_forward_avg":time_avg_forward, + } + global_statistics[f"summary"] = statistics + with open(f"{args.output_path}/result_{args.slice}.json", "w") as f: + json.dump(global_statistics, f, indent=4) + print("Average time per generation: ", time_avg) + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--t5_path", type=str, default='/data/lei/localmodel/') + parser.add_argument("--t5_model_type", type=str, default='flan-t5-xl') + parser.add_argument("--t5_feature_max_len", type=int, default=120) + parser.add_argument("--t5_feature_dim", type=int, default=2048) + parser.add_argument("--no_left_padding", action='store_true', default=False) + parser.add_argument("--gpt_model", type=str, choices=list(GPT_models.keys()), default="GPT-XL") + parser.add_argument("--gpt_ckpt", type=str, default="/home/leihaodong/pretrained_models/t2i_XL_stage2_512.pt") + parser.add_argument("--gpt_type", type=str, choices=['c2i', 't2i'], default="t2i", help="class->image or text->image") + parser.add_argument("--cls_token_num", type=int, default=120, help="max token number of condition input") + parser.add_argument("--precision", type=str, default='bf16', choices=["none", "fp16", "bf16"]) + parser.add_argument("--compile", action='store_true', default=False) + parser.add_argument("--vq_model", type=str, choices=list(VQ_models.keys()), default="VQ-16") + parser.add_argument("--vq_ckpt", type=str, default="/home/leihaodong/pretrained_models/vq_ds16_c2i.pt", help="ckpt path for vq model") + parser.add_argument("--codebook_size", type=int, default=16384, help="codebook size for vector quantization") + parser.add_argument("--codebook_embed_dim", type=int, default=8, help="codebook dimension for vector quantization") + parser.add_argument("--image_size", type=int, choices=[256, 384, 512], default=512) + parser.add_argument("--downsample_size", type=int, choices=[8, 16], default=16) + parser.add_argument("--num_classes", type=int, default=1000) + parser.add_argument("--cfg_scale", type=float, default=7.5) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--temperature", type=float, default=1.0, help="temperature value to sample with") + parser.add_argument("--top_p", type=float, default=1.0, help="top-p value to sample with") + + parser.add_argument("--tokenizer_path", default='/data/lei/localmodel/lumina_mgpt/chameleon/tokenizer',type=str, help="location of the reference images for evaluation") + + # SJD + parser.add_argument("--isp", default='random', type=str,help="repeat_horizon, random") + parser.add_argument("--method", default='speculative_jacobi', type=str,help="'jacobi', 'speculative_jacobi'") + parser.add_argument("--num_init_new_token", type=int, default=16) + + # Benchmark + parser.add_argument("--output_path", default='/home/leihaodong/AAAI25/exp/FSJD',type=str) + parser.add_argument("--benchmark_way", default='order', type=str, help="order or sample",) + parser.add_argument("--prompt", type=str, help="Prompt for image generation", + default="Atlantis, the most Fantasy high-quality photos") + parser.add_argument("--num_images", type=int, help="Number of images to generate", + default=2) + parser.add_argument("--slice", type=str, help="Slice of prompts to use; format: 'start-end'", + default=None) + + args = parser.parse_args() + main(args) \ No newline at end of file diff --git a/sjdtree/requirements.txt b/sjdtree/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbc0000ee3a8257ad252529c850882e701ed8c1d --- /dev/null +++ b/sjdtree/requirements.txt @@ -0,0 +1,24 @@ +torch==2.3.0 +torchvision==0.18.0 +torchaudio==2.3.0 +pandas +tensorboard +fairscale +sentencepiece +gradio==4.19.0 +packaging +transformers>=4.43.3 +pyyaml +pathlib +Ninja +bitsandbytes +httpx[socks] +einops +regex +h5py +accelerate +pre-commit +pycocotools +#llamagen +ftfy +bs4 \ No newline at end of file diff --git a/sjdtree/setup.py b/sjdtree/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f7699df11e4c1975cb16360ef03a732475dfa4af --- /dev/null +++ b/sjdtree/setup.py @@ -0,0 +1,16 @@ +import setuptools + +with open("README.md", "r", encoding="utf-8") as fh: + long_description = fh.read() + +setuptools.setup( + name="xllmx", + version="0.0.1", + author="Alpha-VLLM", + description="An Open-source Toolkit for LLM-centered Any2Any Generation", + long_description=long_description, + long_description_content_type="text/markdown", + url="https://github.com/Alpha-VLLM/Lumina-mGPT", + packages=["xllmx"], + include_package_data=True, +) diff --git a/sjdtree/utils.py b/sjdtree/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..69d039f82d3ca2db59138f0f7876698f60e3a5b0 --- /dev/null +++ b/sjdtree/utils.py @@ -0,0 +1,65 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +import os +from tqdm import tqdm +from torchvision.utils import save_image +from absl import logging +import copy +import datetime +import math + +import einops +from einops import rearrange + +import sys +import glob +import shutil +from torch.utils.tensorboard import SummaryWriter + +UNSAVED_DIRS = ['outputs', 'checkpoint', 'checkpoints', 'workdir', 'build', '.git', '__pycache__', 'assets', 'samples'] + +def backup_code(work_dir, verbose=False): + base_dir = './' + + dir_list = ["*.py", ] + for file in os.listdir(base_dir): + sub_dir = os.path.join(base_dir, file) + if os.path.isdir(sub_dir): + if file in UNSAVED_DIRS: + continue + + for root, dirs, files in os.walk(sub_dir): + for dir_name in dirs: + dir_list.append(os.path.join(root, dir_name)+"/*.py") + + elif file.split('.')[-1] == 'py': + pass + + for pattern in dir_list: + for file in glob.glob(pattern): + src = os.path.join(base_dir, file) + dst = os.path.join(work_dir, 'backup', os.path.dirname(file)) + + if verbose: + logging.info('Copying %s -> %s' % (os.path.relpath(src), os.path.relpath(dst))) + + os.makedirs(dst, exist_ok=True) + shutil.copy2(src, dst) + + +def get_str_time(): + return str(datetime.datetime.now()).replace(':', '_').replace('.', '_').replace('-', "_").replace(' ', '_') + + +def set_logger(log_level='info', fname=None): + import logging as _logging + handler = logging.get_absl_handler() + formatter = _logging.Formatter('%(asctime)s - %(filename)s - %(message)s') + handler.setFormatter(formatter) + logging.set_verbosity(log_level) + if fname is not None: + handler = _logging.FileHandler(fname) + handler.setFormatter(formatter) + logging.get_absl_logger().addHandler(handler) \ No newline at end of file