Shufan Li commited on
Commit ·
f62f9d0
1
Parent(s): 358eadc
commit model
Browse filesupdate model
update code
gradio demo
update code
update code
cleanup
This view is limited to 50 files because it contains too many changes. See raw diff
- .gitignore +6 -0
- assets/demo/an antique shop.jpg +0 -0
- assets/demo/clock ticking.wav +0 -0
- ckpts/imagebind_huge.pth +0 -1
- ckpts/imagebind_huge.pth +3 -0
- ckpts/llm +0 -1
- ckpts/llm/added_tokens.json +11 -0
- ckpts/llm/config.json +42 -0
- ckpts/llm/generation_config.json +7 -0
- ckpts/llm/pytorch_model-00001-of-00002.bin +3 -0
- ckpts/llm/pytorch_model-00002-of-00002.bin +3 -0
- ckpts/llm/pytorch_model.bin.index.json +838 -0
- ckpts/llm/special_tokens_map.json +89 -0
- ckpts/llm/tokenizer.model +3 -0
- ckpts/llm/tokenizer/added_tokens.json +11 -0
- ckpts/llm/tokenizer/special_tokens_map.json +89 -0
- ckpts/llm/tokenizer/tokenizer.model +3 -0
- ckpts/llm/tokenizer/tokenizer_config.json +125 -0
- ckpts/llm/tokenizer_config.json +125 -0
- ckpts/llm/trainer_state.json +0 -0
- ckpts/llm/training_args.bin +3 -0
- ckpts/prior/model.bin +0 -1
- ckpts/prior/model.bin +3 -0
- ckpts/sdxl +0 -1
- ckpts/sdxl/unet/config.json +73 -0
- ckpts/sdxl/unet/diffusion_pytorch_model.safetensors +3 -0
- demo.ipynb +1 -1
- instructany2pix/__init__.py +0 -1
- instructany2pix/ddim/pnp_pipeline.py +0 -524
- instructany2pix/ddim/sdxl_pipeline.py +0 -990
- instructany2pix/diffusion/sdxl_img2img_pipeline.py +0 -70
- instructany2pix/llm/constants.py +0 -30
- instructany2pix/llm/conversation.py +0 -381
- instructany2pix/llm/mm_utils.py +0 -107
- instructany2pix/llm/model/__init__.py +0 -1
- instructany2pix/llm/model/any2pix_arch.py +0 -299
- instructany2pix/llm/model/apply_delta.py +0 -48
- instructany2pix/llm/model/builder.py +0 -136
- instructany2pix/llm/model/consolidate.py +0 -26
- instructany2pix/llm/model/language_model/__init__.py +0 -0
- instructany2pix/llm/model/language_model/any2pix_llama.py +0 -472
- instructany2pix/llm/model/language_model/mpt/adapt_tokenizer.py +0 -41
- instructany2pix/llm/model/language_model/mpt/attention.py +0 -300
- instructany2pix/llm/model/language_model/mpt/blocks.py +0 -41
- instructany2pix/llm/model/language_model/mpt/configuration_mpt.py +0 -118
- instructany2pix/llm/model/language_model/mpt/custom_embedding.py +0 -11
- instructany2pix/llm/model/language_model/mpt/flash_attn_triton.py +0 -484
- instructany2pix/llm/model/language_model/mpt/hf_prefixlm_converter.py +0 -415
- instructany2pix/llm/model/language_model/mpt/meta_init_context.py +0 -94
- instructany2pix/llm/model/language_model/mpt/modeling_mpt.py +0 -331
.gitignore
CHANGED
|
@@ -1,3 +1,9 @@
|
|
| 1 |
**/__pycache__
|
| 2 |
.ipynb_checkpoints
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
# ckpts
|
|
|
|
| 1 |
**/__pycache__
|
| 2 |
.ipynb_checkpoints
|
| 3 |
+
scripts
|
| 4 |
+
demo2.ipynb
|
| 5 |
+
*.py
|
| 6 |
+
*.ipynb
|
| 7 |
+
instructany2pix
|
| 8 |
+
assets
|
| 9 |
# ckpts
|
assets/demo/an antique shop.jpg
DELETED
|
Binary file (124 kB)
|
|
|
assets/demo/clock ticking.wav
DELETED
|
Binary file (640 kB)
|
|
|
ckpts/imagebind_huge.pth
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
/home/jacklishufan/AudioLDM2/.checkpoints/imagebind_huge.pth
|
|
|
|
|
|
ckpts/imagebind_huge.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d6f6c22bedcc90708448d5d2fbb7b2db9c73f505dc89bd0b2e09b23af1b62157
|
| 3 |
+
size 4803584173
|
ckpts/llm
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
/home/jacklishufan/LLaVA/outputs/llava-v1.5-7b-pretrain-any2any2align/
|
|
|
|
|
|
ckpts/llm/added_tokens.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"<audio>": 32005,
|
| 3 |
+
"<audio_gen>": 32003,
|
| 4 |
+
"<audio_gen_start>": 32004,
|
| 5 |
+
"<base>": 32007,
|
| 6 |
+
"<base_null>": 32008,
|
| 7 |
+
"<im_gen>": 32001,
|
| 8 |
+
"<im_gen_start>": 32000,
|
| 9 |
+
"<mask_gen>": 32002,
|
| 10 |
+
"<video>": 32006
|
| 11 |
+
}
|
ckpts/llm/config.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "/home/jacklishufan/LLaVA/outputs/any2anyalign",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"LlavaLlamaForCausalLM"
|
| 5 |
+
],
|
| 6 |
+
"attention_bias": false,
|
| 7 |
+
"bos_token_id": 1,
|
| 8 |
+
"eos_token_id": 2,
|
| 9 |
+
"freeze_mm_mlp_adapter": false,
|
| 10 |
+
"hidden_act": "silu",
|
| 11 |
+
"hidden_size": 4096,
|
| 12 |
+
"image_aspect_ratio": "square",
|
| 13 |
+
"image_grid_pinpoints": null,
|
| 14 |
+
"initializer_range": 0.02,
|
| 15 |
+
"intermediate_size": 11008,
|
| 16 |
+
"max_position_embeddings": 4096,
|
| 17 |
+
"mm_hidden_size": 1024,
|
| 18 |
+
"mm_projector_type": "mlp2x_gelu",
|
| 19 |
+
"mm_use_im_patch_token": false,
|
| 20 |
+
"mm_use_im_start_end": false,
|
| 21 |
+
"mm_vision_select_feature": "projection",
|
| 22 |
+
"mm_vision_select_layer": -2,
|
| 23 |
+
"mm_vision_tower": "laion/CLIP-ViT-H-14-laion2B-s32B-b79K",
|
| 24 |
+
"model_type": "llava",
|
| 25 |
+
"num_attention_heads": 32,
|
| 26 |
+
"num_hidden_layers": 32,
|
| 27 |
+
"num_key_value_heads": 32,
|
| 28 |
+
"pad_token_id": 0,
|
| 29 |
+
"pretraining_tp": 1,
|
| 30 |
+
"rms_norm_eps": 1e-05,
|
| 31 |
+
"rope_scaling": null,
|
| 32 |
+
"rope_theta": 10000.0,
|
| 33 |
+
"tie_word_embeddings": false,
|
| 34 |
+
"torch_dtype": "bfloat16",
|
| 35 |
+
"transformers_version": "4.34.1",
|
| 36 |
+
"tune_mm_mlp_adapter": false,
|
| 37 |
+
"use_cache": true,
|
| 38 |
+
"use_mm_proj": true,
|
| 39 |
+
"vae_audio": "vq-npz",
|
| 40 |
+
"vae_image": "vq-npz",
|
| 41 |
+
"vocab_size": 32009
|
| 42 |
+
}
|
ckpts/llm/generation_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"pad_token_id": 0,
|
| 6 |
+
"transformers_version": "4.34.1"
|
| 7 |
+
}
|
ckpts/llm/pytorch_model-00001-of-00002.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e2135464f292dfe61635e4365706e03f0b116b539e1fd3edc5da952026aafe50
|
| 3 |
+
size 9976693850
|
ckpts/llm/pytorch_model-00002-of-00002.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4eb4805933b421b55a1b4bf4096db8eeb5a35ca996305b32e6d4fe3f785bc0e9
|
| 3 |
+
size 4974527229
|
ckpts/llm/pytorch_model.bin.index.json
ADDED
|
@@ -0,0 +1,838 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"metadata": {
|
| 3 |
+
"total_size": 14950917120
|
| 4 |
+
},
|
| 5 |
+
"weight_map": {
|
| 6 |
+
"lm_head.weight": "pytorch_model-00002-of-00002.bin",
|
| 7 |
+
"model.embed_tokens.weight": "pytorch_model-00001-of-00002.bin",
|
| 8 |
+
"model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 9 |
+
"model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 10 |
+
"model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 11 |
+
"model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 12 |
+
"model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 13 |
+
"model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 14 |
+
"model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 15 |
+
"model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 16 |
+
"model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 17 |
+
"model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 18 |
+
"model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 19 |
+
"model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 20 |
+
"model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 21 |
+
"model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 22 |
+
"model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 23 |
+
"model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 24 |
+
"model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 25 |
+
"model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 26 |
+
"model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 27 |
+
"model.layers.10.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 28 |
+
"model.layers.10.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 29 |
+
"model.layers.10.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 30 |
+
"model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 31 |
+
"model.layers.10.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 32 |
+
"model.layers.10.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 33 |
+
"model.layers.10.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 34 |
+
"model.layers.10.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 35 |
+
"model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 36 |
+
"model.layers.11.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 37 |
+
"model.layers.11.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 38 |
+
"model.layers.11.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 39 |
+
"model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 40 |
+
"model.layers.11.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 41 |
+
"model.layers.11.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 42 |
+
"model.layers.11.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 43 |
+
"model.layers.11.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 44 |
+
"model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 45 |
+
"model.layers.12.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 46 |
+
"model.layers.12.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 47 |
+
"model.layers.12.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 48 |
+
"model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 49 |
+
"model.layers.12.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 50 |
+
"model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 51 |
+
"model.layers.12.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 52 |
+
"model.layers.12.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 53 |
+
"model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 54 |
+
"model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 55 |
+
"model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 56 |
+
"model.layers.13.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 57 |
+
"model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 58 |
+
"model.layers.13.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 59 |
+
"model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 60 |
+
"model.layers.13.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 61 |
+
"model.layers.13.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 62 |
+
"model.layers.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 63 |
+
"model.layers.14.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 64 |
+
"model.layers.14.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 65 |
+
"model.layers.14.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 66 |
+
"model.layers.14.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 67 |
+
"model.layers.14.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 68 |
+
"model.layers.14.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 69 |
+
"model.layers.14.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 70 |
+
"model.layers.14.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 71 |
+
"model.layers.15.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 72 |
+
"model.layers.15.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 73 |
+
"model.layers.15.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 74 |
+
"model.layers.15.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 75 |
+
"model.layers.15.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 76 |
+
"model.layers.15.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 77 |
+
"model.layers.15.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 78 |
+
"model.layers.15.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 79 |
+
"model.layers.15.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 80 |
+
"model.layers.16.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 81 |
+
"model.layers.16.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 82 |
+
"model.layers.16.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 83 |
+
"model.layers.16.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 84 |
+
"model.layers.16.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 85 |
+
"model.layers.16.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 86 |
+
"model.layers.16.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 87 |
+
"model.layers.16.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 88 |
+
"model.layers.16.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 89 |
+
"model.layers.17.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 90 |
+
"model.layers.17.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 91 |
+
"model.layers.17.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 92 |
+
"model.layers.17.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 93 |
+
"model.layers.17.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 94 |
+
"model.layers.17.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 95 |
+
"model.layers.17.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 96 |
+
"model.layers.17.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 97 |
+
"model.layers.17.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 98 |
+
"model.layers.18.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 99 |
+
"model.layers.18.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 100 |
+
"model.layers.18.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 101 |
+
"model.layers.18.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 102 |
+
"model.layers.18.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 103 |
+
"model.layers.18.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 104 |
+
"model.layers.18.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 105 |
+
"model.layers.18.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 106 |
+
"model.layers.18.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 107 |
+
"model.layers.19.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 108 |
+
"model.layers.19.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 109 |
+
"model.layers.19.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 110 |
+
"model.layers.19.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 111 |
+
"model.layers.19.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 112 |
+
"model.layers.19.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 113 |
+
"model.layers.19.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 114 |
+
"model.layers.19.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 115 |
+
"model.layers.19.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 116 |
+
"model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 117 |
+
"model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 118 |
+
"model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 119 |
+
"model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 120 |
+
"model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 121 |
+
"model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 122 |
+
"model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 123 |
+
"model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 124 |
+
"model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 125 |
+
"model.layers.20.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 126 |
+
"model.layers.20.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 127 |
+
"model.layers.20.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 128 |
+
"model.layers.20.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 129 |
+
"model.layers.20.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 130 |
+
"model.layers.20.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 131 |
+
"model.layers.20.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 132 |
+
"model.layers.20.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 133 |
+
"model.layers.20.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 134 |
+
"model.layers.21.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 135 |
+
"model.layers.21.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 136 |
+
"model.layers.21.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 137 |
+
"model.layers.21.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 138 |
+
"model.layers.21.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 139 |
+
"model.layers.21.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 140 |
+
"model.layers.21.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 141 |
+
"model.layers.21.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 142 |
+
"model.layers.21.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 143 |
+
"model.layers.22.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 144 |
+
"model.layers.22.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 145 |
+
"model.layers.22.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 146 |
+
"model.layers.22.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 147 |
+
"model.layers.22.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 148 |
+
"model.layers.22.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 149 |
+
"model.layers.22.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 150 |
+
"model.layers.22.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 151 |
+
"model.layers.22.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 152 |
+
"model.layers.23.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 153 |
+
"model.layers.23.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 154 |
+
"model.layers.23.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 155 |
+
"model.layers.23.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 156 |
+
"model.layers.23.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 157 |
+
"model.layers.23.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 158 |
+
"model.layers.23.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 159 |
+
"model.layers.23.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 160 |
+
"model.layers.23.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 161 |
+
"model.layers.24.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 162 |
+
"model.layers.24.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 163 |
+
"model.layers.24.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 164 |
+
"model.layers.24.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 165 |
+
"model.layers.24.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 166 |
+
"model.layers.24.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 167 |
+
"model.layers.24.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 168 |
+
"model.layers.24.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 169 |
+
"model.layers.24.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 170 |
+
"model.layers.25.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 171 |
+
"model.layers.25.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 172 |
+
"model.layers.25.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 173 |
+
"model.layers.25.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 174 |
+
"model.layers.25.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 175 |
+
"model.layers.25.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 176 |
+
"model.layers.25.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 177 |
+
"model.layers.25.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 178 |
+
"model.layers.25.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 179 |
+
"model.layers.26.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 180 |
+
"model.layers.26.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 181 |
+
"model.layers.26.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 182 |
+
"model.layers.26.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 183 |
+
"model.layers.26.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 184 |
+
"model.layers.26.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 185 |
+
"model.layers.26.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 186 |
+
"model.layers.26.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 187 |
+
"model.layers.26.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 188 |
+
"model.layers.27.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 189 |
+
"model.layers.27.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 190 |
+
"model.layers.27.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 191 |
+
"model.layers.27.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 192 |
+
"model.layers.27.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 193 |
+
"model.layers.27.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 194 |
+
"model.layers.27.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 195 |
+
"model.layers.27.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 196 |
+
"model.layers.27.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 197 |
+
"model.layers.28.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 198 |
+
"model.layers.28.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 199 |
+
"model.layers.28.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 200 |
+
"model.layers.28.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 201 |
+
"model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 202 |
+
"model.layers.28.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 203 |
+
"model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 204 |
+
"model.layers.28.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 205 |
+
"model.layers.28.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 206 |
+
"model.layers.29.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 207 |
+
"model.layers.29.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 208 |
+
"model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 209 |
+
"model.layers.29.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 210 |
+
"model.layers.29.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 211 |
+
"model.layers.29.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 212 |
+
"model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 213 |
+
"model.layers.29.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 214 |
+
"model.layers.29.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 215 |
+
"model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 216 |
+
"model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 217 |
+
"model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 218 |
+
"model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 219 |
+
"model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 220 |
+
"model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 221 |
+
"model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 222 |
+
"model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 223 |
+
"model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 224 |
+
"model.layers.30.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 225 |
+
"model.layers.30.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 226 |
+
"model.layers.30.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 227 |
+
"model.layers.30.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 228 |
+
"model.layers.30.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 229 |
+
"model.layers.30.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 230 |
+
"model.layers.30.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 231 |
+
"model.layers.30.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 232 |
+
"model.layers.30.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 233 |
+
"model.layers.31.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 234 |
+
"model.layers.31.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 235 |
+
"model.layers.31.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 236 |
+
"model.layers.31.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 237 |
+
"model.layers.31.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 238 |
+
"model.layers.31.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 239 |
+
"model.layers.31.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 240 |
+
"model.layers.31.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 241 |
+
"model.layers.31.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 242 |
+
"model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 243 |
+
"model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 244 |
+
"model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 245 |
+
"model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 246 |
+
"model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 247 |
+
"model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 248 |
+
"model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 249 |
+
"model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 250 |
+
"model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 251 |
+
"model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 252 |
+
"model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 253 |
+
"model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 254 |
+
"model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 255 |
+
"model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 256 |
+
"model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 257 |
+
"model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 258 |
+
"model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 259 |
+
"model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 260 |
+
"model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 261 |
+
"model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 262 |
+
"model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 263 |
+
"model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 264 |
+
"model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 265 |
+
"model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 266 |
+
"model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 267 |
+
"model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 268 |
+
"model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 269 |
+
"model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 270 |
+
"model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 271 |
+
"model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 272 |
+
"model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 273 |
+
"model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 274 |
+
"model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 275 |
+
"model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 276 |
+
"model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 277 |
+
"model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 278 |
+
"model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 279 |
+
"model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 280 |
+
"model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 281 |
+
"model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 282 |
+
"model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 283 |
+
"model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 284 |
+
"model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 285 |
+
"model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 286 |
+
"model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 287 |
+
"model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 288 |
+
"model.layers.9.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 289 |
+
"model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 290 |
+
"model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 291 |
+
"model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
| 292 |
+
"model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 293 |
+
"model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 294 |
+
"model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 295 |
+
"model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
| 296 |
+
"model.mm_projector.0.bias": "pytorch_model-00002-of-00002.bin",
|
| 297 |
+
"model.mm_projector.0.weight": "pytorch_model-00002-of-00002.bin",
|
| 298 |
+
"model.mm_projector.2.bias": "pytorch_model-00002-of-00002.bin",
|
| 299 |
+
"model.mm_projector.2.weight": "pytorch_model-00002-of-00002.bin",
|
| 300 |
+
"model.norm.weight": "pytorch_model-00002-of-00002.bin",
|
| 301 |
+
"model.vae_predictor_audio.0.bias": "pytorch_model-00002-of-00002.bin",
|
| 302 |
+
"model.vae_predictor_audio.0.weight": "pytorch_model-00002-of-00002.bin",
|
| 303 |
+
"model.vae_predictor_audio.2.bias": "pytorch_model-00002-of-00002.bin",
|
| 304 |
+
"model.vae_predictor_audio.2.weight": "pytorch_model-00002-of-00002.bin",
|
| 305 |
+
"model.vae_predictor_image.0.bias": "pytorch_model-00002-of-00002.bin",
|
| 306 |
+
"model.vae_predictor_image.0.weight": "pytorch_model-00002-of-00002.bin",
|
| 307 |
+
"model.vae_predictor_image.2.bias": "pytorch_model-00002-of-00002.bin",
|
| 308 |
+
"model.vae_predictor_image.2.weight": "pytorch_model-00002-of-00002.bin",
|
| 309 |
+
"model.vae_projector_audio.0.bias": "pytorch_model-00002-of-00002.bin",
|
| 310 |
+
"model.vae_projector_audio.0.weight": "pytorch_model-00002-of-00002.bin",
|
| 311 |
+
"model.vae_projector_audio.2.bias": "pytorch_model-00002-of-00002.bin",
|
| 312 |
+
"model.vae_projector_audio.2.weight": "pytorch_model-00002-of-00002.bin",
|
| 313 |
+
"model.vae_projector_image.0.bias": "pytorch_model-00002-of-00002.bin",
|
| 314 |
+
"model.vae_projector_image.0.weight": "pytorch_model-00002-of-00002.bin",
|
| 315 |
+
"model.vae_projector_image.2.bias": "pytorch_model-00002-of-00002.bin",
|
| 316 |
+
"model.vae_projector_image.2.weight": "pytorch_model-00002-of-00002.bin",
|
| 317 |
+
"model.vision_tower.vision_tower.vision_model.embeddings.class_embedding": "pytorch_model-00002-of-00002.bin",
|
| 318 |
+
"model.vision_tower.vision_tower.vision_model.embeddings.patch_embedding.weight": "pytorch_model-00002-of-00002.bin",
|
| 319 |
+
"model.vision_tower.vision_tower.vision_model.embeddings.position_embedding.weight": "pytorch_model-00002-of-00002.bin",
|
| 320 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 321 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 322 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 323 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 324 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 325 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 326 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 327 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 328 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 329 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 330 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 331 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 332 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 333 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 334 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 335 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 336 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 337 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 338 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 339 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 340 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 341 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 342 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 343 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 344 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 345 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 346 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 347 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 348 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 349 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 350 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 351 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 352 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 353 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 354 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 355 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 356 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 357 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 358 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 359 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 360 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 361 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 362 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 363 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 364 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 365 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 366 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 367 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 368 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 369 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 370 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 371 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 372 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 373 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 374 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 375 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 376 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 377 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 378 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 379 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 380 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 381 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 382 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 383 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 384 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 385 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 386 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 387 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 388 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 389 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 390 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 391 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 392 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 393 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 394 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 395 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 396 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 397 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 398 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 399 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 400 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 401 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 402 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 403 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 404 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 405 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 406 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 407 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 408 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 409 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 410 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 411 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 412 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 413 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 414 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 415 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 416 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 417 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 418 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 419 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 420 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 421 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 422 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 423 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 424 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 425 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 426 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 427 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 428 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 429 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 430 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 431 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 432 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 433 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 434 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 435 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 436 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 437 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 438 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 439 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 440 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 441 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 442 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 443 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 444 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 445 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 446 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 447 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 448 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 449 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 450 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 451 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 452 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 453 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 454 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 455 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 456 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 457 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 458 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 459 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 460 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 461 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 462 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 463 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 464 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 465 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 466 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 467 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 468 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 469 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 470 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 471 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 472 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 473 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 474 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 475 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 476 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 477 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 478 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 479 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 480 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 481 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 482 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 483 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 484 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 485 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 486 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 487 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 488 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 489 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 490 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 491 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 492 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 493 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 494 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 495 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 496 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 497 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 498 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 499 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 500 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 501 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 502 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 503 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 504 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 505 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 506 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 507 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 508 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 509 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 510 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 511 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 512 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 513 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 514 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 515 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 516 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 517 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 518 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 519 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 520 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 521 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 522 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 523 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 524 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 525 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 526 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 527 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 528 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 529 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 530 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 531 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 532 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 533 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 534 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 535 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 536 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 537 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 538 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 539 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 540 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 541 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 542 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 543 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 544 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 545 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 546 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 547 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 548 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 549 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 550 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 551 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 552 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 553 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 554 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 555 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 556 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 557 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 558 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 559 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 560 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 561 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 562 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 563 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 564 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 565 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 566 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 567 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 568 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 569 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 570 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 571 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 572 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 573 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 574 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 575 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 576 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 577 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 578 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 579 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 580 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 581 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 582 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 583 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 584 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 585 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 586 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 587 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 588 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 589 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 590 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 591 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 592 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 593 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 594 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 595 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 596 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 597 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 598 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 599 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 600 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 601 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 602 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 603 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 604 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 605 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 606 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 607 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 608 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 609 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 610 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 611 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 612 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 613 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 614 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 615 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 616 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 617 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 618 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 619 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 620 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 621 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 622 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 623 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 624 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 625 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 626 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 627 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 628 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 629 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 630 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 631 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 632 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 633 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 634 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 635 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 636 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 637 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 638 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 639 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.26.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 640 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 641 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 642 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 643 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 644 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 645 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 646 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 647 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 648 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 649 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 650 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 651 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 652 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 653 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 654 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 655 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.27.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 656 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 657 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 658 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 659 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 660 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 661 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 662 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 663 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 664 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 665 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 666 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 667 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 668 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 669 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 670 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 671 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.28.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 672 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 673 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 674 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 675 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 676 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 677 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 678 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 679 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 680 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 681 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 682 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 683 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 684 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 685 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 686 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 687 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.29.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 688 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 689 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 690 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 691 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 692 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 693 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 694 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 695 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 696 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 697 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 698 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 699 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 700 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 701 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 702 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 703 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 704 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 705 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 706 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 707 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 708 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 709 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 710 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 711 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 712 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 713 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 714 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 715 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 716 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 717 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 718 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 719 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.30.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 720 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 721 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 722 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 723 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 724 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 725 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 726 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 727 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 728 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 729 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 730 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 731 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 732 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 733 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 734 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 735 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.31.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 736 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 737 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 738 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 739 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 740 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 741 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 742 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 743 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 744 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 745 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 746 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 747 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 748 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 749 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 750 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 751 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 752 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 753 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 754 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 755 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 756 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 757 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 758 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 759 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 760 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 761 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 762 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 763 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 764 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 765 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 766 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 767 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 768 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 769 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 770 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 771 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 772 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 773 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 774 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 775 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 776 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 777 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 778 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 779 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 780 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 781 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 782 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 783 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 784 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 785 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 786 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 787 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 788 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 789 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 790 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 791 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 792 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 793 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 794 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 795 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 796 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 797 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 798 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 799 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 800 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 801 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 802 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 803 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 804 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 805 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 806 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 807 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 808 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 809 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 810 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 811 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 812 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 813 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 814 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 815 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 816 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.layer_norm1.bias": "pytorch_model-00002-of-00002.bin",
|
| 817 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.layer_norm1.weight": "pytorch_model-00002-of-00002.bin",
|
| 818 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.layer_norm2.bias": "pytorch_model-00002-of-00002.bin",
|
| 819 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.layer_norm2.weight": "pytorch_model-00002-of-00002.bin",
|
| 820 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.mlp.fc1.bias": "pytorch_model-00002-of-00002.bin",
|
| 821 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.mlp.fc1.weight": "pytorch_model-00002-of-00002.bin",
|
| 822 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.mlp.fc2.bias": "pytorch_model-00002-of-00002.bin",
|
| 823 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.mlp.fc2.weight": "pytorch_model-00002-of-00002.bin",
|
| 824 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.k_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 825 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 826 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.out_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 827 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.out_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 828 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.q_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 829 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 830 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.v_proj.bias": "pytorch_model-00002-of-00002.bin",
|
| 831 |
+
"model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
| 832 |
+
"model.vision_tower.vision_tower.vision_model.post_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
| 833 |
+
"model.vision_tower.vision_tower.vision_model.post_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 834 |
+
"model.vision_tower.vision_tower.vision_model.pre_layrnorm.bias": "pytorch_model-00002-of-00002.bin",
|
| 835 |
+
"model.vision_tower.vision_tower.vision_model.pre_layrnorm.weight": "pytorch_model-00002-of-00002.bin",
|
| 836 |
+
"model.vision_tower.vision_tower.visual_projection.weight": "pytorch_model-00002-of-00002.bin"
|
| 837 |
+
}
|
| 838 |
+
}
|
ckpts/llm/special_tokens_map.json
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
{
|
| 4 |
+
"content": "<im_gen_start>",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"content": "<im_gen>",
|
| 12 |
+
"lstrip": false,
|
| 13 |
+
"normalized": false,
|
| 14 |
+
"rstrip": false,
|
| 15 |
+
"single_word": false
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"content": "<mask_gen>",
|
| 19 |
+
"lstrip": false,
|
| 20 |
+
"normalized": false,
|
| 21 |
+
"rstrip": false,
|
| 22 |
+
"single_word": false
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"content": "<audio_gen>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": false,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"content": "<audio_gen_start>",
|
| 33 |
+
"lstrip": false,
|
| 34 |
+
"normalized": false,
|
| 35 |
+
"rstrip": false,
|
| 36 |
+
"single_word": false
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"content": "<audio>",
|
| 40 |
+
"lstrip": false,
|
| 41 |
+
"normalized": false,
|
| 42 |
+
"rstrip": false,
|
| 43 |
+
"single_word": false
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"content": "<video>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"content": "<base>",
|
| 54 |
+
"lstrip": false,
|
| 55 |
+
"normalized": false,
|
| 56 |
+
"rstrip": false,
|
| 57 |
+
"single_word": false
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"content": "<base_null>",
|
| 61 |
+
"lstrip": false,
|
| 62 |
+
"normalized": false,
|
| 63 |
+
"rstrip": false,
|
| 64 |
+
"single_word": false
|
| 65 |
+
}
|
| 66 |
+
],
|
| 67 |
+
"bos_token": {
|
| 68 |
+
"content": "<s>",
|
| 69 |
+
"lstrip": false,
|
| 70 |
+
"normalized": false,
|
| 71 |
+
"rstrip": false,
|
| 72 |
+
"single_word": false
|
| 73 |
+
},
|
| 74 |
+
"eos_token": {
|
| 75 |
+
"content": "</s>",
|
| 76 |
+
"lstrip": false,
|
| 77 |
+
"normalized": false,
|
| 78 |
+
"rstrip": false,
|
| 79 |
+
"single_word": false
|
| 80 |
+
},
|
| 81 |
+
"pad_token": "<unk>",
|
| 82 |
+
"unk_token": {
|
| 83 |
+
"content": "<unk>",
|
| 84 |
+
"lstrip": false,
|
| 85 |
+
"normalized": false,
|
| 86 |
+
"rstrip": false,
|
| 87 |
+
"single_word": false
|
| 88 |
+
}
|
| 89 |
+
}
|
ckpts/llm/tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
|
| 3 |
+
size 499723
|
ckpts/llm/tokenizer/added_tokens.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"<audio>": 32005,
|
| 3 |
+
"<audio_gen>": 32003,
|
| 4 |
+
"<audio_gen_start>": 32004,
|
| 5 |
+
"<base>": 32007,
|
| 6 |
+
"<base_null>": 32008,
|
| 7 |
+
"<im_gen>": 32001,
|
| 8 |
+
"<im_gen_start>": 32000,
|
| 9 |
+
"<mask_gen>": 32002,
|
| 10 |
+
"<video>": 32006
|
| 11 |
+
}
|
ckpts/llm/tokenizer/special_tokens_map.json
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
{
|
| 4 |
+
"content": "<im_gen_start>",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"content": "<im_gen>",
|
| 12 |
+
"lstrip": false,
|
| 13 |
+
"normalized": false,
|
| 14 |
+
"rstrip": false,
|
| 15 |
+
"single_word": false
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"content": "<mask_gen>",
|
| 19 |
+
"lstrip": false,
|
| 20 |
+
"normalized": false,
|
| 21 |
+
"rstrip": false,
|
| 22 |
+
"single_word": false
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"content": "<audio_gen>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": false,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"content": "<audio_gen_start>",
|
| 33 |
+
"lstrip": false,
|
| 34 |
+
"normalized": false,
|
| 35 |
+
"rstrip": false,
|
| 36 |
+
"single_word": false
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"content": "<audio>",
|
| 40 |
+
"lstrip": false,
|
| 41 |
+
"normalized": false,
|
| 42 |
+
"rstrip": false,
|
| 43 |
+
"single_word": false
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"content": "<video>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"content": "<base>",
|
| 54 |
+
"lstrip": false,
|
| 55 |
+
"normalized": false,
|
| 56 |
+
"rstrip": false,
|
| 57 |
+
"single_word": false
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"content": "<base_null>",
|
| 61 |
+
"lstrip": false,
|
| 62 |
+
"normalized": false,
|
| 63 |
+
"rstrip": false,
|
| 64 |
+
"single_word": false
|
| 65 |
+
}
|
| 66 |
+
],
|
| 67 |
+
"bos_token": {
|
| 68 |
+
"content": "<s>",
|
| 69 |
+
"lstrip": false,
|
| 70 |
+
"normalized": false,
|
| 71 |
+
"rstrip": false,
|
| 72 |
+
"single_word": false
|
| 73 |
+
},
|
| 74 |
+
"eos_token": {
|
| 75 |
+
"content": "</s>",
|
| 76 |
+
"lstrip": false,
|
| 77 |
+
"normalized": false,
|
| 78 |
+
"rstrip": false,
|
| 79 |
+
"single_word": false
|
| 80 |
+
},
|
| 81 |
+
"pad_token": "<unk>",
|
| 82 |
+
"unk_token": {
|
| 83 |
+
"content": "<unk>",
|
| 84 |
+
"lstrip": false,
|
| 85 |
+
"normalized": false,
|
| 86 |
+
"rstrip": false,
|
| 87 |
+
"single_word": false
|
| 88 |
+
}
|
| 89 |
+
}
|
ckpts/llm/tokenizer/tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
|
| 3 |
+
size 499723
|
ckpts/llm/tokenizer/tokenizer_config.json
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": true,
|
| 3 |
+
"add_eos_token": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"0": {
|
| 6 |
+
"content": "<unk>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"1": {
|
| 14 |
+
"content": "<s>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"2": {
|
| 22 |
+
"content": "</s>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"32000": {
|
| 30 |
+
"content": "<im_gen_start>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"32001": {
|
| 38 |
+
"content": "<im_gen>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"32002": {
|
| 46 |
+
"content": "<mask_gen>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"32003": {
|
| 54 |
+
"content": "<audio_gen>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"32004": {
|
| 62 |
+
"content": "<audio_gen_start>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"32005": {
|
| 70 |
+
"content": "<audio>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"32006": {
|
| 78 |
+
"content": "<video>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"32007": {
|
| 86 |
+
"content": "<base>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"32008": {
|
| 94 |
+
"content": "<base_null>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
}
|
| 101 |
+
},
|
| 102 |
+
"additional_special_tokens": [
|
| 103 |
+
"<im_gen_start>",
|
| 104 |
+
"<im_gen>",
|
| 105 |
+
"<mask_gen>",
|
| 106 |
+
"<audio_gen>",
|
| 107 |
+
"<audio_gen_start>",
|
| 108 |
+
"<audio>",
|
| 109 |
+
"<video>",
|
| 110 |
+
"<base>",
|
| 111 |
+
"<base_null>"
|
| 112 |
+
],
|
| 113 |
+
"bos_token": "<s>",
|
| 114 |
+
"clean_up_tokenization_spaces": false,
|
| 115 |
+
"eos_token": "</s>",
|
| 116 |
+
"legacy": false,
|
| 117 |
+
"model_max_length": 2048,
|
| 118 |
+
"pad_token": "<unk>",
|
| 119 |
+
"padding_side": "right",
|
| 120 |
+
"sp_model_kwargs": {},
|
| 121 |
+
"spaces_between_special_tokens": false,
|
| 122 |
+
"tokenizer_class": "LlamaTokenizer",
|
| 123 |
+
"unk_token": "<unk>",
|
| 124 |
+
"use_default_system_prompt": true
|
| 125 |
+
}
|
ckpts/llm/tokenizer_config.json
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": true,
|
| 3 |
+
"add_eos_token": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"0": {
|
| 6 |
+
"content": "<unk>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"1": {
|
| 14 |
+
"content": "<s>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"2": {
|
| 22 |
+
"content": "</s>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"32000": {
|
| 30 |
+
"content": "<im_gen_start>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"32001": {
|
| 38 |
+
"content": "<im_gen>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"32002": {
|
| 46 |
+
"content": "<mask_gen>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"32003": {
|
| 54 |
+
"content": "<audio_gen>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"32004": {
|
| 62 |
+
"content": "<audio_gen_start>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"32005": {
|
| 70 |
+
"content": "<audio>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"32006": {
|
| 78 |
+
"content": "<video>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"32007": {
|
| 86 |
+
"content": "<base>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"32008": {
|
| 94 |
+
"content": "<base_null>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
}
|
| 101 |
+
},
|
| 102 |
+
"additional_special_tokens": [
|
| 103 |
+
"<im_gen_start>",
|
| 104 |
+
"<im_gen>",
|
| 105 |
+
"<mask_gen>",
|
| 106 |
+
"<audio_gen>",
|
| 107 |
+
"<audio_gen_start>",
|
| 108 |
+
"<audio>",
|
| 109 |
+
"<video>",
|
| 110 |
+
"<base>",
|
| 111 |
+
"<base_null>"
|
| 112 |
+
],
|
| 113 |
+
"bos_token": "<s>",
|
| 114 |
+
"clean_up_tokenization_spaces": false,
|
| 115 |
+
"eos_token": "</s>",
|
| 116 |
+
"legacy": false,
|
| 117 |
+
"model_max_length": 2048,
|
| 118 |
+
"pad_token": "<unk>",
|
| 119 |
+
"padding_side": "right",
|
| 120 |
+
"sp_model_kwargs": {},
|
| 121 |
+
"spaces_between_special_tokens": false,
|
| 122 |
+
"tokenizer_class": "LlamaTokenizer",
|
| 123 |
+
"unk_token": "<unk>",
|
| 124 |
+
"use_default_system_prompt": true
|
| 125 |
+
}
|
ckpts/llm/trainer_state.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
ckpts/llm/training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8155c40679be97018cc40bf6875bbce7adbc0312d8a1fa39e73824896d2fe2f2
|
| 3 |
+
size 6139
|
ckpts/prior/model.bin
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
/home/jacklishufan/AudioLDM2/diffusion_prior_3.bin
|
|
|
|
|
|
ckpts/prior/model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a8a6fe3ed10da0bcbe20dd7bb427ca503584a3a3cdd570fc57c505aaa63c2719
|
| 3 |
+
size 2842310673
|
ckpts/sdxl
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
/localhome/data/ckpts/jacklishufan/sdxl/
|
|
|
|
|
|
ckpts/sdxl/unet/config.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "UnCLipXL",
|
| 3 |
+
"_diffusers_version": "0.22.0.dev0",
|
| 4 |
+
"_name_or_path": "stabilityai/stable-diffusion-xl-base-1.0",
|
| 5 |
+
"act_fn": "silu",
|
| 6 |
+
"addition_embed_type": "text_time",
|
| 7 |
+
"addition_embed_type_num_heads": 64,
|
| 8 |
+
"addition_time_embed_dim": 256,
|
| 9 |
+
"attention_head_dim": [
|
| 10 |
+
5,
|
| 11 |
+
10,
|
| 12 |
+
20
|
| 13 |
+
],
|
| 14 |
+
"attention_type": "default",
|
| 15 |
+
"block_out_channels": [
|
| 16 |
+
320,
|
| 17 |
+
640,
|
| 18 |
+
1280
|
| 19 |
+
],
|
| 20 |
+
"center_input_sample": false,
|
| 21 |
+
"class_embed_type": null,
|
| 22 |
+
"class_embeddings_concat": false,
|
| 23 |
+
"conv_in_kernel": 3,
|
| 24 |
+
"conv_out_kernel": 3,
|
| 25 |
+
"cross_attention_dim": 2048,
|
| 26 |
+
"cross_attention_norm": null,
|
| 27 |
+
"down_block_types": [
|
| 28 |
+
"DownBlock2D",
|
| 29 |
+
"CrossAttnDownBlock2D",
|
| 30 |
+
"CrossAttnDownBlock2D"
|
| 31 |
+
],
|
| 32 |
+
"downsample_padding": 1,
|
| 33 |
+
"dropout": 0,
|
| 34 |
+
"dual_cross_attention": false,
|
| 35 |
+
"encoder_hid_dim": null,
|
| 36 |
+
"encoder_hid_dim_type": null,
|
| 37 |
+
"flip_sin_to_cos": true,
|
| 38 |
+
"freq_shift": 0,
|
| 39 |
+
"in_channels": 4,
|
| 40 |
+
"layers_per_block": 2,
|
| 41 |
+
"mid_block_only_cross_attention": null,
|
| 42 |
+
"mid_block_scale_factor": 1,
|
| 43 |
+
"mid_block_type": "UNetMidBlock2DCrossAttn",
|
| 44 |
+
"norm_eps": 1e-05,
|
| 45 |
+
"norm_num_groups": 32,
|
| 46 |
+
"num_attention_heads": null,
|
| 47 |
+
"num_class_embeds": null,
|
| 48 |
+
"only_cross_attention": false,
|
| 49 |
+
"out_channels": 4,
|
| 50 |
+
"projection_class_embeddings_input_dim": 2816,
|
| 51 |
+
"resnet_out_scale_factor": 1.0,
|
| 52 |
+
"resnet_skip_time_act": false,
|
| 53 |
+
"resnet_time_scale_shift": "default",
|
| 54 |
+
"reverse_transformer_layers_per_block": null,
|
| 55 |
+
"sample_size": 128,
|
| 56 |
+
"time_cond_proj_dim": null,
|
| 57 |
+
"time_embedding_act_fn": null,
|
| 58 |
+
"time_embedding_dim": null,
|
| 59 |
+
"time_embedding_type": "positional",
|
| 60 |
+
"timestep_post_act": null,
|
| 61 |
+
"transformer_layers_per_block": [
|
| 62 |
+
1,
|
| 63 |
+
2,
|
| 64 |
+
10
|
| 65 |
+
],
|
| 66 |
+
"up_block_types": [
|
| 67 |
+
"CrossAttnUpBlock2D",
|
| 68 |
+
"CrossAttnUpBlock2D",
|
| 69 |
+
"UpBlock2D"
|
| 70 |
+
],
|
| 71 |
+
"upcast_attention": null,
|
| 72 |
+
"use_linear_projection": true
|
| 73 |
+
}
|
ckpts/sdxl/unet/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:37086d06af3b51cdd461ff6430fd724805649df554cb39372a7dc644bb6ff49c
|
| 3 |
+
size 5177116640
|
demo.ipynb
CHANGED
|
@@ -213,7 +213,7 @@
|
|
| 213 |
],
|
| 214 |
"source": [
|
| 215 |
"torch.manual_seed(0)\n",
|
| 216 |
-
"res0,res,
|
| 217 |
]
|
| 218 |
},
|
| 219 |
{
|
|
|
|
| 213 |
],
|
| 214 |
"source": [
|
| 215 |
"torch.manual_seed(0)\n",
|
| 216 |
+
"res0,res,_ = pipe(inst,mm_data,alpha = 1.0,h=[0.4,0.6,0.4],norm=20.0,refinement=0.3,llm_only=False,num_inference_steps=50)"
|
| 217 |
]
|
| 218 |
},
|
| 219 |
{
|
instructany2pix/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
from .pipeline import InstructAny2PixPipeline
|
|
|
|
|
|
instructany2pix/ddim/pnp_pipeline.py
DELETED
|
@@ -1,524 +0,0 @@
|
|
| 1 |
-
# Plug&Play Feature Injection
|
| 2 |
-
|
| 3 |
-
import torch
|
| 4 |
-
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 5 |
-
|
| 6 |
-
from diffusers import (
|
| 7 |
-
StableDiffusionXLPipeline,
|
| 8 |
-
StableDiffusionXLImg2ImgPipeline,
|
| 9 |
-
DDIMScheduler,
|
| 10 |
-
)
|
| 11 |
-
|
| 12 |
-
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
|
| 13 |
-
rescale_noise_cfg,
|
| 14 |
-
StableDiffusionXLPipelineOutput,
|
| 15 |
-
)
|
| 16 |
-
|
| 17 |
-
import PIL
|
| 18 |
-
import numpy as np
|
| 19 |
-
|
| 20 |
-
from tqdm import tqdm
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
def _get_add_time_ids(
|
| 24 |
-
self,
|
| 25 |
-
original_size,
|
| 26 |
-
crops_coords_top_left,
|
| 27 |
-
target_size,
|
| 28 |
-
aesthetic_score,
|
| 29 |
-
negative_aesthetic_score,
|
| 30 |
-
negative_original_size,
|
| 31 |
-
negative_crops_coords_top_left,
|
| 32 |
-
negative_target_size,
|
| 33 |
-
dtype,
|
| 34 |
-
):
|
| 35 |
-
if self.config.requires_aesthetics_score:
|
| 36 |
-
add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
|
| 37 |
-
add_neg_time_ids = list(
|
| 38 |
-
negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
|
| 39 |
-
)
|
| 40 |
-
else:
|
| 41 |
-
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
| 42 |
-
add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
|
| 43 |
-
|
| 44 |
-
passed_add_embed_dim = (
|
| 45 |
-
self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
|
| 46 |
-
)
|
| 47 |
-
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
| 48 |
-
|
| 49 |
-
if (
|
| 50 |
-
expected_add_embed_dim > passed_add_embed_dim
|
| 51 |
-
and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
|
| 52 |
-
):
|
| 53 |
-
raise ValueError(
|
| 54 |
-
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
|
| 55 |
-
)
|
| 56 |
-
elif (
|
| 57 |
-
expected_add_embed_dim < passed_add_embed_dim
|
| 58 |
-
and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
|
| 59 |
-
):
|
| 60 |
-
raise ValueError(
|
| 61 |
-
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
|
| 62 |
-
)
|
| 63 |
-
elif expected_add_embed_dim != passed_add_embed_dim:
|
| 64 |
-
raise ValueError(
|
| 65 |
-
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
| 69 |
-
add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
|
| 70 |
-
|
| 71 |
-
return add_time_ids, add_neg_time_ids
|
| 72 |
-
|
| 73 |
-
def _backward_ddim(x_tm1, alpha_t, alpha_tm1, eps_xt):
|
| 74 |
-
"""
|
| 75 |
-
let a = alpha_t, b = alpha_{t - 1}
|
| 76 |
-
We have a > b,
|
| 77 |
-
x_{t} - x_{t - 1} = sqrt(a) ((sqrt(1/b) - sqrt(1/a)) * x_{t-1} + (sqrt(1/a - 1) - sqrt(1/b - 1)) * eps_{t-1})
|
| 78 |
-
From https://arxiv.org/pdf/2105.05233.pdf, section F.
|
| 79 |
-
"""
|
| 80 |
-
|
| 81 |
-
a, b = alpha_t, alpha_tm1
|
| 82 |
-
sa = a**0.5
|
| 83 |
-
sb = b**0.5
|
| 84 |
-
|
| 85 |
-
return sa * ((1 / sb) * x_tm1 + ((1 / a - 1) ** 0.5 - (1 / b - 1) ** 0.5) * eps_xt)
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
class SDXLDDIMPipeline(StableDiffusionXLImg2ImgPipeline):
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
@torch.no_grad()
|
| 92 |
-
def inverse(
|
| 93 |
-
self,
|
| 94 |
-
prompt: Union[str, List[str]] = None,
|
| 95 |
-
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 96 |
-
image: Union[
|
| 97 |
-
torch.FloatTensor,
|
| 98 |
-
PIL.Image.Image,
|
| 99 |
-
np.ndarray,
|
| 100 |
-
List[torch.FloatTensor],
|
| 101 |
-
List[PIL.Image.Image],
|
| 102 |
-
List[np.ndarray],
|
| 103 |
-
] = None,
|
| 104 |
-
strength: float = 0.3,
|
| 105 |
-
num_inference_steps: int = 50,
|
| 106 |
-
denoising_start: Optional[float] = None,
|
| 107 |
-
denoising_end: Optional[float] = None,
|
| 108 |
-
guidance_scale: float = 5.0,
|
| 109 |
-
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 110 |
-
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 111 |
-
num_images_per_prompt: Optional[int] = 1,
|
| 112 |
-
eta: float = 0.0,
|
| 113 |
-
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 114 |
-
latents: Optional[torch.FloatTensor] = None,
|
| 115 |
-
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 116 |
-
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 117 |
-
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 118 |
-
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 119 |
-
output_type: Optional[str] = "pil",
|
| 120 |
-
return_dict: bool = True,
|
| 121 |
-
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 122 |
-
callback_steps: int = 1,
|
| 123 |
-
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 124 |
-
guidance_rescale: float = 0.0,
|
| 125 |
-
original_size: Tuple[int, int] = None,
|
| 126 |
-
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 127 |
-
target_size: Tuple[int, int] = None,
|
| 128 |
-
aesthetic_score: float = 6.0,
|
| 129 |
-
negative_aesthetic_score: float = 2.5,
|
| 130 |
-
#clip_skip=None,
|
| 131 |
-
):
|
| 132 |
-
self.scheduler = DDIMScheduler.from_config(self.scheduler.config)
|
| 133 |
-
|
| 134 |
-
# 1. Check inputs. Raise error if not correct
|
| 135 |
-
self.check_inputs(
|
| 136 |
-
prompt,
|
| 137 |
-
prompt_2,
|
| 138 |
-
strength,
|
| 139 |
-
num_inference_steps,
|
| 140 |
-
callback_steps,
|
| 141 |
-
negative_prompt,
|
| 142 |
-
negative_prompt_2,
|
| 143 |
-
prompt_embeds,
|
| 144 |
-
negative_prompt_embeds,
|
| 145 |
-
)
|
| 146 |
-
|
| 147 |
-
# 2. Define call parameters
|
| 148 |
-
if prompt is not None and isinstance(prompt, str):
|
| 149 |
-
batch_size = 1
|
| 150 |
-
elif prompt is not None and isinstance(prompt, list):
|
| 151 |
-
batch_size = len(prompt)
|
| 152 |
-
else:
|
| 153 |
-
batch_size = prompt_embeds.shape[0]
|
| 154 |
-
|
| 155 |
-
device = self._execution_device
|
| 156 |
-
|
| 157 |
-
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 158 |
-
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 159 |
-
# corresponds to doing no classifier free guidance.
|
| 160 |
-
do_classifier_free_guidance = False
|
| 161 |
-
# 3. Encode input prompt
|
| 162 |
-
text_encoder_lora_scale = (
|
| 163 |
-
cross_attention_kwargs.get("scale", None)
|
| 164 |
-
if cross_attention_kwargs is not None
|
| 165 |
-
else None
|
| 166 |
-
)
|
| 167 |
-
(
|
| 168 |
-
prompt_embeds,
|
| 169 |
-
negative_prompt_embeds,
|
| 170 |
-
pooled_prompt_embeds,
|
| 171 |
-
negative_pooled_prompt_embeds,
|
| 172 |
-
) = self.encode_prompt(
|
| 173 |
-
prompt=prompt,
|
| 174 |
-
prompt_2=prompt_2,
|
| 175 |
-
device=device,
|
| 176 |
-
num_images_per_prompt=num_images_per_prompt,
|
| 177 |
-
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 178 |
-
negative_prompt=negative_prompt,
|
| 179 |
-
negative_prompt_2=negative_prompt_2,
|
| 180 |
-
prompt_embeds=prompt_embeds,
|
| 181 |
-
negative_prompt_embeds=negative_prompt_embeds,
|
| 182 |
-
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 183 |
-
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 184 |
-
lora_scale=text_encoder_lora_scale,
|
| 185 |
-
#clip_skip=clip_skip,
|
| 186 |
-
)
|
| 187 |
-
|
| 188 |
-
# 4. Preprocess image
|
| 189 |
-
image = self.image_processor.preprocess(image)
|
| 190 |
-
|
| 191 |
-
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 192 |
-
|
| 193 |
-
# 6. Prepare latent variables
|
| 194 |
-
latents = self.prepare_latents(
|
| 195 |
-
image,
|
| 196 |
-
None,
|
| 197 |
-
batch_size,
|
| 198 |
-
num_images_per_prompt,
|
| 199 |
-
prompt_embeds.dtype,
|
| 200 |
-
device,
|
| 201 |
-
generator,
|
| 202 |
-
False,
|
| 203 |
-
)
|
| 204 |
-
|
| 205 |
-
height, width = latents.shape[-2:]
|
| 206 |
-
height = height * self.vae_scale_factor
|
| 207 |
-
width = width * self.vae_scale_factor
|
| 208 |
-
|
| 209 |
-
original_size = original_size or (height, width)
|
| 210 |
-
target_size = target_size or (height, width)
|
| 211 |
-
|
| 212 |
-
# 8. Prepare added time ids & embeddings
|
| 213 |
-
add_text_embeds = pooled_prompt_embeds
|
| 214 |
-
negative_original_size = None
|
| 215 |
-
negative_crops_coords_top_left = None
|
| 216 |
-
negative_target_size = None
|
| 217 |
-
if negative_original_size is None:
|
| 218 |
-
negative_original_size = original_size
|
| 219 |
-
if negative_target_size is None:
|
| 220 |
-
negative_target_size = target_size
|
| 221 |
-
negative_crops_coords_top_left = (0,0)
|
| 222 |
-
if self.text_encoder_2 is None:
|
| 223 |
-
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
| 224 |
-
else:
|
| 225 |
-
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
| 226 |
-
|
| 227 |
-
add_time_ids, add_neg_time_ids = _get_add_time_ids(self,
|
| 228 |
-
original_size,
|
| 229 |
-
crops_coords_top_left,
|
| 230 |
-
target_size,
|
| 231 |
-
aesthetic_score,
|
| 232 |
-
negative_aesthetic_score,
|
| 233 |
-
negative_original_size,
|
| 234 |
-
negative_crops_coords_top_left,
|
| 235 |
-
negative_target_size,
|
| 236 |
-
dtype=prompt_embeds.dtype,
|
| 237 |
-
#text_encoder_projection_dim=text_encoder_projection_dim,
|
| 238 |
-
)
|
| 239 |
-
add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
|
| 240 |
-
|
| 241 |
-
prompt_embeds = prompt_embeds.to(device)
|
| 242 |
-
add_text_embeds = add_text_embeds.to(device)
|
| 243 |
-
add_time_ids = add_time_ids.to(device)
|
| 244 |
-
|
| 245 |
-
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 246 |
-
prev_timestep = None
|
| 247 |
-
|
| 248 |
-
for t in tqdm(reversed(self.scheduler.timesteps)):
|
| 249 |
-
latent_model_input = latents
|
| 250 |
-
noise_pred = self.unet(
|
| 251 |
-
latent_model_input,
|
| 252 |
-
t,
|
| 253 |
-
encoder_hidden_states=prompt_embeds,
|
| 254 |
-
cross_attention_kwargs=cross_attention_kwargs,
|
| 255 |
-
added_cond_kwargs={k:v for k,v in added_cond_kwargs.items()},
|
| 256 |
-
return_dict=False,
|
| 257 |
-
)[0]
|
| 258 |
-
|
| 259 |
-
alpha_prod_t = self.scheduler.alphas_cumprod[t]
|
| 260 |
-
alpha_prod_t_prev = (
|
| 261 |
-
self.scheduler.alphas_cumprod[prev_timestep]
|
| 262 |
-
if prev_timestep is not None
|
| 263 |
-
else self.scheduler.final_alpha_cumprod
|
| 264 |
-
)
|
| 265 |
-
prev_timestep = t
|
| 266 |
-
|
| 267 |
-
latents = _backward_ddim(
|
| 268 |
-
x_tm1=latents,
|
| 269 |
-
alpha_t=alpha_prod_t,
|
| 270 |
-
alpha_tm1=alpha_prod_t_prev,
|
| 271 |
-
eps_xt=noise_pred,
|
| 272 |
-
)
|
| 273 |
-
|
| 274 |
-
image = latents
|
| 275 |
-
return StableDiffusionXLPipelineOutput(images=image)
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
class SDXLPNPPipeline(StableDiffusionXLPipeline):
|
| 279 |
-
def __init__(
|
| 280 |
-
self,
|
| 281 |
-
*args,
|
| 282 |
-
**kwargs,
|
| 283 |
-
):
|
| 284 |
-
super().__init__(*args, **kwargs)
|
| 285 |
-
self.feature_bags = {}
|
| 286 |
-
|
| 287 |
-
def __call__(
|
| 288 |
-
self,
|
| 289 |
-
prompt: Union[str, List[str]] = None,
|
| 290 |
-
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 291 |
-
height: Optional[int] = None,
|
| 292 |
-
width: Optional[int] = None,
|
| 293 |
-
num_inference_steps: int = 50,
|
| 294 |
-
denoising_end: Optional[float] = None,
|
| 295 |
-
guidance_scale: float = 5.0,
|
| 296 |
-
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 297 |
-
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 298 |
-
num_images_per_prompt: Optional[int] = 1,
|
| 299 |
-
eta: float = 0.0,
|
| 300 |
-
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 301 |
-
latents: Optional[torch.FloatTensor] = None,
|
| 302 |
-
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 303 |
-
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 304 |
-
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 305 |
-
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 306 |
-
output_type: Optional[str] = "pil",
|
| 307 |
-
return_dict: bool = True,
|
| 308 |
-
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 309 |
-
callback_steps: int = 1,
|
| 310 |
-
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 311 |
-
guidance_rescale: float = 0.0,
|
| 312 |
-
original_size: Optional[Tuple[int, int]] = None,
|
| 313 |
-
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 314 |
-
target_size: Optional[Tuple[int, int]] = None,
|
| 315 |
-
):
|
| 316 |
-
height = height or self.default_sample_size * self.vae_scale_factor
|
| 317 |
-
width = width or self.default_sample_size * self.vae_scale_factor
|
| 318 |
-
|
| 319 |
-
original_size = original_size or (height, width)
|
| 320 |
-
target_size = target_size or (height, width)
|
| 321 |
-
|
| 322 |
-
# 1. Check inputs. Raise error if not correct
|
| 323 |
-
self.check_inputs(
|
| 324 |
-
prompt,
|
| 325 |
-
prompt_2,
|
| 326 |
-
height,
|
| 327 |
-
width,
|
| 328 |
-
callback_steps,
|
| 329 |
-
negative_prompt,
|
| 330 |
-
negative_prompt_2,
|
| 331 |
-
prompt_embeds,
|
| 332 |
-
negative_prompt_embeds,
|
| 333 |
-
pooled_prompt_embeds,
|
| 334 |
-
negative_pooled_prompt_embeds,
|
| 335 |
-
)
|
| 336 |
-
|
| 337 |
-
# 2. Define call parameters
|
| 338 |
-
if prompt is not None and isinstance(prompt, str):
|
| 339 |
-
batch_size = 1
|
| 340 |
-
elif prompt is not None and isinstance(prompt, list):
|
| 341 |
-
batch_size = len(prompt)
|
| 342 |
-
else:
|
| 343 |
-
batch_size = prompt_embeds.shape[0]
|
| 344 |
-
|
| 345 |
-
device = self._execution_device
|
| 346 |
-
|
| 347 |
-
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 348 |
-
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 349 |
-
# corresponds to doing no classifier free guidance.
|
| 350 |
-
do_classifier_free_guidance = guidance_scale > 1.0
|
| 351 |
-
|
| 352 |
-
# 3. Encode input prompt
|
| 353 |
-
text_encoder_lora_scale = (
|
| 354 |
-
cross_attention_kwargs.get("scale", None)
|
| 355 |
-
if cross_attention_kwargs is not None
|
| 356 |
-
else None
|
| 357 |
-
)
|
| 358 |
-
(
|
| 359 |
-
prompt_embeds,
|
| 360 |
-
negative_prompt_embeds,
|
| 361 |
-
pooled_prompt_embeds,
|
| 362 |
-
negative_pooled_prompt_embeds,
|
| 363 |
-
) = self.encode_prompt(
|
| 364 |
-
prompt=prompt,
|
| 365 |
-
prompt_2=prompt_2,
|
| 366 |
-
device=device,
|
| 367 |
-
num_images_per_prompt=num_images_per_prompt,
|
| 368 |
-
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 369 |
-
negative_prompt=negative_prompt,
|
| 370 |
-
negative_prompt_2=negative_prompt_2,
|
| 371 |
-
prompt_embeds=prompt_embeds,
|
| 372 |
-
negative_prompt_embeds=negative_prompt_embeds,
|
| 373 |
-
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 374 |
-
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 375 |
-
lora_scale=text_encoder_lora_scale,
|
| 376 |
-
)
|
| 377 |
-
|
| 378 |
-
# 4. Prepare timesteps
|
| 379 |
-
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 380 |
-
|
| 381 |
-
timesteps = self.scheduler.timesteps
|
| 382 |
-
|
| 383 |
-
# 5. Prepare latent variables
|
| 384 |
-
num_channels_latents = self.unet.config.in_channels
|
| 385 |
-
latents = self.prepare_latents(
|
| 386 |
-
batch_size * num_images_per_prompt,
|
| 387 |
-
num_channels_latents,
|
| 388 |
-
height,
|
| 389 |
-
width,
|
| 390 |
-
prompt_embeds.dtype,
|
| 391 |
-
device,
|
| 392 |
-
generator,
|
| 393 |
-
latents,
|
| 394 |
-
)
|
| 395 |
-
|
| 396 |
-
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 397 |
-
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 398 |
-
|
| 399 |
-
# 7. Prepare added time ids & embeddings
|
| 400 |
-
add_text_embeds = pooled_prompt_embeds
|
| 401 |
-
add_time_ids = self._get_add_time_ids(
|
| 402 |
-
original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
|
| 403 |
-
)
|
| 404 |
-
|
| 405 |
-
if do_classifier_free_guidance:
|
| 406 |
-
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
| 407 |
-
add_text_embeds = torch.cat(
|
| 408 |
-
[negative_pooled_prompt_embeds, add_text_embeds], dim=0
|
| 409 |
-
)
|
| 410 |
-
add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
|
| 411 |
-
|
| 412 |
-
prompt_embeds = prompt_embeds.to(device)
|
| 413 |
-
add_text_embeds = add_text_embeds.to(device)
|
| 414 |
-
add_time_ids = add_time_ids.to(device).repeat(
|
| 415 |
-
batch_size * num_images_per_prompt, 1
|
| 416 |
-
)
|
| 417 |
-
|
| 418 |
-
# 8. Denoising loop
|
| 419 |
-
num_warmup_steps = max(
|
| 420 |
-
len(timesteps) - num_inference_steps * self.scheduler.order, 0
|
| 421 |
-
)
|
| 422 |
-
|
| 423 |
-
# 7.1 Apply denoising_end
|
| 424 |
-
if (
|
| 425 |
-
denoising_end is not None
|
| 426 |
-
and type(denoising_end) == float
|
| 427 |
-
and denoising_end > 0
|
| 428 |
-
and denoising_end < 1
|
| 429 |
-
):
|
| 430 |
-
discrete_timestep_cutoff = int(
|
| 431 |
-
round(
|
| 432 |
-
self.scheduler.config.num_train_timesteps
|
| 433 |
-
- (denoising_end * self.scheduler.config.num_train_timesteps)
|
| 434 |
-
)
|
| 435 |
-
)
|
| 436 |
-
num_inference_steps = len(
|
| 437 |
-
list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps))
|
| 438 |
-
)
|
| 439 |
-
timesteps = timesteps[:num_inference_steps]
|
| 440 |
-
|
| 441 |
-
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 442 |
-
for i, t in enumerate(timesteps):
|
| 443 |
-
# expand the latents if we are doing classifier free guidance
|
| 444 |
-
# print(t)
|
| 445 |
-
latent_model_input = (
|
| 446 |
-
torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 447 |
-
)
|
| 448 |
-
|
| 449 |
-
latent_model_input = self.scheduler.scale_model_input(
|
| 450 |
-
latent_model_input, t
|
| 451 |
-
)
|
| 452 |
-
|
| 453 |
-
# predict the noise residual
|
| 454 |
-
|
| 455 |
-
added_cond_kwargs = {
|
| 456 |
-
"text_embeds": add_text_embeds[:1, ...],
|
| 457 |
-
"time_ids": add_time_ids[:1, ...],
|
| 458 |
-
}
|
| 459 |
-
noise_pred_text, feats = self.unet(
|
| 460 |
-
latent_model_input[:1, ...],
|
| 461 |
-
t,
|
| 462 |
-
encoder_hidden_states=prompt_embeds[:1, ...],
|
| 463 |
-
added_cond_kwargs=added_cond_kwargs,
|
| 464 |
-
return_dict=False,
|
| 465 |
-
)[0]
|
| 466 |
-
|
| 467 |
-
added_cond_kwargs = {
|
| 468 |
-
"text_embeds": add_text_embeds[1:2, ...],
|
| 469 |
-
"time_ids": add_time_ids[1:2, ...],
|
| 470 |
-
}
|
| 471 |
-
noise_pred_uncond, feats = self.unet(
|
| 472 |
-
latent_model_input[1:2, ...],
|
| 473 |
-
t,
|
| 474 |
-
encoder_hidden_states=prompt_embeds[1:2, ...],
|
| 475 |
-
added_cond_kwargs=added_cond_kwargs,
|
| 476 |
-
return_dict=False,
|
| 477 |
-
)[0]
|
| 478 |
-
|
| 479 |
-
noise_pred = noise_pred_uncond + guidance_scale * (
|
| 480 |
-
noise_pred_text - noise_pred_uncond
|
| 481 |
-
)
|
| 482 |
-
|
| 483 |
-
# compute the previous noisy sample x_t -> x_t-1
|
| 484 |
-
latents = self.scheduler.step(
|
| 485 |
-
noise_pred, t, latents, **extra_step_kwargs, return_dict=False
|
| 486 |
-
)[0]
|
| 487 |
-
|
| 488 |
-
# call the callback, if provided
|
| 489 |
-
if i == len(timesteps) - 1 or (
|
| 490 |
-
(i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
|
| 491 |
-
):
|
| 492 |
-
progress_bar.update()
|
| 493 |
-
if callback is not None and i % callback_steps == 0:
|
| 494 |
-
callback(i, t, latents)
|
| 495 |
-
|
| 496 |
-
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 497 |
-
if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
|
| 498 |
-
self.upcast_vae()
|
| 499 |
-
latents = latents.to(
|
| 500 |
-
next(iter(self.vae.post_quant_conv.parameters())).dtype
|
| 501 |
-
)
|
| 502 |
-
|
| 503 |
-
if not output_type == "latent":
|
| 504 |
-
image = self.vae.decode(
|
| 505 |
-
latents / self.vae.config.scaling_factor, return_dict=False
|
| 506 |
-
)[0]
|
| 507 |
-
else:
|
| 508 |
-
image = latents
|
| 509 |
-
return StableDiffusionXLPipelineOutput(images=image)
|
| 510 |
-
|
| 511 |
-
# apply watermark if available
|
| 512 |
-
if self.watermark is not None:
|
| 513 |
-
image = self.watermark.apply_watermark(image)
|
| 514 |
-
|
| 515 |
-
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 516 |
-
|
| 517 |
-
# Offload last model to CPU
|
| 518 |
-
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
| 519 |
-
self.final_offload_hook.offload()
|
| 520 |
-
|
| 521 |
-
if not return_dict:
|
| 522 |
-
return (image,)
|
| 523 |
-
|
| 524 |
-
return StableDiffusionXLPipelineOutput(images=image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/ddim/sdxl_pipeline.py
DELETED
|
@@ -1,990 +0,0 @@
|
|
| 1 |
-
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
-
#
|
| 3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
-
# you may not use this file except in compliance with the License.
|
| 5 |
-
# You may obtain a copy of the License at
|
| 6 |
-
#
|
| 7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
-
#
|
| 9 |
-
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
-
# See the License for the specific language governing permissions and
|
| 13 |
-
# limitations under the License.
|
| 14 |
-
|
| 15 |
-
import inspect
|
| 16 |
-
import os
|
| 17 |
-
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 18 |
-
|
| 19 |
-
import torch
|
| 20 |
-
from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
|
| 21 |
-
|
| 22 |
-
from diffusers.image_processor import VaeImageProcessor
|
| 23 |
-
from diffusers.loaders import (
|
| 24 |
-
FromSingleFileMixin,
|
| 25 |
-
LoraLoaderMixin,
|
| 26 |
-
TextualInversionLoaderMixin,
|
| 27 |
-
)
|
| 28 |
-
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
| 29 |
-
from diffusers.models.attention_processor import (
|
| 30 |
-
AttnProcessor2_0,
|
| 31 |
-
LoRAAttnProcessor2_0,
|
| 32 |
-
LoRAXFormersAttnProcessor,
|
| 33 |
-
XFormersAttnProcessor,
|
| 34 |
-
)
|
| 35 |
-
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
| 36 |
-
from diffusers.schedulers import KarrasDiffusionSchedulers
|
| 37 |
-
from diffusers.utils import (
|
| 38 |
-
is_accelerate_available,
|
| 39 |
-
is_accelerate_version,
|
| 40 |
-
is_invisible_watermark_available,
|
| 41 |
-
logging,
|
| 42 |
-
replace_example_docstring,
|
| 43 |
-
)
|
| 44 |
-
from diffusers.utils.torch_utils import randn_tensor
|
| 45 |
-
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 46 |
-
from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
if is_invisible_watermark_available():
|
| 50 |
-
from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 54 |
-
|
| 55 |
-
EXAMPLE_DOC_STRING = """
|
| 56 |
-
Examples:
|
| 57 |
-
```py
|
| 58 |
-
>>> import torch
|
| 59 |
-
>>> from diffusers import StableDiffusionXLPipeline
|
| 60 |
-
|
| 61 |
-
>>> pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 62 |
-
... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
| 63 |
-
... )
|
| 64 |
-
>>> pipe = pipe.to("cuda")
|
| 65 |
-
|
| 66 |
-
>>> prompt = "a photo of an astronaut riding a horse on mars"
|
| 67 |
-
>>> image = pipe(prompt).images[0]
|
| 68 |
-
```
|
| 69 |
-
"""
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
|
| 73 |
-
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
| 74 |
-
"""
|
| 75 |
-
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
| 76 |
-
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
| 77 |
-
"""
|
| 78 |
-
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
| 79 |
-
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
| 80 |
-
# rescale the results from guidance (fixes overexposure)
|
| 81 |
-
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
| 82 |
-
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
| 83 |
-
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
| 84 |
-
return noise_cfg
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
class StableDiffusionXLPipeline(DiffusionPipeline, FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin):
|
| 88 |
-
r"""
|
| 89 |
-
Pipeline for text-to-image generation using Stable Diffusion XL.
|
| 90 |
-
|
| 91 |
-
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
| 92 |
-
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
| 93 |
-
|
| 94 |
-
In addition the pipeline inherits the following loading methods:
|
| 95 |
-
- *LoRA*: [`StableDiffusionXLPipeline.load_lora_weights`]
|
| 96 |
-
- *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
|
| 97 |
-
|
| 98 |
-
as well as the following saving methods:
|
| 99 |
-
- *LoRA*: [`loaders.StableDiffusionXLPipeline.save_lora_weights`]
|
| 100 |
-
|
| 101 |
-
Args:
|
| 102 |
-
vae ([`AutoencoderKL`]):
|
| 103 |
-
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 104 |
-
text_encoder ([`CLIPTextModel`]):
|
| 105 |
-
Frozen text-encoder. Stable Diffusion XL uses the text portion of
|
| 106 |
-
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
| 107 |
-
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
| 108 |
-
text_encoder_2 ([` CLIPTextModelWithProjection`]):
|
| 109 |
-
Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
|
| 110 |
-
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
| 111 |
-
specifically the
|
| 112 |
-
[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
|
| 113 |
-
variant.
|
| 114 |
-
tokenizer (`CLIPTokenizer`):
|
| 115 |
-
Tokenizer of class
|
| 116 |
-
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 117 |
-
tokenizer_2 (`CLIPTokenizer`):
|
| 118 |
-
Second Tokenizer of class
|
| 119 |
-
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 120 |
-
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
| 121 |
-
scheduler ([`SchedulerMixin`]):
|
| 122 |
-
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 123 |
-
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 124 |
-
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
|
| 125 |
-
Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
|
| 126 |
-
`stabilityai/stable-diffusion-xl-base-1-0`.
|
| 127 |
-
add_watermarker (`bool`, *optional*):
|
| 128 |
-
Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
|
| 129 |
-
watermark output images. If not defined, it will default to True if the package is installed, otherwise no
|
| 130 |
-
watermarker will be used.
|
| 131 |
-
"""
|
| 132 |
-
model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
|
| 133 |
-
|
| 134 |
-
def __init__(
|
| 135 |
-
self,
|
| 136 |
-
vae: AutoencoderKL,
|
| 137 |
-
text_encoder: CLIPTextModel,
|
| 138 |
-
text_encoder_2: CLIPTextModelWithProjection,
|
| 139 |
-
tokenizer: CLIPTokenizer,
|
| 140 |
-
tokenizer_2: CLIPTokenizer,
|
| 141 |
-
unet: UNet2DConditionModel,
|
| 142 |
-
scheduler: KarrasDiffusionSchedulers,
|
| 143 |
-
force_zeros_for_empty_prompt: bool = True,
|
| 144 |
-
add_watermarker: Optional[bool] = False,
|
| 145 |
-
):
|
| 146 |
-
super().__init__()
|
| 147 |
-
|
| 148 |
-
self.register_modules(
|
| 149 |
-
vae=vae,
|
| 150 |
-
text_encoder=text_encoder,
|
| 151 |
-
text_encoder_2=text_encoder_2,
|
| 152 |
-
tokenizer=tokenizer,
|
| 153 |
-
tokenizer_2=tokenizer_2,
|
| 154 |
-
unet=unet,
|
| 155 |
-
scheduler=scheduler,
|
| 156 |
-
)
|
| 157 |
-
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
| 158 |
-
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 159 |
-
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 160 |
-
self.default_sample_size = self.unet.config.sample_size
|
| 161 |
-
|
| 162 |
-
add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
|
| 163 |
-
|
| 164 |
-
if add_watermarker:
|
| 165 |
-
self.watermark = StableDiffusionXLWatermarker()
|
| 166 |
-
else:
|
| 167 |
-
self.watermark = None
|
| 168 |
-
|
| 169 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
|
| 170 |
-
def enable_vae_slicing(self):
|
| 171 |
-
r"""
|
| 172 |
-
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 173 |
-
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 174 |
-
"""
|
| 175 |
-
self.vae.enable_slicing()
|
| 176 |
-
|
| 177 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
|
| 178 |
-
def disable_vae_slicing(self):
|
| 179 |
-
r"""
|
| 180 |
-
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
| 181 |
-
computing decoding in one step.
|
| 182 |
-
"""
|
| 183 |
-
self.vae.disable_slicing()
|
| 184 |
-
|
| 185 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
|
| 186 |
-
def enable_vae_tiling(self):
|
| 187 |
-
r"""
|
| 188 |
-
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 189 |
-
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 190 |
-
processing larger images.
|
| 191 |
-
"""
|
| 192 |
-
self.vae.enable_tiling()
|
| 193 |
-
|
| 194 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
|
| 195 |
-
def disable_vae_tiling(self):
|
| 196 |
-
r"""
|
| 197 |
-
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
| 198 |
-
computing decoding in one step.
|
| 199 |
-
"""
|
| 200 |
-
self.vae.disable_tiling()
|
| 201 |
-
|
| 202 |
-
def encode_prompt(
|
| 203 |
-
self,
|
| 204 |
-
prompt: str,
|
| 205 |
-
prompt_2: Optional[str] = None,
|
| 206 |
-
device: Optional[torch.device] = None,
|
| 207 |
-
num_images_per_prompt: int = 1,
|
| 208 |
-
do_classifier_free_guidance: bool = True,
|
| 209 |
-
negative_prompt: Optional[str] = None,
|
| 210 |
-
negative_prompt_2: Optional[str] = None,
|
| 211 |
-
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 212 |
-
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 213 |
-
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 214 |
-
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 215 |
-
lora_scale: Optional[float] = None,
|
| 216 |
-
):
|
| 217 |
-
r"""
|
| 218 |
-
Encodes the prompt into text encoder hidden states.
|
| 219 |
-
|
| 220 |
-
Args:
|
| 221 |
-
prompt (`str` or `List[str]`, *optional*):
|
| 222 |
-
prompt to be encoded
|
| 223 |
-
prompt_2 (`str` or `List[str]`, *optional*):
|
| 224 |
-
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 225 |
-
used in both text-encoders
|
| 226 |
-
device: (`torch.device`):
|
| 227 |
-
torch device
|
| 228 |
-
num_images_per_prompt (`int`):
|
| 229 |
-
number of images that should be generated per prompt
|
| 230 |
-
do_classifier_free_guidance (`bool`):
|
| 231 |
-
whether to use classifier free guidance or not
|
| 232 |
-
negative_prompt (`str` or `List[str]`, *optional*):
|
| 233 |
-
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 234 |
-
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 235 |
-
less than `1`).
|
| 236 |
-
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 237 |
-
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
| 238 |
-
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
| 239 |
-
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 240 |
-
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 241 |
-
provided, text embeddings will be generated from `prompt` input argument.
|
| 242 |
-
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 243 |
-
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 244 |
-
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 245 |
-
argument.
|
| 246 |
-
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 247 |
-
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 248 |
-
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 249 |
-
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 250 |
-
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 251 |
-
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 252 |
-
input argument.
|
| 253 |
-
lora_scale (`float`, *optional*):
|
| 254 |
-
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 255 |
-
"""
|
| 256 |
-
device = device or self._execution_device
|
| 257 |
-
|
| 258 |
-
# set lora scale so that monkey patched LoRA
|
| 259 |
-
# function of text encoder can correctly access it
|
| 260 |
-
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 261 |
-
self._lora_scale = lora_scale
|
| 262 |
-
|
| 263 |
-
# dynamically adjust the LoRA scale
|
| 264 |
-
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 265 |
-
adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
|
| 266 |
-
|
| 267 |
-
if prompt is not None and isinstance(prompt, str):
|
| 268 |
-
batch_size = 1
|
| 269 |
-
elif prompt is not None and isinstance(prompt, list):
|
| 270 |
-
batch_size = len(prompt)
|
| 271 |
-
else:
|
| 272 |
-
batch_size = prompt_embeds.shape[0]
|
| 273 |
-
|
| 274 |
-
# Define tokenizers and text encoders
|
| 275 |
-
tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
|
| 276 |
-
text_encoders = (
|
| 277 |
-
[self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
|
| 278 |
-
)
|
| 279 |
-
|
| 280 |
-
if prompt_embeds is None:
|
| 281 |
-
prompt_2 = prompt_2 or prompt
|
| 282 |
-
# textual inversion: procecss multi-vector tokens if necessary
|
| 283 |
-
prompt_embeds_list = []
|
| 284 |
-
prompts = [prompt, prompt_2]
|
| 285 |
-
for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
|
| 286 |
-
if isinstance(self, TextualInversionLoaderMixin):
|
| 287 |
-
prompt = self.maybe_convert_prompt(prompt, tokenizer)
|
| 288 |
-
|
| 289 |
-
text_inputs = tokenizer(
|
| 290 |
-
prompt,
|
| 291 |
-
padding="max_length",
|
| 292 |
-
max_length=tokenizer.model_max_length,
|
| 293 |
-
truncation=True,
|
| 294 |
-
return_tensors="pt",
|
| 295 |
-
)
|
| 296 |
-
|
| 297 |
-
text_input_ids = text_inputs.input_ids
|
| 298 |
-
untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 299 |
-
|
| 300 |
-
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 301 |
-
text_input_ids, untruncated_ids
|
| 302 |
-
):
|
| 303 |
-
removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
|
| 304 |
-
logger.warning(
|
| 305 |
-
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 306 |
-
f" {tokenizer.model_max_length} tokens: {removed_text}"
|
| 307 |
-
)
|
| 308 |
-
|
| 309 |
-
prompt_embeds = text_encoder(
|
| 310 |
-
text_input_ids.to(device),
|
| 311 |
-
output_hidden_states=True,
|
| 312 |
-
)
|
| 313 |
-
|
| 314 |
-
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 315 |
-
pooled_prompt_embeds = prompt_embeds[0]
|
| 316 |
-
prompt_embeds = prompt_embeds.hidden_states[-2]
|
| 317 |
-
|
| 318 |
-
prompt_embeds_list.append(prompt_embeds)
|
| 319 |
-
|
| 320 |
-
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
| 321 |
-
|
| 322 |
-
# get unconditional embeddings for classifier free guidance
|
| 323 |
-
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
| 324 |
-
if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
|
| 325 |
-
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
| 326 |
-
negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
|
| 327 |
-
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 328 |
-
negative_prompt = negative_prompt or ""
|
| 329 |
-
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
| 330 |
-
|
| 331 |
-
uncond_tokens: List[str]
|
| 332 |
-
if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 333 |
-
raise TypeError(
|
| 334 |
-
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 335 |
-
f" {type(prompt)}."
|
| 336 |
-
)
|
| 337 |
-
elif isinstance(negative_prompt, str):
|
| 338 |
-
uncond_tokens = [negative_prompt, negative_prompt_2]
|
| 339 |
-
elif batch_size != len(negative_prompt):
|
| 340 |
-
raise ValueError(
|
| 341 |
-
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 342 |
-
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 343 |
-
" the batch size of `prompt`."
|
| 344 |
-
)
|
| 345 |
-
else:
|
| 346 |
-
uncond_tokens = [negative_prompt, negative_prompt_2]
|
| 347 |
-
|
| 348 |
-
negative_prompt_embeds_list = []
|
| 349 |
-
for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
|
| 350 |
-
if isinstance(self, TextualInversionLoaderMixin):
|
| 351 |
-
negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
|
| 352 |
-
|
| 353 |
-
max_length = prompt_embeds.shape[1]
|
| 354 |
-
uncond_input = tokenizer(
|
| 355 |
-
negative_prompt,
|
| 356 |
-
padding="max_length",
|
| 357 |
-
max_length=max_length,
|
| 358 |
-
truncation=True,
|
| 359 |
-
return_tensors="pt",
|
| 360 |
-
)
|
| 361 |
-
|
| 362 |
-
negative_prompt_embeds = text_encoder(
|
| 363 |
-
uncond_input.input_ids.to(device),
|
| 364 |
-
output_hidden_states=True,
|
| 365 |
-
)
|
| 366 |
-
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 367 |
-
negative_pooled_prompt_embeds = negative_prompt_embeds[0]
|
| 368 |
-
negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
|
| 369 |
-
|
| 370 |
-
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
| 371 |
-
|
| 372 |
-
negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
|
| 373 |
-
|
| 374 |
-
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
| 375 |
-
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 376 |
-
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 377 |
-
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 378 |
-
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 379 |
-
|
| 380 |
-
if do_classifier_free_guidance:
|
| 381 |
-
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 382 |
-
seq_len = negative_prompt_embeds.shape[1]
|
| 383 |
-
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
| 384 |
-
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 385 |
-
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 386 |
-
|
| 387 |
-
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
| 388 |
-
bs_embed * num_images_per_prompt, -1
|
| 389 |
-
)
|
| 390 |
-
if do_classifier_free_guidance:
|
| 391 |
-
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
| 392 |
-
bs_embed * num_images_per_prompt, -1
|
| 393 |
-
)
|
| 394 |
-
|
| 395 |
-
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
| 396 |
-
|
| 397 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 398 |
-
def prepare_extra_step_kwargs(self, generator, eta):
|
| 399 |
-
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 400 |
-
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 401 |
-
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 402 |
-
# and should be between [0, 1]
|
| 403 |
-
|
| 404 |
-
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 405 |
-
extra_step_kwargs = {}
|
| 406 |
-
if accepts_eta:
|
| 407 |
-
extra_step_kwargs["eta"] = eta
|
| 408 |
-
|
| 409 |
-
# check if the scheduler accepts generator
|
| 410 |
-
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 411 |
-
if accepts_generator:
|
| 412 |
-
extra_step_kwargs["generator"] = generator
|
| 413 |
-
return extra_step_kwargs
|
| 414 |
-
|
| 415 |
-
def check_inputs(
|
| 416 |
-
self,
|
| 417 |
-
prompt,
|
| 418 |
-
prompt_2,
|
| 419 |
-
height,
|
| 420 |
-
width,
|
| 421 |
-
callback_steps,
|
| 422 |
-
negative_prompt=None,
|
| 423 |
-
negative_prompt_2=None,
|
| 424 |
-
prompt_embeds=None,
|
| 425 |
-
negative_prompt_embeds=None,
|
| 426 |
-
pooled_prompt_embeds=None,
|
| 427 |
-
negative_pooled_prompt_embeds=None,
|
| 428 |
-
):
|
| 429 |
-
if height % 8 != 0 or width % 8 != 0:
|
| 430 |
-
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 431 |
-
|
| 432 |
-
if (callback_steps is None) or (
|
| 433 |
-
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 434 |
-
):
|
| 435 |
-
raise ValueError(
|
| 436 |
-
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 437 |
-
f" {type(callback_steps)}."
|
| 438 |
-
)
|
| 439 |
-
|
| 440 |
-
if prompt is not None and prompt_embeds is not None:
|
| 441 |
-
raise ValueError(
|
| 442 |
-
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 443 |
-
" only forward one of the two."
|
| 444 |
-
)
|
| 445 |
-
elif prompt_2 is not None and prompt_embeds is not None:
|
| 446 |
-
raise ValueError(
|
| 447 |
-
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 448 |
-
" only forward one of the two."
|
| 449 |
-
)
|
| 450 |
-
elif prompt is None and prompt_embeds is None:
|
| 451 |
-
raise ValueError(
|
| 452 |
-
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 453 |
-
)
|
| 454 |
-
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 455 |
-
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 456 |
-
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
| 457 |
-
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
| 458 |
-
|
| 459 |
-
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 460 |
-
raise ValueError(
|
| 461 |
-
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 462 |
-
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 463 |
-
)
|
| 464 |
-
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
| 465 |
-
raise ValueError(
|
| 466 |
-
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
| 467 |
-
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 468 |
-
)
|
| 469 |
-
|
| 470 |
-
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 471 |
-
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 472 |
-
raise ValueError(
|
| 473 |
-
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 474 |
-
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 475 |
-
f" {negative_prompt_embeds.shape}."
|
| 476 |
-
)
|
| 477 |
-
|
| 478 |
-
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
| 479 |
-
raise ValueError(
|
| 480 |
-
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
| 481 |
-
)
|
| 482 |
-
|
| 483 |
-
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
| 484 |
-
raise ValueError(
|
| 485 |
-
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
| 486 |
-
)
|
| 487 |
-
|
| 488 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 489 |
-
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 490 |
-
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 491 |
-
if isinstance(generator, list) and len(generator) != batch_size:
|
| 492 |
-
raise ValueError(
|
| 493 |
-
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 494 |
-
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 495 |
-
)
|
| 496 |
-
|
| 497 |
-
if latents is None:
|
| 498 |
-
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 499 |
-
else:
|
| 500 |
-
latents = latents.to(device)
|
| 501 |
-
|
| 502 |
-
# scale the initial noise by the standard deviation required by the scheduler
|
| 503 |
-
latents = latents * self.scheduler.init_noise_sigma
|
| 504 |
-
return latents
|
| 505 |
-
|
| 506 |
-
def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
|
| 507 |
-
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
| 508 |
-
|
| 509 |
-
passed_add_embed_dim = (
|
| 510 |
-
self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
|
| 511 |
-
)
|
| 512 |
-
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
| 513 |
-
|
| 514 |
-
if expected_add_embed_dim != passed_add_embed_dim:
|
| 515 |
-
raise ValueError(
|
| 516 |
-
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
| 517 |
-
)
|
| 518 |
-
|
| 519 |
-
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
| 520 |
-
return add_time_ids
|
| 521 |
-
|
| 522 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
|
| 523 |
-
def upcast_vae(self):
|
| 524 |
-
dtype = self.vae.dtype
|
| 525 |
-
self.vae.to(dtype=torch.float32)
|
| 526 |
-
use_torch_2_0_or_xformers = isinstance(
|
| 527 |
-
self.vae.decoder.mid_block.attentions[0].processor,
|
| 528 |
-
(
|
| 529 |
-
AttnProcessor2_0,
|
| 530 |
-
XFormersAttnProcessor,
|
| 531 |
-
LoRAXFormersAttnProcessor,
|
| 532 |
-
LoRAAttnProcessor2_0,
|
| 533 |
-
),
|
| 534 |
-
)
|
| 535 |
-
# if xformers or torch_2_0 is used attention block does not need
|
| 536 |
-
# to be in float32 which can save lots of memory
|
| 537 |
-
if use_torch_2_0_or_xformers:
|
| 538 |
-
self.vae.post_quant_conv.to(dtype)
|
| 539 |
-
self.vae.decoder.conv_in.to(dtype)
|
| 540 |
-
self.vae.decoder.mid_block.to(dtype)
|
| 541 |
-
|
| 542 |
-
@torch.no_grad()
|
| 543 |
-
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 544 |
-
def __call__(
|
| 545 |
-
self,
|
| 546 |
-
prompt: Union[str, List[str]] = None,
|
| 547 |
-
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 548 |
-
height: Optional[int] = None,
|
| 549 |
-
width: Optional[int] = None,
|
| 550 |
-
num_inference_steps: int = 50,
|
| 551 |
-
denoising_end: Optional[float] = None,
|
| 552 |
-
guidance_scale: float = 5.0,
|
| 553 |
-
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 554 |
-
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 555 |
-
num_images_per_prompt: Optional[int] = 1,
|
| 556 |
-
eta: float = 0.0,
|
| 557 |
-
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 558 |
-
latents: Optional[torch.FloatTensor] = None,
|
| 559 |
-
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 560 |
-
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 561 |
-
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 562 |
-
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 563 |
-
output_type: Optional[str] = "pil",
|
| 564 |
-
return_dict: bool = True,
|
| 565 |
-
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 566 |
-
callback_steps: int = 1,
|
| 567 |
-
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 568 |
-
guidance_rescale: float = 0.0,
|
| 569 |
-
original_size: Optional[Tuple[int, int]] = None,
|
| 570 |
-
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 571 |
-
target_size: Optional[Tuple[int, int]] = None,
|
| 572 |
-
negative_original_size: Optional[Tuple[int, int]] = None,
|
| 573 |
-
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 574 |
-
negative_target_size: Optional[Tuple[int, int]] = None,
|
| 575 |
-
):
|
| 576 |
-
r"""
|
| 577 |
-
Function invoked when calling the pipeline for generation.
|
| 578 |
-
|
| 579 |
-
Args:
|
| 580 |
-
prompt (`str` or `List[str]`, *optional*):
|
| 581 |
-
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 582 |
-
instead.
|
| 583 |
-
prompt_2 (`str` or `List[str]`, *optional*):
|
| 584 |
-
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 585 |
-
used in both text-encoders
|
| 586 |
-
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 587 |
-
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 588 |
-
Anything below 512 pixels won't work well for
|
| 589 |
-
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 590 |
-
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 591 |
-
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 592 |
-
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 593 |
-
Anything below 512 pixels won't work well for
|
| 594 |
-
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 595 |
-
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 596 |
-
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 597 |
-
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 598 |
-
expense of slower inference.
|
| 599 |
-
denoising_end (`float`, *optional*):
|
| 600 |
-
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
| 601 |
-
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
| 602 |
-
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
| 603 |
-
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
| 604 |
-
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
| 605 |
-
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
| 606 |
-
guidance_scale (`float`, *optional*, defaults to 5.0):
|
| 607 |
-
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 608 |
-
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 609 |
-
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 610 |
-
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 611 |
-
usually at the expense of lower image quality.
|
| 612 |
-
negative_prompt (`str` or `List[str]`, *optional*):
|
| 613 |
-
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 614 |
-
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 615 |
-
less than `1`).
|
| 616 |
-
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 617 |
-
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
| 618 |
-
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
| 619 |
-
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 620 |
-
The number of images to generate per prompt.
|
| 621 |
-
eta (`float`, *optional*, defaults to 0.0):
|
| 622 |
-
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
| 623 |
-
[`schedulers.DDIMScheduler`], will be ignored for others.
|
| 624 |
-
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 625 |
-
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 626 |
-
to make generation deterministic.
|
| 627 |
-
latents (`torch.FloatTensor`, *optional*):
|
| 628 |
-
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 629 |
-
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 630 |
-
tensor will ge generated by sampling using the supplied random `generator`.
|
| 631 |
-
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 632 |
-
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 633 |
-
provided, text embeddings will be generated from `prompt` input argument.
|
| 634 |
-
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 635 |
-
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 636 |
-
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 637 |
-
argument.
|
| 638 |
-
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 639 |
-
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 640 |
-
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 641 |
-
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 642 |
-
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 643 |
-
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 644 |
-
input argument.
|
| 645 |
-
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 646 |
-
The output format of the generate image. Choose between
|
| 647 |
-
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 648 |
-
return_dict (`bool`, *optional*, defaults to `True`):
|
| 649 |
-
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
| 650 |
-
of a plain tuple.
|
| 651 |
-
callback (`Callable`, *optional*):
|
| 652 |
-
A function that will be called every `callback_steps` steps during inference. The function will be
|
| 653 |
-
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 654 |
-
callback_steps (`int`, *optional*, defaults to 1):
|
| 655 |
-
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
| 656 |
-
called at every step.
|
| 657 |
-
cross_attention_kwargs (`dict`, *optional*):
|
| 658 |
-
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 659 |
-
`self.processor` in
|
| 660 |
-
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 661 |
-
guidance_rescale (`float`, *optional*, defaults to 0.7):
|
| 662 |
-
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
| 663 |
-
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
| 664 |
-
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
| 665 |
-
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
| 666 |
-
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 667 |
-
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
| 668 |
-
`original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
|
| 669 |
-
explained in section 2.2 of
|
| 670 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 671 |
-
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 672 |
-
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
| 673 |
-
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
| 674 |
-
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 675 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 676 |
-
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 677 |
-
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
| 678 |
-
not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
|
| 679 |
-
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 680 |
-
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 681 |
-
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
| 682 |
-
micro-conditioning as explained in section 2.2 of
|
| 683 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
| 684 |
-
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
| 685 |
-
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 686 |
-
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
| 687 |
-
micro-conditioning as explained in section 2.2 of
|
| 688 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
| 689 |
-
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
| 690 |
-
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 691 |
-
To negatively condition the generation process based on a target image resolution. It should be as same
|
| 692 |
-
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 693 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
| 694 |
-
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
| 695 |
-
|
| 696 |
-
Examples:
|
| 697 |
-
|
| 698 |
-
Returns:
|
| 699 |
-
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
|
| 700 |
-
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
|
| 701 |
-
`tuple`. When returning a tuple, the first element is a list with the generated images.
|
| 702 |
-
"""
|
| 703 |
-
# 0. Default height and width to unet
|
| 704 |
-
height = height or self.default_sample_size * self.vae_scale_factor
|
| 705 |
-
width = width or self.default_sample_size * self.vae_scale_factor
|
| 706 |
-
|
| 707 |
-
original_size = original_size or (height, width)
|
| 708 |
-
target_size = target_size or (height, width)
|
| 709 |
-
|
| 710 |
-
# 1. Check inputs. Raise error if not correct
|
| 711 |
-
self.check_inputs(
|
| 712 |
-
prompt,
|
| 713 |
-
prompt_2,
|
| 714 |
-
height,
|
| 715 |
-
width,
|
| 716 |
-
callback_steps,
|
| 717 |
-
negative_prompt,
|
| 718 |
-
negative_prompt_2,
|
| 719 |
-
prompt_embeds,
|
| 720 |
-
negative_prompt_embeds,
|
| 721 |
-
pooled_prompt_embeds,
|
| 722 |
-
negative_pooled_prompt_embeds,
|
| 723 |
-
)
|
| 724 |
-
|
| 725 |
-
# 2. Define call parameters
|
| 726 |
-
if prompt is not None and isinstance(prompt, str):
|
| 727 |
-
batch_size = 1
|
| 728 |
-
elif prompt is not None and isinstance(prompt, list):
|
| 729 |
-
batch_size = len(prompt)
|
| 730 |
-
else:
|
| 731 |
-
batch_size = prompt_embeds.shape[0]
|
| 732 |
-
|
| 733 |
-
device = self._execution_device
|
| 734 |
-
|
| 735 |
-
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 736 |
-
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 737 |
-
# corresponds to doing no classifier free guidance.
|
| 738 |
-
do_classifier_free_guidance = guidance_scale > 1.0
|
| 739 |
-
|
| 740 |
-
# 3. Encode input prompt
|
| 741 |
-
text_encoder_lora_scale = (
|
| 742 |
-
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
| 743 |
-
)
|
| 744 |
-
(
|
| 745 |
-
prompt_embeds,
|
| 746 |
-
negative_prompt_embeds,
|
| 747 |
-
pooled_prompt_embeds,
|
| 748 |
-
negative_pooled_prompt_embeds,
|
| 749 |
-
) = self.encode_prompt(
|
| 750 |
-
prompt=prompt,
|
| 751 |
-
prompt_2=prompt_2,
|
| 752 |
-
device=device,
|
| 753 |
-
num_images_per_prompt=num_images_per_prompt,
|
| 754 |
-
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 755 |
-
negative_prompt=negative_prompt,
|
| 756 |
-
negative_prompt_2=negative_prompt_2,
|
| 757 |
-
prompt_embeds=prompt_embeds,
|
| 758 |
-
negative_prompt_embeds=negative_prompt_embeds,
|
| 759 |
-
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 760 |
-
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 761 |
-
lora_scale=text_encoder_lora_scale,
|
| 762 |
-
)
|
| 763 |
-
|
| 764 |
-
# 4. Prepare timesteps
|
| 765 |
-
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 766 |
-
|
| 767 |
-
timesteps = self.scheduler.timesteps
|
| 768 |
-
|
| 769 |
-
# 5. Prepare latent variables
|
| 770 |
-
num_channels_latents = self.unet.config.in_channels
|
| 771 |
-
latents = self.prepare_latents(
|
| 772 |
-
batch_size * num_images_per_prompt,
|
| 773 |
-
num_channels_latents,
|
| 774 |
-
height,
|
| 775 |
-
width,
|
| 776 |
-
prompt_embeds.dtype,
|
| 777 |
-
device,
|
| 778 |
-
generator,
|
| 779 |
-
latents,
|
| 780 |
-
)
|
| 781 |
-
|
| 782 |
-
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 783 |
-
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 784 |
-
|
| 785 |
-
# 7. Prepare added time ids & embeddings
|
| 786 |
-
add_text_embeds = pooled_prompt_embeds
|
| 787 |
-
add_time_ids = self._get_add_time_ids(
|
| 788 |
-
original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
|
| 789 |
-
)
|
| 790 |
-
if negative_original_size is not None and negative_target_size is not None:
|
| 791 |
-
negative_add_time_ids = self._get_add_time_ids(
|
| 792 |
-
negative_original_size,
|
| 793 |
-
negative_crops_coords_top_left,
|
| 794 |
-
negative_target_size,
|
| 795 |
-
dtype=prompt_embeds.dtype,
|
| 796 |
-
)
|
| 797 |
-
else:
|
| 798 |
-
negative_add_time_ids = add_time_ids
|
| 799 |
-
|
| 800 |
-
if do_classifier_free_guidance:
|
| 801 |
-
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
| 802 |
-
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
| 803 |
-
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
| 804 |
-
|
| 805 |
-
prompt_embeds = prompt_embeds.to(device)
|
| 806 |
-
add_text_embeds = add_text_embeds.to(device)
|
| 807 |
-
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
| 808 |
-
|
| 809 |
-
# 8. Denoising loop
|
| 810 |
-
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
| 811 |
-
|
| 812 |
-
# 7.1 Apply denoising_end
|
| 813 |
-
if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
|
| 814 |
-
discrete_timestep_cutoff = int(
|
| 815 |
-
round(
|
| 816 |
-
self.scheduler.config.num_train_timesteps
|
| 817 |
-
- (denoising_end * self.scheduler.config.num_train_timesteps)
|
| 818 |
-
)
|
| 819 |
-
)
|
| 820 |
-
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
| 821 |
-
timesteps = timesteps[:num_inference_steps]
|
| 822 |
-
|
| 823 |
-
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 824 |
-
for i, t in enumerate(timesteps):
|
| 825 |
-
# expand the latents if we are doing classifier free guidance
|
| 826 |
-
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 827 |
-
|
| 828 |
-
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 829 |
-
|
| 830 |
-
# predict the noise residual
|
| 831 |
-
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 832 |
-
noise_pred = self.unet(
|
| 833 |
-
latent_model_input,
|
| 834 |
-
t,
|
| 835 |
-
encoder_hidden_states=prompt_embeds,
|
| 836 |
-
cross_attention_kwargs=cross_attention_kwargs,
|
| 837 |
-
added_cond_kwargs=added_cond_kwargs,
|
| 838 |
-
return_dict=False,
|
| 839 |
-
)[0]
|
| 840 |
-
|
| 841 |
-
# perform guidance
|
| 842 |
-
if do_classifier_free_guidance:
|
| 843 |
-
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 844 |
-
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 845 |
-
|
| 846 |
-
if do_classifier_free_guidance and guidance_rescale > 0.0:
|
| 847 |
-
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
| 848 |
-
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
|
| 849 |
-
|
| 850 |
-
# compute the previous noisy sample x_t -> x_t-1
|
| 851 |
-
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
| 852 |
-
|
| 853 |
-
# call the callback, if provided
|
| 854 |
-
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 855 |
-
progress_bar.update()
|
| 856 |
-
if callback is not None and i % callback_steps == 0:
|
| 857 |
-
callback(i, t, latents)
|
| 858 |
-
|
| 859 |
-
if not output_type == "latent":
|
| 860 |
-
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 861 |
-
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
| 862 |
-
|
| 863 |
-
if needs_upcasting:
|
| 864 |
-
self.upcast_vae()
|
| 865 |
-
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
| 866 |
-
|
| 867 |
-
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 868 |
-
|
| 869 |
-
# cast back to fp16 if needed
|
| 870 |
-
if needs_upcasting:
|
| 871 |
-
self.vae.to(dtype=torch.float16)
|
| 872 |
-
else:
|
| 873 |
-
image = latents
|
| 874 |
-
|
| 875 |
-
if not output_type == "latent":
|
| 876 |
-
# apply watermark if available
|
| 877 |
-
if self.watermark is not None:
|
| 878 |
-
image = self.watermark.apply_watermark(image)
|
| 879 |
-
|
| 880 |
-
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 881 |
-
|
| 882 |
-
# Offload all models
|
| 883 |
-
self.maybe_free_model_hooks()
|
| 884 |
-
|
| 885 |
-
if not return_dict:
|
| 886 |
-
return (image,)
|
| 887 |
-
|
| 888 |
-
return StableDiffusionXLPipelineOutput(images=image)
|
| 889 |
-
|
| 890 |
-
# Overrride to properly handle the loading and unloading of the additional text encoder.
|
| 891 |
-
def load_lora_weights(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
|
| 892 |
-
# We could have accessed the unet config from `lora_state_dict()` too. We pass
|
| 893 |
-
# it here explicitly to be able to tell that it's coming from an SDXL
|
| 894 |
-
# pipeline.
|
| 895 |
-
|
| 896 |
-
# Remove any existing hooks.
|
| 897 |
-
if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
|
| 898 |
-
from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
|
| 899 |
-
else:
|
| 900 |
-
raise ImportError("Offloading requires `accelerate v0.17.0` or higher.")
|
| 901 |
-
|
| 902 |
-
is_model_cpu_offload = False
|
| 903 |
-
is_sequential_cpu_offload = False
|
| 904 |
-
recursive = False
|
| 905 |
-
for _, component in self.components.items():
|
| 906 |
-
if isinstance(component, torch.nn.Module):
|
| 907 |
-
if hasattr(component, "_hf_hook"):
|
| 908 |
-
is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
|
| 909 |
-
is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
|
| 910 |
-
logger.info(
|
| 911 |
-
"Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
|
| 912 |
-
)
|
| 913 |
-
recursive = is_sequential_cpu_offload
|
| 914 |
-
remove_hook_from_module(component, recurse=recursive)
|
| 915 |
-
state_dict, network_alphas = self.lora_state_dict(
|
| 916 |
-
pretrained_model_name_or_path_or_dict,
|
| 917 |
-
unet_config=self.unet.config,
|
| 918 |
-
**kwargs,
|
| 919 |
-
)
|
| 920 |
-
self.load_lora_into_unet(state_dict, network_alphas=network_alphas, unet=self.unet)
|
| 921 |
-
|
| 922 |
-
text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
|
| 923 |
-
if len(text_encoder_state_dict) > 0:
|
| 924 |
-
self.load_lora_into_text_encoder(
|
| 925 |
-
text_encoder_state_dict,
|
| 926 |
-
network_alphas=network_alphas,
|
| 927 |
-
text_encoder=self.text_encoder,
|
| 928 |
-
prefix="text_encoder",
|
| 929 |
-
lora_scale=self.lora_scale,
|
| 930 |
-
)
|
| 931 |
-
|
| 932 |
-
text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
|
| 933 |
-
if len(text_encoder_2_state_dict) > 0:
|
| 934 |
-
self.load_lora_into_text_encoder(
|
| 935 |
-
text_encoder_2_state_dict,
|
| 936 |
-
network_alphas=network_alphas,
|
| 937 |
-
text_encoder=self.text_encoder_2,
|
| 938 |
-
prefix="text_encoder_2",
|
| 939 |
-
lora_scale=self.lora_scale,
|
| 940 |
-
)
|
| 941 |
-
|
| 942 |
-
# Offload back.
|
| 943 |
-
if is_model_cpu_offload:
|
| 944 |
-
self.enable_model_cpu_offload()
|
| 945 |
-
elif is_sequential_cpu_offload:
|
| 946 |
-
self.enable_sequential_cpu_offload()
|
| 947 |
-
|
| 948 |
-
@classmethod
|
| 949 |
-
def save_lora_weights(
|
| 950 |
-
self,
|
| 951 |
-
save_directory: Union[str, os.PathLike],
|
| 952 |
-
unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 953 |
-
text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 954 |
-
text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 955 |
-
is_main_process: bool = True,
|
| 956 |
-
weight_name: str = None,
|
| 957 |
-
save_function: Callable = None,
|
| 958 |
-
safe_serialization: bool = True,
|
| 959 |
-
):
|
| 960 |
-
state_dict = {}
|
| 961 |
-
|
| 962 |
-
def pack_weights(layers, prefix):
|
| 963 |
-
layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
|
| 964 |
-
layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
|
| 965 |
-
return layers_state_dict
|
| 966 |
-
|
| 967 |
-
if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
|
| 968 |
-
raise ValueError(
|
| 969 |
-
"You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
|
| 970 |
-
)
|
| 971 |
-
|
| 972 |
-
if unet_lora_layers:
|
| 973 |
-
state_dict.update(pack_weights(unet_lora_layers, "unet"))
|
| 974 |
-
|
| 975 |
-
if text_encoder_lora_layers and text_encoder_2_lora_layers:
|
| 976 |
-
state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
|
| 977 |
-
state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
|
| 978 |
-
|
| 979 |
-
self.write_lora_layers(
|
| 980 |
-
state_dict=state_dict,
|
| 981 |
-
save_directory=save_directory,
|
| 982 |
-
is_main_process=is_main_process,
|
| 983 |
-
weight_name=weight_name,
|
| 984 |
-
save_function=save_function,
|
| 985 |
-
safe_serialization=safe_serialization,
|
| 986 |
-
)
|
| 987 |
-
|
| 988 |
-
def _remove_text_encoder_monkey_patch(self):
|
| 989 |
-
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
|
| 990 |
-
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/diffusion/sdxl_img2img_pipeline.py
DELETED
|
@@ -1,70 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
#from diffusers import StableDiffusionXLImg2ImgPipeline,StableDiffusionXLPipeline
|
| 3 |
-
from ..ddim.sdxl_pipeline import StableDiffusionXLPipeline
|
| 4 |
-
from diffusers.utils import load_image
|
| 5 |
-
from diffusers.models.unet_2d_condition import UNet2DConditionOutput
|
| 6 |
-
import diffusers
|
| 7 |
-
from diffusers import (
|
| 8 |
-
AutoencoderKL,
|
| 9 |
-
DDPMScheduler,
|
| 10 |
-
StableDiffusionXLPipeline,
|
| 11 |
-
UNet2DConditionModel,
|
| 12 |
-
StableDiffusionXLImg2ImgPipeline
|
| 13 |
-
)
|
| 14 |
-
from typing import Any, Dict, Optional, Tuple, Union
|
| 15 |
-
from torch import nn
|
| 16 |
-
from torch import FloatTensor,Tensor
|
| 17 |
-
import torch
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
class UnCLipXL(UNet2DConditionModel):
|
| 21 |
-
|
| 22 |
-
def __init__(self, adapt_project_dim=[1024,1024*4,2048],adapt_project_dim_2=[768,1024*4,1280],sample_size: int | None = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ..., mid_block_type: str | None = "UNetMidBlock2DCrossAttn", up_block_types: Tuple[str] = ..., only_cross_attention: bool | Tuple[bool] = False, block_out_channels: Tuple[int] = ..., layers_per_block: int | Tuple[int] = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, dropout: float = 0, act_fn: str = "silu", norm_num_groups: int | None = 32, norm_eps: float = 0.00001, cross_attention_dim: int | Tuple[int] = 1280, transformer_layers_per_block: int | Tuple[int] | Tuple[Tuple] = 1, reverse_transformer_layers_per_block: Tuple[Tuple[int]] | None = None, encoder_hid_dim: int | None = None, encoder_hid_dim_type: str | None = None, attention_head_dim: int | Tuple[int] = 8, num_attention_heads: int | Tuple[int] | None = None, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: str | None = None, addition_embed_type: str | None = None, addition_time_embed_dim: int | None = None, num_class_embeds: int | None = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", resnet_skip_time_act: bool = False, resnet_out_scale_factor: int = 1, time_embedding_type: str = "positional", time_embedding_dim: int | None = None, time_embedding_act_fn: str | None = None, timestep_post_act: str | None = None, time_cond_proj_dim: int | None = None, conv_in_kernel: int = 3, conv_out_kernel: int = 3, projection_class_embeddings_input_dim: int | None = None, attention_type: str = "default", class_embeddings_concat: bool = False, mid_block_only_cross_attention: bool | None = None, cross_attention_norm: str | None = None, addition_embed_type_num_heads=64):
|
| 23 |
-
super().__init__(sample_size, in_channels, out_channels, center_input_sample, flip_sin_to_cos, freq_shift, down_block_types, mid_block_type, up_block_types, only_cross_attention, block_out_channels, layers_per_block, downsample_padding, mid_block_scale_factor, dropout, act_fn, norm_num_groups, norm_eps, cross_attention_dim, transformer_layers_per_block, reverse_transformer_layers_per_block, encoder_hid_dim, encoder_hid_dim_type, attention_head_dim, num_attention_heads, dual_cross_attention, use_linear_projection, class_embed_type, addition_embed_type, addition_time_embed_dim, num_class_embeds, upcast_attention, resnet_time_scale_shift, resnet_skip_time_act, resnet_out_scale_factor, time_embedding_type, time_embedding_dim, time_embedding_act_fn, timestep_post_act, time_cond_proj_dim, conv_in_kernel, conv_out_kernel, projection_class_embeddings_input_dim, attention_type, class_embeddings_concat, mid_block_only_cross_attention, cross_attention_norm, addition_embed_type_num_heads)
|
| 24 |
-
self.adapt_project_dim = adapt_project_dim
|
| 25 |
-
self.adapt_project_dim_2 = adapt_project_dim_2
|
| 26 |
-
self.add_prjection()
|
| 27 |
-
|
| 28 |
-
def add_prjection(self):
|
| 29 |
-
adapt_project_dim = self.adapt_project_dim
|
| 30 |
-
adapt_project_dim_2 = self.adapt_project_dim_2
|
| 31 |
-
self.projector_unclip = nn.Sequential(
|
| 32 |
-
nn.Linear(adapt_project_dim[0],adapt_project_dim[1]),
|
| 33 |
-
nn.GELU(),
|
| 34 |
-
nn.Linear(adapt_project_dim[1],adapt_project_dim[2]),
|
| 35 |
-
)
|
| 36 |
-
self.projector_unclip2 = nn.Sequential(
|
| 37 |
-
nn.Linear(adapt_project_dim_2[0],adapt_project_dim_2[1]),
|
| 38 |
-
nn.GELU(),
|
| 39 |
-
nn.Linear(adapt_project_dim_2[1],adapt_project_dim_2[2]),
|
| 40 |
-
)
|
| 41 |
-
|
| 42 |
-
def forward(self, sample: FloatTensor, timestep: Tensor | float | int, encoder_hidden_states: Tensor, class_labels: Tensor | None = None, timestep_cond: Tensor | None = None, attention_mask: Tensor | None = None, cross_attention_kwargs: Dict[str, Any] | None = None, added_cond_kwargs: Dict[str, Tensor] | None = None, down_block_additional_residuals: Tuple[Tensor] | None = None, mid_block_additional_residual: Tensor | None = None, down_intrablock_additional_residuals: Tuple[Tensor] | None = None, encoder_attention_mask: Tensor | None = None, return_dict: bool = True) -> UNet2DConditionOutput | Tuple:
|
| 43 |
-
added_cond_kwargs['text_embeds'] = self.projector_unclip2(added_cond_kwargs['text_embeds'].to(encoder_hidden_states))
|
| 44 |
-
encoder_hidden_states = self.projector_unclip(encoder_hidden_states)
|
| 45 |
-
return super().forward(sample, timestep, encoder_hidden_states, class_labels, timestep_cond, attention_mask, cross_attention_kwargs, added_cond_kwargs, down_block_additional_residuals, mid_block_additional_residual, down_intrablock_additional_residuals, encoder_attention_mask, return_dict)
|
| 46 |
-
|
| 47 |
-
def process_clip(batch,clip_processor=None):
|
| 48 |
-
image = batch['pixel_values']
|
| 49 |
-
image = clip_processor(image)
|
| 50 |
-
batch['clip_input'] = image
|
| 51 |
-
return batch
|
| 52 |
-
|
| 53 |
-
def build_sdxl(pretrained = "stabilityai/stable-diffusion-xl-base-1.0",
|
| 54 |
-
ckpt="/localhome/data/ckpts/jacklishufan/sdxl/"):
|
| 55 |
-
unet = UnCLipXL.from_pretrained(
|
| 56 |
-
ckpt, subfolder="unet"
|
| 57 |
-
)
|
| 58 |
-
vae = AutoencoderKL.from_pretrained(
|
| 59 |
-
pretrained,
|
| 60 |
-
subfolder="vae" ,
|
| 61 |
-
# revision=args.revision,
|
| 62 |
-
)
|
| 63 |
-
pipeline = StableDiffusionXLPipeline.from_pretrained(
|
| 64 |
-
pretrained,
|
| 65 |
-
vae=vae,
|
| 66 |
-
unet=unet,
|
| 67 |
-
#revision=args.revision,
|
| 68 |
-
torch_dtype=torch.float16,
|
| 69 |
-
)
|
| 70 |
-
return pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/constants.py
DELETED
|
@@ -1,30 +0,0 @@
|
|
| 1 |
-
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
| 2 |
-
WORKER_HEART_BEAT_INTERVAL = 15
|
| 3 |
-
|
| 4 |
-
LOGDIR = "."
|
| 5 |
-
|
| 6 |
-
# Model Constants
|
| 7 |
-
IGNORE_INDEX = -100
|
| 8 |
-
IMAGE_TOKEN_INDEX = -200
|
| 9 |
-
DEFAULT_IMAGE_TOKEN = "<image>"
|
| 10 |
-
DEFAULT_AUDIO_TOKEN = "<audio>"
|
| 11 |
-
DEFAULT_VIDEO_TOKEN = "<video>"
|
| 12 |
-
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
| 13 |
-
DEFAULT_IM_START_TOKEN = "<im_start>"
|
| 14 |
-
DEFAULT_IM_END_TOKEN = "<im_end>"
|
| 15 |
-
DEFAULT_IM_GEN_START_TOKEN = "<im_gen_start>"
|
| 16 |
-
DEFAULT_AUDIO_GEN_START_TOKEN = "<au_gen_start>"
|
| 17 |
-
DEFAULT_VIDEO_GEN_START_TOKEN = "<vd_gen_start>"
|
| 18 |
-
DEFAULT_IM_GEN_END_TOKEN = "<im_gen_end>"
|
| 19 |
-
DEFAULT_IM_GEN_TOKEN = "<im_gen>"
|
| 20 |
-
DEFAULT_AUDIO_GEN_TOKEN = "<audio_gen>"
|
| 21 |
-
DEFAULT_VIDEO_GEN_TOKEN = "<video_gen>"
|
| 22 |
-
DEFAULT_AUDIO_GEN_START_TOKEN = "<audio_gen_start>"
|
| 23 |
-
DEFAULT_MSK_TOKEN = '<mask_gen>'
|
| 24 |
-
DEFAULT_BASE_TOKEN = '<base>'
|
| 25 |
-
DEFAULT_BASE_NULL_TOKEN = '<base_null>'
|
| 26 |
-
|
| 27 |
-
class REPLACEMENT_TYPE:
|
| 28 |
-
INPUT = 0
|
| 29 |
-
BASE = 1
|
| 30 |
-
GEN = 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/conversation.py
DELETED
|
@@ -1,381 +0,0 @@
|
|
| 1 |
-
import dataclasses
|
| 2 |
-
from enum import auto, Enum
|
| 3 |
-
from typing import List, Tuple
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
class SeparatorStyle(Enum):
|
| 7 |
-
"""Different separator style."""
|
| 8 |
-
SINGLE = auto()
|
| 9 |
-
TWO = auto()
|
| 10 |
-
MPT = auto()
|
| 11 |
-
PLAIN = auto()
|
| 12 |
-
LLAMA_2 = auto()
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
@dataclasses.dataclass
|
| 16 |
-
class Conversation:
|
| 17 |
-
"""A class that keeps all conversation history."""
|
| 18 |
-
system: str
|
| 19 |
-
roles: List[str]
|
| 20 |
-
messages: List[List[str]]
|
| 21 |
-
offset: int
|
| 22 |
-
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
| 23 |
-
sep: str = "###"
|
| 24 |
-
sep2: str = None
|
| 25 |
-
version: str = "Unknown"
|
| 26 |
-
|
| 27 |
-
skip_next: bool = False
|
| 28 |
-
|
| 29 |
-
def get_prompt(self):
|
| 30 |
-
messages = self.messages
|
| 31 |
-
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
| 32 |
-
messages = self.messages.copy()
|
| 33 |
-
init_role, init_msg = messages[0].copy()
|
| 34 |
-
init_msg = init_msg[0].replace("<image>", "").strip()
|
| 35 |
-
if 'mmtag' in self.version:
|
| 36 |
-
messages[0] = (init_role, init_msg)
|
| 37 |
-
messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
| 38 |
-
messages.insert(1, (self.roles[1], "Received."))
|
| 39 |
-
else:
|
| 40 |
-
messages[0] = (init_role, "<image>\n" + init_msg)
|
| 41 |
-
|
| 42 |
-
if self.sep_style == SeparatorStyle.SINGLE:
|
| 43 |
-
ret = self.system + self.sep
|
| 44 |
-
for role, message in messages:
|
| 45 |
-
if message:
|
| 46 |
-
if type(message) is tuple:
|
| 47 |
-
message, _, _ = message
|
| 48 |
-
ret += role + ": " + message + self.sep
|
| 49 |
-
else:
|
| 50 |
-
ret += role + ":"
|
| 51 |
-
elif self.sep_style == SeparatorStyle.TWO:
|
| 52 |
-
seps = [self.sep, self.sep2]
|
| 53 |
-
ret = self.system + seps[0]
|
| 54 |
-
for i, (role, message) in enumerate(messages):
|
| 55 |
-
if message:
|
| 56 |
-
if type(message) is tuple:
|
| 57 |
-
message, _, _ = message
|
| 58 |
-
ret += role + ": " + message + seps[i % 2]
|
| 59 |
-
else:
|
| 60 |
-
ret += role + ":"
|
| 61 |
-
elif self.sep_style == SeparatorStyle.MPT:
|
| 62 |
-
ret = self.system + self.sep
|
| 63 |
-
for role, message in messages:
|
| 64 |
-
if message:
|
| 65 |
-
if type(message) is tuple:
|
| 66 |
-
message, _, _ = message
|
| 67 |
-
ret += role + message + self.sep
|
| 68 |
-
else:
|
| 69 |
-
ret += role
|
| 70 |
-
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
| 71 |
-
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
|
| 72 |
-
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
| 73 |
-
ret = ""
|
| 74 |
-
|
| 75 |
-
for i, (role, message) in enumerate(messages):
|
| 76 |
-
if i == 0:
|
| 77 |
-
assert message, "first message should not be none"
|
| 78 |
-
assert role == self.roles[0], "first message should come from user"
|
| 79 |
-
if message:
|
| 80 |
-
if type(message) is tuple:
|
| 81 |
-
message, _, _ = message
|
| 82 |
-
if i == 0: message = wrap_sys(self.system) + message
|
| 83 |
-
if i % 2 == 0:
|
| 84 |
-
message = wrap_inst(message)
|
| 85 |
-
ret += self.sep + message
|
| 86 |
-
else:
|
| 87 |
-
ret += " " + message + " " + self.sep2
|
| 88 |
-
else:
|
| 89 |
-
ret += ""
|
| 90 |
-
ret = ret.lstrip(self.sep)
|
| 91 |
-
elif self.sep_style == SeparatorStyle.PLAIN:
|
| 92 |
-
seps = [self.sep, self.sep2]
|
| 93 |
-
ret = self.system
|
| 94 |
-
for i, (role, message) in enumerate(messages):
|
| 95 |
-
if message:
|
| 96 |
-
if type(message) is tuple:
|
| 97 |
-
message, _, _ = message
|
| 98 |
-
ret += message + seps[i % 2]
|
| 99 |
-
else:
|
| 100 |
-
ret += ""
|
| 101 |
-
else:
|
| 102 |
-
raise ValueError(f"Invalid style: {self.sep_style}")
|
| 103 |
-
|
| 104 |
-
return ret
|
| 105 |
-
|
| 106 |
-
def append_message(self, role, message):
|
| 107 |
-
self.messages.append([role, message])
|
| 108 |
-
|
| 109 |
-
def get_images(self, return_pil=False):
|
| 110 |
-
images = []
|
| 111 |
-
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 112 |
-
if i % 2 == 0:
|
| 113 |
-
if type(msg) is tuple:
|
| 114 |
-
import base64
|
| 115 |
-
from io import BytesIO
|
| 116 |
-
from PIL import Image
|
| 117 |
-
msg, image, image_process_mode = msg
|
| 118 |
-
if image_process_mode == "Pad":
|
| 119 |
-
def expand2square(pil_img, background_color=(122, 116, 104)):
|
| 120 |
-
width, height = pil_img.size
|
| 121 |
-
if width == height:
|
| 122 |
-
return pil_img
|
| 123 |
-
elif width > height:
|
| 124 |
-
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 125 |
-
result.paste(pil_img, (0, (width - height) // 2))
|
| 126 |
-
return result
|
| 127 |
-
else:
|
| 128 |
-
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 129 |
-
result.paste(pil_img, ((height - width) // 2, 0))
|
| 130 |
-
return result
|
| 131 |
-
image = expand2square(image)
|
| 132 |
-
elif image_process_mode in ["Default", "Crop"]:
|
| 133 |
-
pass
|
| 134 |
-
elif image_process_mode == "Resize":
|
| 135 |
-
image = image.resize((336, 336))
|
| 136 |
-
else:
|
| 137 |
-
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
| 138 |
-
max_hw, min_hw = max(image.size), min(image.size)
|
| 139 |
-
aspect_ratio = max_hw / min_hw
|
| 140 |
-
max_len, min_len = 800, 400
|
| 141 |
-
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 142 |
-
longest_edge = int(shortest_edge * aspect_ratio)
|
| 143 |
-
W, H = image.size
|
| 144 |
-
if longest_edge != max(image.size):
|
| 145 |
-
if H > W:
|
| 146 |
-
H, W = longest_edge, shortest_edge
|
| 147 |
-
else:
|
| 148 |
-
H, W = shortest_edge, longest_edge
|
| 149 |
-
image = image.resize((W, H))
|
| 150 |
-
if return_pil:
|
| 151 |
-
images.append(image)
|
| 152 |
-
else:
|
| 153 |
-
buffered = BytesIO()
|
| 154 |
-
image.save(buffered, format="PNG")
|
| 155 |
-
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 156 |
-
images.append(img_b64_str)
|
| 157 |
-
return images
|
| 158 |
-
|
| 159 |
-
def to_gradio_chatbot(self):
|
| 160 |
-
ret = []
|
| 161 |
-
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 162 |
-
if i % 2 == 0:
|
| 163 |
-
if type(msg) is tuple:
|
| 164 |
-
import base64
|
| 165 |
-
from io import BytesIO
|
| 166 |
-
msg, image, image_process_mode = msg
|
| 167 |
-
max_hw, min_hw = max(image.size), min(image.size)
|
| 168 |
-
aspect_ratio = max_hw / min_hw
|
| 169 |
-
max_len, min_len = 800, 400
|
| 170 |
-
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 171 |
-
longest_edge = int(shortest_edge * aspect_ratio)
|
| 172 |
-
W, H = image.size
|
| 173 |
-
if H > W:
|
| 174 |
-
H, W = longest_edge, shortest_edge
|
| 175 |
-
else:
|
| 176 |
-
H, W = shortest_edge, longest_edge
|
| 177 |
-
image = image.resize((W, H))
|
| 178 |
-
buffered = BytesIO()
|
| 179 |
-
image.save(buffered, format="JPEG")
|
| 180 |
-
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 181 |
-
img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
|
| 182 |
-
msg = img_str + msg.replace('<image>', '').strip()
|
| 183 |
-
ret.append([msg, None])
|
| 184 |
-
else:
|
| 185 |
-
ret.append([msg, None])
|
| 186 |
-
else:
|
| 187 |
-
ret[-1][-1] = msg
|
| 188 |
-
return ret
|
| 189 |
-
|
| 190 |
-
def copy(self):
|
| 191 |
-
return Conversation(
|
| 192 |
-
system=self.system,
|
| 193 |
-
roles=self.roles,
|
| 194 |
-
messages=[[x, y] for x, y in self.messages],
|
| 195 |
-
offset=self.offset,
|
| 196 |
-
sep_style=self.sep_style,
|
| 197 |
-
sep=self.sep,
|
| 198 |
-
sep2=self.sep2,
|
| 199 |
-
version=self.version)
|
| 200 |
-
|
| 201 |
-
def dict(self):
|
| 202 |
-
if len(self.get_images()) > 0:
|
| 203 |
-
return {
|
| 204 |
-
"system": self.system,
|
| 205 |
-
"roles": self.roles,
|
| 206 |
-
"messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
|
| 207 |
-
"offset": self.offset,
|
| 208 |
-
"sep": self.sep,
|
| 209 |
-
"sep2": self.sep2,
|
| 210 |
-
}
|
| 211 |
-
return {
|
| 212 |
-
"system": self.system,
|
| 213 |
-
"roles": self.roles,
|
| 214 |
-
"messages": self.messages,
|
| 215 |
-
"offset": self.offset,
|
| 216 |
-
"sep": self.sep,
|
| 217 |
-
"sep2": self.sep2,
|
| 218 |
-
}
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
conv_vicuna_v0 = Conversation(
|
| 222 |
-
system="A chat between a curious human and an artificial intelligence assistant. "
|
| 223 |
-
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 224 |
-
roles=("Human", "Assistant"),
|
| 225 |
-
messages=(
|
| 226 |
-
("Human", "What are the key differences between renewable and non-renewable energy sources?"),
|
| 227 |
-
("Assistant",
|
| 228 |
-
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
| 229 |
-
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
| 230 |
-
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
| 231 |
-
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
| 232 |
-
"renewable and non-renewable energy sources:\n"
|
| 233 |
-
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
| 234 |
-
"energy sources are finite and will eventually run out.\n"
|
| 235 |
-
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
| 236 |
-
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
| 237 |
-
"and other negative effects.\n"
|
| 238 |
-
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
| 239 |
-
"have lower operational costs than non-renewable sources.\n"
|
| 240 |
-
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
| 241 |
-
"locations than non-renewable sources.\n"
|
| 242 |
-
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
| 243 |
-
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
| 244 |
-
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
| 245 |
-
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
|
| 246 |
-
),
|
| 247 |
-
offset=2,
|
| 248 |
-
sep_style=SeparatorStyle.SINGLE,
|
| 249 |
-
sep="###",
|
| 250 |
-
)
|
| 251 |
-
|
| 252 |
-
conv_vicuna_v1 = Conversation(
|
| 253 |
-
system="A chat between a curious user and an artificial intelligence assistant. "
|
| 254 |
-
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
| 255 |
-
roles=("USER", "ASSISTANT"),
|
| 256 |
-
version="v1",
|
| 257 |
-
messages=(),
|
| 258 |
-
offset=0,
|
| 259 |
-
sep_style=SeparatorStyle.TWO,
|
| 260 |
-
sep=" ",
|
| 261 |
-
sep2="</s>",
|
| 262 |
-
)
|
| 263 |
-
|
| 264 |
-
conv_llama_2 = Conversation(
|
| 265 |
-
system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
| 266 |
-
|
| 267 |
-
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
|
| 268 |
-
roles=("USER", "ASSISTANT"),
|
| 269 |
-
version="llama_v2",
|
| 270 |
-
messages=(),
|
| 271 |
-
offset=0,
|
| 272 |
-
sep_style=SeparatorStyle.LLAMA_2,
|
| 273 |
-
sep="<s>",
|
| 274 |
-
sep2="</s>",
|
| 275 |
-
)
|
| 276 |
-
|
| 277 |
-
conv_llava_llama_2 = Conversation(
|
| 278 |
-
system="You are a helpful language and vision assistant. "
|
| 279 |
-
"You are able to understand the visual content that the user provides, "
|
| 280 |
-
"and assist the user with a variety of tasks using natural language.",
|
| 281 |
-
roles=("USER", "ASSISTANT"),
|
| 282 |
-
version="llama_v2",
|
| 283 |
-
messages=(),
|
| 284 |
-
offset=0,
|
| 285 |
-
sep_style=SeparatorStyle.LLAMA_2,
|
| 286 |
-
sep="<s>",
|
| 287 |
-
sep2="</s>",
|
| 288 |
-
)
|
| 289 |
-
|
| 290 |
-
conv_mpt = Conversation(
|
| 291 |
-
system="""<|im_start|>system
|
| 292 |
-
A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
|
| 293 |
-
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
| 294 |
-
version="mpt",
|
| 295 |
-
messages=(),
|
| 296 |
-
offset=0,
|
| 297 |
-
sep_style=SeparatorStyle.MPT,
|
| 298 |
-
sep="<|im_end|>",
|
| 299 |
-
)
|
| 300 |
-
|
| 301 |
-
conv_llava_plain = Conversation(
|
| 302 |
-
system="",
|
| 303 |
-
roles=("", ""),
|
| 304 |
-
messages=(
|
| 305 |
-
),
|
| 306 |
-
offset=0,
|
| 307 |
-
sep_style=SeparatorStyle.PLAIN,
|
| 308 |
-
sep="\n",
|
| 309 |
-
)
|
| 310 |
-
|
| 311 |
-
conv_llava_v0 = Conversation(
|
| 312 |
-
system="A chat between a curious human and an artificial intelligence assistant. "
|
| 313 |
-
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 314 |
-
roles=("Human", "Assistant"),
|
| 315 |
-
messages=(
|
| 316 |
-
),
|
| 317 |
-
offset=0,
|
| 318 |
-
sep_style=SeparatorStyle.SINGLE,
|
| 319 |
-
sep="###",
|
| 320 |
-
)
|
| 321 |
-
|
| 322 |
-
conv_llava_v0_mmtag = Conversation(
|
| 323 |
-
system="A chat between a curious user and an artificial intelligence assistant. "
|
| 324 |
-
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
| 325 |
-
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
| 326 |
-
roles=("Human", "Assistant"),
|
| 327 |
-
messages=(
|
| 328 |
-
),
|
| 329 |
-
offset=0,
|
| 330 |
-
sep_style=SeparatorStyle.SINGLE,
|
| 331 |
-
sep="###",
|
| 332 |
-
version="v0_mmtag",
|
| 333 |
-
)
|
| 334 |
-
|
| 335 |
-
conv_llava_v1 = Conversation(
|
| 336 |
-
system="A chat between a curious human and an artificial intelligence assistant. "
|
| 337 |
-
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 338 |
-
roles=("USER", "ASSISTANT"),
|
| 339 |
-
version="v1",
|
| 340 |
-
messages=(),
|
| 341 |
-
offset=0,
|
| 342 |
-
sep_style=SeparatorStyle.TWO,
|
| 343 |
-
sep=" ",
|
| 344 |
-
sep2="</s>",
|
| 345 |
-
)
|
| 346 |
-
|
| 347 |
-
conv_llava_v1_mmtag = Conversation(
|
| 348 |
-
system="A chat between a curious user and an artificial intelligence assistant. "
|
| 349 |
-
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
| 350 |
-
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
| 351 |
-
roles=("USER", "ASSISTANT"),
|
| 352 |
-
messages=(),
|
| 353 |
-
offset=0,
|
| 354 |
-
sep_style=SeparatorStyle.TWO,
|
| 355 |
-
sep=" ",
|
| 356 |
-
sep2="</s>",
|
| 357 |
-
version="v1_mmtag",
|
| 358 |
-
)
|
| 359 |
-
|
| 360 |
-
default_conversation = conv_vicuna_v0
|
| 361 |
-
conv_templates = {
|
| 362 |
-
"default": conv_vicuna_v0,
|
| 363 |
-
"v0": conv_vicuna_v0,
|
| 364 |
-
"v1": conv_vicuna_v1,
|
| 365 |
-
"vicuna_v1": conv_vicuna_v1,
|
| 366 |
-
"llama_2": conv_llama_2,
|
| 367 |
-
|
| 368 |
-
"plain": conv_llava_plain,
|
| 369 |
-
"v0_plain": conv_llava_plain,
|
| 370 |
-
"llava_v0": conv_llava_v0,
|
| 371 |
-
"v0_mmtag": conv_llava_v0_mmtag,
|
| 372 |
-
"llava_v1": conv_llava_v1,
|
| 373 |
-
"v1_mmtag": conv_llava_v1_mmtag,
|
| 374 |
-
"llava_llama_2": conv_llava_llama_2,
|
| 375 |
-
|
| 376 |
-
"mpt": conv_mpt,
|
| 377 |
-
}
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
if __name__ == "__main__":
|
| 381 |
-
print(default_conversation.get_prompt())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/mm_utils.py
DELETED
|
@@ -1,107 +0,0 @@
|
|
| 1 |
-
from typing import Any
|
| 2 |
-
from PIL import Image
|
| 3 |
-
from io import BytesIO
|
| 4 |
-
import base64
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
from transformers import StoppingCriteria
|
| 8 |
-
from instructany2pix.llm.constants import IMAGE_TOKEN_INDEX
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def load_image_from_base64(image):
|
| 12 |
-
return Image.open(BytesIO(base64.b64decode(image)))
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def expand2square(pil_img, background_color):
|
| 16 |
-
width, height = pil_img.size
|
| 17 |
-
if width == height:
|
| 18 |
-
return pil_img
|
| 19 |
-
elif width > height:
|
| 20 |
-
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 21 |
-
result.paste(pil_img, (0, (width - height) // 2))
|
| 22 |
-
return result
|
| 23 |
-
else:
|
| 24 |
-
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 25 |
-
result.paste(pil_img, ((height - width) // 2, 0))
|
| 26 |
-
return result
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def process_images(images, image_processor, model_cfg):
|
| 30 |
-
image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
|
| 31 |
-
new_images = []
|
| 32 |
-
if image_aspect_ratio == 'pad':
|
| 33 |
-
for image in images:
|
| 34 |
-
image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean))
|
| 35 |
-
image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
| 36 |
-
new_images.append(image)
|
| 37 |
-
else:
|
| 38 |
-
return image_processor(images, return_tensors='pt')['pixel_values']
|
| 39 |
-
if all(x.shape == new_images[0].shape for x in new_images):
|
| 40 |
-
new_images = torch.stack(new_images, dim=0)
|
| 41 |
-
return new_images
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
|
| 45 |
-
prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split('<image>')]
|
| 46 |
-
|
| 47 |
-
def insert_separator(X, sep):
|
| 48 |
-
return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]
|
| 49 |
-
|
| 50 |
-
input_ids = []
|
| 51 |
-
offset = 0
|
| 52 |
-
if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
|
| 53 |
-
offset = 1
|
| 54 |
-
input_ids.append(prompt_chunks[0][0])
|
| 55 |
-
|
| 56 |
-
for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
|
| 57 |
-
input_ids.extend(x[offset:])
|
| 58 |
-
|
| 59 |
-
if return_tensors is not None:
|
| 60 |
-
if return_tensors == 'pt':
|
| 61 |
-
return torch.tensor(input_ids, dtype=torch.long)
|
| 62 |
-
raise ValueError(f'Unsupported tensor type: {return_tensors}')
|
| 63 |
-
return input_ids
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def get_model_name_from_path(model_path):
|
| 67 |
-
model_path = model_path.strip("/")
|
| 68 |
-
model_paths = model_path.split("/")
|
| 69 |
-
if model_paths[-1].startswith('checkpoint-'):
|
| 70 |
-
return model_paths[-2] + "_" + model_paths[-1]
|
| 71 |
-
else:
|
| 72 |
-
return model_paths[-1]
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
class KeywordsStoppingCriteria(StoppingCriteria):
|
| 78 |
-
def __init__(self, keywords, tokenizer, input_ids):
|
| 79 |
-
self.keywords = keywords
|
| 80 |
-
self.keyword_ids = []
|
| 81 |
-
self.max_keyword_len = 0
|
| 82 |
-
for keyword in keywords:
|
| 83 |
-
cur_keyword_ids = tokenizer(keyword).input_ids
|
| 84 |
-
if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
|
| 85 |
-
cur_keyword_ids = cur_keyword_ids[1:]
|
| 86 |
-
if len(cur_keyword_ids) > self.max_keyword_len:
|
| 87 |
-
self.max_keyword_len = len(cur_keyword_ids)
|
| 88 |
-
self.keyword_ids.append(torch.tensor(cur_keyword_ids))
|
| 89 |
-
self.tokenizer = tokenizer
|
| 90 |
-
self.start_len = input_ids.shape[1]
|
| 91 |
-
|
| 92 |
-
def call_bse(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 93 |
-
assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
|
| 94 |
-
offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len)
|
| 95 |
-
self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
|
| 96 |
-
for keyword_id in self.keyword_ids:
|
| 97 |
-
if (output_ids[0, -keyword_id.shape[0]:] == keyword_id).all():
|
| 98 |
-
return True
|
| 99 |
-
outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
|
| 100 |
-
for keyword in self.keywords:
|
| 101 |
-
if keyword in outputs:
|
| 102 |
-
return True
|
| 103 |
-
return False
|
| 104 |
-
|
| 105 |
-
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 106 |
-
res = [self.call_bse(output_ids[i:i+1],scores=None,**kwargs) for i,z in enumerate(output_ids) ]
|
| 107 |
-
return all(res)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
from .language_model.any2pix_llama import InstructAny2PixLMForCausalLM, InstructAny2PixLMConfig
|
|
|
|
|
|
instructany2pix/llm/model/any2pix_arch.py
DELETED
|
@@ -1,299 +0,0 @@
|
|
| 1 |
-
# Copyright 2023 Haotian Liu
|
| 2 |
-
#
|
| 3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
-
# you may not use this file except in compliance with the License.
|
| 5 |
-
# You may obtain a copy of the License at
|
| 6 |
-
#
|
| 7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
-
#
|
| 9 |
-
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
-
# See the License for the specific language governing permissions and
|
| 13 |
-
# limitations under the License.
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
from abc import ABC, abstractmethod
|
| 17 |
-
|
| 18 |
-
import torch
|
| 19 |
-
import torch.nn as nn
|
| 20 |
-
|
| 21 |
-
from .multimodal_encoder.builder import build_vision_tower
|
| 22 |
-
from .multimodal_projector.builder import build_vision_projector,build_vision_predictor
|
| 23 |
-
|
| 24 |
-
from instructany2pix.llm.constants import (IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN,
|
| 25 |
-
DEFAULT_IM_END_TOKEN,DEFAULT_IM_GEN_TOKEN,DEFAULT_MSK_TOKEN,DEFAULT_IM_GEN_START_TOKEN,
|
| 26 |
-
DEFAULT_AUDIO_GEN_TOKEN,DEFAULT_AUDIO_GEN_START_TOKEN,DEFAULT_AUDIO_TOKEN,
|
| 27 |
-
DEFAULT_BASE_TOKEN,DEFAULT_VIDEO_TOKEN,DEFAULT_BASE_NULL_TOKEN)
|
| 28 |
-
import logging
|
| 29 |
-
from .vae.builder import build_vae,VQVAE
|
| 30 |
-
class InstructAny2PixLMMetaModel:
|
| 31 |
-
|
| 32 |
-
def __init__(self, config):
|
| 33 |
-
super(InstructAny2PixLMMetaModel, self).__init__(config)
|
| 34 |
-
|
| 35 |
-
if hasattr(config, "mm_vision_tower"):
|
| 36 |
-
print("pre_init")
|
| 37 |
-
self.vision_tower = build_vision_tower(config, delay_load=False)
|
| 38 |
-
self.mm_projector = build_vision_projector(config)
|
| 39 |
-
self.vae = VQVAE(self.config.vae_image,self.config.vae_audio)
|
| 40 |
-
self.generator_processor = self.vae.processor
|
| 41 |
-
self.vae_projector_image = build_vision_projector(self.config,input_size=self.vae.embed_dim_image)
|
| 42 |
-
self.vae_projector_audio = build_vision_projector(self.config,input_size=self.vae.embed_dim_audio)
|
| 43 |
-
self.vae_predictor_image = build_vision_predictor(self.config,output_size=self.vae.vocab_size_image)
|
| 44 |
-
self.vae_predictor_audio = build_vision_predictor(self.config,output_size=self.vae.vocab_size_audio)
|
| 45 |
-
|
| 46 |
-
#raise NotImplemented
|
| 47 |
-
|
| 48 |
-
def get_vision_tower(self):
|
| 49 |
-
vision_tower = getattr(self, 'vision_tower', None)
|
| 50 |
-
if type(vision_tower) is list:
|
| 51 |
-
vision_tower = vision_tower[0]
|
| 52 |
-
return vision_tower
|
| 53 |
-
|
| 54 |
-
def get_vae(self):
|
| 55 |
-
return self.vae
|
| 56 |
-
|
| 57 |
-
def initialize_vision_modules(self, model_args, fsdp=None):
|
| 58 |
-
vision_tower = model_args.vision_tower
|
| 59 |
-
mm_vision_select_layer = model_args.mm_vision_select_layer
|
| 60 |
-
mm_vision_select_feature = model_args.mm_vision_select_feature
|
| 61 |
-
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
|
| 62 |
-
print('load_vision_tower')
|
| 63 |
-
self.config.mm_vision_tower = vision_tower
|
| 64 |
-
|
| 65 |
-
vision_tower = build_vision_tower(model_args)
|
| 66 |
-
|
| 67 |
-
if fsdp is not None and len(fsdp) > 0:
|
| 68 |
-
self.vision_tower = [vision_tower]
|
| 69 |
-
else:
|
| 70 |
-
self.vision_tower = vision_tower
|
| 71 |
-
|
| 72 |
-
self.config.use_mm_proj = True
|
| 73 |
-
self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
|
| 74 |
-
self.config.mm_hidden_size = vision_tower.hidden_size
|
| 75 |
-
self.config.mm_vision_select_layer = mm_vision_select_layer
|
| 76 |
-
self.config.mm_vision_select_feature = mm_vision_select_feature
|
| 77 |
-
|
| 78 |
-
self.mm_projector = build_vision_projector(self.config)
|
| 79 |
-
|
| 80 |
-
if pretrain_mm_mlp_adapter is not None:
|
| 81 |
-
mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
|
| 82 |
-
def get_w(weights, keyword):
|
| 83 |
-
return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
|
| 84 |
-
|
| 85 |
-
self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
|
| 86 |
-
# generation
|
| 87 |
-
self.config.vae_image = ''
|
| 88 |
-
self.config.vae_audio = ''
|
| 89 |
-
if model_args.vae_image:
|
| 90 |
-
self.config.vae_image = model_args.vae_image
|
| 91 |
-
if model_args.vae_audio:
|
| 92 |
-
self.config.vae_audio = model_args.vae_audio
|
| 93 |
-
print('load_vae')
|
| 94 |
-
self.vae = VQVAE(self.config.vae_image,self.config.vae_audio)
|
| 95 |
-
self.generator_processor = self.vae.processor
|
| 96 |
-
self.vae_projector_image = build_vision_projector(self.config,input_size=self.vae.embed_dim_image)
|
| 97 |
-
self.vae_projector_audio = build_vision_projector(self.config,input_size=self.vae.embed_dim_audio)
|
| 98 |
-
self.vae_predictor_image = build_vision_predictor(self.config,output_size=self.vae.vocab_size_image)
|
| 99 |
-
self.vae_predictor_audio = build_vision_predictor(self.config,output_size=self.vae.vocab_size_audio)
|
| 100 |
-
|
| 101 |
-
class InstructAny2PixLMMetaForCausalLM(ABC):
|
| 102 |
-
|
| 103 |
-
@abstractmethod
|
| 104 |
-
def get_model(self):
|
| 105 |
-
pass
|
| 106 |
-
|
| 107 |
-
def get_vision_tower(self):
|
| 108 |
-
return self.get_model().get_vision_tower()
|
| 109 |
-
|
| 110 |
-
def get_vae(self):
|
| 111 |
-
return self.get_model().get_vae()
|
| 112 |
-
|
| 113 |
-
def encode_images(self, images):
|
| 114 |
-
image_features = self.get_model().get_vision_tower()(images)
|
| 115 |
-
image_features = self.get_model().mm_projector(image_features)
|
| 116 |
-
return image_features
|
| 117 |
-
|
| 118 |
-
def prepare_inputs_labels_for_multimodal(
|
| 119 |
-
self, input_ids, attention_mask, past_key_values, labels, images,novision=False
|
| 120 |
-
):
|
| 121 |
-
vision_tower = self.get_vision_tower()
|
| 122 |
-
if vision_tower is None or images is None or input_ids.shape[1] == 1 or novision:
|
| 123 |
-
if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
|
| 124 |
-
attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
|
| 125 |
-
return None, attention_mask, past_key_values, self.get_model().embed_tokens(input_ids), labels
|
| 126 |
-
|
| 127 |
-
if False: # and type(images) is list or images.ndim == 5:
|
| 128 |
-
concat_images = torch.cat([image for image in images], dim=0)
|
| 129 |
-
image_features = self.encode_images(concat_images)
|
| 130 |
-
split_sizes = [image.shape[0] for image in images]
|
| 131 |
-
image_features = torch.split(image_features, split_sizes, dim=0)
|
| 132 |
-
image_features = [x.flatten(0, 1) for x in image_features]
|
| 133 |
-
else:
|
| 134 |
-
assert type(images)== dict
|
| 135 |
-
image_features = self.encode_images(images)
|
| 136 |
-
|
| 137 |
-
new_input_embeds = []
|
| 138 |
-
new_labels = [] if labels is not None else None
|
| 139 |
-
cur_image_idx = 0
|
| 140 |
-
for batch_idx, cur_input_ids in enumerate(input_ids):
|
| 141 |
-
if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0:
|
| 142 |
-
# multimodal LLM, but the current sample is not multimodal
|
| 143 |
-
# FIXME: this is a hacky fix, for deepspeed zero3 to work
|
| 144 |
-
half_len = cur_input_ids.shape[0] // 2
|
| 145 |
-
cur_image_features = image_features[cur_image_idx]
|
| 146 |
-
cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len])
|
| 147 |
-
cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:])
|
| 148 |
-
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0)
|
| 149 |
-
new_input_embeds.append(cur_input_embeds)
|
| 150 |
-
if labels is not None:
|
| 151 |
-
new_labels.append(labels[batch_idx])
|
| 152 |
-
cur_image_idx += 1
|
| 153 |
-
continue
|
| 154 |
-
image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
|
| 155 |
-
cur_new_input_embeds = []
|
| 156 |
-
if labels is not None:
|
| 157 |
-
cur_labels = labels[batch_idx]
|
| 158 |
-
cur_new_labels = []
|
| 159 |
-
assert cur_labels.shape == cur_input_ids.shape
|
| 160 |
-
while image_token_indices.numel() > 0:
|
| 161 |
-
cur_image_features = image_features[cur_image_idx]
|
| 162 |
-
if len(cur_image_features.shape) == 1:
|
| 163 |
-
cur_image_features = cur_image_features[None,]
|
| 164 |
-
image_token_start = image_token_indices[0]
|
| 165 |
-
if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
|
| 166 |
-
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start-1]).detach())
|
| 167 |
-
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start-1:image_token_start]))
|
| 168 |
-
cur_new_input_embeds.append(cur_image_features)
|
| 169 |
-
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start+1:image_token_start+2]))
|
| 170 |
-
if labels is not None:
|
| 171 |
-
cur_new_labels.append(cur_labels[:image_token_start])
|
| 172 |
-
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
|
| 173 |
-
cur_new_labels.append(cur_labels[image_token_start:image_token_start+1])
|
| 174 |
-
cur_labels = cur_labels[image_token_start+2:]
|
| 175 |
-
else:
|
| 176 |
-
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start]))
|
| 177 |
-
cur_new_input_embeds.append(cur_image_features)
|
| 178 |
-
if labels is not None:
|
| 179 |
-
cur_new_labels.append(cur_labels[:image_token_start])
|
| 180 |
-
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
|
| 181 |
-
cur_labels = cur_labels[image_token_start+1:]
|
| 182 |
-
cur_image_idx += 1
|
| 183 |
-
if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
|
| 184 |
-
cur_input_ids = cur_input_ids[image_token_start+2:]
|
| 185 |
-
else:
|
| 186 |
-
cur_input_ids = cur_input_ids[image_token_start+1:]
|
| 187 |
-
image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
|
| 188 |
-
if cur_input_ids.numel() > 0:
|
| 189 |
-
if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
|
| 190 |
-
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids).detach())
|
| 191 |
-
else:
|
| 192 |
-
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
|
| 193 |
-
if labels is not None:
|
| 194 |
-
cur_new_labels.append(cur_labels)
|
| 195 |
-
cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds]
|
| 196 |
-
cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
|
| 197 |
-
new_input_embeds.append(cur_new_input_embeds)
|
| 198 |
-
if labels is not None:
|
| 199 |
-
cur_new_labels = torch.cat(cur_new_labels, dim=0)
|
| 200 |
-
new_labels.append(cur_new_labels)
|
| 201 |
-
|
| 202 |
-
if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds):
|
| 203 |
-
max_len = max(x.shape[0] for x in new_input_embeds)
|
| 204 |
-
|
| 205 |
-
new_input_embeds_align = []
|
| 206 |
-
for cur_new_embed in new_input_embeds:
|
| 207 |
-
cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0)
|
| 208 |
-
new_input_embeds_align.append(cur_new_embed)
|
| 209 |
-
new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
|
| 210 |
-
|
| 211 |
-
if labels is not None:
|
| 212 |
-
new_labels_align = []
|
| 213 |
-
_new_labels = new_labels
|
| 214 |
-
for cur_new_label in new_labels:
|
| 215 |
-
cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0)
|
| 216 |
-
new_labels_align.append(cur_new_label)
|
| 217 |
-
new_labels = torch.stack(new_labels_align, dim=0)
|
| 218 |
-
|
| 219 |
-
if attention_mask is not None:
|
| 220 |
-
new_attention_mask = []
|
| 221 |
-
for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels):
|
| 222 |
-
new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device)
|
| 223 |
-
new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device)
|
| 224 |
-
cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0)
|
| 225 |
-
new_attention_mask.append(cur_new_attention_mask)
|
| 226 |
-
attention_mask = torch.stack(new_attention_mask, dim=0)
|
| 227 |
-
assert attention_mask.shape == new_labels.shape
|
| 228 |
-
else:
|
| 229 |
-
new_input_embeds = torch.stack(new_input_embeds, dim=0)
|
| 230 |
-
if labels is not None:
|
| 231 |
-
new_labels = torch.stack(new_labels, dim=0)
|
| 232 |
-
|
| 233 |
-
if attention_mask is not None:
|
| 234 |
-
new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device)
|
| 235 |
-
attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1)
|
| 236 |
-
assert attention_mask.shape == new_input_embeds.shape[:2]
|
| 237 |
-
|
| 238 |
-
return None, attention_mask, past_key_values, new_input_embeds, new_labels
|
| 239 |
-
|
| 240 |
-
def initialize_vision_tokenizer(self, model_args, tokenizer,pre_init=False):
|
| 241 |
-
if not pre_init:
|
| 242 |
-
if model_args.mm_use_im_patch_token:
|
| 243 |
-
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
| 244 |
-
self.resize_token_embeddings(len(tokenizer))
|
| 245 |
-
|
| 246 |
-
if model_args.mm_use_im_start_end:
|
| 247 |
-
num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
| 248 |
-
self.resize_token_embeddings(len(tokenizer))
|
| 249 |
-
|
| 250 |
-
if num_new_tokens > 0:
|
| 251 |
-
input_embeddings = self.get_input_embeddings().weight.data
|
| 252 |
-
output_embeddings = self.get_output_embeddings().weight.data
|
| 253 |
-
|
| 254 |
-
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
| 255 |
-
dim=0, keepdim=True)
|
| 256 |
-
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
| 257 |
-
dim=0, keepdim=True)
|
| 258 |
-
|
| 259 |
-
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
| 260 |
-
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
| 261 |
-
|
| 262 |
-
if model_args.tune_mm_mlp_adapter:
|
| 263 |
-
for p in self.get_input_embeddings().parameters():
|
| 264 |
-
p.requires_grad = True
|
| 265 |
-
for p in self.get_output_embeddings().parameters():
|
| 266 |
-
p.requires_grad = False
|
| 267 |
-
|
| 268 |
-
if model_args.pretrain_mm_mlp_adapter:
|
| 269 |
-
mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
|
| 270 |
-
embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
|
| 271 |
-
assert num_new_tokens == 2
|
| 272 |
-
if input_embeddings.shape == embed_tokens_weight.shape:
|
| 273 |
-
input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
|
| 274 |
-
elif embed_tokens_weight.shape[0] == num_new_tokens:
|
| 275 |
-
input_embeddings[-num_new_tokens:] = embed_tokens_weight
|
| 276 |
-
else:
|
| 277 |
-
raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
|
| 278 |
-
elif model_args.mm_use_im_patch_token:
|
| 279 |
-
if model_args.tune_mm_mlp_adapter:
|
| 280 |
-
for p in self.get_input_embeddings().parameters():
|
| 281 |
-
p.requires_grad = False
|
| 282 |
-
for p in self.get_output_embeddings().parameters():
|
| 283 |
-
p.requires_grad = False
|
| 284 |
-
|
| 285 |
-
if model_args.mm_use_gen:
|
| 286 |
-
tokenizer.add_tokens([DEFAULT_IM_GEN_START_TOKEN,DEFAULT_IM_GEN_TOKEN,DEFAULT_MSK_TOKEN,DEFAULT_AUDIO_GEN_TOKEN,DEFAULT_AUDIO_GEN_START_TOKEN,DEFAULT_AUDIO_TOKEN,
|
| 287 |
-
DEFAULT_VIDEO_TOKEN,DEFAULT_BASE_TOKEN,DEFAULT_BASE_NULL_TOKEN], special_tokens=True)
|
| 288 |
-
self.resize_token_embeddings(len(tokenizer))
|
| 289 |
-
#tokenizer(DEFAULT_IM_GEN_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 290 |
-
self.DEFAULT_IM_GEN_TOKEN_IDX = tokenizer(DEFAULT_IM_GEN_START_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 291 |
-
self.DEFAULT_IM_GEN_TOKEN_IDX = tokenizer(DEFAULT_IM_GEN_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 292 |
-
self.DEFAULT_MSK_TOKEN_IDX = tokenizer(DEFAULT_MSK_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 293 |
-
self.DEFAULT_AUDIO_GEN_TOKEN_IDX = tokenizer(DEFAULT_AUDIO_GEN_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 294 |
-
self.DEFAULT_AUDIO_GEN_START_TOKEN_IDX = tokenizer(DEFAULT_AUDIO_GEN_START_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 295 |
-
self.DEFAULT_AUDIO_TOKEN_IDX = tokenizer(DEFAULT_AUDIO_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 296 |
-
self.DEFAULT_VIDEO_TOKEN_IDX = tokenizer(DEFAULT_VIDEO_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 297 |
-
self.DEFAULT_BASE_TOKEN_IDX = tokenizer(DEFAULT_BASE_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 298 |
-
self.DEFAULT_BASE_NULL_TOKEN_IDX = tokenizer(DEFAULT_BASE_NULL_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 299 |
-
self.tokenizer = tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/apply_delta.py
DELETED
|
@@ -1,48 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Usage:
|
| 3 |
-
python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta
|
| 4 |
-
"""
|
| 5 |
-
import argparse
|
| 6 |
-
|
| 7 |
-
import torch
|
| 8 |
-
from tqdm import tqdm
|
| 9 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 10 |
-
from ..model import InstructAny2PixLMForCausalLM
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
def apply_delta(base_model_path, target_model_path, delta_path):
|
| 14 |
-
print("Loading base model")
|
| 15 |
-
base = AutoModelForCausalLM.from_pretrained(
|
| 16 |
-
base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 17 |
-
|
| 18 |
-
print("Loading delta")
|
| 19 |
-
delta = InstructAny2PixLMForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 20 |
-
delta_tokenizer = AutoTokenizer.from_pretrained(delta_path)
|
| 21 |
-
|
| 22 |
-
print("Applying delta")
|
| 23 |
-
for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"):
|
| 24 |
-
if name not in base.state_dict():
|
| 25 |
-
assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
|
| 26 |
-
continue
|
| 27 |
-
if param.data.shape == base.state_dict()[name].shape:
|
| 28 |
-
param.data += base.state_dict()[name]
|
| 29 |
-
else:
|
| 30 |
-
assert name in ['model.embed_tokens.weight', 'lm_head.weight'], \
|
| 31 |
-
f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
|
| 32 |
-
bparam = base.state_dict()[name]
|
| 33 |
-
param.data[:bparam.shape[0], :bparam.shape[1]] += bparam
|
| 34 |
-
|
| 35 |
-
print("Saving target model")
|
| 36 |
-
delta.save_pretrained(target_model_path)
|
| 37 |
-
delta_tokenizer.save_pretrained(target_model_path)
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
if __name__ == "__main__":
|
| 41 |
-
parser = argparse.ArgumentParser()
|
| 42 |
-
parser.add_argument("--base-model-path", type=str, required=True)
|
| 43 |
-
parser.add_argument("--target-model-path", type=str, required=True)
|
| 44 |
-
parser.add_argument("--delta-path", type=str, required=True)
|
| 45 |
-
|
| 46 |
-
args = parser.parse_args()
|
| 47 |
-
|
| 48 |
-
apply_delta(args.base_model_path, args.target_model_path, args.delta_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/builder.py
DELETED
|
@@ -1,136 +0,0 @@
|
|
| 1 |
-
# Copyright 2023 Haotian Liu
|
| 2 |
-
#
|
| 3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
-
# you may not use this file except in compliance with the License.
|
| 5 |
-
# You may obtain a copy of the License at
|
| 6 |
-
#
|
| 7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
-
#
|
| 9 |
-
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
-
# See the License for the specific language governing permissions and
|
| 13 |
-
# limitations under the License.
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
import os
|
| 17 |
-
import warnings
|
| 18 |
-
import shutil
|
| 19 |
-
|
| 20 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
|
| 21 |
-
import torch
|
| 22 |
-
from . import *
|
| 23 |
-
from instructany2pix.llm.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN,DEFAULT_AUDIO_TOKEN
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda"):
|
| 27 |
-
kwargs = {"device_map": device_map}
|
| 28 |
-
|
| 29 |
-
if load_8bit:
|
| 30 |
-
kwargs['load_in_8bit'] = True
|
| 31 |
-
elif load_4bit:
|
| 32 |
-
kwargs['load_in_4bit'] = True
|
| 33 |
-
kwargs['quantization_config'] = BitsAndBytesConfig(
|
| 34 |
-
load_in_4bit=True,
|
| 35 |
-
bnb_4bit_compute_dtype=torch.float16,
|
| 36 |
-
bnb_4bit_use_double_quant=True,
|
| 37 |
-
bnb_4bit_quant_type='nf4'
|
| 38 |
-
)
|
| 39 |
-
else:
|
| 40 |
-
kwargs['torch_dtype'] = torch.float16
|
| 41 |
-
|
| 42 |
-
if 'instructany2pix' in model_name.lower():
|
| 43 |
-
if 'lora' in model_name.lower() and model_base is None:
|
| 44 |
-
warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.')
|
| 45 |
-
if 'lora' in model_name.lower() and model_base is not None:
|
| 46 |
-
lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
|
| 47 |
-
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 48 |
-
print('Loading instructany2pix from base model...')
|
| 49 |
-
model = InstructAny2PixLMForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
|
| 50 |
-
token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
|
| 51 |
-
if model.lm_head.weight.shape[0] != token_num:
|
| 52 |
-
model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
|
| 53 |
-
model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
|
| 54 |
-
|
| 55 |
-
print('Loading additional instructany2pix weights...')
|
| 56 |
-
if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
|
| 57 |
-
non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
|
| 58 |
-
else:
|
| 59 |
-
# this is probably from HF Hub
|
| 60 |
-
from huggingface_hub import hf_hub_download
|
| 61 |
-
def load_from_hf(repo_id, filename, subfolder=None):
|
| 62 |
-
cache_file = hf_hub_download(
|
| 63 |
-
repo_id=repo_id,
|
| 64 |
-
filename=filename,
|
| 65 |
-
subfolder=subfolder)
|
| 66 |
-
return torch.load(cache_file, map_location='cpu')
|
| 67 |
-
non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
|
| 68 |
-
non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
|
| 69 |
-
if any(k.startswith('model.model.') for k in non_lora_trainables):
|
| 70 |
-
non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
|
| 71 |
-
model.load_state_dict(non_lora_trainables, strict=False)
|
| 72 |
-
|
| 73 |
-
from peft import PeftModel
|
| 74 |
-
print('Loading LoRA weights...')
|
| 75 |
-
model = PeftModel.from_pretrained(model, model_path)
|
| 76 |
-
print('Merging LoRA weights...')
|
| 77 |
-
model = model.merge_and_unload()
|
| 78 |
-
print('Model is loaded...')
|
| 79 |
-
elif model_base is not None:
|
| 80 |
-
# this may be mm projector only
|
| 81 |
-
print('Loading InstructAny2Pix from base model...')
|
| 82 |
-
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 83 |
-
cfg_pretrained = AutoConfig.from_pretrained(model_path)
|
| 84 |
-
model = InstructAny2PixLMForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
|
| 85 |
-
|
| 86 |
-
mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
|
| 87 |
-
mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
|
| 88 |
-
model.load_state_dict(mm_projector_weights, strict=False)
|
| 89 |
-
else:
|
| 90 |
-
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
| 91 |
-
model = InstructAny2PixLMForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
|
| 92 |
-
else:
|
| 93 |
-
# Load language model
|
| 94 |
-
if model_base is not None:
|
| 95 |
-
# PEFT model
|
| 96 |
-
from peft import PeftModel
|
| 97 |
-
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 98 |
-
model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto")
|
| 99 |
-
print(f"Loading LoRA weights from {model_path}")
|
| 100 |
-
model = PeftModel.from_pretrained(model, model_path)
|
| 101 |
-
print(f"Merging weights")
|
| 102 |
-
model = model.merge_and_unload()
|
| 103 |
-
print('Convert to FP16...')
|
| 104 |
-
model.to(torch.float16)
|
| 105 |
-
else:
|
| 106 |
-
use_fast = False
|
| 107 |
-
if 'mpt' in model_name.lower():
|
| 108 |
-
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
|
| 109 |
-
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs)
|
| 110 |
-
else:
|
| 111 |
-
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
| 112 |
-
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
|
| 113 |
-
|
| 114 |
-
image_processor = None
|
| 115 |
-
|
| 116 |
-
if 'instructany2pix' in model_name.lower():
|
| 117 |
-
mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
|
| 118 |
-
mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
|
| 119 |
-
if mm_use_im_patch_token:
|
| 120 |
-
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
| 121 |
-
if mm_use_im_start_end:
|
| 122 |
-
tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
| 123 |
-
model.resize_token_embeddings(len(tokenizer))
|
| 124 |
-
|
| 125 |
-
vision_tower = model.get_vision_tower()
|
| 126 |
-
if not vision_tower.is_loaded:
|
| 127 |
-
vision_tower.load_model()
|
| 128 |
-
vision_tower.to(device=device, dtype=torch.float16)
|
| 129 |
-
image_processor = vision_tower.image_processor
|
| 130 |
-
|
| 131 |
-
if hasattr(model.config, "max_sequence_length"):
|
| 132 |
-
context_len = model.config.max_sequence_length
|
| 133 |
-
else:
|
| 134 |
-
context_len = 2048
|
| 135 |
-
|
| 136 |
-
return tokenizer, model, image_processor, context_len
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/consolidate.py
DELETED
|
@@ -1,26 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
import argparse
|
| 3 |
-
|
| 4 |
-
import torch
|
| 5 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
-
from . import *
|
| 7 |
-
from .utils import auto_upgrade
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
def consolidate_ckpt(src_path, dst_path):
|
| 11 |
-
print("Loading model")
|
| 12 |
-
auto_upgrade(src_path)
|
| 13 |
-
src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 14 |
-
src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False)
|
| 15 |
-
src_model.save_pretrained(dst_path)
|
| 16 |
-
src_tokenizer.save_pretrained(dst_path)
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
if __name__ == "__main__":
|
| 20 |
-
parser = argparse.ArgumentParser()
|
| 21 |
-
parser.add_argument("--src", type=str, required=True)
|
| 22 |
-
parser.add_argument("--dst", type=str, required=True)
|
| 23 |
-
|
| 24 |
-
args = parser.parse_args()
|
| 25 |
-
|
| 26 |
-
consolidate_ckpt(args.src, args.dst)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/__init__.py
DELETED
|
File without changes
|
instructany2pix/llm/model/language_model/any2pix_llama.py
DELETED
|
@@ -1,472 +0,0 @@
|
|
| 1 |
-
# Copyright 2023 Haotian Liu
|
| 2 |
-
#
|
| 3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
-
# you may not use this file except in compliance with the License.
|
| 5 |
-
# You may obtain a copy of the License at
|
| 6 |
-
#
|
| 7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
-
#
|
| 9 |
-
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
-
# See the License for the specific language governing permissions and
|
| 13 |
-
# limitations under the License.
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
from typing import List, Optional, Tuple, Union,Dict
|
| 17 |
-
from einops import rearrange
|
| 18 |
-
import torch
|
| 19 |
-
import torch.nn as nn
|
| 20 |
-
from torch.nn import CrossEntropyLoss
|
| 21 |
-
|
| 22 |
-
from transformers import AutoConfig, AutoModelForCausalLM, \
|
| 23 |
-
LlamaConfig, LlamaModel, LlamaForCausalLM
|
| 24 |
-
|
| 25 |
-
from transformers.modeling_outputs import CausalLMOutputWithPast,ModelOutput
|
| 26 |
-
|
| 27 |
-
from ..any2pix_arch import InstructAny2PixLMMetaModel, InstructAny2PixLMMetaForCausalLM
|
| 28 |
-
from instructany2pix.llm.constants import IGNORE_INDEX
|
| 29 |
-
from transformers.modeling_outputs import BaseModelOutputWithPast
|
| 30 |
-
import logging
|
| 31 |
-
|
| 32 |
-
logger = logging.getLogger(__name__)
|
| 33 |
-
|
| 34 |
-
class InstructAny2PixLMConfig(LlamaConfig):
|
| 35 |
-
model_type = "instructany2pix"
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
class InstructAny2PixLMModel(InstructAny2PixLMMetaModel, LlamaModel):
|
| 39 |
-
config_class = InstructAny2PixLMConfig
|
| 40 |
-
|
| 41 |
-
def __init__(self, config: LlamaConfig):
|
| 42 |
-
super(InstructAny2PixLMModel, self).__init__(config)
|
| 43 |
-
|
| 44 |
-
def forward(
|
| 45 |
-
self,
|
| 46 |
-
input_ids: torch.LongTensor = None,
|
| 47 |
-
attention_mask: Optional[torch.Tensor] = None,
|
| 48 |
-
position_ids: Optional[torch.LongTensor] = None,
|
| 49 |
-
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 50 |
-
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 51 |
-
use_cache: Optional[bool] = None,
|
| 52 |
-
output_attentions: Optional[bool] = None,
|
| 53 |
-
output_hidden_states: Optional[bool] = None,
|
| 54 |
-
return_dict: Optional[bool] = None,
|
| 55 |
-
#replacement_mask = None
|
| 56 |
-
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 57 |
-
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 58 |
-
output_hidden_states = (
|
| 59 |
-
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 60 |
-
)
|
| 61 |
-
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 62 |
-
|
| 63 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 64 |
-
|
| 65 |
-
# retrieve input_ids and inputs_embeds
|
| 66 |
-
if input_ids is not None and inputs_embeds is not None:
|
| 67 |
-
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 68 |
-
elif input_ids is not None:
|
| 69 |
-
batch_size, seq_length = input_ids.shape
|
| 70 |
-
elif inputs_embeds is not None:
|
| 71 |
-
batch_size, seq_length, _ = inputs_embeds.shape
|
| 72 |
-
else:
|
| 73 |
-
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 74 |
-
|
| 75 |
-
seq_length_with_past = seq_length
|
| 76 |
-
past_key_values_length = 0
|
| 77 |
-
|
| 78 |
-
if past_key_values is not None:
|
| 79 |
-
past_key_values_length = past_key_values[0][0].shape[2]
|
| 80 |
-
seq_length_with_past = seq_length_with_past + past_key_values_length
|
| 81 |
-
|
| 82 |
-
if position_ids is None:
|
| 83 |
-
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 84 |
-
position_ids = torch.arange(
|
| 85 |
-
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
| 86 |
-
)
|
| 87 |
-
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
| 88 |
-
else:
|
| 89 |
-
position_ids = position_ids.view(-1, seq_length).long()
|
| 90 |
-
|
| 91 |
-
if inputs_embeds is None:
|
| 92 |
-
inputs_embeds = self.embed_tokens(input_ids)
|
| 93 |
-
# embed positions
|
| 94 |
-
if attention_mask is None:
|
| 95 |
-
attention_mask = torch.ones(
|
| 96 |
-
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
| 97 |
-
)
|
| 98 |
-
|
| 99 |
-
attention_mask = self._prepare_decoder_attention_mask(
|
| 100 |
-
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
| 101 |
-
)
|
| 102 |
-
# if replacement_mask is not None and len(attention_mask.shape) == 4:
|
| 103 |
-
# replacement_mask = replacement_mask[:,None,:] & replacement_mask[:,:,None] # B X N X N
|
| 104 |
-
# replacement_mask = replacement_mask[:,None] # B X H X N X N
|
| 105 |
-
# attention_mask[replacement_mask] = 0.0
|
| 106 |
-
hidden_states = inputs_embeds
|
| 107 |
-
|
| 108 |
-
if self.gradient_checkpointing and self.training:
|
| 109 |
-
if use_cache:
|
| 110 |
-
logger.warning_once(
|
| 111 |
-
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 112 |
-
)
|
| 113 |
-
use_cache = False
|
| 114 |
-
|
| 115 |
-
# decoder layers
|
| 116 |
-
all_hidden_states = () if output_hidden_states else None
|
| 117 |
-
all_self_attns = () if output_attentions else None
|
| 118 |
-
next_decoder_cache = () if use_cache else None
|
| 119 |
-
|
| 120 |
-
for idx, decoder_layer in enumerate(self.layers):
|
| 121 |
-
if output_hidden_states:
|
| 122 |
-
all_hidden_states += (hidden_states,)
|
| 123 |
-
|
| 124 |
-
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 125 |
-
|
| 126 |
-
if self.gradient_checkpointing and self.training:
|
| 127 |
-
|
| 128 |
-
def create_custom_forward(module):
|
| 129 |
-
def custom_forward(*inputs):
|
| 130 |
-
# None for past_key_value
|
| 131 |
-
return module(*inputs, output_attentions, None)
|
| 132 |
-
|
| 133 |
-
return custom_forward
|
| 134 |
-
|
| 135 |
-
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 136 |
-
create_custom_forward(decoder_layer),
|
| 137 |
-
hidden_states,
|
| 138 |
-
attention_mask,
|
| 139 |
-
position_ids,
|
| 140 |
-
None,
|
| 141 |
-
)
|
| 142 |
-
else:
|
| 143 |
-
layer_outputs = decoder_layer(
|
| 144 |
-
hidden_states,
|
| 145 |
-
attention_mask=attention_mask,
|
| 146 |
-
position_ids=position_ids,
|
| 147 |
-
past_key_value=past_key_value,
|
| 148 |
-
output_attentions=output_attentions,
|
| 149 |
-
use_cache=use_cache,
|
| 150 |
-
)
|
| 151 |
-
|
| 152 |
-
hidden_states = layer_outputs[0]
|
| 153 |
-
|
| 154 |
-
if use_cache:
|
| 155 |
-
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
| 156 |
-
|
| 157 |
-
if output_attentions:
|
| 158 |
-
all_self_attns += (layer_outputs[1],)
|
| 159 |
-
|
| 160 |
-
hidden_states = self.norm(hidden_states)
|
| 161 |
-
|
| 162 |
-
# add hidden states from the last decoder layer
|
| 163 |
-
if output_hidden_states:
|
| 164 |
-
all_hidden_states += (hidden_states,)
|
| 165 |
-
|
| 166 |
-
next_cache = next_decoder_cache if use_cache else None
|
| 167 |
-
if not return_dict:
|
| 168 |
-
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 169 |
-
return BaseModelOutputWithPast(
|
| 170 |
-
last_hidden_state=hidden_states,
|
| 171 |
-
past_key_values=next_cache,
|
| 172 |
-
hidden_states=all_hidden_states,
|
| 173 |
-
attentions=all_self_attns,
|
| 174 |
-
)
|
| 175 |
-
from instructany2pix.llm.constants import REPLACEMENT_TYPE
|
| 176 |
-
|
| 177 |
-
class InstructAny2PixLMForCausalLM(LlamaForCausalLM, InstructAny2PixLMMetaForCausalLM):
|
| 178 |
-
config_class = InstructAny2PixLMConfig
|
| 179 |
-
|
| 180 |
-
def __init__(self, config):
|
| 181 |
-
super(LlamaForCausalLM, self).__init__(config)
|
| 182 |
-
self.model = InstructAny2PixLMModel(config)
|
| 183 |
-
|
| 184 |
-
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 185 |
-
#self.lm_head_img = nn.Linear(3, config.vocab_size, bias=False) # FIXME: Add config
|
| 186 |
-
# Initialize weights and apply final processing
|
| 187 |
-
self.post_init()
|
| 188 |
-
|
| 189 |
-
def get_model(self):
|
| 190 |
-
return self.model
|
| 191 |
-
|
| 192 |
-
def forward(
|
| 193 |
-
self,
|
| 194 |
-
input_ids: torch.LongTensor = None,
|
| 195 |
-
attention_mask: Optional[torch.Tensor] = None,
|
| 196 |
-
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 197 |
-
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 198 |
-
labels: Optional[torch.LongTensor] = None,
|
| 199 |
-
use_cache: Optional[bool] = None,
|
| 200 |
-
output_attentions: Optional[bool] = None,
|
| 201 |
-
output_hidden_states: Optional[bool] = None,
|
| 202 |
-
images: Optional[Dict] = None,
|
| 203 |
-
return_dict: Optional[bool] = None,
|
| 204 |
-
generation_target: Optional[Dict] = None,
|
| 205 |
-
return_generations=True,
|
| 206 |
-
extra_inputs=None,
|
| 207 |
-
extra_replacement=None,
|
| 208 |
-
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 209 |
-
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 210 |
-
output_hidden_states = (
|
| 211 |
-
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 212 |
-
)
|
| 213 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 214 |
-
|
| 215 |
-
if self.training:
|
| 216 |
-
encodings = self.get_model().get_vae()(generation_target)
|
| 217 |
-
else:
|
| 218 |
-
encodings = {}
|
| 219 |
-
# encode vae for
|
| 220 |
-
replacement_mask = torch.zeros_like(input_ids,dtype=bool).to(input_ids.device)
|
| 221 |
-
if 'image' in encodings:
|
| 222 |
-
quant_image,ind_image,info_image = encodings['image']
|
| 223 |
-
n = quant_image.shape[0]
|
| 224 |
-
if info_image:
|
| 225 |
-
ind_image = ind_image.view(n,-1)
|
| 226 |
-
loss_fct_img = nn.CrossEntropyLoss()
|
| 227 |
-
img_loss_obj = 'ar'
|
| 228 |
-
else:
|
| 229 |
-
ind_image = quant_image.squeeze(-1).squeeze(-1).unsqueeze(1)
|
| 230 |
-
loss_fct_img = nn.MSELoss()
|
| 231 |
-
img_loss_obj = 'latent'
|
| 232 |
-
img_embded = self.get_model().vae_projector_image(rearrange(quant_image,'n c h w -> n (h w) c') )
|
| 233 |
-
replacement_mask_img = input_ids == self.DEFAULT_IM_GEN_TOKEN_IDX
|
| 234 |
-
replacement_mask = replacement_mask | replacement_mask_img
|
| 235 |
-
if 'audio' in encodings:
|
| 236 |
-
quant_audio,ind_audio,info_audio = encodings['audio']
|
| 237 |
-
n = quant_audio.shape[0]
|
| 238 |
-
if info_audio:
|
| 239 |
-
ind_audio = ind_audio.view(n,-1)
|
| 240 |
-
loss_fct_aud = nn.CrossEntropyLoss()
|
| 241 |
-
audloss_obj = 'ar'
|
| 242 |
-
else:
|
| 243 |
-
ind_aud = quant_audio.squeeze(1)# N H W C -> N L C
|
| 244 |
-
loss_fct_aud = nn.MSELoss()
|
| 245 |
-
aud_loss_obj = 'latent'
|
| 246 |
-
audio_embded = self.get_model().vae_projector_audio(rearrange(quant_audio,'n h w c-> n (h w) c') )
|
| 247 |
-
replacement_mask_audio = input_ids == self.DEFAULT_AUDIO_GEN_TOKEN_IDX
|
| 248 |
-
replacement_mask = replacement_mask | replacement_mask_audio
|
| 249 |
-
|
| 250 |
-
# replacement_audio = input_ids == self.DEFAULT_AUDIO_GEN_TOKEN_IDX
|
| 251 |
-
# audio_input_embded = self.get_model().vae_projector_audio(rearrange(quant_audio,'n h w c-> n (h w) c') )
|
| 252 |
-
|
| 253 |
-
raw_input_ids = input_ids
|
| 254 |
-
input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images,novision=True)
|
| 255 |
-
if extra_replacement is not None:
|
| 256 |
-
if self.training:
|
| 257 |
-
extra_replacement_mask = (raw_input_ids == self.DEFAULT_VIDEO_TOKEN_IDX ) # | (
|
| 258 |
-
# raw_input_ids == self.DEFAULT_IM_GEN_TOKEN_IDX) | (raw_input_ids == self.DEFAULT_BASE_TOKEN_IDX) self.get_model().vae_projector_image[0].weight.grad
|
| 259 |
-
if extra_replacement['mask'].shape[0] != inputs_embeds[extra_replacement_mask].shape[0]:
|
| 260 |
-
print("SKIPPED")
|
| 261 |
-
extra_replacement['mask'] = torch.zeros(inputs_embeds[extra_replacement_mask].shape[0]).to(extra_replacement['mask'])
|
| 262 |
-
z = torch.zeros_like(inputs_embeds)
|
| 263 |
-
z2 = self.get_model().vae_projector_image(
|
| 264 |
-
extra_replacement['data'][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT])
|
| 265 |
-
a,b = torch.where(extra_replacement_mask)
|
| 266 |
-
z[a[extra_replacement['mask']==REPLACEMENT_TYPE.INPUT],b[extra_replacement['mask']==REPLACEMENT_TYPE.INPUT]] += z2
|
| 267 |
-
inputs_embeds[extra_replacement_mask][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT] = 0.0
|
| 268 |
-
z = z + inputs_embeds
|
| 269 |
-
inputs_embeds = z
|
| 270 |
-
print("Replaced:",len(extra_replacement['mask']==REPLACEMENT_TYPE.INPUT))
|
| 271 |
-
extra_tgt_mask = (extra_replacement['mask']==REPLACEMENT_TYPE.BASE )| (extra_replacement['mask']==REPLACEMENT_TYPE.GEN)
|
| 272 |
-
extra_replacement_gt = extra_replacement['data'][extra_tgt_mask]
|
| 273 |
-
loss_fn_extra = nn.L1Loss()
|
| 274 |
-
if extra_replacement_gt.shape[0]==0:
|
| 275 |
-
loss_fn_extra = None
|
| 276 |
-
else:
|
| 277 |
-
assert labels is None
|
| 278 |
-
extra_replacement_mask = (raw_input_ids == self.DEFAULT_VIDEO_TOKEN_IDX )
|
| 279 |
-
#print(len(extra_replacement['mask']==REPLACEMENT_TYPE.INPUT))
|
| 280 |
-
|
| 281 |
-
z = torch.zeros_like(inputs_embeds)
|
| 282 |
-
z2 = self.get_model().vae_projector_image(
|
| 283 |
-
extra_replacement['data'][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT])
|
| 284 |
-
#print("z2",z2)
|
| 285 |
-
a,b = torch.where(extra_replacement_mask)
|
| 286 |
-
a = a[:extra_replacement['mask'].shape[0]]
|
| 287 |
-
b = b[:extra_replacement['mask'].shape[0]]
|
| 288 |
-
z[a[extra_replacement['mask']==REPLACEMENT_TYPE.INPUT],b[extra_replacement['mask']==REPLACEMENT_TYPE.INPUT]] += z2
|
| 289 |
-
inputs_embeds[extra_replacement_mask][:extra_replacement['mask'].shape[0]][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT] = 0.0
|
| 290 |
-
z = z + inputs_embeds
|
| 291 |
-
inputs_embeds = z
|
| 292 |
-
#print("HERE")
|
| 293 |
-
#print(inputs_embeds[extra_replacement_mask][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT])
|
| 294 |
-
|
| 295 |
-
# inputs_embeds[extra_replacement_mask][:extra_replacement['mask'].shape[0]][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT] = self.get_model().vae_projector_image(
|
| 296 |
-
# extra_replacement['data'][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT].to(inputs_embeds))
|
| 297 |
-
# z.sum().backward()
|
| 298 |
-
if self.training:
|
| 299 |
-
for replace_info in generation_target['info']:
|
| 300 |
-
ii = replace_info['idx']
|
| 301 |
-
mm = replace_info['modality']
|
| 302 |
-
if mm == 'image':
|
| 303 |
-
inputs_embeds[replace_info['batch']][replacement_mask_img[replace_info['batch']]] = img_embded[ii]
|
| 304 |
-
#labels[replace_info['batch']][torch.where(replacement_mask_img[ii])[0]-1] just for sanity check <gen start>, <gen> ....
|
| 305 |
-
elif mm == 'audio':
|
| 306 |
-
inputs_embeds[replace_info['batch']][replacement_mask_audio[replace_info['batch']]] = audio_embded[ii]
|
| 307 |
-
# labels[labels==self.DEFAULT_IM_GEN_TOKEN_IDX] = IGNORE_INDEX
|
| 308 |
-
# labels[labels==self.DEFAULT_AUDIO_GEN_TOKEN_IDX] = IGNORE_INDEX
|
| 309 |
-
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 310 |
-
|
| 311 |
-
if extra_inputs is not None:
|
| 312 |
-
if 'audio' in extra_inputs:
|
| 313 |
-
audio_in = extra_inputs['audio'].squeeze(1) # N 8 768
|
| 314 |
-
audio_in = self.get_model().vae_projector_audio(audio_in)
|
| 315 |
-
msk_in = raw_input_ids == self.DEFAULT_AUDIO_TOKEN_IDX
|
| 316 |
-
for rinfo in extra_inputs['info']:
|
| 317 |
-
l_mask = msk_in[rinfo['bn']]
|
| 318 |
-
if l_mask.sum() !=8:
|
| 319 |
-
continue
|
| 320 |
-
else:
|
| 321 |
-
inputs_embeds[rinfo['bn'],l_mask]=audio_in[rinfo['idx']]
|
| 322 |
-
# hack, assume has N audio inp
|
| 323 |
-
|
| 324 |
-
outputs = self.model(
|
| 325 |
-
input_ids=input_ids,
|
| 326 |
-
attention_mask=attention_mask,
|
| 327 |
-
past_key_values=past_key_values,
|
| 328 |
-
inputs_embeds=inputs_embeds,
|
| 329 |
-
use_cache=use_cache,
|
| 330 |
-
output_attentions=output_attentions,
|
| 331 |
-
output_hidden_states=output_hidden_states,
|
| 332 |
-
return_dict=return_dict,
|
| 333 |
-
# replacement_mask=replacement_mask, # allow looking into future for images
|
| 334 |
-
)
|
| 335 |
-
|
| 336 |
-
hidden_states = outputs[0]
|
| 337 |
-
logits = self.lm_head(hidden_states)
|
| 338 |
-
|
| 339 |
-
loss = None
|
| 340 |
-
img_decode = None
|
| 341 |
-
aud_decode=None
|
| 342 |
-
individual_losses = {}
|
| 343 |
-
extra_gen = None
|
| 344 |
-
extra_gen_idx = None
|
| 345 |
-
if labels is not None:
|
| 346 |
-
# Shift so that tokens < n predict n
|
| 347 |
-
shift_logits = logits[..., :-1, :].contiguous()
|
| 348 |
-
shift_labels = labels[..., 1:].contiguous()
|
| 349 |
-
hidden_states.shape
|
| 350 |
-
output_vae_img = []
|
| 351 |
-
target_vae_img = []
|
| 352 |
-
output_vae_audio = []
|
| 353 |
-
target_vae_audio = []
|
| 354 |
-
for replace_info in generation_target['info']:
|
| 355 |
-
ii = replace_info['idx']
|
| 356 |
-
mm = replace_info['modality']
|
| 357 |
-
if mm == 'image':
|
| 358 |
-
output_vae_img.append(hidden_states[replace_info['batch']][:-1][replacement_mask_img[replace_info['batch']][1:]])
|
| 359 |
-
target_vae_img.append(ind_image[ii])
|
| 360 |
-
#labels[replace_info['batch']][torch.where(replacement_mask_img[ii])[0]-1] just for sanity check <gen start>, <gen> ....
|
| 361 |
-
elif mm == 'audio':
|
| 362 |
-
output_vae_audio.append(hidden_states[replace_info['batch']][:-1][replacement_mask_audio[replace_info['batch']][1:]])
|
| 363 |
-
target_vae_audio.append(ind_aud[ii])
|
| 364 |
-
loss_fct = CrossEntropyLoss()
|
| 365 |
-
|
| 366 |
-
#prediction = logits_img.argmax(-1)
|
| 367 |
-
|
| 368 |
-
# Flatten the tokens
|
| 369 |
-
|
| 370 |
-
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 371 |
-
shift_labels = shift_labels.view(-1)
|
| 372 |
-
# Enable model/pipeline parallelism
|
| 373 |
-
shift_labels = shift_labels.to(shift_logits.device)
|
| 374 |
-
loss = loss_fct(shift_logits, shift_labels)
|
| 375 |
-
loss_lang = loss.detach().item()
|
| 376 |
-
individual_losses['loss_lang'] = loss_lang
|
| 377 |
-
if len(output_vae_img):
|
| 378 |
-
logits_img = self.get_model().vae_predictor_image(torch.cat(output_vae_img))
|
| 379 |
-
tgt_img = torch.cat(target_vae_img)
|
| 380 |
-
if img_loss_obj =='ar':
|
| 381 |
-
tgt_img = tgt_img.view(-1) # discrete tokens
|
| 382 |
-
loss_img = loss_fct_img(logits_img,tgt_img)
|
| 383 |
-
if img_loss_obj =='ar':
|
| 384 |
-
pass
|
| 385 |
-
else:
|
| 386 |
-
loss_img *= logits_img.shape[-1]
|
| 387 |
-
loss += loss_img
|
| 388 |
-
individual_losses['loss_img'] =loss_img.detach().item()
|
| 389 |
-
if return_generations:
|
| 390 |
-
with torch.no_grad():
|
| 391 |
-
if img_loss_obj =='ar':
|
| 392 |
-
img_encodings_pred = logits_img.argmax(-1).view(len(output_vae_img),-1)
|
| 393 |
-
else:
|
| 394 |
-
img_encodings_pred = logits_img.detach() # N, D_emb
|
| 395 |
-
img_decode = self.get_vae().image_vae.decode_seq(img_encodings_pred,info_image)
|
| 396 |
-
|
| 397 |
-
if len(output_vae_audio):
|
| 398 |
-
logits_aud = self.get_model().vae_predictor_audio(torch.cat(output_vae_audio))
|
| 399 |
-
tgt_aud = torch.cat(target_vae_audio)
|
| 400 |
-
if aud_loss_obj =='ar':
|
| 401 |
-
tgt_aud = tgt_aud.view(-1) # discrete tokens
|
| 402 |
-
loss_aud = loss_fct_aud(logits_aud,tgt_aud)
|
| 403 |
-
if aud_loss_obj =='ar':
|
| 404 |
-
pass
|
| 405 |
-
else:
|
| 406 |
-
loss_aud *= logits_aud.shape[-1]
|
| 407 |
-
loss += loss_aud
|
| 408 |
-
individual_losses['loss_aud'] =loss_aud.detach().item()
|
| 409 |
-
if return_generations:
|
| 410 |
-
with torch.no_grad():
|
| 411 |
-
if aud_loss_obj =='ar':
|
| 412 |
-
aud_encodings_pred = logits_aud.argmax(-1).view(len(output_vae_audio),-1)
|
| 413 |
-
else:
|
| 414 |
-
aud_encodings_pred = logits_aud.detach() # N, D_emb
|
| 415 |
-
aud_decode = self.get_vae().image_vae.decode_seq(aud_encodings_pred,info_audio)
|
| 416 |
-
if extra_replacement is not None:
|
| 417 |
-
extra_pred = self.get_model().vae_predictor_image(hidden_states[:,:-1][extra_replacement_mask[:,1:]])
|
| 418 |
-
extra_pred = extra_pred[extra_tgt_mask]
|
| 419 |
-
if labels is not None:
|
| 420 |
-
if loss_fn_extra is None:
|
| 421 |
-
loss_extra = extra_pred.sum() * 0.0
|
| 422 |
-
else:
|
| 423 |
-
loss_extra = loss_fn_extra(extra_pred,extra_replacement_gt)
|
| 424 |
-
if torch.isnan(loss_extra):
|
| 425 |
-
loss_extra = 0.0
|
| 426 |
-
loss += loss_extra
|
| 427 |
-
individual_losses['loss_extra'] =loss_extra.detach().item()
|
| 428 |
-
if return_generations:
|
| 429 |
-
extra_gen = extra_pred
|
| 430 |
-
extra_gen_idx = extra_replacement_mask[:,1:]
|
| 431 |
-
if not return_dict:
|
| 432 |
-
output = (logits,) + outputs[1:]
|
| 433 |
-
return (loss,) + output if loss is not None else output
|
| 434 |
-
|
| 435 |
-
return ModelOutput(
|
| 436 |
-
loss=loss,
|
| 437 |
-
logits=logits,
|
| 438 |
-
past_key_values=outputs.past_key_values,
|
| 439 |
-
hidden_states=outputs.hidden_states,
|
| 440 |
-
extra_gen=extra_gen,
|
| 441 |
-
extra_gen_idx=extra_gen_idx,
|
| 442 |
-
attentions=outputs.attentions,
|
| 443 |
-
img_decode=img_decode,
|
| 444 |
-
aud_decode=aud_decode,
|
| 445 |
-
individual_losses=individual_losses,
|
| 446 |
-
)
|
| 447 |
-
|
| 448 |
-
def prepare_inputs_for_generation(
|
| 449 |
-
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
| 450 |
-
):
|
| 451 |
-
if past_key_values:
|
| 452 |
-
input_ids = input_ids[:, -1:]
|
| 453 |
-
|
| 454 |
-
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 455 |
-
if inputs_embeds is not None and past_key_values is None:
|
| 456 |
-
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 457 |
-
else:
|
| 458 |
-
model_inputs = {"input_ids": input_ids}
|
| 459 |
-
|
| 460 |
-
model_inputs.update(
|
| 461 |
-
{
|
| 462 |
-
"past_key_values": past_key_values,
|
| 463 |
-
"use_cache": kwargs.get("use_cache"),
|
| 464 |
-
"attention_mask": attention_mask,
|
| 465 |
-
"images": kwargs.get("images", None),
|
| 466 |
-
"extra_replacement": kwargs.get("extra_replacement", None),
|
| 467 |
-
}
|
| 468 |
-
)
|
| 469 |
-
return model_inputs
|
| 470 |
-
|
| 471 |
-
AutoConfig.register("instructany2pix", InstructAny2PixLMConfig)
|
| 472 |
-
AutoModelForCausalLM.register(InstructAny2PixLMConfig, InstructAny2PixLMForCausalLM)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/mpt/adapt_tokenizer.py
DELETED
|
@@ -1,41 +0,0 @@
|
|
| 1 |
-
from typing import Union
|
| 2 |
-
from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
|
| 3 |
-
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
|
| 4 |
-
NUM_SENTINEL_TOKENS: int = 100
|
| 5 |
-
|
| 6 |
-
def adapt_tokenizer_for_denoising(tokenizer: Tokenizer):
|
| 7 |
-
"""Adds sentinel tokens and padding token (if missing).
|
| 8 |
-
|
| 9 |
-
Expands the tokenizer vocabulary to include sentinel tokens
|
| 10 |
-
used in mixture-of-denoiser tasks as well as a padding token.
|
| 11 |
-
|
| 12 |
-
All added tokens are added as special tokens. No tokens are
|
| 13 |
-
added if sentinel tokens and padding token already exist.
|
| 14 |
-
"""
|
| 15 |
-
sentinels_to_add = [f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)]
|
| 16 |
-
tokenizer.add_tokens(sentinels_to_add, special_tokens=True)
|
| 17 |
-
if tokenizer.pad_token is None:
|
| 18 |
-
tokenizer.add_tokens('<pad>', special_tokens=True)
|
| 19 |
-
tokenizer.pad_token = '<pad>'
|
| 20 |
-
assert tokenizer.pad_token_id is not None
|
| 21 |
-
sentinels = ''.join([f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)])
|
| 22 |
-
_sentinel_token_ids = tokenizer(sentinels, add_special_tokens=False).input_ids
|
| 23 |
-
tokenizer.sentinel_token_ids = _sentinel_token_ids
|
| 24 |
-
|
| 25 |
-
class AutoTokenizerForMOD(AutoTokenizer):
|
| 26 |
-
"""AutoTokenizer + Adaptation for MOD.
|
| 27 |
-
|
| 28 |
-
A simple wrapper around AutoTokenizer to make instantiating
|
| 29 |
-
an MOD-adapted tokenizer a bit easier.
|
| 30 |
-
|
| 31 |
-
MOD-adapted tokenizers have sentinel tokens (e.g., <extra_id_0>),
|
| 32 |
-
a padding token, and a property to get the token ids of the
|
| 33 |
-
sentinel tokens.
|
| 34 |
-
"""
|
| 35 |
-
|
| 36 |
-
@classmethod
|
| 37 |
-
def from_pretrained(cls, *args, **kwargs):
|
| 38 |
-
"""See `AutoTokenizer.from_pretrained` docstring."""
|
| 39 |
-
tokenizer = super().from_pretrained(*args, **kwargs)
|
| 40 |
-
adapt_tokenizer_for_denoising(tokenizer)
|
| 41 |
-
return tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/mpt/attention.py
DELETED
|
@@ -1,300 +0,0 @@
|
|
| 1 |
-
"""Attention layers."""
|
| 2 |
-
import math
|
| 3 |
-
import warnings
|
| 4 |
-
from typing import Optional
|
| 5 |
-
import torch
|
| 6 |
-
import torch.nn as nn
|
| 7 |
-
from einops import rearrange
|
| 8 |
-
from packaging import version
|
| 9 |
-
from torch import nn
|
| 10 |
-
from .norm import LPLayerNorm
|
| 11 |
-
|
| 12 |
-
def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool):
|
| 13 |
-
if original_is_causal and num_query_tokens != num_key_tokens:
|
| 14 |
-
if num_query_tokens != 1:
|
| 15 |
-
raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.')
|
| 16 |
-
else:
|
| 17 |
-
return False
|
| 18 |
-
return original_is_causal
|
| 19 |
-
|
| 20 |
-
def scaled_multihead_dot_product_attention(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
|
| 21 |
-
q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads)
|
| 22 |
-
kv_n_heads = 1 if multiquery else n_heads
|
| 23 |
-
k = rearrange(key, 'b s (h d) -> b h d s', h=kv_n_heads)
|
| 24 |
-
v = rearrange(value, 'b s (h d) -> b h s d', h=kv_n_heads)
|
| 25 |
-
if past_key_value is not None:
|
| 26 |
-
if len(past_key_value) != 0:
|
| 27 |
-
k = torch.cat([past_key_value[0], k], dim=3)
|
| 28 |
-
v = torch.cat([past_key_value[1], v], dim=2)
|
| 29 |
-
past_key_value = (k, v)
|
| 30 |
-
(b, _, s_q, d) = q.shape
|
| 31 |
-
s_k = k.size(-1)
|
| 32 |
-
if softmax_scale is None:
|
| 33 |
-
softmax_scale = 1 / math.sqrt(d)
|
| 34 |
-
attn_weight = q.matmul(k) * softmax_scale
|
| 35 |
-
if attn_bias is not None:
|
| 36 |
-
_s_q = max(0, attn_bias.size(2) - s_q)
|
| 37 |
-
_s_k = max(0, attn_bias.size(3) - s_k)
|
| 38 |
-
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
| 39 |
-
if attn_bias.size(-1) != 1 and attn_bias.size(-1) != s_k or (attn_bias.size(-2) != 1 and attn_bias.size(-2) != s_q):
|
| 40 |
-
raise RuntimeError(f'attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}.')
|
| 41 |
-
attn_weight = attn_weight + attn_bias
|
| 42 |
-
min_val = torch.finfo(q.dtype).min
|
| 43 |
-
if key_padding_mask is not None:
|
| 44 |
-
if attn_bias is not None:
|
| 45 |
-
warnings.warn('Propogating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unneccessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
|
| 46 |
-
attn_weight = attn_weight.masked_fill(~key_padding_mask.view((b, 1, 1, s_k)), min_val)
|
| 47 |
-
if is_causal and (not q.size(2) == 1):
|
| 48 |
-
s = max(s_q, s_k)
|
| 49 |
-
causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
|
| 50 |
-
causal_mask = causal_mask.tril()
|
| 51 |
-
causal_mask = causal_mask.to(torch.bool)
|
| 52 |
-
causal_mask = ~causal_mask
|
| 53 |
-
causal_mask = causal_mask[-s_q:, -s_k:]
|
| 54 |
-
attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k), min_val)
|
| 55 |
-
attn_weight = torch.softmax(attn_weight, dim=-1)
|
| 56 |
-
if dropout_p:
|
| 57 |
-
attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p, training=training, inplace=True)
|
| 58 |
-
out = attn_weight.to(v.dtype).matmul(v)
|
| 59 |
-
out = rearrange(out, 'b h s d -> b s (h d)')
|
| 60 |
-
if needs_weights:
|
| 61 |
-
return (out, attn_weight, past_key_value)
|
| 62 |
-
return (out, None, past_key_value)
|
| 63 |
-
|
| 64 |
-
def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
|
| 65 |
-
for tensor in tensors:
|
| 66 |
-
if tensor.dtype not in valid_dtypes:
|
| 67 |
-
raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.')
|
| 68 |
-
if not tensor.is_cuda:
|
| 69 |
-
raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
|
| 70 |
-
|
| 71 |
-
def flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
|
| 72 |
-
try:
|
| 73 |
-
from flash_attn import bert_padding, flash_attn_interface
|
| 74 |
-
except:
|
| 75 |
-
raise RuntimeError('Please install flash-attn==1.0.3.post0')
|
| 76 |
-
check_valid_inputs(query, key, value)
|
| 77 |
-
if past_key_value is not None:
|
| 78 |
-
if len(past_key_value) != 0:
|
| 79 |
-
key = torch.cat([past_key_value[0], key], dim=1)
|
| 80 |
-
value = torch.cat([past_key_value[1], value], dim=1)
|
| 81 |
-
past_key_value = (key, value)
|
| 82 |
-
if attn_bias is not None:
|
| 83 |
-
_s_q = max(0, attn_bias.size(2) - query.size(1))
|
| 84 |
-
_s_k = max(0, attn_bias.size(3) - key.size(1))
|
| 85 |
-
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
| 86 |
-
if attn_bias is not None:
|
| 87 |
-
raise NotImplementedError(f'attn_bias not implemented for flash attn.')
|
| 88 |
-
(batch_size, seqlen) = query.shape[:2]
|
| 89 |
-
if key_padding_mask is None:
|
| 90 |
-
key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
|
| 91 |
-
query_padding_mask = key_padding_mask[:, -query.size(1):]
|
| 92 |
-
(query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(query, query_padding_mask)
|
| 93 |
-
query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
|
| 94 |
-
(key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(key, key_padding_mask)
|
| 95 |
-
key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
|
| 96 |
-
(value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
|
| 97 |
-
value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
|
| 98 |
-
if multiquery:
|
| 99 |
-
key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
|
| 100 |
-
value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
|
| 101 |
-
dropout_p = dropout_p if training else 0.0
|
| 102 |
-
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
| 103 |
-
output_unpad = flash_attn_interface.flash_attn_unpadded_func(query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
|
| 104 |
-
output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
|
| 105 |
-
return (output, None, past_key_value)
|
| 106 |
-
|
| 107 |
-
def triton_flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
|
| 108 |
-
try:
|
| 109 |
-
from .flash_attn_triton import flash_attn_func
|
| 110 |
-
except:
|
| 111 |
-
_installed = False
|
| 112 |
-
if version.parse(torch.__version__) < version.parse('2.0.0'):
|
| 113 |
-
_installed = True
|
| 114 |
-
try:
|
| 115 |
-
from flash_attn.flash_attn_triton import flash_attn_func
|
| 116 |
-
except:
|
| 117 |
-
_installed = False
|
| 118 |
-
if not _installed:
|
| 119 |
-
raise RuntimeError('Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU and `pip install .[gpu]` if installing from llm-foundry source or `pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). Note: (1) requires you have CMake and PyTorch already installed.')
|
| 120 |
-
check_valid_inputs(query, key, value)
|
| 121 |
-
if past_key_value is not None:
|
| 122 |
-
if len(past_key_value) != 0:
|
| 123 |
-
key = torch.cat([past_key_value[0], key], dim=1)
|
| 124 |
-
value = torch.cat([past_key_value[1], value], dim=1)
|
| 125 |
-
past_key_value = (key, value)
|
| 126 |
-
if attn_bias is not None:
|
| 127 |
-
_s_q = max(0, attn_bias.size(2) - query.size(1))
|
| 128 |
-
_s_k = max(0, attn_bias.size(3) - key.size(1))
|
| 129 |
-
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
| 130 |
-
if dropout_p:
|
| 131 |
-
raise NotImplementedError(f'Dropout not implemented for attn_impl: triton.')
|
| 132 |
-
if needs_weights:
|
| 133 |
-
raise NotImplementedError(f'attn_impl: triton cannot return attn weights.')
|
| 134 |
-
if key_padding_mask is not None:
|
| 135 |
-
warnings.warn('Propagating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unnecessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
|
| 136 |
-
(b_size, s_k) = key_padding_mask.shape[:2]
|
| 137 |
-
if attn_bias is None:
|
| 138 |
-
attn_bias = query.new_zeros(b_size, 1, 1, s_k)
|
| 139 |
-
attn_bias = attn_bias.masked_fill(~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min)
|
| 140 |
-
query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
|
| 141 |
-
key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
|
| 142 |
-
value = rearrange(value, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
|
| 143 |
-
if multiquery:
|
| 144 |
-
key = key.expand(*key.shape[:2], n_heads, key.size(-1))
|
| 145 |
-
value = value.expand(*value.shape[:2], n_heads, value.size(-1))
|
| 146 |
-
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
| 147 |
-
attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
|
| 148 |
-
output = attn_output.view(*attn_output.shape[:2], -1)
|
| 149 |
-
return (output, None, past_key_value)
|
| 150 |
-
|
| 151 |
-
class MultiheadAttention(nn.Module):
|
| 152 |
-
"""Multi-head self attention.
|
| 153 |
-
|
| 154 |
-
Using torch or triton attention implementation enables user to also use
|
| 155 |
-
additive bias.
|
| 156 |
-
"""
|
| 157 |
-
|
| 158 |
-
def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
|
| 159 |
-
super().__init__()
|
| 160 |
-
self.attn_impl = attn_impl
|
| 161 |
-
self.clip_qkv = clip_qkv
|
| 162 |
-
self.qk_ln = qk_ln
|
| 163 |
-
self.d_model = d_model
|
| 164 |
-
self.n_heads = n_heads
|
| 165 |
-
self.softmax_scale = softmax_scale
|
| 166 |
-
if self.softmax_scale is None:
|
| 167 |
-
self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
|
| 168 |
-
self.attn_dropout_p = attn_pdrop
|
| 169 |
-
self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device)
|
| 170 |
-
fuse_splits = (d_model, 2 * d_model)
|
| 171 |
-
self.Wqkv._fused = (0, fuse_splits)
|
| 172 |
-
if self.qk_ln:
|
| 173 |
-
layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
|
| 174 |
-
self.q_ln = layernorm_class(self.d_model, device=device)
|
| 175 |
-
self.k_ln = layernorm_class(self.d_model, device=device)
|
| 176 |
-
if self.attn_impl == 'flash':
|
| 177 |
-
self.attn_fn = flash_attn_fn
|
| 178 |
-
elif self.attn_impl == 'triton':
|
| 179 |
-
self.attn_fn = triton_flash_attn_fn
|
| 180 |
-
if verbose:
|
| 181 |
-
warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
|
| 182 |
-
elif self.attn_impl == 'torch':
|
| 183 |
-
self.attn_fn = scaled_multihead_dot_product_attention
|
| 184 |
-
if torch.cuda.is_available() and verbose:
|
| 185 |
-
warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
|
| 186 |
-
else:
|
| 187 |
-
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
| 188 |
-
self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
|
| 189 |
-
self.out_proj._is_residual = True
|
| 190 |
-
|
| 191 |
-
def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
|
| 192 |
-
qkv = self.Wqkv(x)
|
| 193 |
-
if self.clip_qkv:
|
| 194 |
-
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
|
| 195 |
-
(query, key, value) = qkv.chunk(3, dim=2)
|
| 196 |
-
key_padding_mask = attention_mask
|
| 197 |
-
if self.qk_ln:
|
| 198 |
-
dtype = query.dtype
|
| 199 |
-
query = self.q_ln(query).to(dtype)
|
| 200 |
-
key = self.k_ln(key).to(dtype)
|
| 201 |
-
(context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights)
|
| 202 |
-
return (self.out_proj(context), attn_weights, past_key_value)
|
| 203 |
-
|
| 204 |
-
class MultiQueryAttention(nn.Module):
|
| 205 |
-
"""Multi-Query self attention.
|
| 206 |
-
|
| 207 |
-
Using torch or triton attention implementation enables user to also use
|
| 208 |
-
additive bias.
|
| 209 |
-
"""
|
| 210 |
-
|
| 211 |
-
def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
|
| 212 |
-
super().__init__()
|
| 213 |
-
self.attn_impl = attn_impl
|
| 214 |
-
self.clip_qkv = clip_qkv
|
| 215 |
-
self.qk_ln = qk_ln
|
| 216 |
-
self.d_model = d_model
|
| 217 |
-
self.n_heads = n_heads
|
| 218 |
-
self.head_dim = d_model // n_heads
|
| 219 |
-
self.softmax_scale = softmax_scale
|
| 220 |
-
if self.softmax_scale is None:
|
| 221 |
-
self.softmax_scale = 1 / math.sqrt(self.head_dim)
|
| 222 |
-
self.attn_dropout_p = attn_pdrop
|
| 223 |
-
self.Wqkv = nn.Linear(d_model, d_model + 2 * self.head_dim, device=device)
|
| 224 |
-
fuse_splits = (d_model, d_model + self.head_dim)
|
| 225 |
-
self.Wqkv._fused = (0, fuse_splits)
|
| 226 |
-
if self.qk_ln:
|
| 227 |
-
layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
|
| 228 |
-
self.q_ln = layernorm_class(d_model, device=device)
|
| 229 |
-
self.k_ln = layernorm_class(self.head_dim, device=device)
|
| 230 |
-
if self.attn_impl == 'flash':
|
| 231 |
-
self.attn_fn = flash_attn_fn
|
| 232 |
-
elif self.attn_impl == 'triton':
|
| 233 |
-
self.attn_fn = triton_flash_attn_fn
|
| 234 |
-
if verbose:
|
| 235 |
-
warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
|
| 236 |
-
elif self.attn_impl == 'torch':
|
| 237 |
-
self.attn_fn = scaled_multihead_dot_product_attention
|
| 238 |
-
if torch.cuda.is_available() and verbose:
|
| 239 |
-
warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
|
| 240 |
-
else:
|
| 241 |
-
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
| 242 |
-
self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
|
| 243 |
-
self.out_proj._is_residual = True
|
| 244 |
-
|
| 245 |
-
def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
|
| 246 |
-
qkv = self.Wqkv(x)
|
| 247 |
-
if self.clip_qkv:
|
| 248 |
-
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
|
| 249 |
-
(query, key, value) = qkv.split([self.d_model, self.head_dim, self.head_dim], dim=2)
|
| 250 |
-
key_padding_mask = attention_mask
|
| 251 |
-
if self.qk_ln:
|
| 252 |
-
dtype = query.dtype
|
| 253 |
-
query = self.q_ln(query).to(dtype)
|
| 254 |
-
key = self.k_ln(key).to(dtype)
|
| 255 |
-
(context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, multiquery=True)
|
| 256 |
-
return (self.out_proj(context), attn_weights, past_key_value)
|
| 257 |
-
|
| 258 |
-
def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):
|
| 259 |
-
if attn_impl == 'flash':
|
| 260 |
-
return None
|
| 261 |
-
elif attn_impl in ['torch', 'triton']:
|
| 262 |
-
if alibi:
|
| 263 |
-
if (prefix_lm or not causal) or use_sequence_id:
|
| 264 |
-
return (1, n_heads, seq_len, seq_len)
|
| 265 |
-
return (1, n_heads, 1, seq_len)
|
| 266 |
-
elif prefix_lm or use_sequence_id:
|
| 267 |
-
return (1, 1, seq_len, seq_len)
|
| 268 |
-
return None
|
| 269 |
-
else:
|
| 270 |
-
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
| 271 |
-
|
| 272 |
-
def build_attn_bias(attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8):
|
| 273 |
-
if attn_impl == 'flash':
|
| 274 |
-
return None
|
| 275 |
-
elif attn_impl in ['torch', 'triton']:
|
| 276 |
-
if alibi:
|
| 277 |
-
(device, dtype) = (attn_bias.device, attn_bias.dtype)
|
| 278 |
-
attn_bias = attn_bias.add(build_alibi_bias(n_heads, seq_len, full=not causal, alibi_bias_max=alibi_bias_max, device=device, dtype=dtype))
|
| 279 |
-
return attn_bias
|
| 280 |
-
else:
|
| 281 |
-
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
| 282 |
-
|
| 283 |
-
def gen_slopes(n_heads, alibi_bias_max=8, device=None):
|
| 284 |
-
_n_heads = 2 ** math.ceil(math.log2(n_heads))
|
| 285 |
-
m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
|
| 286 |
-
m = m.mul(alibi_bias_max / _n_heads)
|
| 287 |
-
slopes = 1.0 / torch.pow(2, m)
|
| 288 |
-
if _n_heads != n_heads:
|
| 289 |
-
slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
|
| 290 |
-
return slopes.view(1, n_heads, 1, 1)
|
| 291 |
-
|
| 292 |
-
def build_alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None):
|
| 293 |
-
alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, 1, seq_len)
|
| 294 |
-
if full:
|
| 295 |
-
alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, seq_len, 1)
|
| 296 |
-
alibi_bias = alibi_bias.abs().mul(-1)
|
| 297 |
-
slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
|
| 298 |
-
alibi_bias = alibi_bias * slopes
|
| 299 |
-
return alibi_bias.to(dtype=dtype)
|
| 300 |
-
ATTN_CLASS_REGISTRY = {'multihead_attention': MultiheadAttention, 'multiquery_attention': MultiQueryAttention}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/mpt/blocks.py
DELETED
|
@@ -1,41 +0,0 @@
|
|
| 1 |
-
"""GPT Blocks used for the GPT Model."""
|
| 2 |
-
from typing import Dict, Optional, Tuple
|
| 3 |
-
import torch
|
| 4 |
-
import torch.nn as nn
|
| 5 |
-
from .attention import ATTN_CLASS_REGISTRY
|
| 6 |
-
from .norm import NORM_CLASS_REGISTRY
|
| 7 |
-
|
| 8 |
-
class MPTMLP(nn.Module):
|
| 9 |
-
|
| 10 |
-
def __init__(self, d_model: int, expansion_ratio: int, device: Optional[str]=None):
|
| 11 |
-
super().__init__()
|
| 12 |
-
self.up_proj = nn.Linear(d_model, expansion_ratio * d_model, device=device)
|
| 13 |
-
self.act = nn.GELU(approximate='none')
|
| 14 |
-
self.down_proj = nn.Linear(expansion_ratio * d_model, d_model, device=device)
|
| 15 |
-
self.down_proj._is_residual = True
|
| 16 |
-
|
| 17 |
-
def forward(self, x):
|
| 18 |
-
return self.down_proj(self.act(self.up_proj(x)))
|
| 19 |
-
|
| 20 |
-
class MPTBlock(nn.Module):
|
| 21 |
-
|
| 22 |
-
def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Dict={'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}, resid_pdrop: float=0.0, norm_type: str='low_precision_layernorm', verbose: int=0, device: Optional[str]=None, **kwargs):
|
| 23 |
-
del kwargs
|
| 24 |
-
super().__init__()
|
| 25 |
-
norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
|
| 26 |
-
attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']]
|
| 27 |
-
self.norm_1 = norm_class(d_model, device=device)
|
| 28 |
-
self.attn = attn_class(attn_impl=attn_config['attn_impl'], clip_qkv=attn_config['clip_qkv'], qk_ln=attn_config['qk_ln'], softmax_scale=attn_config['softmax_scale'], attn_pdrop=attn_config['attn_pdrop'], d_model=d_model, n_heads=n_heads, verbose=verbose, device=device)
|
| 29 |
-
self.norm_2 = norm_class(d_model, device=device)
|
| 30 |
-
self.ffn = MPTMLP(d_model=d_model, expansion_ratio=expansion_ratio, device=device)
|
| 31 |
-
self.resid_attn_dropout = nn.Dropout(resid_pdrop)
|
| 32 |
-
self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
|
| 33 |
-
|
| 34 |
-
def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.ByteTensor]=None, is_causal: bool=True) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor]]]:
|
| 35 |
-
a = self.norm_1(x)
|
| 36 |
-
(b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=is_causal)
|
| 37 |
-
x = x + self.resid_attn_dropout(b)
|
| 38 |
-
m = self.norm_2(x)
|
| 39 |
-
n = self.ffn(m)
|
| 40 |
-
x = x + self.resid_ffn_dropout(n)
|
| 41 |
-
return (x, attn_weights, past_key_value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/mpt/configuration_mpt.py
DELETED
|
@@ -1,118 +0,0 @@
|
|
| 1 |
-
"""A HuggingFace-style model configuration."""
|
| 2 |
-
from typing import Dict, Optional, Union
|
| 3 |
-
from transformers import PretrainedConfig
|
| 4 |
-
attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
|
| 5 |
-
init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
|
| 6 |
-
|
| 7 |
-
class MPTConfig(PretrainedConfig):
|
| 8 |
-
model_type = 'mpt'
|
| 9 |
-
|
| 10 |
-
def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, verbose: int=0, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, **kwargs):
|
| 11 |
-
"""The MPT configuration class.
|
| 12 |
-
|
| 13 |
-
Args:
|
| 14 |
-
d_model (int): The size of the embedding dimension of the model.
|
| 15 |
-
n_heads (int): The number of attention heads.
|
| 16 |
-
n_layers (int): The number of layers in the model.
|
| 17 |
-
expansion_ratio (int): The ratio of the up/down scale in the MLP.
|
| 18 |
-
max_seq_len (int): The maximum sequence length of the model.
|
| 19 |
-
vocab_size (int): The size of the vocabulary.
|
| 20 |
-
resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
|
| 21 |
-
emb_pdrop (float): The dropout probability for the embedding layer.
|
| 22 |
-
learned_pos_emb (bool): Whether to use learned positional embeddings
|
| 23 |
-
attn_config (Dict): A dictionary used to configure the model's attention module:
|
| 24 |
-
attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention
|
| 25 |
-
attn_pdrop (float): The dropout probability for the attention layers.
|
| 26 |
-
attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
|
| 27 |
-
qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
|
| 28 |
-
clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to
|
| 29 |
-
this value.
|
| 30 |
-
softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None,
|
| 31 |
-
use the default scale of ``1/sqrt(d_keys)``.
|
| 32 |
-
prefix_lm (Optional[bool]): Whether the model should operate as a Prefix LM. This requires passing an
|
| 33 |
-
extra `prefix_mask` argument which indicates which tokens belong to the prefix. Tokens in the prefix
|
| 34 |
-
can attend to one another bi-directionally. Tokens outside the prefix use causal attention.
|
| 35 |
-
attn_uses_sequence_id (Optional[bool]): Whether to restrict attention to tokens that have the same sequence_id.
|
| 36 |
-
When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
|
| 37 |
-
which sub-sequence each token belongs to.
|
| 38 |
-
Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
|
| 39 |
-
alibi (bool): Whether to use the alibi bias instead of position embeddings.
|
| 40 |
-
alibi_bias_max (int): The maximum value of the alibi bias.
|
| 41 |
-
init_device (str): The device to use for parameter initialization.
|
| 42 |
-
logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
|
| 43 |
-
no_bias (bool): Whether to use bias in all layers.
|
| 44 |
-
verbose (int): The verbosity level. 0 is silent.
|
| 45 |
-
embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
|
| 46 |
-
norm_type (str): choose type of norm to use
|
| 47 |
-
multiquery_attention (bool): Whether to use multiquery attention implementation.
|
| 48 |
-
use_cache (bool): Whether or not the model should return the last key/values attentions
|
| 49 |
-
init_config (Dict): A dictionary used to configure the model initialization:
|
| 50 |
-
init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
|
| 51 |
-
'kaiming_uniform_', 'kaiming_normal_', 'neox_init_', 'small_init_', 'xavier_uniform_', or
|
| 52 |
-
'xavier_normal_'. These mimic the parameter initialization methods in PyTorch.
|
| 53 |
-
init_div_is_residual (Union[int, float, str, bool]): Value to divide initial weights by if ``module._is_residual`` is True.
|
| 54 |
-
emb_init_std (Optional[float]): The standard deviation of the normal distribution used to initialize the embedding layer.
|
| 55 |
-
emb_init_uniform_lim (Optional[Union[Tuple[float, float], float]]): The lower and upper limits of the uniform distribution
|
| 56 |
-
used to initialize the embedding layer. Mutually exclusive with ``emb_init_std``.
|
| 57 |
-
init_std (float): The standard deviation of the normal distribution used to initialize the model,
|
| 58 |
-
if using the baseline_ parameter initialization scheme.
|
| 59 |
-
init_gain (float): The gain to use for parameter initialization with kaiming or xavier initialization schemes.
|
| 60 |
-
fan_mode (str): The fan mode to use for parameter initialization with kaiming initialization schemes.
|
| 61 |
-
init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
|
| 62 |
-
---
|
| 63 |
-
See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
|
| 64 |
-
"""
|
| 65 |
-
self.d_model = d_model
|
| 66 |
-
self.n_heads = n_heads
|
| 67 |
-
self.n_layers = n_layers
|
| 68 |
-
self.expansion_ratio = expansion_ratio
|
| 69 |
-
self.max_seq_len = max_seq_len
|
| 70 |
-
self.vocab_size = vocab_size
|
| 71 |
-
self.resid_pdrop = resid_pdrop
|
| 72 |
-
self.emb_pdrop = emb_pdrop
|
| 73 |
-
self.learned_pos_emb = learned_pos_emb
|
| 74 |
-
self.attn_config = attn_config
|
| 75 |
-
self.init_device = init_device
|
| 76 |
-
self.logit_scale = logit_scale
|
| 77 |
-
self.no_bias = no_bias
|
| 78 |
-
self.verbose = verbose
|
| 79 |
-
self.embedding_fraction = embedding_fraction
|
| 80 |
-
self.norm_type = norm_type
|
| 81 |
-
self.use_cache = use_cache
|
| 82 |
-
self.init_config = init_config
|
| 83 |
-
if 'name' in kwargs:
|
| 84 |
-
del kwargs['name']
|
| 85 |
-
if 'loss_fn' in kwargs:
|
| 86 |
-
del kwargs['loss_fn']
|
| 87 |
-
super().__init__(**kwargs)
|
| 88 |
-
self._validate_config()
|
| 89 |
-
|
| 90 |
-
def _set_config_defaults(self, config, config_defaults):
|
| 91 |
-
for (k, v) in config_defaults.items():
|
| 92 |
-
if k not in config:
|
| 93 |
-
config[k] = v
|
| 94 |
-
return config
|
| 95 |
-
|
| 96 |
-
def _validate_config(self):
|
| 97 |
-
self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
|
| 98 |
-
self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
|
| 99 |
-
if self.d_model % self.n_heads != 0:
|
| 100 |
-
raise ValueError('d_model must be divisible by n_heads')
|
| 101 |
-
if any((prob < 0 or prob > 1 for prob in [self.attn_config['attn_pdrop'], self.resid_pdrop, self.emb_pdrop])):
|
| 102 |
-
raise ValueError("self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are probabilities and must be between 0 and 1")
|
| 103 |
-
if self.attn_config['attn_impl'] not in ['torch', 'flash', 'triton']:
|
| 104 |
-
raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
|
| 105 |
-
if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
| 106 |
-
raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
|
| 107 |
-
if self.attn_config['alibi'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
| 108 |
-
raise NotImplementedError('alibi only implemented with torch and triton attention.')
|
| 109 |
-
if self.attn_config['attn_uses_sequence_id'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
| 110 |
-
raise NotImplementedError('attn_uses_sequence_id only implemented with torch and triton attention.')
|
| 111 |
-
if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
|
| 112 |
-
raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
|
| 113 |
-
if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
|
| 114 |
-
raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
|
| 115 |
-
if self.init_config.get('name', None) is None:
|
| 116 |
-
raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
|
| 117 |
-
if not self.learned_pos_emb and (not self.attn_config['alibi']):
|
| 118 |
-
raise ValueError(f'Positional information must be provided to the model using either learned_pos_emb or alibi.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/mpt/custom_embedding.py
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
import torch.nn.functional as F
|
| 4 |
-
from torch import Tensor
|
| 5 |
-
|
| 6 |
-
class SharedEmbedding(nn.Embedding):
|
| 7 |
-
|
| 8 |
-
def forward(self, input: Tensor, unembed: bool=False) -> Tensor:
|
| 9 |
-
if unembed:
|
| 10 |
-
return F.linear(input, self.weight)
|
| 11 |
-
return super().forward(input)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/mpt/flash_attn_triton.py
DELETED
|
@@ -1,484 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py
|
| 3 |
-
update imports to use 'triton_pre_mlir'
|
| 4 |
-
|
| 5 |
-
*Experimental* implementation of FlashAttention in Triton.
|
| 6 |
-
Tested with triton==2.0.0.dev20221202.
|
| 7 |
-
Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions
|
| 8 |
-
other than 64:
|
| 9 |
-
https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207
|
| 10 |
-
We'll update this implementation with the new Triton backend once this is fixed.
|
| 11 |
-
|
| 12 |
-
We use the FlashAttention implementation from Phil Tillet a starting point.
|
| 13 |
-
https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
|
| 14 |
-
|
| 15 |
-
Changes:
|
| 16 |
-
- Implement both causal and non-causal attention.
|
| 17 |
-
- Implement both self-attention and cross-attention.
|
| 18 |
-
- Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
|
| 19 |
-
- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
|
| 20 |
-
- Support attention bias.
|
| 21 |
-
- Speed up the forward pass a bit, and only store the LSE instead of m and l.
|
| 22 |
-
- Make the backward for d=128 much faster by reducing register spilling.
|
| 23 |
-
- Optionally parallelize the backward pass across seqlen_k, to deal with the case of
|
| 24 |
-
small batch size * nheads.
|
| 25 |
-
|
| 26 |
-
Caution:
|
| 27 |
-
- This is an *experimental* implementation. The forward pass should be quite robust but
|
| 28 |
-
I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler).
|
| 29 |
-
- This implementation has only been tested on A100.
|
| 30 |
-
- If you plan to use headdim other than 64 and 128, you should test for race conditions
|
| 31 |
-
(due to the Triton compiler), as done in tests/test_flash_attn.py
|
| 32 |
-
"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
|
| 33 |
-
for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
|
| 34 |
-
that there are none left for other head dimensions.
|
| 35 |
-
|
| 36 |
-
Differences between this Triton version and the CUDA version:
|
| 37 |
-
- Triton version doesn't support dropout.
|
| 38 |
-
- Triton forward is generally faster than CUDA forward, while Triton backward is
|
| 39 |
-
generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
|
| 40 |
-
than CUDA forward + backward.
|
| 41 |
-
- Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
|
| 42 |
-
- Triton version supports attention bias, while CUDA version doesn't.
|
| 43 |
-
"""
|
| 44 |
-
import math
|
| 45 |
-
import torch
|
| 46 |
-
import triton_pre_mlir as triton
|
| 47 |
-
import triton_pre_mlir.language as tl
|
| 48 |
-
|
| 49 |
-
@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
|
| 50 |
-
@triton.jit
|
| 51 |
-
def _fwd_kernel(Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_ob, stride_oh, stride_om, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 52 |
-
start_m = tl.program_id(0)
|
| 53 |
-
off_hb = tl.program_id(1)
|
| 54 |
-
off_b = off_hb // nheads
|
| 55 |
-
off_h = off_hb % nheads
|
| 56 |
-
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 57 |
-
offs_n = tl.arange(0, BLOCK_N)
|
| 58 |
-
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 59 |
-
q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :])
|
| 60 |
-
k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :])
|
| 61 |
-
v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :])
|
| 62 |
-
if BIAS_TYPE == 'vector':
|
| 63 |
-
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
|
| 64 |
-
elif BIAS_TYPE == 'matrix':
|
| 65 |
-
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :])
|
| 66 |
-
t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
|
| 67 |
-
lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
|
| 68 |
-
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
|
| 69 |
-
acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
|
| 70 |
-
if EVEN_M & EVEN_N:
|
| 71 |
-
if EVEN_HEADDIM:
|
| 72 |
-
q = tl.load(q_ptrs)
|
| 73 |
-
else:
|
| 74 |
-
q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
| 75 |
-
elif EVEN_HEADDIM:
|
| 76 |
-
q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
|
| 77 |
-
else:
|
| 78 |
-
q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
|
| 79 |
-
end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
|
| 80 |
-
for start_n in range(0, end_n, BLOCK_N):
|
| 81 |
-
start_n = tl.multiple_of(start_n, BLOCK_N)
|
| 82 |
-
if EVEN_N & EVEN_M:
|
| 83 |
-
if EVEN_HEADDIM:
|
| 84 |
-
k = tl.load(k_ptrs + start_n * stride_kn)
|
| 85 |
-
else:
|
| 86 |
-
k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0)
|
| 87 |
-
elif EVEN_HEADDIM:
|
| 88 |
-
k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
|
| 89 |
-
else:
|
| 90 |
-
k = tl.load(k_ptrs + start_n * stride_kn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 91 |
-
qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
|
| 92 |
-
qk += tl.dot(q, k, trans_b=True)
|
| 93 |
-
if not EVEN_N:
|
| 94 |
-
qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float('-inf'))
|
| 95 |
-
if IS_CAUSAL:
|
| 96 |
-
qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float('-inf'))
|
| 97 |
-
if BIAS_TYPE != 'none':
|
| 98 |
-
if BIAS_TYPE == 'vector':
|
| 99 |
-
if EVEN_N:
|
| 100 |
-
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
| 101 |
-
else:
|
| 102 |
-
bias = tl.load(b_ptrs + start_n, mask=start_n + offs_n < seqlen_k, other=0.0).to(tl.float32)
|
| 103 |
-
bias = bias[None, :]
|
| 104 |
-
elif BIAS_TYPE == 'matrix':
|
| 105 |
-
if EVEN_M & EVEN_N:
|
| 106 |
-
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
| 107 |
-
else:
|
| 108 |
-
bias = tl.load(b_ptrs + start_n, mask=(offs_m[:, None] < seqlen_q) & ((start_n + offs_n)[None, :] < seqlen_k), other=0.0).to(tl.float32)
|
| 109 |
-
qk = qk * softmax_scale + bias
|
| 110 |
-
m_ij = tl.maximum(tl.max(qk, 1), lse_i)
|
| 111 |
-
p = tl.exp(qk - m_ij[:, None])
|
| 112 |
-
else:
|
| 113 |
-
m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
|
| 114 |
-
p = tl.exp(qk * softmax_scale - m_ij[:, None])
|
| 115 |
-
l_ij = tl.sum(p, 1)
|
| 116 |
-
acc_o_scale = tl.exp(m_i - m_ij)
|
| 117 |
-
tl.store(t_ptrs, acc_o_scale)
|
| 118 |
-
acc_o_scale = tl.load(t_ptrs)
|
| 119 |
-
acc_o = acc_o * acc_o_scale[:, None]
|
| 120 |
-
if EVEN_N & EVEN_M:
|
| 121 |
-
if EVEN_HEADDIM:
|
| 122 |
-
v = tl.load(v_ptrs + start_n * stride_vn)
|
| 123 |
-
else:
|
| 124 |
-
v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0)
|
| 125 |
-
elif EVEN_HEADDIM:
|
| 126 |
-
v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
|
| 127 |
-
else:
|
| 128 |
-
v = tl.load(v_ptrs + start_n * stride_vn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 129 |
-
p = p.to(v.dtype)
|
| 130 |
-
acc_o += tl.dot(p, v)
|
| 131 |
-
m_i = m_ij
|
| 132 |
-
l_i_new = tl.exp(lse_i - m_ij) + l_ij
|
| 133 |
-
lse_i = m_ij + tl.log(l_i_new)
|
| 134 |
-
o_scale = tl.exp(m_i - lse_i)
|
| 135 |
-
tl.store(t_ptrs, o_scale)
|
| 136 |
-
o_scale = tl.load(t_ptrs)
|
| 137 |
-
acc_o = acc_o * o_scale[:, None]
|
| 138 |
-
start_m = tl.program_id(0)
|
| 139 |
-
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 140 |
-
lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
|
| 141 |
-
tl.store(lse_ptrs, lse_i)
|
| 142 |
-
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 143 |
-
out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :])
|
| 144 |
-
if EVEN_M:
|
| 145 |
-
if EVEN_HEADDIM:
|
| 146 |
-
tl.store(out_ptrs, acc_o)
|
| 147 |
-
else:
|
| 148 |
-
tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
|
| 149 |
-
elif EVEN_HEADDIM:
|
| 150 |
-
tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
|
| 151 |
-
else:
|
| 152 |
-
tl.store(out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
|
| 153 |
-
|
| 154 |
-
@triton.jit
|
| 155 |
-
def _bwd_preprocess_do_o_dot(Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr):
|
| 156 |
-
start_m = tl.program_id(0)
|
| 157 |
-
off_hb = tl.program_id(1)
|
| 158 |
-
off_b = off_hb // nheads
|
| 159 |
-
off_h = off_hb % nheads
|
| 160 |
-
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 161 |
-
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 162 |
-
o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
|
| 163 |
-
do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
|
| 164 |
-
delta = tl.sum(o * do, axis=1)
|
| 165 |
-
tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
|
| 166 |
-
|
| 167 |
-
@triton.jit
|
| 168 |
-
def _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr):
|
| 169 |
-
if EVEN_N & EVEN_M:
|
| 170 |
-
if EVEN_HEADDIM:
|
| 171 |
-
tl.store(dv_ptrs, dv)
|
| 172 |
-
tl.store(dk_ptrs, dk)
|
| 173 |
-
else:
|
| 174 |
-
tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
|
| 175 |
-
tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
|
| 176 |
-
elif EVEN_HEADDIM:
|
| 177 |
-
tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
|
| 178 |
-
tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
|
| 179 |
-
else:
|
| 180 |
-
tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
|
| 181 |
-
tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
|
| 182 |
-
|
| 183 |
-
@triton.jit
|
| 184 |
-
def _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD: tl.constexpr, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 185 |
-
begin_m = 0 if not IS_CAUSAL else start_n * BLOCK_N // BLOCK_M * BLOCK_M
|
| 186 |
-
offs_qm = begin_m + tl.arange(0, BLOCK_M)
|
| 187 |
-
offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
| 188 |
-
offs_m = tl.arange(0, BLOCK_M)
|
| 189 |
-
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 190 |
-
q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
|
| 191 |
-
k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
|
| 192 |
-
v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
|
| 193 |
-
do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
|
| 194 |
-
dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
|
| 195 |
-
if BIAS_TYPE == 'vector':
|
| 196 |
-
b_ptrs = Bias + offs_n
|
| 197 |
-
elif BIAS_TYPE == 'matrix':
|
| 198 |
-
b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
|
| 199 |
-
dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
| 200 |
-
dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
| 201 |
-
if begin_m >= seqlen_q:
|
| 202 |
-
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
|
| 203 |
-
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
|
| 204 |
-
_bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
|
| 205 |
-
return
|
| 206 |
-
if EVEN_N & EVEN_M:
|
| 207 |
-
if EVEN_HEADDIM:
|
| 208 |
-
k = tl.load(k_ptrs)
|
| 209 |
-
v = tl.load(v_ptrs)
|
| 210 |
-
else:
|
| 211 |
-
k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
| 212 |
-
v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
| 213 |
-
elif EVEN_HEADDIM:
|
| 214 |
-
k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
| 215 |
-
v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
| 216 |
-
else:
|
| 217 |
-
k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 218 |
-
v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 219 |
-
num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
|
| 220 |
-
for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
|
| 221 |
-
start_m = tl.multiple_of(start_m, BLOCK_M)
|
| 222 |
-
offs_m_curr = start_m + offs_m
|
| 223 |
-
if EVEN_M & EVEN_HEADDIM:
|
| 224 |
-
q = tl.load(q_ptrs)
|
| 225 |
-
elif EVEN_HEADDIM:
|
| 226 |
-
q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
|
| 227 |
-
else:
|
| 228 |
-
q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
|
| 229 |
-
qk = tl.dot(q, k, trans_b=True)
|
| 230 |
-
if not EVEN_N:
|
| 231 |
-
qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf'))
|
| 232 |
-
if IS_CAUSAL:
|
| 233 |
-
qk = tl.where(offs_m_curr[:, None] >= offs_n[None, :], qk, float('-inf'))
|
| 234 |
-
if BIAS_TYPE != 'none':
|
| 235 |
-
tl.debug_barrier()
|
| 236 |
-
if BIAS_TYPE == 'vector':
|
| 237 |
-
if EVEN_N:
|
| 238 |
-
bias = tl.load(b_ptrs).to(tl.float32)
|
| 239 |
-
else:
|
| 240 |
-
bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32)
|
| 241 |
-
bias = bias[None, :]
|
| 242 |
-
elif BIAS_TYPE == 'matrix':
|
| 243 |
-
if EVEN_M & EVEN_N:
|
| 244 |
-
bias = tl.load(b_ptrs).to(tl.float32)
|
| 245 |
-
else:
|
| 246 |
-
bias = tl.load(b_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), other=0.0).to(tl.float32)
|
| 247 |
-
qk = qk * softmax_scale + bias
|
| 248 |
-
if not EVEN_M & EVEN_HEADDIM:
|
| 249 |
-
tl.debug_barrier()
|
| 250 |
-
lse_i = tl.load(LSE + offs_m_curr)
|
| 251 |
-
if BIAS_TYPE == 'none':
|
| 252 |
-
p = tl.exp(qk * softmax_scale - lse_i[:, None])
|
| 253 |
-
else:
|
| 254 |
-
p = tl.exp(qk - lse_i[:, None])
|
| 255 |
-
if EVEN_M & EVEN_HEADDIM:
|
| 256 |
-
do = tl.load(do_ptrs)
|
| 257 |
-
else:
|
| 258 |
-
do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
|
| 259 |
-
dv += tl.dot(p.to(do.dtype), do, trans_a=True)
|
| 260 |
-
if not EVEN_M & EVEN_HEADDIM:
|
| 261 |
-
tl.debug_barrier()
|
| 262 |
-
dp = tl.dot(do, v, trans_b=True)
|
| 263 |
-
if not EVEN_HEADDIM:
|
| 264 |
-
tl.debug_barrier()
|
| 265 |
-
Di = tl.load(D + offs_m_curr)
|
| 266 |
-
ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
|
| 267 |
-
dk += tl.dot(ds, q, trans_a=True)
|
| 268 |
-
if not EVEN_M & EVEN_HEADDIM:
|
| 269 |
-
tl.debug_barrier()
|
| 270 |
-
if not ATOMIC_ADD:
|
| 271 |
-
if EVEN_M & EVEN_HEADDIM:
|
| 272 |
-
dq = tl.load(dq_ptrs, eviction_policy='evict_last')
|
| 273 |
-
dq += tl.dot(ds, k)
|
| 274 |
-
tl.store(dq_ptrs, dq, eviction_policy='evict_last')
|
| 275 |
-
elif EVEN_HEADDIM:
|
| 276 |
-
dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0, eviction_policy='evict_last')
|
| 277 |
-
dq += tl.dot(ds, k)
|
| 278 |
-
tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q, eviction_policy='evict_last')
|
| 279 |
-
else:
|
| 280 |
-
dq = tl.load(dq_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0, eviction_policy='evict_last')
|
| 281 |
-
dq += tl.dot(ds, k)
|
| 282 |
-
tl.store(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), eviction_policy='evict_last')
|
| 283 |
-
else:
|
| 284 |
-
dq = tl.dot(ds, k)
|
| 285 |
-
if EVEN_M & EVEN_HEADDIM:
|
| 286 |
-
tl.atomic_add(dq_ptrs, dq)
|
| 287 |
-
elif EVEN_HEADDIM:
|
| 288 |
-
tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
|
| 289 |
-
else:
|
| 290 |
-
tl.atomic_add(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
|
| 291 |
-
dq_ptrs += BLOCK_M * stride_dqm
|
| 292 |
-
q_ptrs += BLOCK_M * stride_qm
|
| 293 |
-
do_ptrs += BLOCK_M * stride_dom
|
| 294 |
-
if BIAS_TYPE == 'matrix':
|
| 295 |
-
b_ptrs += BLOCK_M * stride_bm
|
| 296 |
-
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
|
| 297 |
-
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
|
| 298 |
-
_bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
|
| 299 |
-
|
| 300 |
-
def init_to_zero(name):
|
| 301 |
-
return lambda nargs: nargs[name].zero_()
|
| 302 |
-
|
| 303 |
-
@triton.autotune(configs=[triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ'))], key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'])
|
| 304 |
-
@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
|
| 305 |
-
@triton.jit
|
| 306 |
-
def _bwd_kernel(Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_dob, stride_doh, stride_dom, stride_dqb, stride_dqh, stride_dqm, stride_dkb, stride_dkh, stride_dkn, stride_dvb, stride_dvh, stride_dvn, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, SEQUENCE_PARALLEL: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 307 |
-
off_hb = tl.program_id(1)
|
| 308 |
-
off_b = off_hb // nheads
|
| 309 |
-
off_h = off_hb % nheads
|
| 310 |
-
Q += off_b * stride_qb + off_h * stride_qh
|
| 311 |
-
K += off_b * stride_kb + off_h * stride_kh
|
| 312 |
-
V += off_b * stride_vb + off_h * stride_vh
|
| 313 |
-
DO += off_b * stride_dob + off_h * stride_doh
|
| 314 |
-
DQ += off_b * stride_dqb + off_h * stride_dqh
|
| 315 |
-
DK += off_b * stride_dkb + off_h * stride_dkh
|
| 316 |
-
DV += off_b * stride_dvb + off_h * stride_dvh
|
| 317 |
-
if BIAS_TYPE != 'none':
|
| 318 |
-
Bias += off_b * stride_bb + off_h * stride_bh
|
| 319 |
-
D += off_hb * seqlen_q_rounded
|
| 320 |
-
LSE += off_hb * seqlen_q_rounded
|
| 321 |
-
if not SEQUENCE_PARALLEL:
|
| 322 |
-
num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
|
| 323 |
-
for start_n in range(0, num_block_n):
|
| 324 |
-
_bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=False, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
|
| 325 |
-
else:
|
| 326 |
-
start_n = tl.program_id(0)
|
| 327 |
-
_bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=True, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
|
| 328 |
-
|
| 329 |
-
def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
|
| 330 |
-
(batch, seqlen_q, nheads, d) = q.shape
|
| 331 |
-
(_, seqlen_k, _, _) = k.shape
|
| 332 |
-
assert k.shape == (batch, seqlen_k, nheads, d)
|
| 333 |
-
assert v.shape == (batch, seqlen_k, nheads, d)
|
| 334 |
-
assert d <= 128, 'FlashAttention only support head dimensions up to 128'
|
| 335 |
-
assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
|
| 336 |
-
assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16'
|
| 337 |
-
assert q.is_cuda and k.is_cuda and v.is_cuda
|
| 338 |
-
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
| 339 |
-
has_bias = bias is not None
|
| 340 |
-
bias_type = 'none'
|
| 341 |
-
if has_bias:
|
| 342 |
-
assert bias.dtype in [q.dtype, torch.float]
|
| 343 |
-
assert bias.is_cuda
|
| 344 |
-
assert bias.dim() == 4
|
| 345 |
-
if bias.stride(-1) != 1:
|
| 346 |
-
bias = bias.contiguous()
|
| 347 |
-
if bias.shape[2:] == (1, seqlen_k):
|
| 348 |
-
bias_type = 'vector'
|
| 349 |
-
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
| 350 |
-
bias_type = 'matrix'
|
| 351 |
-
else:
|
| 352 |
-
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
|
| 353 |
-
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
|
| 354 |
-
bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
|
| 355 |
-
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
| 356 |
-
lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
|
| 357 |
-
tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
|
| 358 |
-
o = torch.empty_like(q)
|
| 359 |
-
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
| 360 |
-
BLOCK = 128
|
| 361 |
-
num_warps = 4 if d <= 64 else 8
|
| 362 |
-
grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
|
| 363 |
-
_fwd_kernel[grid](q, k, v, bias, o, lse, tmp, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, o.stride(0), o.stride(2), o.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM, BLOCK_M=BLOCK, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1)
|
| 364 |
-
return (o, lse, softmax_scale)
|
| 365 |
-
|
| 366 |
-
def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None):
|
| 367 |
-
if do.stride(-1) != 1:
|
| 368 |
-
do = do.contiguous()
|
| 369 |
-
(batch, seqlen_q, nheads, d) = q.shape
|
| 370 |
-
(_, seqlen_k, _, _) = k.shape
|
| 371 |
-
assert d <= 128
|
| 372 |
-
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
| 373 |
-
assert lse.shape == (batch, nheads, seqlen_q_rounded)
|
| 374 |
-
assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
|
| 375 |
-
assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
|
| 376 |
-
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
| 377 |
-
dq_accum = torch.empty_like(q, dtype=torch.float32)
|
| 378 |
-
delta = torch.empty_like(lse)
|
| 379 |
-
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
| 380 |
-
grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
|
| 381 |
-
_bwd_preprocess_do_o_dot[grid](o, do, delta, o.stride(0), o.stride(2), o.stride(1), do.stride(0), do.stride(2), do.stride(1), nheads, seqlen_q, seqlen_q_rounded, d, BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM)
|
| 382 |
-
has_bias = bias is not None
|
| 383 |
-
bias_type = 'none'
|
| 384 |
-
if has_bias:
|
| 385 |
-
assert bias.dtype in [q.dtype, torch.float]
|
| 386 |
-
assert bias.is_cuda
|
| 387 |
-
assert bias.dim() == 4
|
| 388 |
-
assert bias.stride(-1) == 1
|
| 389 |
-
if bias.shape[2:] == (1, seqlen_k):
|
| 390 |
-
bias_type = 'vector'
|
| 391 |
-
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
| 392 |
-
bias_type = 'matrix'
|
| 393 |
-
else:
|
| 394 |
-
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
|
| 395 |
-
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
|
| 396 |
-
bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
|
| 397 |
-
grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N']) if META['SEQUENCE_PARALLEL'] else 1, batch * nheads)
|
| 398 |
-
_bwd_kernel[grid](q, k, v, bias, do, dq_accum, dk, dv, lse, delta, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, do.stride(0), do.stride(2), do.stride(1), dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1), dk.stride(0), dk.stride(2), dk.stride(1), dv.stride(0), dv.stride(2), dv.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM)
|
| 399 |
-
dq.copy_(dq_accum)
|
| 400 |
-
|
| 401 |
-
class FlashAttnQKVPackedFunc(torch.autograd.Function):
|
| 402 |
-
|
| 403 |
-
@staticmethod
|
| 404 |
-
def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
|
| 405 |
-
"""
|
| 406 |
-
qkv: (batch, seqlen, 3, nheads, headdim)
|
| 407 |
-
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
|
| 408 |
-
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
|
| 409 |
-
ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
|
| 410 |
-
"""
|
| 411 |
-
if qkv.stride(-1) != 1:
|
| 412 |
-
qkv = qkv.contiguous()
|
| 413 |
-
(o, lse, ctx.softmax_scale) = _flash_attn_forward(qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal, softmax_scale=softmax_scale)
|
| 414 |
-
ctx.save_for_backward(qkv, o, lse, bias)
|
| 415 |
-
ctx.causal = causal
|
| 416 |
-
return o
|
| 417 |
-
|
| 418 |
-
@staticmethod
|
| 419 |
-
def backward(ctx, do):
|
| 420 |
-
(qkv, o, lse, bias) = ctx.saved_tensors
|
| 421 |
-
assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet'
|
| 422 |
-
with torch.inference_mode():
|
| 423 |
-
dqkv = torch.empty_like(qkv)
|
| 424 |
-
_flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse, dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
|
| 425 |
-
return (dqkv, None, None, None)
|
| 426 |
-
flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
|
| 427 |
-
|
| 428 |
-
class FlashAttnKVPackedFunc(torch.autograd.Function):
|
| 429 |
-
|
| 430 |
-
@staticmethod
|
| 431 |
-
def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
|
| 432 |
-
"""
|
| 433 |
-
q: (batch, seqlen_q, nheads, headdim)
|
| 434 |
-
kv: (batch, seqlen_k, 2, nheads, headdim)
|
| 435 |
-
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
|
| 436 |
-
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
|
| 437 |
-
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
|
| 438 |
-
"""
|
| 439 |
-
(q, kv) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
|
| 440 |
-
(o, lse, ctx.softmax_scale) = _flash_attn_forward(q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale)
|
| 441 |
-
ctx.save_for_backward(q, kv, o, lse, bias)
|
| 442 |
-
ctx.causal = causal
|
| 443 |
-
return o
|
| 444 |
-
|
| 445 |
-
@staticmethod
|
| 446 |
-
def backward(ctx, do):
|
| 447 |
-
(q, kv, o, lse, bias) = ctx.saved_tensors
|
| 448 |
-
if len(ctx.needs_input_grad) >= 3:
|
| 449 |
-
assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet'
|
| 450 |
-
with torch.inference_mode():
|
| 451 |
-
dq = torch.empty_like(q)
|
| 452 |
-
dkv = torch.empty_like(kv)
|
| 453 |
-
_flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse, dq, dkv[:, :, 0], dkv[:, :, 1], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
|
| 454 |
-
return (dq, dkv, None, None, None)
|
| 455 |
-
flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
|
| 456 |
-
|
| 457 |
-
class FlashAttnFunc(torch.autograd.Function):
|
| 458 |
-
|
| 459 |
-
@staticmethod
|
| 460 |
-
def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
|
| 461 |
-
"""
|
| 462 |
-
q: (batch_size, seqlen_q, nheads, headdim)
|
| 463 |
-
k, v: (batch_size, seqlen_k, nheads, headdim)
|
| 464 |
-
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
|
| 465 |
-
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
|
| 466 |
-
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
|
| 467 |
-
"""
|
| 468 |
-
(q, k, v) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
|
| 469 |
-
(o, lse, ctx.softmax_scale) = _flash_attn_forward(q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale)
|
| 470 |
-
ctx.save_for_backward(q, k, v, o, lse, bias)
|
| 471 |
-
ctx.causal = causal
|
| 472 |
-
return o
|
| 473 |
-
|
| 474 |
-
@staticmethod
|
| 475 |
-
def backward(ctx, do):
|
| 476 |
-
(q, k, v, o, lse, bias) = ctx.saved_tensors
|
| 477 |
-
assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet'
|
| 478 |
-
with torch.inference_mode():
|
| 479 |
-
dq = torch.empty_like(q)
|
| 480 |
-
dk = torch.empty_like(k)
|
| 481 |
-
dv = torch.empty_like(v)
|
| 482 |
-
_flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
|
| 483 |
-
return (dq, dk, dv, None, None, None)
|
| 484 |
-
flash_attn_func = FlashAttnFunc.apply
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/mpt/hf_prefixlm_converter.py
DELETED
|
@@ -1,415 +0,0 @@
|
|
| 1 |
-
"""Converts Huggingface Causal LM to Prefix LM.
|
| 2 |
-
|
| 3 |
-
Conversion does lightweight surgery on a HuggingFace
|
| 4 |
-
Causal LM to convert it to a Prefix LM.
|
| 5 |
-
|
| 6 |
-
Prefix LMs accepts a `bidirectional_mask` input in `forward`
|
| 7 |
-
and treat the input prompt as the prefix in `generate`.
|
| 8 |
-
"""
|
| 9 |
-
import math
|
| 10 |
-
import warnings
|
| 11 |
-
from types import MethodType
|
| 12 |
-
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 13 |
-
import torch
|
| 14 |
-
from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
|
| 15 |
-
from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
|
| 16 |
-
from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
|
| 17 |
-
from transformers.models.bloom.modeling_bloom import logging
|
| 18 |
-
from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
|
| 19 |
-
from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
|
| 20 |
-
from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
|
| 21 |
-
from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
|
| 22 |
-
from transformers.models.opt.modeling_opt import OPTForCausalLM
|
| 23 |
-
from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
|
| 24 |
-
from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
|
| 25 |
-
logger = logging.get_logger(__name__)
|
| 26 |
-
_SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
|
| 27 |
-
CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
|
| 28 |
-
|
| 29 |
-
def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_TYPES:
|
| 30 |
-
"""Converts a GPT-style Causal LM to a Prefix LM.
|
| 31 |
-
|
| 32 |
-
Supported HuggingFace model classes:
|
| 33 |
-
- `GPT2LMHeadModel`
|
| 34 |
-
- `GPTNeoForCausalLM`
|
| 35 |
-
- `GPTNeoXForCausalLM`
|
| 36 |
-
- `GPTJForCausalLM`
|
| 37 |
-
|
| 38 |
-
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
| 39 |
-
"""
|
| 40 |
-
if hasattr(model, '_prefix_lm_converted'):
|
| 41 |
-
return model
|
| 42 |
-
assert isinstance(model, _SUPPORTED_GPT_MODELS)
|
| 43 |
-
assert model.config.add_cross_attention == False, 'Only supports GPT-style decoder-only models'
|
| 44 |
-
|
| 45 |
-
def _get_attn_modules(model: CAUSAL_GPT_TYPES) -> List[torch.nn.Module]:
|
| 46 |
-
"""Helper that gets a list of the model's attention modules.
|
| 47 |
-
|
| 48 |
-
Each module has a `bias` buffer used for causal masking. The Prefix LM
|
| 49 |
-
conversion adds logic to dynamically manipulate these biases to support
|
| 50 |
-
Prefix LM attention masking.
|
| 51 |
-
"""
|
| 52 |
-
attn_modules = []
|
| 53 |
-
if isinstance(model, GPTNeoXForCausalLM):
|
| 54 |
-
blocks = model.gpt_neox.layers
|
| 55 |
-
else:
|
| 56 |
-
blocks = model.transformer.h
|
| 57 |
-
for block in blocks:
|
| 58 |
-
if isinstance(model, GPTNeoForCausalLM):
|
| 59 |
-
if block.attn.attention_type != 'global':
|
| 60 |
-
continue
|
| 61 |
-
attn_module = block.attn.attention
|
| 62 |
-
elif isinstance(model, GPTNeoXForCausalLM):
|
| 63 |
-
attn_module = block.attention
|
| 64 |
-
else:
|
| 65 |
-
attn_module = block.attn
|
| 66 |
-
attn_modules.append(attn_module)
|
| 67 |
-
return attn_modules
|
| 68 |
-
setattr(model, '_original_forward', getattr(model, 'forward'))
|
| 69 |
-
setattr(model, '_original_generate', getattr(model, 'generate'))
|
| 70 |
-
|
| 71 |
-
def forward(self: CAUSAL_GPT_TYPES, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, attention_mask: Optional[torch.FloatTensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=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):
|
| 72 |
-
"""Wraps original forward to enable PrefixLM attention."""
|
| 73 |
-
|
| 74 |
-
def call_og_forward():
|
| 75 |
-
if isinstance(self, GPTNeoXForCausalLM):
|
| 76 |
-
return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 77 |
-
else:
|
| 78 |
-
return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 79 |
-
if bidirectional_mask is None:
|
| 80 |
-
return call_og_forward()
|
| 81 |
-
assert isinstance(bidirectional_mask, torch.Tensor)
|
| 82 |
-
attn_modules = _get_attn_modules(model)
|
| 83 |
-
(b, s) = bidirectional_mask.shape
|
| 84 |
-
max_length = attn_modules[0].bias.shape[-1]
|
| 85 |
-
if s > max_length:
|
| 86 |
-
raise ValueError(f'bidirectional_mask sequence length (={s}) exceeds the ' + f'max length allowed by the model ({max_length}).')
|
| 87 |
-
assert s <= max_length
|
| 88 |
-
if s < max_length:
|
| 89 |
-
pad = torch.zeros((int(b), int(max_length - s)), dtype=bidirectional_mask.dtype, device=bidirectional_mask.device)
|
| 90 |
-
bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
|
| 91 |
-
bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
|
| 92 |
-
for attn_module in attn_modules:
|
| 93 |
-
attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)
|
| 94 |
-
output = call_og_forward()
|
| 95 |
-
for attn_module in attn_modules:
|
| 96 |
-
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
|
| 97 |
-
return output
|
| 98 |
-
|
| 99 |
-
def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
|
| 100 |
-
"""Wraps original generate to enable PrefixLM attention."""
|
| 101 |
-
attn_modules = _get_attn_modules(model)
|
| 102 |
-
for attn_module in attn_modules:
|
| 103 |
-
attn_module.bias.data[:] = 1
|
| 104 |
-
output = self._original_generate(*args, **kwargs)
|
| 105 |
-
for attn_module in attn_modules:
|
| 106 |
-
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
|
| 107 |
-
return output
|
| 108 |
-
setattr(model, 'forward', MethodType(forward, model))
|
| 109 |
-
setattr(model, 'generate', MethodType(generate, model))
|
| 110 |
-
setattr(model, '_prefix_lm_converted', True)
|
| 111 |
-
return model
|
| 112 |
-
|
| 113 |
-
def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
|
| 114 |
-
"""Converts a BLOOM Causal LM to a Prefix LM.
|
| 115 |
-
|
| 116 |
-
Supported HuggingFace model classes:
|
| 117 |
-
- `BloomForCausalLM`
|
| 118 |
-
|
| 119 |
-
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
| 120 |
-
"""
|
| 121 |
-
if hasattr(model, '_prefix_lm_converted'):
|
| 122 |
-
return model
|
| 123 |
-
assert isinstance(model, BloomForCausalLM)
|
| 124 |
-
assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'
|
| 125 |
-
|
| 126 |
-
def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:
|
| 127 |
-
combined_attention_mask = None
|
| 128 |
-
device = attention_mask.device
|
| 129 |
-
(_, src_length) = input_shape
|
| 130 |
-
if src_length > 1:
|
| 131 |
-
combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)
|
| 132 |
-
if bidirectional_mask is not None:
|
| 133 |
-
assert attention_mask.shape == bidirectional_mask.shape
|
| 134 |
-
expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)
|
| 135 |
-
combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)
|
| 136 |
-
expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
|
| 137 |
-
combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
|
| 138 |
-
return combined_attention_mask
|
| 139 |
-
|
| 140 |
-
def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
|
| 141 |
-
num_heads = self.config.n_head
|
| 142 |
-
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
|
| 143 |
-
base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)
|
| 144 |
-
powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
|
| 145 |
-
slopes = torch.pow(base, powers)
|
| 146 |
-
if closest_power_of_2 != num_heads:
|
| 147 |
-
extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)
|
| 148 |
-
num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
|
| 149 |
-
extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
|
| 150 |
-
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
|
| 151 |
-
qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
|
| 152 |
-
ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
|
| 153 |
-
diffs = qa - ka + key_length - query_length
|
| 154 |
-
diffs = -diffs.abs()
|
| 155 |
-
alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)
|
| 156 |
-
alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)
|
| 157 |
-
return alibi.to(dtype)
|
| 158 |
-
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
|
| 159 |
-
|
| 160 |
-
def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: 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, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
|
| 161 |
-
if deprecated_arguments.pop('position_ids', False) is not False:
|
| 162 |
-
warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)
|
| 163 |
-
if len(deprecated_arguments) > 0:
|
| 164 |
-
raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
|
| 165 |
-
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 166 |
-
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 167 |
-
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 168 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 169 |
-
if input_ids is not None and inputs_embeds is not None:
|
| 170 |
-
raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
|
| 171 |
-
elif input_ids is not None:
|
| 172 |
-
(batch_size, seq_length) = input_ids.shape
|
| 173 |
-
elif inputs_embeds is not None:
|
| 174 |
-
(batch_size, seq_length, _) = inputs_embeds.shape
|
| 175 |
-
else:
|
| 176 |
-
raise ValueError('You have to specify either input_ids or inputs_embeds')
|
| 177 |
-
if past_key_values is None:
|
| 178 |
-
past_key_values = tuple([None] * len(self.h))
|
| 179 |
-
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
| 180 |
-
if inputs_embeds is None:
|
| 181 |
-
inputs_embeds = self.word_embeddings(input_ids)
|
| 182 |
-
hidden_states = self.word_embeddings_layernorm(inputs_embeds)
|
| 183 |
-
presents = () if use_cache else None
|
| 184 |
-
all_self_attentions = () if output_attentions else None
|
| 185 |
-
all_hidden_states = () if output_hidden_states else None
|
| 186 |
-
seq_length_with_past = seq_length
|
| 187 |
-
past_key_values_length = 0
|
| 188 |
-
if past_key_values[0] is not None:
|
| 189 |
-
tmp = past_key_values[0][0]
|
| 190 |
-
past_key_values_length = tmp.shape[2]
|
| 191 |
-
seq_length_with_past = seq_length_with_past + past_key_values_length
|
| 192 |
-
if attention_mask is None:
|
| 193 |
-
attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
|
| 194 |
-
else:
|
| 195 |
-
attention_mask = attention_mask.to(hidden_states.device)
|
| 196 |
-
alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)
|
| 197 |
-
causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)
|
| 198 |
-
for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):
|
| 199 |
-
if output_hidden_states:
|
| 200 |
-
hst = (hidden_states,)
|
| 201 |
-
all_hidden_states = all_hidden_states + hst
|
| 202 |
-
if self.gradient_checkpointing and self.training:
|
| 203 |
-
if use_cache:
|
| 204 |
-
logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
|
| 205 |
-
use_cache = False
|
| 206 |
-
|
| 207 |
-
def create_custom_forward(module):
|
| 208 |
-
|
| 209 |
-
def custom_forward(*inputs):
|
| 210 |
-
return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
|
| 211 |
-
return custom_forward
|
| 212 |
-
outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])
|
| 213 |
-
else:
|
| 214 |
-
outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)
|
| 215 |
-
hidden_states = outputs[0]
|
| 216 |
-
if use_cache is True:
|
| 217 |
-
presents = presents + (outputs[1],)
|
| 218 |
-
if output_attentions:
|
| 219 |
-
oa = (outputs[2 if use_cache else 1],)
|
| 220 |
-
all_self_attentions = all_self_attentions + oa
|
| 221 |
-
hidden_states = self.ln_f(hidden_states)
|
| 222 |
-
if output_hidden_states:
|
| 223 |
-
hst = (hidden_states,)
|
| 224 |
-
all_hidden_states = all_hidden_states + hst
|
| 225 |
-
if not return_dict:
|
| 226 |
-
return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))
|
| 227 |
-
return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)
|
| 228 |
-
setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))
|
| 229 |
-
setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))
|
| 230 |
-
setattr(model.transformer, 'forward', MethodType(forward, model.transformer))
|
| 231 |
-
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
|
| 232 |
-
|
| 233 |
-
def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
| 234 |
-
"""Replacement forward method for BloomCausalLM."""
|
| 235 |
-
if deprecated_arguments.pop('position_ids', False) is not False:
|
| 236 |
-
warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)
|
| 237 |
-
if len(deprecated_arguments) > 0:
|
| 238 |
-
raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
|
| 239 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 240 |
-
transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 241 |
-
hidden_states = transformer_outputs[0]
|
| 242 |
-
lm_logits = self.lm_head(hidden_states)
|
| 243 |
-
loss = None
|
| 244 |
-
if labels is not None:
|
| 245 |
-
shift_logits = lm_logits[..., :-1, :].contiguous()
|
| 246 |
-
shift_labels = labels[..., 1:].contiguous()
|
| 247 |
-
(batch_size, seq_length, vocab_size) = shift_logits.shape
|
| 248 |
-
loss_fct = CrossEntropyLoss()
|
| 249 |
-
loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))
|
| 250 |
-
if not return_dict:
|
| 251 |
-
output = (lm_logits,) + transformer_outputs[1:]
|
| 252 |
-
return (loss,) + output if loss is not None else output
|
| 253 |
-
return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)
|
| 254 |
-
|
| 255 |
-
def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict:
|
| 256 |
-
if past:
|
| 257 |
-
input_ids = input_ids[:, -1].unsqueeze(-1)
|
| 258 |
-
bidirectional_mask = None
|
| 259 |
-
if past[0][0].shape[0] == input_ids.shape[0]:
|
| 260 |
-
past = self._convert_to_bloom_cache(past)
|
| 261 |
-
else:
|
| 262 |
-
bidirectional_mask = torch.ones_like(input_ids)
|
| 263 |
-
return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}
|
| 264 |
-
setattr(model, 'forward', MethodType(forward, model))
|
| 265 |
-
setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))
|
| 266 |
-
setattr(model, '_prefix_lm_converted', True)
|
| 267 |
-
return model
|
| 268 |
-
|
| 269 |
-
def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
|
| 270 |
-
"""Converts an OPT Causal LM to a Prefix LM.
|
| 271 |
-
|
| 272 |
-
Supported HuggingFace model classes:
|
| 273 |
-
- `OPTForCausalLM`
|
| 274 |
-
|
| 275 |
-
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
| 276 |
-
"""
|
| 277 |
-
if hasattr(model, '_prefix_lm_converted'):
|
| 278 |
-
return model
|
| 279 |
-
assert isinstance(model, OPTForCausalLM)
|
| 280 |
-
assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'
|
| 281 |
-
setattr(model, '_original_forward', getattr(model, 'forward'))
|
| 282 |
-
setattr(model, '_original_generate', getattr(model, 'generate'))
|
| 283 |
-
model.model.decoder.bidirectional_mask = None
|
| 284 |
-
|
| 285 |
-
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
| 286 |
-
combined_attention_mask = None
|
| 287 |
-
if input_shape[-1] > 1:
|
| 288 |
-
if self.bidirectional_mask == 'g':
|
| 289 |
-
(bsz, src_length) = input_shape
|
| 290 |
-
combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
| 291 |
-
else:
|
| 292 |
-
combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)
|
| 293 |
-
if self.bidirectional_mask is not None:
|
| 294 |
-
assert attention_mask.shape == self.bidirectional_mask.shape
|
| 295 |
-
expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
|
| 296 |
-
combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)
|
| 297 |
-
if attention_mask is not None:
|
| 298 |
-
expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
|
| 299 |
-
combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
| 300 |
-
return combined_attention_mask
|
| 301 |
-
setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))
|
| 302 |
-
|
| 303 |
-
def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=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):
|
| 304 |
-
|
| 305 |
-
def call_og_forward():
|
| 306 |
-
return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 307 |
-
if bidirectional_mask is None:
|
| 308 |
-
return call_og_forward()
|
| 309 |
-
self.model.decoder.bidirectional_mask = bidirectional_mask
|
| 310 |
-
try:
|
| 311 |
-
outputs = call_og_forward()
|
| 312 |
-
except:
|
| 313 |
-
self.model.decoder.bidirectional_mask = None
|
| 314 |
-
raise
|
| 315 |
-
self.model.decoder.bidirectional_mask = None
|
| 316 |
-
return outputs
|
| 317 |
-
|
| 318 |
-
def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):
|
| 319 |
-
"""Wraps original generate to enable PrefixLM-style attention."""
|
| 320 |
-
self.model.decoder.bidirectional_mask = 'g'
|
| 321 |
-
try:
|
| 322 |
-
output = self._original_generate(*args, **kwargs)
|
| 323 |
-
except:
|
| 324 |
-
self.model.decoder.bidirectional_mask = None
|
| 325 |
-
raise
|
| 326 |
-
self.model.decoder.bidirectional_mask = None
|
| 327 |
-
return output
|
| 328 |
-
setattr(model, 'forward', MethodType(forward, model))
|
| 329 |
-
setattr(model, 'generate', MethodType(generate, model))
|
| 330 |
-
setattr(model, '_prefix_lm_converted', True)
|
| 331 |
-
return model
|
| 332 |
-
_SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
|
| 333 |
-
CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]
|
| 334 |
-
|
| 335 |
-
def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
|
| 336 |
-
"""Converts a HuggingFace Causal LM to a Prefix LM.
|
| 337 |
-
|
| 338 |
-
Supported HuggingFace model classes:
|
| 339 |
-
- `GPT2LMHeadModel`
|
| 340 |
-
- `GPTNeoForCausalLM`
|
| 341 |
-
- `GPTNeoXForCausalLM`
|
| 342 |
-
- `GPTJForCausalLM`
|
| 343 |
-
- `BloomForCausalLM`
|
| 344 |
-
- `OPTForCausalLM`
|
| 345 |
-
|
| 346 |
-
Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
|
| 347 |
-
`generate` method and/or select underlying methods depending on the model class.
|
| 348 |
-
|
| 349 |
-
These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask".
|
| 350 |
-
|
| 351 |
-
Notes on training:
|
| 352 |
-
To actually train the converted model as a Prefix LM, training batches will need to indicate
|
| 353 |
-
the prefix/target structure by including `bidirectional_mask` as part of the batch inputs.
|
| 354 |
-
|
| 355 |
-
**This is not a standard input and requires custom layers either within or after your dataloader.**
|
| 356 |
-
|
| 357 |
-
In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels`
|
| 358 |
-
such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`.
|
| 359 |
-
That is, the prefix portion of the sequence should not generate any loss. Loss should only be
|
| 360 |
-
generated by the target portion of the sequence.
|
| 361 |
-
|
| 362 |
-
Notes on `GPTNeoForCausalLM`:
|
| 363 |
-
To simplify the implementation, "global" and "local" attention layers are handled differently.
|
| 364 |
-
For "global" layers, we handle conversion as described above. For "local" layers, which use a
|
| 365 |
-
causal attention mask within a restricted local window, we do not alter the masking.
|
| 366 |
-
|
| 367 |
-
Notes on `forward` method conversion:
|
| 368 |
-
After conversion, the `forward` method will handle a new input, `bidirectional_mask`,
|
| 369 |
-
which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions
|
| 370 |
-
belonging to the prefix (prefix tokens can attend to one another bidirectionally), and
|
| 371 |
-
0 indicates token positions belonging to the target.
|
| 372 |
-
|
| 373 |
-
The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing
|
| 374 |
-
causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset
|
| 375 |
-
the causal masks before returning the result.
|
| 376 |
-
|
| 377 |
-
Notes on `generate` method conversion:
|
| 378 |
-
After conversion, the `generate` method will have the same signature but will internally
|
| 379 |
-
convert all causal masks to be purely bidirectional, call the original `generate` method, and
|
| 380 |
-
(where appropriate) reset the causal masks before returning the result.
|
| 381 |
-
|
| 382 |
-
This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token
|
| 383 |
-
"prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates
|
| 384 |
-
each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one
|
| 385 |
-
another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and
|
| 386 |
-
previously-generated tokens (also as expected in a Prefix LM).
|
| 387 |
-
|
| 388 |
-
To preserve the API, the original methods are renamed to `_original_forward` and
|
| 389 |
-
`_original_generate`, and replaced with new `forward` and `generate` methods that wrap
|
| 390 |
-
them, respectively. Although implementation details vary by model class.
|
| 391 |
-
"""
|
| 392 |
-
if isinstance(model, _SUPPORTED_GPT_MODELS):
|
| 393 |
-
return _convert_gpt_causal_lm_to_prefix_lm(model)
|
| 394 |
-
elif isinstance(model, BloomForCausalLM):
|
| 395 |
-
return _convert_bloom_causal_lm_to_prefix_lm(model)
|
| 396 |
-
elif isinstance(model, OPTForCausalLM):
|
| 397 |
-
return _convert_opt_causal_lm_to_prefix_lm(model)
|
| 398 |
-
else:
|
| 399 |
-
raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
|
| 400 |
-
|
| 401 |
-
def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):
|
| 402 |
-
"""Attempts to add bidirectional_mask to batch if missing.
|
| 403 |
-
|
| 404 |
-
Raises:
|
| 405 |
-
KeyError if bidirectional_mask is missing and can't be inferred
|
| 406 |
-
"""
|
| 407 |
-
if 'bidirectional_mask' not in batch:
|
| 408 |
-
if batch.get('mode', None) == 'icl_task':
|
| 409 |
-
batch['bidirectional_mask'] = batch['attention_mask'].clone()
|
| 410 |
-
for (i, continuation_indices) in enumerate(batch['continuation_indices']):
|
| 411 |
-
batch['bidirectional_mask'][i, continuation_indices] = 0
|
| 412 |
-
elif 'labels' in batch and 'attention_mask' in batch:
|
| 413 |
-
batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask'])
|
| 414 |
-
else:
|
| 415 |
-
raise KeyError('No bidirectional_mask in batch and not sure how to construct one.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/mpt/meta_init_context.py
DELETED
|
@@ -1,94 +0,0 @@
|
|
| 1 |
-
from contextlib import contextmanager
|
| 2 |
-
import torch
|
| 3 |
-
import torch.nn as nn
|
| 4 |
-
|
| 5 |
-
@contextmanager
|
| 6 |
-
def init_empty_weights(include_buffers: bool=False):
|
| 7 |
-
"""Meta initialization context manager.
|
| 8 |
-
|
| 9 |
-
A context manager under which models are initialized with all parameters
|
| 10 |
-
on the meta device, therefore creating an empty model. Useful when just
|
| 11 |
-
initializing the model would blow the available RAM.
|
| 12 |
-
|
| 13 |
-
Args:
|
| 14 |
-
include_buffers (`bool`, *optional*, defaults to `False`): Whether or
|
| 15 |
-
not to also put all buffers on the meta device while initializing.
|
| 16 |
-
|
| 17 |
-
Example:
|
| 18 |
-
```python
|
| 19 |
-
import torch.nn as nn
|
| 20 |
-
|
| 21 |
-
# Initialize a model with 100 billions parameters in no time and without using any RAM.
|
| 22 |
-
with init_empty_weights():
|
| 23 |
-
tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
|
| 24 |
-
```
|
| 25 |
-
|
| 26 |
-
<Tip warning={true}>
|
| 27 |
-
|
| 28 |
-
Any model created under this context manager has no weights. As such you can't do something like
|
| 29 |
-
`model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
|
| 30 |
-
|
| 31 |
-
</Tip>
|
| 32 |
-
"""
|
| 33 |
-
with init_on_device(torch.device('meta'), include_buffers=include_buffers) as f:
|
| 34 |
-
yield f
|
| 35 |
-
|
| 36 |
-
@contextmanager
|
| 37 |
-
def init_on_device(device: torch.device, include_buffers: bool=False):
|
| 38 |
-
"""Device initialization context manager.
|
| 39 |
-
|
| 40 |
-
A context manager under which models are initialized with all parameters
|
| 41 |
-
on the specified device.
|
| 42 |
-
|
| 43 |
-
Args:
|
| 44 |
-
device (`torch.device`): Device to initialize all parameters on.
|
| 45 |
-
include_buffers (`bool`, *optional*, defaults to `False`): Whether or
|
| 46 |
-
not to also put all buffers on the meta device while initializing.
|
| 47 |
-
|
| 48 |
-
Example:
|
| 49 |
-
```python
|
| 50 |
-
import torch.nn as nn
|
| 51 |
-
|
| 52 |
-
with init_on_device(device=torch.device("cuda")):
|
| 53 |
-
tst = nn.Liner(100, 100) # on `cuda` device
|
| 54 |
-
```
|
| 55 |
-
"""
|
| 56 |
-
old_register_parameter = nn.Module.register_parameter
|
| 57 |
-
if include_buffers:
|
| 58 |
-
old_register_buffer = nn.Module.register_buffer
|
| 59 |
-
|
| 60 |
-
def register_empty_parameter(module, name, param):
|
| 61 |
-
old_register_parameter(module, name, param)
|
| 62 |
-
if param is not None:
|
| 63 |
-
param_cls = type(module._parameters[name])
|
| 64 |
-
kwargs = module._parameters[name].__dict__
|
| 65 |
-
module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
|
| 66 |
-
|
| 67 |
-
def register_empty_buffer(module, name, buffer):
|
| 68 |
-
old_register_buffer(module, name, buffer)
|
| 69 |
-
if buffer is not None:
|
| 70 |
-
module._buffers[name] = module._buffers[name].to(device)
|
| 71 |
-
if include_buffers:
|
| 72 |
-
tensor_constructors_to_patch = {torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ['empty', 'zeros', 'ones', 'full']}
|
| 73 |
-
else:
|
| 74 |
-
tensor_constructors_to_patch = {}
|
| 75 |
-
|
| 76 |
-
def patch_tensor_constructor(fn):
|
| 77 |
-
|
| 78 |
-
def wrapper(*args, **kwargs):
|
| 79 |
-
kwargs['device'] = device
|
| 80 |
-
return fn(*args, **kwargs)
|
| 81 |
-
return wrapper
|
| 82 |
-
try:
|
| 83 |
-
nn.Module.register_parameter = register_empty_parameter
|
| 84 |
-
if include_buffers:
|
| 85 |
-
nn.Module.register_buffer = register_empty_buffer
|
| 86 |
-
for torch_function_name in tensor_constructors_to_patch.keys():
|
| 87 |
-
setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
|
| 88 |
-
yield
|
| 89 |
-
finally:
|
| 90 |
-
nn.Module.register_parameter = old_register_parameter
|
| 91 |
-
if include_buffers:
|
| 92 |
-
nn.Module.register_buffer = old_register_buffer
|
| 93 |
-
for (torch_function_name, old_torch_function) in tensor_constructors_to_patch.items():
|
| 94 |
-
setattr(torch, torch_function_name, old_torch_function)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
instructany2pix/llm/model/language_model/mpt/modeling_mpt.py
DELETED
|
@@ -1,331 +0,0 @@
|
|
| 1 |
-
"""A simple, flexible implementation of a GPT model.
|
| 2 |
-
|
| 3 |
-
Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
|
| 4 |
-
"""
|
| 5 |
-
import math
|
| 6 |
-
import warnings
|
| 7 |
-
from typing import List, Optional, Tuple, Union
|
| 8 |
-
import torch
|
| 9 |
-
import torch.nn as nn
|
| 10 |
-
import torch.nn.functional as F
|
| 11 |
-
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
|
| 12 |
-
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 13 |
-
from .attention import attn_bias_shape, build_attn_bias
|
| 14 |
-
from .blocks import MPTBlock
|
| 15 |
-
from .custom_embedding import SharedEmbedding
|
| 16 |
-
from .norm import NORM_CLASS_REGISTRY
|
| 17 |
-
from .configuration_mpt import MPTConfig
|
| 18 |
-
from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
|
| 19 |
-
from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm
|
| 20 |
-
from .meta_init_context import init_empty_weights
|
| 21 |
-
from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_
|
| 22 |
-
try:
|
| 23 |
-
from .flash_attn_triton import flash_attn_func
|
| 24 |
-
except:
|
| 25 |
-
pass
|
| 26 |
-
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
|
| 27 |
-
|
| 28 |
-
class MPTPreTrainedModel(PreTrainedModel):
|
| 29 |
-
config_class = MPTConfig
|
| 30 |
-
base_model_prefix = 'model'
|
| 31 |
-
_no_split_modules = ['MPTBlock']
|
| 32 |
-
|
| 33 |
-
class MPTModel(MPTPreTrainedModel):
|
| 34 |
-
|
| 35 |
-
def __init__(self, config: MPTConfig):
|
| 36 |
-
config._validate_config()
|
| 37 |
-
super().__init__(config)
|
| 38 |
-
self.attn_impl = config.attn_config['attn_impl']
|
| 39 |
-
self.prefix_lm = config.attn_config['prefix_lm']
|
| 40 |
-
self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
|
| 41 |
-
self.alibi = config.attn_config['alibi']
|
| 42 |
-
self.alibi_bias_max = config.attn_config['alibi_bias_max']
|
| 43 |
-
if config.init_device == 'mixed':
|
| 44 |
-
if dist.get_local_rank() == 0:
|
| 45 |
-
config.init_device = 'cpu'
|
| 46 |
-
else:
|
| 47 |
-
config.init_device = 'meta'
|
| 48 |
-
if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
|
| 49 |
-
norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())
|
| 50 |
-
raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')
|
| 51 |
-
norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
|
| 52 |
-
self.embedding_fraction = config.embedding_fraction
|
| 53 |
-
self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device)
|
| 54 |
-
if not self.alibi:
|
| 55 |
-
self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device)
|
| 56 |
-
self.emb_drop = nn.Dropout(config.emb_pdrop)
|
| 57 |
-
self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
|
| 58 |
-
self.norm_f = norm_class(config.d_model, device=config.init_device)
|
| 59 |
-
if config.init_device != 'meta':
|
| 60 |
-
print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.')
|
| 61 |
-
self.apply(self.param_init_fn)
|
| 62 |
-
self.is_causal = not self.prefix_lm
|
| 63 |
-
self._attn_bias_initialized = False
|
| 64 |
-
self.attn_bias = None
|
| 65 |
-
self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id)
|
| 66 |
-
if config.no_bias:
|
| 67 |
-
for module in self.modules():
|
| 68 |
-
if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
|
| 69 |
-
if config.verbose:
|
| 70 |
-
warnings.warn(f'Removing bias ({module.bias}) from {module}.')
|
| 71 |
-
module.register_parameter('bias', None)
|
| 72 |
-
if config.verbose and config.verbose > 2:
|
| 73 |
-
print(self)
|
| 74 |
-
if 'verbose' not in self.config.init_config:
|
| 75 |
-
self.config.init_config['verbose'] = self.config.verbose
|
| 76 |
-
if self.config.init_config['verbose'] > 1:
|
| 77 |
-
init_fn_name = self.config.init_config['name']
|
| 78 |
-
warnings.warn(f'Using {init_fn_name} initialization.')
|
| 79 |
-
self.gradient_checkpointing = False
|
| 80 |
-
|
| 81 |
-
def get_input_embeddings(self):
|
| 82 |
-
return self.wte
|
| 83 |
-
|
| 84 |
-
def set_input_embeddings(self, value):
|
| 85 |
-
self.wte = value
|
| 86 |
-
|
| 87 |
-
@torch.no_grad()
|
| 88 |
-
def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None):
|
| 89 |
-
if not self._attn_bias_initialized:
|
| 90 |
-
if self.attn_bias_shape:
|
| 91 |
-
self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
|
| 92 |
-
self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max)
|
| 93 |
-
self._attn_bias_initialized = True
|
| 94 |
-
if self.attn_impl == 'flash':
|
| 95 |
-
return (self.attn_bias, attention_mask)
|
| 96 |
-
if self.attn_bias is not None:
|
| 97 |
-
self.attn_bias = self.attn_bias.to(dtype=dtype, device=device)
|
| 98 |
-
attn_bias = self.attn_bias
|
| 99 |
-
if self.prefix_lm:
|
| 100 |
-
assert isinstance(attn_bias, torch.Tensor)
|
| 101 |
-
assert isinstance(prefix_mask, torch.Tensor)
|
| 102 |
-
attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
|
| 103 |
-
if self.attn_uses_sequence_id and sequence_id is not None:
|
| 104 |
-
assert isinstance(attn_bias, torch.Tensor)
|
| 105 |
-
attn_bias = self._apply_sequence_id(attn_bias, sequence_id)
|
| 106 |
-
if attention_mask is not None:
|
| 107 |
-
s_k = attention_mask.shape[-1]
|
| 108 |
-
if attn_bias is None:
|
| 109 |
-
attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype)
|
| 110 |
-
else:
|
| 111 |
-
_s_k = max(0, attn_bias.size(-1) - s_k)
|
| 112 |
-
attn_bias = attn_bias[:, :, :, _s_k:]
|
| 113 |
-
if prefix_mask is not None and attention_mask.shape != prefix_mask.shape:
|
| 114 |
-
raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
|
| 115 |
-
min_val = torch.finfo(attn_bias.dtype).min
|
| 116 |
-
attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
|
| 117 |
-
return (attn_bias, None)
|
| 118 |
-
|
| 119 |
-
def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor):
|
| 120 |
-
(s_k, s_q) = attn_bias.shape[-2:]
|
| 121 |
-
if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:
|
| 122 |
-
raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.')
|
| 123 |
-
seq_len = prefix_mask.shape[-1]
|
| 124 |
-
if seq_len > self.config.max_seq_len:
|
| 125 |
-
raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
|
| 126 |
-
attn_bias = attn_bias[..., :seq_len, :seq_len]
|
| 127 |
-
causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len)
|
| 128 |
-
prefix = prefix_mask.view(-1, 1, 1, seq_len)
|
| 129 |
-
cannot_attend = ~torch.logical_or(causal, prefix.bool())
|
| 130 |
-
min_val = torch.finfo(attn_bias.dtype).min
|
| 131 |
-
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
| 132 |
-
return attn_bias
|
| 133 |
-
|
| 134 |
-
def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor):
|
| 135 |
-
seq_len = sequence_id.shape[-1]
|
| 136 |
-
if seq_len > self.config.max_seq_len:
|
| 137 |
-
raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
|
| 138 |
-
attn_bias = attn_bias[..., :seq_len, :seq_len]
|
| 139 |
-
cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
|
| 140 |
-
min_val = torch.finfo(attn_bias.dtype).min
|
| 141 |
-
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
| 142 |
-
return attn_bias
|
| 143 |
-
|
| 144 |
-
def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None):
|
| 145 |
-
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 146 |
-
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 147 |
-
if attention_mask is not None:
|
| 148 |
-
attention_mask = attention_mask.bool()
|
| 149 |
-
if prefix_mask is not None:
|
| 150 |
-
prefix_mask = prefix_mask.bool()
|
| 151 |
-
if not return_dict:
|
| 152 |
-
raise NotImplementedError('return_dict False is not implemented yet for MPT')
|
| 153 |
-
if output_attentions:
|
| 154 |
-
if self.attn_impl != 'torch':
|
| 155 |
-
raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.')
|
| 156 |
-
if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training:
|
| 157 |
-
raise NotImplementedError('MPT does not support training with left padding.')
|
| 158 |
-
if self.prefix_lm and prefix_mask is None:
|
| 159 |
-
raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
|
| 160 |
-
if self.training:
|
| 161 |
-
if self.attn_uses_sequence_id and sequence_id is None:
|
| 162 |
-
raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
|
| 163 |
-
elif self.attn_uses_sequence_id is False and sequence_id is not None:
|
| 164 |
-
warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
|
| 165 |
-
if input_ids is not None:
|
| 166 |
-
S = input_ids.size(1)
|
| 167 |
-
assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
|
| 168 |
-
tok_emb = self.wte(input_ids)
|
| 169 |
-
else:
|
| 170 |
-
assert inputs_embeds is not None
|
| 171 |
-
assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.'
|
| 172 |
-
S = inputs_embeds.size(1)
|
| 173 |
-
tok_emb = inputs_embeds
|
| 174 |
-
if self.alibi:
|
| 175 |
-
x = tok_emb
|
| 176 |
-
else:
|
| 177 |
-
past_position = 0
|
| 178 |
-
if past_key_values is not None:
|
| 179 |
-
if len(past_key_values) != self.config.n_layers:
|
| 180 |
-
raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).')
|
| 181 |
-
past_position = past_key_values[0][0].size(1)
|
| 182 |
-
if self.attn_impl == 'torch':
|
| 183 |
-
past_position = past_key_values[0][0].size(3)
|
| 184 |
-
if S + past_position > self.config.max_seq_len:
|
| 185 |
-
raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')
|
| 186 |
-
pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0)
|
| 187 |
-
if attention_mask is not None:
|
| 188 |
-
pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
|
| 189 |
-
pos_emb = self.wpe(pos)
|
| 190 |
-
x = tok_emb + pos_emb
|
| 191 |
-
if self.embedding_fraction == 1:
|
| 192 |
-
x = self.emb_drop(x)
|
| 193 |
-
else:
|
| 194 |
-
x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction)
|
| 195 |
-
assert isinstance(self.emb_drop, nn.Module)
|
| 196 |
-
x = self.emb_drop(x_shrunk)
|
| 197 |
-
(attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
|
| 198 |
-
if use_cache and past_key_values is None:
|
| 199 |
-
past_key_values = [() for _ in range(self.config.n_layers)]
|
| 200 |
-
all_hidden_states = () if output_hidden_states else None
|
| 201 |
-
all_self_attns = () if output_attentions else None
|
| 202 |
-
for (b_idx, block) in enumerate(self.blocks):
|
| 203 |
-
if output_hidden_states:
|
| 204 |
-
assert all_hidden_states is not None
|
| 205 |
-
all_hidden_states = all_hidden_states + (x,)
|
| 206 |
-
past_key_value = past_key_values[b_idx] if past_key_values is not None else None
|
| 207 |
-
if self.gradient_checkpointing and self.training:
|
| 208 |
-
(x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal)
|
| 209 |
-
else:
|
| 210 |
-
(x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal)
|
| 211 |
-
if past_key_values is not None:
|
| 212 |
-
past_key_values[b_idx] = past_key_value
|
| 213 |
-
if output_attentions:
|
| 214 |
-
assert all_self_attns is not None
|
| 215 |
-
all_self_attns = all_self_attns + (attn_weights,)
|
| 216 |
-
x = self.norm_f(x)
|
| 217 |
-
if output_hidden_states:
|
| 218 |
-
assert all_hidden_states is not None
|
| 219 |
-
all_hidden_states = all_hidden_states + (x,)
|
| 220 |
-
return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns)
|
| 221 |
-
|
| 222 |
-
def param_init_fn(self, module):
|
| 223 |
-
init_fn_name = self.config.init_config['name']
|
| 224 |
-
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
|
| 225 |
-
|
| 226 |
-
def fsdp_wrap_fn(self, module):
|
| 227 |
-
return isinstance(module, MPTBlock)
|
| 228 |
-
|
| 229 |
-
def activation_checkpointing_fn(self, module):
|
| 230 |
-
return isinstance(module, MPTBlock)
|
| 231 |
-
|
| 232 |
-
class MPTForCausalLM(MPTPreTrainedModel):
|
| 233 |
-
|
| 234 |
-
def __init__(self, config: MPTConfig):
|
| 235 |
-
super().__init__(config)
|
| 236 |
-
if not config.tie_word_embeddings:
|
| 237 |
-
raise ValueError('MPTForCausalLM only supports tied word embeddings')
|
| 238 |
-
print(f'Instantiating an MPTForCausalLM model from {__file__}')
|
| 239 |
-
self.transformer = MPTModel(config)
|
| 240 |
-
for child in self.transformer.children():
|
| 241 |
-
if isinstance(child, torch.nn.ModuleList):
|
| 242 |
-
continue
|
| 243 |
-
if isinstance(child, torch.nn.Module):
|
| 244 |
-
child._fsdp_wrap = True
|
| 245 |
-
self.logit_scale = None
|
| 246 |
-
if config.logit_scale is not None:
|
| 247 |
-
logit_scale = config.logit_scale
|
| 248 |
-
if isinstance(logit_scale, str):
|
| 249 |
-
if logit_scale == 'inv_sqrt_d_model':
|
| 250 |
-
logit_scale = 1 / math.sqrt(config.d_model)
|
| 251 |
-
else:
|
| 252 |
-
raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
|
| 253 |
-
self.logit_scale = logit_scale
|
| 254 |
-
|
| 255 |
-
def get_input_embeddings(self):
|
| 256 |
-
return self.transformer.wte
|
| 257 |
-
|
| 258 |
-
def set_input_embeddings(self, value):
|
| 259 |
-
self.transformer.wte = value
|
| 260 |
-
|
| 261 |
-
def get_output_embeddings(self):
|
| 262 |
-
return self.transformer.wte
|
| 263 |
-
|
| 264 |
-
def set_output_embeddings(self, new_embeddings):
|
| 265 |
-
self.transformer.wte = new_embeddings
|
| 266 |
-
|
| 267 |
-
def set_decoder(self, decoder):
|
| 268 |
-
self.transformer = decoder
|
| 269 |
-
|
| 270 |
-
def get_decoder(self):
|
| 271 |
-
return self.transformer
|
| 272 |
-
|
| 273 |
-
def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None):
|
| 274 |
-
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 275 |
-
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 276 |
-
if inputs_embeds is not None:
|
| 277 |
-
raise NotImplementedError('inputs_embeds has to be None (for hf/peft support).')
|
| 278 |
-
outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
|
| 279 |
-
logits = self.transformer.wte(outputs.last_hidden_state.to(self.transformer.wte.weight.device), True)
|
| 280 |
-
if self.logit_scale is not None:
|
| 281 |
-
if self.logit_scale == 0:
|
| 282 |
-
warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
|
| 283 |
-
logits *= self.logit_scale
|
| 284 |
-
loss = None
|
| 285 |
-
if labels is not None:
|
| 286 |
-
labels = torch.roll(labels, shifts=-1)
|
| 287 |
-
labels[:, -1] = -100
|
| 288 |
-
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))
|
| 289 |
-
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
|
| 290 |
-
|
| 291 |
-
def param_init_fn(self, module):
|
| 292 |
-
init_fn_name = self.config.init_config['name']
|
| 293 |
-
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
|
| 294 |
-
|
| 295 |
-
def fsdp_wrap_fn(self, module):
|
| 296 |
-
return isinstance(module, MPTBlock)
|
| 297 |
-
|
| 298 |
-
def activation_checkpointing_fn(self, module):
|
| 299 |
-
return isinstance(module, MPTBlock)
|
| 300 |
-
|
| 301 |
-
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
|
| 302 |
-
if inputs_embeds is not None:
|
| 303 |
-
raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
|
| 304 |
-
attention_mask = kwargs['attention_mask'].bool()
|
| 305 |
-
if attention_mask[:, -1].sum() != attention_mask.shape[0]:
|
| 306 |
-
raise NotImplementedError('MPT does not support generation with right padding.')
|
| 307 |
-
if self.transformer.attn_uses_sequence_id and self.training:
|
| 308 |
-
sequence_id = torch.zeros_like(input_ids[:1])
|
| 309 |
-
else:
|
| 310 |
-
sequence_id = None
|
| 311 |
-
if past_key_values is not None:
|
| 312 |
-
input_ids = input_ids[:, -1].unsqueeze(-1)
|
| 313 |
-
if self.transformer.prefix_lm:
|
| 314 |
-
prefix_mask = torch.ones_like(attention_mask)
|
| 315 |
-
if kwargs.get('use_cache') == False:
|
| 316 |
-
raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
|
| 317 |
-
else:
|
| 318 |
-
prefix_mask = None
|
| 319 |
-
return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)}
|
| 320 |
-
|
| 321 |
-
@staticmethod
|
| 322 |
-
def _reorder_cache(past_key_values, beam_idx):
|
| 323 |
-
"""Used by HuggingFace generate when using beam search with kv-caching.
|
| 324 |
-
|
| 325 |
-
See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133
|
| 326 |
-
for an example in transformers.
|
| 327 |
-
"""
|
| 328 |
-
reordered_past = []
|
| 329 |
-
for layer_past in past_key_values:
|
| 330 |
-
reordered_past += [tuple((past_state.index_select(0, beam_idx) for past_state in layer_past))]
|
| 331 |
-
return reordered_past
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|