Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- added_tokens.json +27 -0
- config.json +84 -0
- diffusion-decoder/.gitattributes +35 -0
- diffusion-decoder/README.md +137 -0
- diffusion-decoder/feature_extractor/preprocessor_config.json +28 -0
- diffusion-decoder/model_index.json +32 -0
- diffusion-decoder/pipeline_ar_gen.py +292 -0
- diffusion-decoder/pipeline_emu2_gen.py +250 -0
- diffusion-decoder/pipeline_llava_gen.py +287 -0
- diffusion-decoder/safety_checker_none/config.json +168 -0
- diffusion-decoder/safety_checker_none/model.bf16.safetensors +3 -0
- diffusion-decoder/scheduler/scheduler_config.json +18 -0
- diffusion-decoder/tokenizer/added_tokens.json +274 -0
- diffusion-decoder/tokenizer/special_tokens_map.json +285 -0
- diffusion-decoder/tokenizer/tokenizer.json +0 -0
- diffusion-decoder/tokenizer/tokenizer.model +3 -0
- diffusion-decoder/tokenizer/tokenizer_config.json +34 -0
- diffusion-decoder/unet/config.json +72 -0
- diffusion-decoder/unet/diffusion_pytorch_model.bf16.safetensors +3 -0
- diffusion-decoder/vae/config.json +32 -0
- diffusion-decoder/vae/diffusion_pytorch_model.bf16.safetensors +3 -0
- generation_config.json +13 -0
- global_step1400/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
- global_step1400/mp_rank_00_model_states.pt +3 -0
- latest +1 -0
- merges.txt +0 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +0 -0
- rng_state.pth +3 -0
- scheduler.pt +3 -0
- special_tokens_map.json +21 -0
- tokenizer.json +3 -0
- tokenizer_config.json +222 -0
- trainer_state.json +0 -0
- training_args.bin +3 -0
- vocab.json +0 -0
- zero_to_fp32.py +760 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
added_tokens.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"</tool_call>": 151658,
|
| 3 |
+
"<image>": 151667,
|
| 4 |
+
"<tool_call>": 151657,
|
| 5 |
+
"<|box_end|>": 151649,
|
| 6 |
+
"<|box_start|>": 151648,
|
| 7 |
+
"<|endoftext|>": 151643,
|
| 8 |
+
"<|file_sep|>": 151664,
|
| 9 |
+
"<|fim_middle|>": 151660,
|
| 10 |
+
"<|fim_pad|>": 151662,
|
| 11 |
+
"<|fim_prefix|>": 151659,
|
| 12 |
+
"<|fim_suffix|>": 151661,
|
| 13 |
+
"<|im_end|>": 151645,
|
| 14 |
+
"<|im_start|>": 151644,
|
| 15 |
+
"<|image_pad|>": 151655,
|
| 16 |
+
"<|object_ref_end|>": 151647,
|
| 17 |
+
"<|object_ref_start|>": 151646,
|
| 18 |
+
"<|quad_end|>": 151651,
|
| 19 |
+
"<|quad_start|>": 151650,
|
| 20 |
+
"<|repo_name|>": 151663,
|
| 21 |
+
"<|video_pad|>": 151656,
|
| 22 |
+
"<|vision_end|>": 151653,
|
| 23 |
+
"<|vision_pad|>": 151654,
|
| 24 |
+
"<|vision_start|>": 151652,
|
| 25 |
+
"[/IMG]": 151666,
|
| 26 |
+
"[IMG]": 151665
|
| 27 |
+
}
|
config.json
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"blip3oQwenForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.0,
|
| 6 |
+
"bos_token_id": 151643,
|
| 7 |
+
"eos_token_id": 151645,
|
| 8 |
+
"freeze_mm_mlp_adapter": false,
|
| 9 |
+
"gen_hidden_size": 1792,
|
| 10 |
+
"gen_pooling": "early_pool2d_4",
|
| 11 |
+
"gen_vision_tower": "eva-clip-E-14-plus",
|
| 12 |
+
"hidden_act": "silu",
|
| 13 |
+
"hidden_size": 2048,
|
| 14 |
+
"image_aspect_ratio": "square",
|
| 15 |
+
"image_token_id": 151655,
|
| 16 |
+
"initializer_range": 0.02,
|
| 17 |
+
"intermediate_size": 11008,
|
| 18 |
+
"max_position_embeddings": 128000,
|
| 19 |
+
"max_window_layers": 70,
|
| 20 |
+
"mm_patch_merge_type": "flat",
|
| 21 |
+
"mm_projector_lr": null,
|
| 22 |
+
"mm_projector_type": "mlp2x_gelu",
|
| 23 |
+
"mm_use_im_patch_token": false,
|
| 24 |
+
"mm_use_im_start_end": false,
|
| 25 |
+
"mm_vision_select_feature": "patch",
|
| 26 |
+
"mm_vision_select_layer": -2,
|
| 27 |
+
"model_type": "blip3o_qwen",
|
| 28 |
+
"n_query": 64,
|
| 29 |
+
"num_attention_heads": 16,
|
| 30 |
+
"num_hidden_layers": 36,
|
| 31 |
+
"num_key_value_heads": 2,
|
| 32 |
+
"pad_token_id": 151643,
|
| 33 |
+
"rms_norm_eps": 1e-06,
|
| 34 |
+
"rope_scaling": {
|
| 35 |
+
"mrope_section": [
|
| 36 |
+
16,
|
| 37 |
+
24,
|
| 38 |
+
24
|
| 39 |
+
],
|
| 40 |
+
"rope_type": "default",
|
| 41 |
+
"type": "default"
|
| 42 |
+
},
|
| 43 |
+
"rope_theta": 1000000.0,
|
| 44 |
+
"sliding_window": 32768,
|
| 45 |
+
"tie_word_embeddings": true,
|
| 46 |
+
"tokenizer_model_max_length": 512,
|
| 47 |
+
"tokenizer_padding_side": "right",
|
| 48 |
+
"torch_dtype": "bfloat16",
|
| 49 |
+
"transformers_version": "4.51.3",
|
| 50 |
+
"tune_mm_mlp_adapter": false,
|
| 51 |
+
"use_cache": false,
|
| 52 |
+
"use_mm_proj": true,
|
| 53 |
+
"use_sliding_window": false,
|
| 54 |
+
"video_token_id": 151656,
|
| 55 |
+
"vision_config": {
|
| 56 |
+
"depth": 32,
|
| 57 |
+
"fullatt_block_indexes": [
|
| 58 |
+
7,
|
| 59 |
+
15,
|
| 60 |
+
23,
|
| 61 |
+
31
|
| 62 |
+
],
|
| 63 |
+
"hidden_act": "silu",
|
| 64 |
+
"hidden_size": 1280,
|
| 65 |
+
"in_channels": 3,
|
| 66 |
+
"in_chans": 3,
|
| 67 |
+
"intermediate_size": 3420,
|
| 68 |
+
"model_type": "qwen2_5_vl",
|
| 69 |
+
"num_heads": 16,
|
| 70 |
+
"out_hidden_size": 2048,
|
| 71 |
+
"patch_size": 14,
|
| 72 |
+
"spatial_merge_size": 2,
|
| 73 |
+
"spatial_patch_size": 14,
|
| 74 |
+
"temporal_patch_size": 2,
|
| 75 |
+
"tokens_per_second": 2,
|
| 76 |
+
"torch_dtype": "bfloat16",
|
| 77 |
+
"window_size": 112
|
| 78 |
+
},
|
| 79 |
+
"vision_end_token_id": 151653,
|
| 80 |
+
"vision_start_token_id": 151652,
|
| 81 |
+
"vision_token_id": 151654,
|
| 82 |
+
"vision_tower_pretrained": null,
|
| 83 |
+
"vocab_size": 151668
|
| 84 |
+
}
|
diffusion-decoder/.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
diffusion-decoder/README.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Emu2-Gen
|
| 8 |
+
|
| 9 |
+
[Paper](https://arxiv.org/abs/2312.13286) | [🤗HF Demo](https://huggingface.co/spaces/BAAI/Emu2) | [Demo](https://emu.ssi.plus) | [Project Page](https://baaivision.github.io/emu2/) | [Github](https://github.com/baaivision/Emu)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
## Model Weights
|
| 13 |
+
|
| 14 |
+
| Model name | Weight |
|
| 15 |
+
| ------------------ | ------------------------------------------------------- |
|
| 16 |
+
| **Emu2** | [🤗 HF link](https://huggingface.co/BAAI/Emu2) |
|
| 17 |
+
| **Emu2-Chat** | [🤗 HF link](https://huggingface.co/BAAI/Emu2-Chat) |
|
| 18 |
+
| **Emu2-Gen** | [🤗 HF link](https://huggingface.co/BAAI/Emu2-Gen) |
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
## Inference (Huggingface Version)
|
| 22 |
+
|
| 23 |
+
### Emu2-Gen
|
| 24 |
+
|
| 25 |
+
```python
|
| 26 |
+
import cv2
|
| 27 |
+
from diffusers import DiffusionPipeline
|
| 28 |
+
import numpy as np
|
| 29 |
+
from PIL import Image
|
| 30 |
+
import requests
|
| 31 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 32 |
+
import torch
|
| 33 |
+
|
| 34 |
+
# For the first time of using,
|
| 35 |
+
# you need to download the huggingface repo "BAAI/Emu2-GEN" to local first
|
| 36 |
+
path = "path to local BAAI/Emu2-GEN"
|
| 37 |
+
|
| 38 |
+
multimodal_encoder = AutoModelForCausalLM.from_pretrained(
|
| 39 |
+
f"{path}/multimodal_encoder",
|
| 40 |
+
trust_remote_code=True,
|
| 41 |
+
torch_dtype=torch.bfloat16,
|
| 42 |
+
use_safetensors=True,
|
| 43 |
+
variant="bf16"
|
| 44 |
+
)
|
| 45 |
+
tokenizer = AutoTokenizer.from_pretrained(f"{path}/tokenizer")
|
| 46 |
+
|
| 47 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 48 |
+
path,
|
| 49 |
+
custom_pipeline="pipeline_emu2_gen",
|
| 50 |
+
torch_dtype=torch.bfloat16,
|
| 51 |
+
use_safetensors=True,
|
| 52 |
+
variant="bf16",
|
| 53 |
+
multimodal_encoder=multimodal_encoder,
|
| 54 |
+
tokenizer=tokenizer,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# For the non-first time of using, you can init the pipeline directly
|
| 58 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 59 |
+
path,
|
| 60 |
+
custom_pipeline="pipeline_emu2_gen",
|
| 61 |
+
torch_dtype=torch.bfloat16,
|
| 62 |
+
use_safetensors=True,
|
| 63 |
+
variant="bf16",
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
pipe.to("cuda")
|
| 67 |
+
|
| 68 |
+
# text-to-image
|
| 69 |
+
prompt = "impressionist painting of an astronaut in a jungle"
|
| 70 |
+
ret = pipe(prompt)
|
| 71 |
+
ret.image.save("astronaut.png")
|
| 72 |
+
|
| 73 |
+
# image editing
|
| 74 |
+
image = Image.open(requests.get('https://github.com/baaivision/Emu/Emu2/examples/dog.jpg?raw=true',stream=True).raw).convert('RGB')
|
| 75 |
+
prompt = [image, "wearing a red hat on the beach."]
|
| 76 |
+
ret = pipe(prompt)
|
| 77 |
+
ret.image.save("dog_hat_beach.png")
|
| 78 |
+
|
| 79 |
+
# grounding generation
|
| 80 |
+
def draw_box(left, top, right, bottom):
|
| 81 |
+
mask = np.zeros((448, 448, 3), dtype=np.uint8)
|
| 82 |
+
mask = cv2.rectangle(mask, (left, top), (right, bottom), (255, 255, 255), 3)
|
| 83 |
+
mask = Image.fromarray(mask)
|
| 84 |
+
return mask
|
| 85 |
+
|
| 86 |
+
dog1 = Image.open(requests.get('https://github.com/baaivision/Emu/Emu2/examples/dog1.jpg?raw=true',stream=True).raw).convert('RGB')
|
| 87 |
+
dog2 = Image.open(requests.get('https://github.com/baaivision/Emu/Emu2/examples/dog2.jpg?raw=true',stream=True).raw).convert('RGB')
|
| 88 |
+
dog3 = Image.open(requests.get('https://github.com/baaivision/Emu/Emu2/examples/dog3.jpg?raw=true',stream=True).raw).convert('RGB')
|
| 89 |
+
dog1_mask = draw_box( 22, 14, 224, 224)
|
| 90 |
+
dog2_mask = draw_box(224, 10, 448, 224)
|
| 91 |
+
dog3_mask = draw_box(120, 264, 320, 438)
|
| 92 |
+
|
| 93 |
+
prompt = [
|
| 94 |
+
"<grounding>",
|
| 95 |
+
"An oil painting of three dogs,",
|
| 96 |
+
"<phrase>the first dog</phrase>"
|
| 97 |
+
"<object>",
|
| 98 |
+
dog1_mask,
|
| 99 |
+
"</object>",
|
| 100 |
+
dog1,
|
| 101 |
+
"<phrase>the second dog</phrase>"
|
| 102 |
+
"<object>",
|
| 103 |
+
dog2_mask,
|
| 104 |
+
"</object>",
|
| 105 |
+
dog2,
|
| 106 |
+
"<phrase>the third dog</phrase>"
|
| 107 |
+
"<object>",
|
| 108 |
+
dog3_mask,
|
| 109 |
+
"</object>",
|
| 110 |
+
dog3,
|
| 111 |
+
]
|
| 112 |
+
ret = pipe(prompt)
|
| 113 |
+
ret.image.save("three_dogs.png")
|
| 114 |
+
|
| 115 |
+
# Autoencoding
|
| 116 |
+
# to enable the autoencoding mode, you can only input exactly one image as prompt
|
| 117 |
+
# if you want the model to generate an image,
|
| 118 |
+
# please input extra empty text "" besides the image, e.g.
|
| 119 |
+
# autoencoding mode: prompt = image or [image]
|
| 120 |
+
# generation mode: prompt = ["", image] or [image, ""]
|
| 121 |
+
prompt = Image.open("./examples/doodle.jpg").convert("RGB")
|
| 122 |
+
ret = pipe(prompt)
|
| 123 |
+
ret.image.save("doodle_ae.png")
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
## Citation
|
| 127 |
+
|
| 128 |
+
If you find Emu2 useful for your research and applications, please consider starring this repository and citing:
|
| 129 |
+
|
| 130 |
+
```
|
| 131 |
+
@article{Emu2,
|
| 132 |
+
title={Generative Multimodal Models are In-Context Learners},
|
| 133 |
+
author={Quan Sun and Yufeng Cui and Xiaosong Zhang and Fan Zhang and Qiying Yu and Zhengxiong Luo and Yueze Wang and Yongming Rao and Jingjing Liu and Tiejun Huang and Xinlong Wang},
|
| 134 |
+
publisher={arXiv preprint arXiv:2312.13286},
|
| 135 |
+
year={2023},
|
| 136 |
+
}
|
| 137 |
+
```
|
diffusion-decoder/feature_extractor/preprocessor_config.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"crop_size": {
|
| 3 |
+
"height": 224,
|
| 4 |
+
"width": 224
|
| 5 |
+
},
|
| 6 |
+
"do_center_crop": true,
|
| 7 |
+
"do_convert_rgb": true,
|
| 8 |
+
"do_normalize": true,
|
| 9 |
+
"do_rescale": true,
|
| 10 |
+
"do_resize": true,
|
| 11 |
+
"feature_extractor_type": "CLIPFeatureExtractor",
|
| 12 |
+
"image_mean": [
|
| 13 |
+
0.48145466,
|
| 14 |
+
0.4578275,
|
| 15 |
+
0.40821073
|
| 16 |
+
],
|
| 17 |
+
"image_processor_type": "CLIPImageProcessor",
|
| 18 |
+
"image_std": [
|
| 19 |
+
0.26862954,
|
| 20 |
+
0.26130258,
|
| 21 |
+
0.27577711
|
| 22 |
+
],
|
| 23 |
+
"resample": 3,
|
| 24 |
+
"rescale_factor": 0.00392156862745098,
|
| 25 |
+
"size": {
|
| 26 |
+
"shortest_edge": 224
|
| 27 |
+
}
|
| 28 |
+
}
|
diffusion-decoder/model_index.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "EmuVisualGenerationPipeline",
|
| 3 |
+
"_diffusers_version": "0.21.2",
|
| 4 |
+
"feature_extractor": [
|
| 5 |
+
"transformers",
|
| 6 |
+
"CLIPImageProcessor"
|
| 7 |
+
],
|
| 8 |
+
"multimodal_encoder": [
|
| 9 |
+
"transformers_modules.multimodal_encoder.modeling_emu",
|
| 10 |
+
"EmuForCausalLM"
|
| 11 |
+
],
|
| 12 |
+
"safety_checker": [
|
| 13 |
+
"stable_diffusion",
|
| 14 |
+
"StableDiffusionSafetyChecker"
|
| 15 |
+
],
|
| 16 |
+
"scheduler": [
|
| 17 |
+
"diffusers",
|
| 18 |
+
"EulerDiscreteScheduler"
|
| 19 |
+
],
|
| 20 |
+
"tokenizer": [
|
| 21 |
+
"transformers",
|
| 22 |
+
"LlamaTokenizerFast"
|
| 23 |
+
],
|
| 24 |
+
"unet": [
|
| 25 |
+
"diffusers",
|
| 26 |
+
"UNet2DConditionModel"
|
| 27 |
+
],
|
| 28 |
+
"vae": [
|
| 29 |
+
"diffusers",
|
| 30 |
+
"AutoencoderKL"
|
| 31 |
+
]
|
| 32 |
+
}
|
diffusion-decoder/pipeline_ar_gen.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
# ===========================================================================================
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) Beijing Academy of Artificial Intelligence (BAAI). All rights reserved.
|
| 7 |
+
#
|
| 8 |
+
# Author : Fan Zhang
|
| 9 |
+
# Email : [email protected]
|
| 10 |
+
# Institute : Beijing Academy of Artificial Intelligence (BAAI)
|
| 11 |
+
# Create On : 2023-12-19 10:45
|
| 12 |
+
# Last Modified : 2023-12-25 07:59
|
| 13 |
+
# File Name : pipeline_emu2_gen.py
|
| 14 |
+
# Description :
|
| 15 |
+
#
|
| 16 |
+
# ===========================================================================================
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import List, Optional
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
from PIL import Image
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
from torchvision import transforms as TF
|
| 27 |
+
from tqdm import tqdm
|
| 28 |
+
import pdb
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
from diffusers import DiffusionPipeline
|
| 32 |
+
from diffusers.utils import BaseOutput
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
from diffusers import UNet2DConditionModel, EulerDiscreteScheduler, AutoencoderKL
|
| 36 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 37 |
+
from transformers import CLIPImageProcessor
|
| 38 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
EVA_IMAGE_SIZE = 448
|
| 42 |
+
OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)
|
| 43 |
+
OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711)
|
| 44 |
+
DEFAULT_IMG_PLACEHOLDER = "<image>"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class EmuVisualGenerationPipelineOutput(BaseOutput):
|
| 49 |
+
image: Image.Image
|
| 50 |
+
nsfw_content_detected: Optional[bool]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class EmuVisualGenerationPipeline(DiffusionPipeline):
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def __init__(
|
| 59 |
+
self,
|
| 60 |
+
tokenizer: AutoTokenizer,
|
| 61 |
+
multimodal_encoder: AutoModelForCausalLM,
|
| 62 |
+
scheduler: EulerDiscreteScheduler,
|
| 63 |
+
unet: UNet2DConditionModel,
|
| 64 |
+
vae: AutoencoderKL,
|
| 65 |
+
feature_extractor: CLIPImageProcessor,
|
| 66 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 67 |
+
eva_size=EVA_IMAGE_SIZE,
|
| 68 |
+
eva_mean=OPENAI_DATASET_MEAN,
|
| 69 |
+
eva_std=OPENAI_DATASET_STD,
|
| 70 |
+
):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.register_modules(
|
| 73 |
+
tokenizer=tokenizer,
|
| 74 |
+
multimodal_encoder=multimodal_encoder,
|
| 75 |
+
scheduler=scheduler,
|
| 76 |
+
unet=unet,
|
| 77 |
+
vae=vae,
|
| 78 |
+
feature_extractor=feature_extractor,
|
| 79 |
+
safety_checker=safety_checker,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
self.transform = TF.Compose([
|
| 87 |
+
TF.Resize((eva_size, eva_size), interpolation=TF.InterpolationMode.BICUBIC),
|
| 88 |
+
TF.ToTensor(),
|
| 89 |
+
TF.Normalize(mean=eva_mean, std=eva_std),
|
| 90 |
+
])
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
self.negative_prompt = {}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def device(self, module):
|
| 97 |
+
return next(module.parameters()).device
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def dtype(self, module):
|
| 101 |
+
return next(module.parameters()).dtype
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@torch.no_grad()
|
| 105 |
+
def __call__(
|
| 106 |
+
self,
|
| 107 |
+
inputs: List[Image.Image | str] | str | Image.Image,
|
| 108 |
+
height: int = 1024,
|
| 109 |
+
width: int = 1024,
|
| 110 |
+
num_inference_steps: int = 50,
|
| 111 |
+
guidance_scale: float = 3.,
|
| 112 |
+
crop_info: List[int] = [0, 0],
|
| 113 |
+
original_size: List[int] = [1024, 1024],
|
| 114 |
+
):
|
| 115 |
+
if not isinstance(inputs, list):
|
| 116 |
+
inputs = [inputs]
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# 0. Default height and width to unet
|
| 120 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 121 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
device = self.device(self.unet)
|
| 125 |
+
dtype = self.dtype(self.unet)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# 1. Encode input prompt
|
| 132 |
+
prompt_embeds = self._prepare_and_encode_inputs(
|
| 133 |
+
inputs,
|
| 134 |
+
do_classifier_free_guidance,
|
| 135 |
+
).to(dtype).to(device)
|
| 136 |
+
batch_size = prompt_embeds.shape[0] // 2 if do_classifier_free_guidance else prompt_embeds.shape[0]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
unet_added_conditions = {}
|
| 140 |
+
time_ids = torch.LongTensor(original_size + crop_info + [height, width]).to(device)
|
| 141 |
+
if do_classifier_free_guidance:
|
| 142 |
+
unet_added_conditions["time_ids"] = torch.cat([time_ids, time_ids], dim=0)
|
| 143 |
+
else:
|
| 144 |
+
unet_added_conditions["time_ids"] = time_ids
|
| 145 |
+
unet_added_conditions["text_embeds"] = torch.mean(prompt_embeds, dim=1)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# 2. Prepare timesteps
|
| 149 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 150 |
+
timesteps = self.scheduler.timesteps
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# 3. Prepare latent variables
|
| 154 |
+
shape = (
|
| 155 |
+
batch_size,
|
| 156 |
+
self.unet.config.in_channels,
|
| 157 |
+
height // self.vae_scale_factor,
|
| 158 |
+
width // self.vae_scale_factor,
|
| 159 |
+
)
|
| 160 |
+
latents = torch.randn(shape, device=device, dtype=dtype)
|
| 161 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# 4. Denoising loop
|
| 165 |
+
for t in tqdm(timesteps):
|
| 166 |
+
# expand the latents if we are doing classifier free guidance
|
| 167 |
+
# 2B x 4 x H x W
|
| 168 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 169 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
noise_pred = self.unet(
|
| 173 |
+
latent_model_input,
|
| 174 |
+
t,
|
| 175 |
+
encoder_hidden_states=prompt_embeds,
|
| 176 |
+
added_cond_kwargs=unet_added_conditions,
|
| 177 |
+
).sample
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# perform guidance
|
| 181 |
+
if do_classifier_free_guidance:
|
| 182 |
+
noise_pred_cond, noise_pred_uncond = noise_pred.chunk(2)
|
| 183 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 187 |
+
latents = self.scheduler.step(noise_pred, t, latents).prev_sample
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# 5. Post-processing
|
| 191 |
+
images = self.decode_latents(latents)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
# 6. Run safety checker
|
| 195 |
+
images, has_nsfw_concept = self.run_safety_checker(images)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
# 7. Convert to PIL
|
| 199 |
+
images = self.numpy_to_pil(images)
|
| 200 |
+
return EmuVisualGenerationPipelineOutput(
|
| 201 |
+
image=images[0],
|
| 202 |
+
nsfw_content_detected=None if has_nsfw_concept is None else has_nsfw_concept[0],
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _prepare_and_encode_inputs(
|
| 207 |
+
self,
|
| 208 |
+
inputs: List[str | Image.Image],
|
| 209 |
+
do_classifier_free_guidance: bool = False,
|
| 210 |
+
placeholder: str = DEFAULT_IMG_PLACEHOLDER,
|
| 211 |
+
):
|
| 212 |
+
# pdb.set_trace()
|
| 213 |
+
device = self.device(self.multimodal_encoder.model)
|
| 214 |
+
dtype = self.dtype(self.multimodal_encoder.model)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
has_image, has_text = False, False
|
| 218 |
+
text_prompt, image_prompt = "", []
|
| 219 |
+
for x in inputs:
|
| 220 |
+
if isinstance(x, str):
|
| 221 |
+
has_text = True
|
| 222 |
+
text_prompt += x
|
| 223 |
+
else:
|
| 224 |
+
has_image = True
|
| 225 |
+
text_prompt += placeholder
|
| 226 |
+
image_prompt.append(self.transform(x))
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
if len(image_prompt) == 0:
|
| 230 |
+
image_prompt = None
|
| 231 |
+
else:
|
| 232 |
+
image_prompt = torch.stack(image_prompt)
|
| 233 |
+
image_prompt = image_prompt.type(dtype).to(device)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
if has_image and not has_text:
|
| 237 |
+
prompt = self.multimodal_encoder.model.encode_image(image=image_prompt)
|
| 238 |
+
if do_classifier_free_guidance:
|
| 239 |
+
key = "[NULL_IMAGE]"
|
| 240 |
+
if key not in self.negative_prompt:
|
| 241 |
+
negative_image = torch.zeros_like(image_prompt)
|
| 242 |
+
self.negative_prompt[key] = self.multimodal_encoder.model.encode_image(image=negative_image)
|
| 243 |
+
prompt = torch.cat([prompt, self.negative_prompt[key]], dim=0)
|
| 244 |
+
else:
|
| 245 |
+
prompt = self.multimodal_encoder.generate_image(text=[text_prompt], image=image_prompt, tokenizer=self.tokenizer)
|
| 246 |
+
if do_classifier_free_guidance:
|
| 247 |
+
key = ""
|
| 248 |
+
if key not in self.negative_prompt:
|
| 249 |
+
self.negative_prompt[key] = self.multimodal_encoder.generate_image(text=[""], tokenizer=self.tokenizer)
|
| 250 |
+
prompt = torch.cat([prompt, self.negative_prompt[key]], dim=0)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
return prompt
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def decode_latents(self, latents: torch.Tensor) -> np.ndarray:
|
| 257 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 258 |
+
image = self.vae.decode(latents).sample
|
| 259 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 260 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 261 |
+
return image
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def numpy_to_pil(self, images: np.ndarray) -> List[Image.Image]:
|
| 265 |
+
"""
|
| 266 |
+
Convert a numpy image or a batch of images to a PIL image.
|
| 267 |
+
"""
|
| 268 |
+
if images.ndim == 3:
|
| 269 |
+
images = images[None, ...]
|
| 270 |
+
images = (images * 255).round().astype("uint8")
|
| 271 |
+
if images.shape[-1] == 1:
|
| 272 |
+
# special case for grayscale (single channel) images
|
| 273 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
| 274 |
+
else:
|
| 275 |
+
pil_images = [Image.fromarray(image) for image in images]
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
return pil_images
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def run_safety_checker(self, images: np.ndarray):
|
| 282 |
+
if self.safety_checker is not None:
|
| 283 |
+
device = self.device(self.safety_checker)
|
| 284 |
+
dtype = self.dtype(self.safety_checker)
|
| 285 |
+
safety_checker_input = self.feature_extractor(self.numpy_to_pil(images), return_tensors="pt").to(device)
|
| 286 |
+
images, has_nsfw_concept = self.safety_checker(
|
| 287 |
+
images=images, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 288 |
+
)
|
| 289 |
+
else:
|
| 290 |
+
has_nsfw_concept = None
|
| 291 |
+
return images, has_nsfw_concept
|
| 292 |
+
|
diffusion-decoder/pipeline_emu2_gen.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 3 |
+
# ===========================================================================================
|
| 4 |
+
#
|
| 5 |
+
# Copyright (c) Beijing Academy of Artificial Intelligence (BAAI). All rights reserved.
|
| 6 |
+
#
|
| 7 |
+
# Author : Fan Zhang
|
| 8 |
+
# Email : [email protected]
|
| 9 |
+
# Institute : Beijing Academy of Artificial Intelligence (BAAI)
|
| 10 |
+
# Create On : 2023-12-19 10:45
|
| 11 |
+
# Last Modified : 2023-12-25 07:59
|
| 12 |
+
# File Name : pipeline_emu2_gen.py
|
| 13 |
+
# Description :
|
| 14 |
+
#
|
| 15 |
+
# ===========================================================================================
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import List, Optional
|
| 19 |
+
|
| 20 |
+
from PIL import Image
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from torchvision import transforms as TF
|
| 24 |
+
from tqdm import tqdm
|
| 25 |
+
|
| 26 |
+
from diffusers import DiffusionPipeline
|
| 27 |
+
from diffusers.utils import BaseOutput
|
| 28 |
+
|
| 29 |
+
from diffusers import UNet2DConditionModel, EulerDiscreteScheduler, AutoencoderKL
|
| 30 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 31 |
+
from transformers import CLIPImageProcessor
|
| 32 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 33 |
+
|
| 34 |
+
EVA_IMAGE_SIZE = 448
|
| 35 |
+
OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)
|
| 36 |
+
OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711)
|
| 37 |
+
DEFAULT_IMG_PLACEHOLDER = "[<IMG_PLH>]"
|
| 38 |
+
|
| 39 |
+
@dataclass
|
| 40 |
+
class EmuVisualGenerationPipelineOutput(BaseOutput):
|
| 41 |
+
image: Image.Image
|
| 42 |
+
nsfw_content_detected: Optional[bool]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class EmuVisualGenerationPipeline(DiffusionPipeline):
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
tokenizer: AutoTokenizer,
|
| 50 |
+
multimodal_encoder: AutoModelForCausalLM,
|
| 51 |
+
scheduler: EulerDiscreteScheduler,
|
| 52 |
+
unet: UNet2DConditionModel,
|
| 53 |
+
vae: AutoencoderKL,
|
| 54 |
+
feature_extractor: CLIPImageProcessor,
|
| 55 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 56 |
+
eva_size=EVA_IMAGE_SIZE,
|
| 57 |
+
eva_mean=OPENAI_DATASET_MEAN,
|
| 58 |
+
eva_std=OPENAI_DATASET_STD,
|
| 59 |
+
):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.register_modules(
|
| 62 |
+
tokenizer=tokenizer,
|
| 63 |
+
multimodal_encoder=multimodal_encoder,
|
| 64 |
+
scheduler=scheduler,
|
| 65 |
+
unet=unet,
|
| 66 |
+
vae=vae,
|
| 67 |
+
feature_extractor=feature_extractor,
|
| 68 |
+
safety_checker=safety_checker,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 72 |
+
|
| 73 |
+
self.transform = TF.Compose([
|
| 74 |
+
TF.Resize((eva_size, eva_size), interpolation=TF.InterpolationMode.BICUBIC),
|
| 75 |
+
TF.ToTensor(),
|
| 76 |
+
TF.Normalize(mean=eva_mean, std=eva_std),
|
| 77 |
+
])
|
| 78 |
+
|
| 79 |
+
self.negative_prompt = {}
|
| 80 |
+
|
| 81 |
+
def device(self, module):
|
| 82 |
+
return next(module.parameters()).device
|
| 83 |
+
|
| 84 |
+
def dtype(self, module):
|
| 85 |
+
return next(module.parameters()).dtype
|
| 86 |
+
|
| 87 |
+
@torch.no_grad()
|
| 88 |
+
def __call__(
|
| 89 |
+
self,
|
| 90 |
+
inputs: List[Image.Image | str] | str | Image.Image,
|
| 91 |
+
height: int = 1024,
|
| 92 |
+
width: int = 1024,
|
| 93 |
+
num_inference_steps: int = 50,
|
| 94 |
+
guidance_scale: float = 3.,
|
| 95 |
+
crop_info: List[int] = [0, 0],
|
| 96 |
+
original_size: List[int] = [1024, 1024],
|
| 97 |
+
):
|
| 98 |
+
if not isinstance(inputs, list):
|
| 99 |
+
inputs = [inputs]
|
| 100 |
+
|
| 101 |
+
# 0. Default height and width to unet
|
| 102 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 103 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 104 |
+
|
| 105 |
+
device = self.device(self.unet)
|
| 106 |
+
dtype = self.dtype(self.unet)
|
| 107 |
+
|
| 108 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 109 |
+
|
| 110 |
+
# 1. Encode input prompt
|
| 111 |
+
prompt_embeds = self._prepare_and_encode_inputs(
|
| 112 |
+
inputs,
|
| 113 |
+
do_classifier_free_guidance,
|
| 114 |
+
).to(dtype).to(device)
|
| 115 |
+
batch_size = prompt_embeds.shape[0] // 2 if do_classifier_free_guidance else prompt_embeds.shape[0]
|
| 116 |
+
|
| 117 |
+
unet_added_conditions = {}
|
| 118 |
+
time_ids = torch.LongTensor(original_size + crop_info + [height, width]).to(device)
|
| 119 |
+
if do_classifier_free_guidance:
|
| 120 |
+
unet_added_conditions["time_ids"] = torch.cat([time_ids, time_ids], dim=0)
|
| 121 |
+
else:
|
| 122 |
+
unet_added_conditions["time_ids"] = time_ids
|
| 123 |
+
unet_added_conditions["text_embeds"] = torch.mean(prompt_embeds, dim=1)
|
| 124 |
+
|
| 125 |
+
# 2. Prepare timesteps
|
| 126 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 127 |
+
timesteps = self.scheduler.timesteps
|
| 128 |
+
|
| 129 |
+
# 3. Prepare latent variables
|
| 130 |
+
shape = (
|
| 131 |
+
batch_size,
|
| 132 |
+
self.unet.config.in_channels,
|
| 133 |
+
height // self.vae_scale_factor,
|
| 134 |
+
width // self.vae_scale_factor,
|
| 135 |
+
)
|
| 136 |
+
latents = torch.randn(shape, device=device, dtype=dtype)
|
| 137 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 138 |
+
|
| 139 |
+
# 4. Denoising loop
|
| 140 |
+
for t in tqdm(timesteps):
|
| 141 |
+
# expand the latents if we are doing classifier free guidance
|
| 142 |
+
# 2B x 4 x H x W
|
| 143 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 144 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 145 |
+
|
| 146 |
+
noise_pred = self.unet(
|
| 147 |
+
latent_model_input,
|
| 148 |
+
t,
|
| 149 |
+
encoder_hidden_states=prompt_embeds,
|
| 150 |
+
added_cond_kwargs=unet_added_conditions,
|
| 151 |
+
).sample
|
| 152 |
+
|
| 153 |
+
# perform guidance
|
| 154 |
+
if do_classifier_free_guidance:
|
| 155 |
+
noise_pred_cond, noise_pred_uncond = noise_pred.chunk(2)
|
| 156 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
| 157 |
+
|
| 158 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 159 |
+
latents = self.scheduler.step(noise_pred, t, latents).prev_sample
|
| 160 |
+
|
| 161 |
+
# 5. Post-processing
|
| 162 |
+
images = self.decode_latents(latents)
|
| 163 |
+
|
| 164 |
+
# 6. Run safety checker
|
| 165 |
+
images, has_nsfw_concept = self.run_safety_checker(images)
|
| 166 |
+
|
| 167 |
+
# 7. Convert to PIL
|
| 168 |
+
images = self.numpy_to_pil(images)
|
| 169 |
+
return EmuVisualGenerationPipelineOutput(
|
| 170 |
+
image=images[0],
|
| 171 |
+
nsfw_content_detected=None if has_nsfw_concept is None else has_nsfw_concept[0],
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
def _prepare_and_encode_inputs(
|
| 175 |
+
self,
|
| 176 |
+
inputs: List[str | Image.Image],
|
| 177 |
+
do_classifier_free_guidance: bool = False,
|
| 178 |
+
placeholder: str = DEFAULT_IMG_PLACEHOLDER,
|
| 179 |
+
):
|
| 180 |
+
device = self.device(self.multimodal_encoder.model.visual)
|
| 181 |
+
dtype = self.dtype(self.multimodal_encoder.model.visual)
|
| 182 |
+
|
| 183 |
+
has_image, has_text = False, False
|
| 184 |
+
text_prompt, image_prompt = "", []
|
| 185 |
+
for x in inputs:
|
| 186 |
+
if isinstance(x, str):
|
| 187 |
+
has_text = True
|
| 188 |
+
text_prompt += x
|
| 189 |
+
else:
|
| 190 |
+
has_image = True
|
| 191 |
+
text_prompt += placeholder
|
| 192 |
+
image_prompt.append(self.transform(x))
|
| 193 |
+
|
| 194 |
+
if len(image_prompt) == 0:
|
| 195 |
+
image_prompt = None
|
| 196 |
+
else:
|
| 197 |
+
image_prompt = torch.stack(image_prompt)
|
| 198 |
+
image_prompt = image_prompt.type(dtype).to(device)
|
| 199 |
+
|
| 200 |
+
if has_image and not has_text:
|
| 201 |
+
prompt = self.multimodal_encoder.model.encode_image(image=image_prompt)
|
| 202 |
+
if do_classifier_free_guidance:
|
| 203 |
+
key = "[NULL_IMAGE]"
|
| 204 |
+
if key not in self.negative_prompt:
|
| 205 |
+
negative_image = torch.zeros_like(image_prompt)
|
| 206 |
+
self.negative_prompt[key] = self.multimodal_encoder.model.encode_image(image=negative_image)
|
| 207 |
+
prompt = torch.cat([prompt, self.negative_prompt[key]], dim=0)
|
| 208 |
+
else:
|
| 209 |
+
prompt = self.multimodal_encoder.generate_image(text=[text_prompt], image=image_prompt, tokenizer=self.tokenizer)
|
| 210 |
+
if do_classifier_free_guidance:
|
| 211 |
+
key = ""
|
| 212 |
+
if key not in self.negative_prompt:
|
| 213 |
+
self.negative_prompt[key] = self.multimodal_encoder.generate_image(text=[""], tokenizer=self.tokenizer)
|
| 214 |
+
prompt = torch.cat([prompt, self.negative_prompt[key]], dim=0)
|
| 215 |
+
|
| 216 |
+
return prompt
|
| 217 |
+
|
| 218 |
+
def decode_latents(self, latents: torch.Tensor) -> np.ndarray:
|
| 219 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 220 |
+
image = self.vae.decode(latents).sample
|
| 221 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 222 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 223 |
+
return image
|
| 224 |
+
|
| 225 |
+
def numpy_to_pil(self, images: np.ndarray) -> List[Image.Image]:
|
| 226 |
+
"""
|
| 227 |
+
Convert a numpy image or a batch of images to a PIL image.
|
| 228 |
+
"""
|
| 229 |
+
if images.ndim == 3:
|
| 230 |
+
images = images[None, ...]
|
| 231 |
+
images = (images * 255).round().astype("uint8")
|
| 232 |
+
if images.shape[-1] == 1:
|
| 233 |
+
# special case for grayscale (single channel) images
|
| 234 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
| 235 |
+
else:
|
| 236 |
+
pil_images = [Image.fromarray(image) for image in images]
|
| 237 |
+
|
| 238 |
+
return pil_images
|
| 239 |
+
|
| 240 |
+
def run_safety_checker(self, images: np.ndarray):
|
| 241 |
+
if self.safety_checker is not None:
|
| 242 |
+
device = self.device(self.safety_checker)
|
| 243 |
+
dtype = self.dtype(self.safety_checker)
|
| 244 |
+
safety_checker_input = self.feature_extractor(self.numpy_to_pil(images), return_tensors="pt").to(device)
|
| 245 |
+
images, has_nsfw_concept = self.safety_checker(
|
| 246 |
+
images=images, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 247 |
+
)
|
| 248 |
+
else:
|
| 249 |
+
has_nsfw_concept = None
|
| 250 |
+
return images, has_nsfw_concept
|
diffusion-decoder/pipeline_llava_gen.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# ===========================================================================================
|
| 3 |
+
#
|
| 4 |
+
# Copyright (c) Beijing Academy of Artificial Intelligence (BAAI). All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Author : Fan Zhang
|
| 7 |
+
# Email : [email protected]
|
| 8 |
+
# Institute : Beijing Academy of Artificial Intelligence (BAAI)
|
| 9 |
+
# Create On : 2023-12-19 10:45
|
| 10 |
+
# Last Modified : 2023-12-25 07:59
|
| 11 |
+
# File Name : pipeline_emu2_gen.py
|
| 12 |
+
# Description :
|
| 13 |
+
#
|
| 14 |
+
# ===========================================================================================
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import List, Optional
|
| 18 |
+
|
| 19 |
+
from PIL import Image
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from torchvision import transforms as TF
|
| 23 |
+
from tqdm import tqdm
|
| 24 |
+
import pdb
|
| 25 |
+
|
| 26 |
+
from diffusers import DiffusionPipeline
|
| 27 |
+
from diffusers.utils import BaseOutput
|
| 28 |
+
|
| 29 |
+
from diffusers import UNet2DConditionModel, EulerDiscreteScheduler, AutoencoderKL
|
| 30 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 31 |
+
from transformers import CLIPImageProcessor
|
| 32 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 33 |
+
|
| 34 |
+
EVA_IMAGE_SIZE = 448
|
| 35 |
+
OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)
|
| 36 |
+
OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711)
|
| 37 |
+
DEFAULT_IMG_PLACEHOLDER = "<image>"
|
| 38 |
+
|
| 39 |
+
from transformers import AutoProcessor
|
| 40 |
+
image_processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct").image_processor
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class EmuVisualGenerationPipelineOutput(BaseOutput):
|
| 45 |
+
image: Image.Image
|
| 46 |
+
nsfw_content_detected: Optional[bool]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class EmuVisualGenerationPipeline(DiffusionPipeline):
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
tokenizer: AutoTokenizer,
|
| 54 |
+
multimodal_encoder: AutoModelForCausalLM,
|
| 55 |
+
scheduler: EulerDiscreteScheduler,
|
| 56 |
+
unet: UNet2DConditionModel,
|
| 57 |
+
vae: AutoencoderKL,
|
| 58 |
+
feature_extractor: CLIPImageProcessor,
|
| 59 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 60 |
+
eva_size=EVA_IMAGE_SIZE,
|
| 61 |
+
eva_mean=OPENAI_DATASET_MEAN,
|
| 62 |
+
eva_std=OPENAI_DATASET_STD,
|
| 63 |
+
):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.register_modules(
|
| 66 |
+
tokenizer=tokenizer,
|
| 67 |
+
multimodal_encoder=multimodal_encoder,
|
| 68 |
+
scheduler=scheduler,
|
| 69 |
+
unet=unet,
|
| 70 |
+
vae=vae,
|
| 71 |
+
feature_extractor=feature_extractor,
|
| 72 |
+
safety_checker=None,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 76 |
+
|
| 77 |
+
self.transform = TF.Compose([
|
| 78 |
+
TF.Resize((eva_size, eva_size), interpolation=TF.InterpolationMode.BICUBIC),
|
| 79 |
+
TF.ToTensor(),
|
| 80 |
+
TF.Normalize(mean=eva_mean, std=eva_std),
|
| 81 |
+
])
|
| 82 |
+
|
| 83 |
+
self.negative_prompt = {}
|
| 84 |
+
|
| 85 |
+
def device(self, module):
|
| 86 |
+
return next(module.parameters()).device
|
| 87 |
+
|
| 88 |
+
def dtype(self, module):
|
| 89 |
+
return next(module.parameters()).dtype
|
| 90 |
+
|
| 91 |
+
@torch.no_grad()
|
| 92 |
+
def __call__(
|
| 93 |
+
self,
|
| 94 |
+
inputs: List[Image.Image | str] | str | Image.Image,
|
| 95 |
+
height: int = 1024,
|
| 96 |
+
width: int = 1024,
|
| 97 |
+
num_inference_steps: int = 50,
|
| 98 |
+
guidance_scale: float = 3.0,
|
| 99 |
+
crop_info: List[int] = [0, 0],
|
| 100 |
+
original_size: List[int] = [1024, 1024],
|
| 101 |
+
):
|
| 102 |
+
if not isinstance(inputs, list):
|
| 103 |
+
inputs = [inputs]
|
| 104 |
+
|
| 105 |
+
# 0. Default height and width to unet
|
| 106 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 107 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 108 |
+
|
| 109 |
+
device = self.device(self.unet)
|
| 110 |
+
dtype = self.dtype(self.unet)
|
| 111 |
+
|
| 112 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 113 |
+
|
| 114 |
+
# 1. Encode input prompt
|
| 115 |
+
prompt_embeds = self._prepare_and_encode_inputs(
|
| 116 |
+
inputs,
|
| 117 |
+
do_classifier_free_guidance,
|
| 118 |
+
).to(dtype).to(device)
|
| 119 |
+
batch_size = prompt_embeds.shape[0] // 2 if do_classifier_free_guidance else prompt_embeds.shape[0]
|
| 120 |
+
|
| 121 |
+
unet_added_conditions = {}
|
| 122 |
+
time_ids = torch.LongTensor(original_size + crop_info + [height, width]).to(device)
|
| 123 |
+
if do_classifier_free_guidance:
|
| 124 |
+
unet_added_conditions["time_ids"] = torch.cat([time_ids, time_ids], dim=0)
|
| 125 |
+
else:
|
| 126 |
+
unet_added_conditions["time_ids"] = time_ids
|
| 127 |
+
unet_added_conditions["text_embeds"] = torch.mean(prompt_embeds, dim=1)
|
| 128 |
+
|
| 129 |
+
# 2. Prepare timesteps
|
| 130 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 131 |
+
timesteps = self.scheduler.timesteps
|
| 132 |
+
|
| 133 |
+
# 3. Prepare latent variables
|
| 134 |
+
shape = (
|
| 135 |
+
batch_size,
|
| 136 |
+
self.unet.config.in_channels,
|
| 137 |
+
height // self.vae_scale_factor,
|
| 138 |
+
width // self.vae_scale_factor,
|
| 139 |
+
)
|
| 140 |
+
latents = torch.randn(shape, device=device, dtype=dtype)
|
| 141 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 142 |
+
|
| 143 |
+
# 4. Denoising loop
|
| 144 |
+
for t in tqdm(timesteps):
|
| 145 |
+
# Expand the latents if doing classifier free guidance: 2B x 4 x H x W
|
| 146 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 147 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 148 |
+
|
| 149 |
+
noise_pred = self.unet(
|
| 150 |
+
latent_model_input,
|
| 151 |
+
t,
|
| 152 |
+
encoder_hidden_states=prompt_embeds,
|
| 153 |
+
added_cond_kwargs=unet_added_conditions,
|
| 154 |
+
).sample
|
| 155 |
+
|
| 156 |
+
# Perform guidance
|
| 157 |
+
if do_classifier_free_guidance:
|
| 158 |
+
noise_pred_cond, noise_pred_uncond = noise_pred.chunk(2)
|
| 159 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
| 160 |
+
|
| 161 |
+
# Compute the previous noisy sample x_t -> x_t-1
|
| 162 |
+
latents = self.scheduler.step(noise_pred, t, latents).prev_sample
|
| 163 |
+
|
| 164 |
+
# 5. Post-processing
|
| 165 |
+
images = self.decode_latents(latents)
|
| 166 |
+
# 6. Run safety checker
|
| 167 |
+
# images, has_nsfw_concept = self.run_safety_checker(images)
|
| 168 |
+
|
| 169 |
+
# 7. Convert to PIL
|
| 170 |
+
images = self.numpy_to_pil(images)
|
| 171 |
+
|
| 172 |
+
# return EmuVisualGenerationPipelineOutput(
|
| 173 |
+
# image=images[0],
|
| 174 |
+
# nsfw_content_detected=None if has_nsfw_concept is None else has_nsfw_concept[0],
|
| 175 |
+
# )
|
| 176 |
+
|
| 177 |
+
return EmuVisualGenerationPipelineOutput(
|
| 178 |
+
image=images[0],
|
| 179 |
+
nsfw_content_detected=None
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def _prepare_and_encode_inputs(
|
| 183 |
+
self,
|
| 184 |
+
inputs: List[str | Image.Image],
|
| 185 |
+
do_classifier_free_guidance: bool = False,
|
| 186 |
+
placeholder: str = DEFAULT_IMG_PLACEHOLDER,
|
| 187 |
+
):
|
| 188 |
+
# pdb.set_trace()
|
| 189 |
+
device = self.device(self.multimodal_encoder.model)
|
| 190 |
+
dtype = self.dtype(self.multimodal_encoder.model)
|
| 191 |
+
|
| 192 |
+
has_image, has_text = False, False
|
| 193 |
+
text_prompt, image_prompt, image_grid_thw = "", [], []
|
| 194 |
+
for x in inputs:
|
| 195 |
+
if isinstance(x, str):
|
| 196 |
+
has_text = True
|
| 197 |
+
text_prompt += x
|
| 198 |
+
else:
|
| 199 |
+
has_image = True
|
| 200 |
+
text_prompt = text_prompt.replace(
|
| 201 |
+
"<image>",
|
| 202 |
+
"<|vision_start|>" + "<|image_pad|>" * 256 + "<|vision_end|>"
|
| 203 |
+
)
|
| 204 |
+
resized_images = x.resize((448, 448))
|
| 205 |
+
image_inputs = image_processor(resized_images, return_tensors="pt")
|
| 206 |
+
image_prompt.append(image_inputs.pixel_values)
|
| 207 |
+
image_grid_thw.append(image_inputs.image_grid_thw)
|
| 208 |
+
|
| 209 |
+
if len(image_prompt) == 0:
|
| 210 |
+
image_prompt = None
|
| 211 |
+
image_grid_thw = None
|
| 212 |
+
else:
|
| 213 |
+
image_prompt = torch.cat(image_prompt, dim=0)
|
| 214 |
+
image_grid_thw = torch.cat(image_grid_thw, dim=0)
|
| 215 |
+
# breakpoint()
|
| 216 |
+
if has_image and not has_text:
|
| 217 |
+
prompt = self.multimodal_encoder.model.encode_image(image=image_prompt)
|
| 218 |
+
if do_classifier_free_guidance:
|
| 219 |
+
key = "[NULL_IMAGE]"
|
| 220 |
+
if key not in self.negative_prompt:
|
| 221 |
+
negative_image = torch.zeros_like(image_prompt)
|
| 222 |
+
self.negative_prompt[key] = self.multimodal_encoder.model.encode_image(image=negative_image)
|
| 223 |
+
prompt = torch.cat([prompt, self.negative_prompt[key]], dim=0)
|
| 224 |
+
elif has_text and not has_image:
|
| 225 |
+
|
| 226 |
+
prompt = self.multimodal_encoder.generate_image(
|
| 227 |
+
text=[text_prompt], tokenizer=self.tokenizer
|
| 228 |
+
)
|
| 229 |
+
if do_classifier_free_guidance:
|
| 230 |
+
key = ""
|
| 231 |
+
if key not in self.negative_prompt:
|
| 232 |
+
self.negative_prompt[key] = self.multimodal_encoder.generate_image(
|
| 233 |
+
text=[" "],
|
| 234 |
+
tokenizer=self.tokenizer
|
| 235 |
+
)
|
| 236 |
+
prompt = torch.cat([prompt, self.negative_prompt[key]], dim=0)
|
| 237 |
+
elif has_text and has_image:
|
| 238 |
+
prompt = self.multimodal_encoder.generate_image(
|
| 239 |
+
text=[text_prompt],
|
| 240 |
+
pixel_values=image_prompt.cuda(),
|
| 241 |
+
image_grid_thw=image_grid_thw.cuda(),
|
| 242 |
+
tokenizer=self.tokenizer
|
| 243 |
+
)
|
| 244 |
+
if do_classifier_free_guidance:
|
| 245 |
+
key = ""
|
| 246 |
+
if key not in self.negative_prompt:
|
| 247 |
+
self.negative_prompt[key] = self.multimodal_encoder.generate_image(
|
| 248 |
+
text=[" "],
|
| 249 |
+
tokenizer=self.tokenizer
|
| 250 |
+
)
|
| 251 |
+
prompt = torch.cat([prompt, self.negative_prompt[key]], dim=0)
|
| 252 |
+
return prompt
|
| 253 |
+
|
| 254 |
+
def decode_latents(self, latents: torch.Tensor) -> np.ndarray:
|
| 255 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 256 |
+
image = self.vae.decode(latents).sample
|
| 257 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 258 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 259 |
+
return image
|
| 260 |
+
|
| 261 |
+
def numpy_to_pil(self, images: np.ndarray) -> List[Image.Image]:
|
| 262 |
+
"""
|
| 263 |
+
Convert a numpy image or a batch of images to a PIL image.
|
| 264 |
+
"""
|
| 265 |
+
if images.ndim == 3:
|
| 266 |
+
images = images[None, ...]
|
| 267 |
+
images = (images * 255).round().astype("uint8")
|
| 268 |
+
if images.shape[-1] == 1:
|
| 269 |
+
# Special case for grayscale (single channel) images.
|
| 270 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
| 271 |
+
else:
|
| 272 |
+
pil_images = [Image.fromarray(image) for image in images]
|
| 273 |
+
return pil_images
|
| 274 |
+
|
| 275 |
+
def run_safety_checker(self, images: np.ndarray):
|
| 276 |
+
if self.safety_checker is not None:
|
| 277 |
+
device = self.device(self.safety_checker)
|
| 278 |
+
dtype = self.dtype(self.safety_checker)
|
| 279 |
+
safety_checker_input = self.feature_extractor(
|
| 280 |
+
self.numpy_to_pil(images), return_tensors="pt"
|
| 281 |
+
).to(device)
|
| 282 |
+
images, has_nsfw_concept = self.safety_checker(
|
| 283 |
+
images=images, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 284 |
+
)
|
| 285 |
+
else:
|
| 286 |
+
has_nsfw_concept = None
|
| 287 |
+
return images, has_nsfw_concept
|
diffusion-decoder/safety_checker_none/config.json
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_commit_hash": null,
|
| 3 |
+
"_name_or_path": "/share/project/quansun/release_hf/Emu2-VisualGeneration/safety_checker",
|
| 4 |
+
"architectures": [
|
| 5 |
+
"StableDiffusionSafetyChecker"
|
| 6 |
+
],
|
| 7 |
+
"initializer_factor": 1.0,
|
| 8 |
+
"logit_scale_init_value": 2.6592,
|
| 9 |
+
"model_type": "clip",
|
| 10 |
+
"projection_dim": 768,
|
| 11 |
+
"text_config": {
|
| 12 |
+
"_name_or_path": "",
|
| 13 |
+
"add_cross_attention": false,
|
| 14 |
+
"architectures": null,
|
| 15 |
+
"attention_dropout": 0.0,
|
| 16 |
+
"bad_words_ids": null,
|
| 17 |
+
"begin_suppress_tokens": null,
|
| 18 |
+
"bos_token_id": 49406,
|
| 19 |
+
"chunk_size_feed_forward": 0,
|
| 20 |
+
"cross_attention_hidden_size": null,
|
| 21 |
+
"decoder_start_token_id": null,
|
| 22 |
+
"diversity_penalty": 0.0,
|
| 23 |
+
"do_sample": false,
|
| 24 |
+
"dropout": 0.0,
|
| 25 |
+
"early_stopping": false,
|
| 26 |
+
"encoder_no_repeat_ngram_size": 0,
|
| 27 |
+
"eos_token_id": 49407,
|
| 28 |
+
"exponential_decay_length_penalty": null,
|
| 29 |
+
"finetuning_task": null,
|
| 30 |
+
"forced_bos_token_id": null,
|
| 31 |
+
"forced_eos_token_id": null,
|
| 32 |
+
"hidden_act": "quick_gelu",
|
| 33 |
+
"hidden_size": 768,
|
| 34 |
+
"id2label": {
|
| 35 |
+
"0": "LABEL_0",
|
| 36 |
+
"1": "LABEL_1"
|
| 37 |
+
},
|
| 38 |
+
"initializer_factor": 1.0,
|
| 39 |
+
"initializer_range": 0.02,
|
| 40 |
+
"intermediate_size": 3072,
|
| 41 |
+
"is_decoder": false,
|
| 42 |
+
"is_encoder_decoder": false,
|
| 43 |
+
"label2id": {
|
| 44 |
+
"LABEL_0": 0,
|
| 45 |
+
"LABEL_1": 1
|
| 46 |
+
},
|
| 47 |
+
"layer_norm_eps": 1e-05,
|
| 48 |
+
"length_penalty": 1.0,
|
| 49 |
+
"max_length": 20,
|
| 50 |
+
"max_position_embeddings": 77,
|
| 51 |
+
"min_length": 0,
|
| 52 |
+
"model_type": "clip_text_model",
|
| 53 |
+
"no_repeat_ngram_size": 0,
|
| 54 |
+
"num_attention_heads": 12,
|
| 55 |
+
"num_beam_groups": 1,
|
| 56 |
+
"num_beams": 1,
|
| 57 |
+
"num_hidden_layers": 12,
|
| 58 |
+
"num_return_sequences": 1,
|
| 59 |
+
"output_attentions": false,
|
| 60 |
+
"output_hidden_states": false,
|
| 61 |
+
"output_scores": false,
|
| 62 |
+
"pad_token_id": 1,
|
| 63 |
+
"prefix": null,
|
| 64 |
+
"problem_type": null,
|
| 65 |
+
"projection_dim": 512,
|
| 66 |
+
"pruned_heads": {},
|
| 67 |
+
"remove_invalid_values": false,
|
| 68 |
+
"repetition_penalty": 1.0,
|
| 69 |
+
"return_dict": true,
|
| 70 |
+
"return_dict_in_generate": false,
|
| 71 |
+
"sep_token_id": null,
|
| 72 |
+
"suppress_tokens": null,
|
| 73 |
+
"task_specific_params": null,
|
| 74 |
+
"temperature": 1.0,
|
| 75 |
+
"tf_legacy_loss": false,
|
| 76 |
+
"tie_encoder_decoder": false,
|
| 77 |
+
"tie_word_embeddings": true,
|
| 78 |
+
"tokenizer_class": null,
|
| 79 |
+
"top_k": 50,
|
| 80 |
+
"top_p": 1.0,
|
| 81 |
+
"torch_dtype": null,
|
| 82 |
+
"torchscript": false,
|
| 83 |
+
"transformers_version": "4.31.0",
|
| 84 |
+
"typical_p": 1.0,
|
| 85 |
+
"use_bfloat16": false,
|
| 86 |
+
"vocab_size": 49408
|
| 87 |
+
},
|
| 88 |
+
"torch_dtype": "bfloat16",
|
| 89 |
+
"transformers_version": null,
|
| 90 |
+
"vision_config": {
|
| 91 |
+
"_name_or_path": "",
|
| 92 |
+
"add_cross_attention": false,
|
| 93 |
+
"architectures": null,
|
| 94 |
+
"attention_dropout": 0.0,
|
| 95 |
+
"bad_words_ids": null,
|
| 96 |
+
"begin_suppress_tokens": null,
|
| 97 |
+
"bos_token_id": null,
|
| 98 |
+
"chunk_size_feed_forward": 0,
|
| 99 |
+
"cross_attention_hidden_size": null,
|
| 100 |
+
"decoder_start_token_id": null,
|
| 101 |
+
"diversity_penalty": 0.0,
|
| 102 |
+
"do_sample": false,
|
| 103 |
+
"dropout": 0.0,
|
| 104 |
+
"early_stopping": false,
|
| 105 |
+
"encoder_no_repeat_ngram_size": 0,
|
| 106 |
+
"eos_token_id": null,
|
| 107 |
+
"exponential_decay_length_penalty": null,
|
| 108 |
+
"finetuning_task": null,
|
| 109 |
+
"forced_bos_token_id": null,
|
| 110 |
+
"forced_eos_token_id": null,
|
| 111 |
+
"hidden_act": "quick_gelu",
|
| 112 |
+
"hidden_size": 1024,
|
| 113 |
+
"id2label": {
|
| 114 |
+
"0": "LABEL_0",
|
| 115 |
+
"1": "LABEL_1"
|
| 116 |
+
},
|
| 117 |
+
"image_size": 224,
|
| 118 |
+
"initializer_factor": 1.0,
|
| 119 |
+
"initializer_range": 0.02,
|
| 120 |
+
"intermediate_size": 4096,
|
| 121 |
+
"is_decoder": false,
|
| 122 |
+
"is_encoder_decoder": false,
|
| 123 |
+
"label2id": {
|
| 124 |
+
"LABEL_0": 0,
|
| 125 |
+
"LABEL_1": 1
|
| 126 |
+
},
|
| 127 |
+
"layer_norm_eps": 1e-05,
|
| 128 |
+
"length_penalty": 1.0,
|
| 129 |
+
"max_length": 20,
|
| 130 |
+
"min_length": 0,
|
| 131 |
+
"model_type": "clip_vision_model",
|
| 132 |
+
"no_repeat_ngram_size": 0,
|
| 133 |
+
"num_attention_heads": 16,
|
| 134 |
+
"num_beam_groups": 1,
|
| 135 |
+
"num_beams": 1,
|
| 136 |
+
"num_channels": 3,
|
| 137 |
+
"num_hidden_layers": 24,
|
| 138 |
+
"num_return_sequences": 1,
|
| 139 |
+
"output_attentions": false,
|
| 140 |
+
"output_hidden_states": false,
|
| 141 |
+
"output_scores": false,
|
| 142 |
+
"pad_token_id": null,
|
| 143 |
+
"patch_size": 14,
|
| 144 |
+
"prefix": null,
|
| 145 |
+
"problem_type": null,
|
| 146 |
+
"projection_dim": 512,
|
| 147 |
+
"pruned_heads": {},
|
| 148 |
+
"remove_invalid_values": false,
|
| 149 |
+
"repetition_penalty": 1.0,
|
| 150 |
+
"return_dict": true,
|
| 151 |
+
"return_dict_in_generate": false,
|
| 152 |
+
"sep_token_id": null,
|
| 153 |
+
"suppress_tokens": null,
|
| 154 |
+
"task_specific_params": null,
|
| 155 |
+
"temperature": 1.0,
|
| 156 |
+
"tf_legacy_loss": false,
|
| 157 |
+
"tie_encoder_decoder": false,
|
| 158 |
+
"tie_word_embeddings": true,
|
| 159 |
+
"tokenizer_class": null,
|
| 160 |
+
"top_k": 50,
|
| 161 |
+
"top_p": 1.0,
|
| 162 |
+
"torch_dtype": null,
|
| 163 |
+
"torchscript": false,
|
| 164 |
+
"transformers_version": "4.31.0",
|
| 165 |
+
"typical_p": 1.0,
|
| 166 |
+
"use_bfloat16": false
|
| 167 |
+
}
|
| 168 |
+
}
|
diffusion-decoder/safety_checker_none/model.bf16.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:013ddb2eb3e3ddb6b91fd739de8abbc8281de91f2ae9f5067ac8586d6aa29cf6
|
| 3 |
+
size 608016672
|
diffusion-decoder/scheduler/scheduler_config.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "EulerDiscreteScheduler",
|
| 3 |
+
"_diffusers_version": "0.21.2",
|
| 4 |
+
"beta_end": 0.012,
|
| 5 |
+
"beta_schedule": "scaled_linear",
|
| 6 |
+
"beta_start": 0.00085,
|
| 7 |
+
"clip_sample": false,
|
| 8 |
+
"interpolation_type": "linear",
|
| 9 |
+
"num_train_timesteps": 1000,
|
| 10 |
+
"prediction_type": "epsilon",
|
| 11 |
+
"sample_max_value": 1.0,
|
| 12 |
+
"set_alpha_to_one": false,
|
| 13 |
+
"skip_prk_steps": true,
|
| 14 |
+
"steps_offset": 1,
|
| 15 |
+
"timestep_spacing": "leading",
|
| 16 |
+
"trained_betas": null,
|
| 17 |
+
"use_karras_sigmas": false
|
| 18 |
+
}
|
diffusion-decoder/tokenizer/added_tokens.json
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"</delimiter_of_multi_objects/>": 32013,
|
| 3 |
+
"</object>": 32012,
|
| 4 |
+
"</phrase>": 32010,
|
| 5 |
+
"<REC>": 32014,
|
| 6 |
+
"<grounding>": 32008,
|
| 7 |
+
"<image>": 32003,
|
| 8 |
+
"<object>": 32011,
|
| 9 |
+
"<patch_index_0000>": 32015,
|
| 10 |
+
"<patch_index_0001>": 32016,
|
| 11 |
+
"<patch_index_0002>": 32017,
|
| 12 |
+
"<patch_index_0003>": 32018,
|
| 13 |
+
"<patch_index_0004>": 32019,
|
| 14 |
+
"<patch_index_0005>": 32020,
|
| 15 |
+
"<patch_index_0006>": 32021,
|
| 16 |
+
"<patch_index_0007>": 32022,
|
| 17 |
+
"<patch_index_0008>": 32023,
|
| 18 |
+
"<patch_index_0009>": 32024,
|
| 19 |
+
"<patch_index_0010>": 32025,
|
| 20 |
+
"<patch_index_0011>": 32026,
|
| 21 |
+
"<patch_index_0012>": 32027,
|
| 22 |
+
"<patch_index_0013>": 32028,
|
| 23 |
+
"<patch_index_0014>": 32029,
|
| 24 |
+
"<patch_index_0015>": 32030,
|
| 25 |
+
"<patch_index_0016>": 32031,
|
| 26 |
+
"<patch_index_0017>": 32032,
|
| 27 |
+
"<patch_index_0018>": 32033,
|
| 28 |
+
"<patch_index_0019>": 32034,
|
| 29 |
+
"<patch_index_0020>": 32035,
|
| 30 |
+
"<patch_index_0021>": 32036,
|
| 31 |
+
"<patch_index_0022>": 32037,
|
| 32 |
+
"<patch_index_0023>": 32038,
|
| 33 |
+
"<patch_index_0024>": 32039,
|
| 34 |
+
"<patch_index_0025>": 32040,
|
| 35 |
+
"<patch_index_0026>": 32041,
|
| 36 |
+
"<patch_index_0027>": 32042,
|
| 37 |
+
"<patch_index_0028>": 32043,
|
| 38 |
+
"<patch_index_0029>": 32044,
|
| 39 |
+
"<patch_index_0030>": 32045,
|
| 40 |
+
"<patch_index_0031>": 32046,
|
| 41 |
+
"<patch_index_0032>": 32047,
|
| 42 |
+
"<patch_index_0033>": 32048,
|
| 43 |
+
"<patch_index_0034>": 32049,
|
| 44 |
+
"<patch_index_0035>": 32050,
|
| 45 |
+
"<patch_index_0036>": 32051,
|
| 46 |
+
"<patch_index_0037>": 32052,
|
| 47 |
+
"<patch_index_0038>": 32053,
|
| 48 |
+
"<patch_index_0039>": 32054,
|
| 49 |
+
"<patch_index_0040>": 32055,
|
| 50 |
+
"<patch_index_0041>": 32056,
|
| 51 |
+
"<patch_index_0042>": 32057,
|
| 52 |
+
"<patch_index_0043>": 32058,
|
| 53 |
+
"<patch_index_0044>": 32059,
|
| 54 |
+
"<patch_index_0045>": 32060,
|
| 55 |
+
"<patch_index_0046>": 32061,
|
| 56 |
+
"<patch_index_0047>": 32062,
|
| 57 |
+
"<patch_index_0048>": 32063,
|
| 58 |
+
"<patch_index_0049>": 32064,
|
| 59 |
+
"<patch_index_0050>": 32065,
|
| 60 |
+
"<patch_index_0051>": 32066,
|
| 61 |
+
"<patch_index_0052>": 32067,
|
| 62 |
+
"<patch_index_0053>": 32068,
|
| 63 |
+
"<patch_index_0054>": 32069,
|
| 64 |
+
"<patch_index_0055>": 32070,
|
| 65 |
+
"<patch_index_0056>": 32071,
|
| 66 |
+
"<patch_index_0057>": 32072,
|
| 67 |
+
"<patch_index_0058>": 32073,
|
| 68 |
+
"<patch_index_0059>": 32074,
|
| 69 |
+
"<patch_index_0060>": 32075,
|
| 70 |
+
"<patch_index_0061>": 32076,
|
| 71 |
+
"<patch_index_0062>": 32077,
|
| 72 |
+
"<patch_index_0063>": 32078,
|
| 73 |
+
"<patch_index_0064>": 32079,
|
| 74 |
+
"<patch_index_0065>": 32080,
|
| 75 |
+
"<patch_index_0066>": 32081,
|
| 76 |
+
"<patch_index_0067>": 32082,
|
| 77 |
+
"<patch_index_0068>": 32083,
|
| 78 |
+
"<patch_index_0069>": 32084,
|
| 79 |
+
"<patch_index_0070>": 32085,
|
| 80 |
+
"<patch_index_0071>": 32086,
|
| 81 |
+
"<patch_index_0072>": 32087,
|
| 82 |
+
"<patch_index_0073>": 32088,
|
| 83 |
+
"<patch_index_0074>": 32089,
|
| 84 |
+
"<patch_index_0075>": 32090,
|
| 85 |
+
"<patch_index_0076>": 32091,
|
| 86 |
+
"<patch_index_0077>": 32092,
|
| 87 |
+
"<patch_index_0078>": 32093,
|
| 88 |
+
"<patch_index_0079>": 32094,
|
| 89 |
+
"<patch_index_0080>": 32095,
|
| 90 |
+
"<patch_index_0081>": 32096,
|
| 91 |
+
"<patch_index_0082>": 32097,
|
| 92 |
+
"<patch_index_0083>": 32098,
|
| 93 |
+
"<patch_index_0084>": 32099,
|
| 94 |
+
"<patch_index_0085>": 32100,
|
| 95 |
+
"<patch_index_0086>": 32101,
|
| 96 |
+
"<patch_index_0087>": 32102,
|
| 97 |
+
"<patch_index_0088>": 32103,
|
| 98 |
+
"<patch_index_0089>": 32104,
|
| 99 |
+
"<patch_index_0090>": 32105,
|
| 100 |
+
"<patch_index_0091>": 32106,
|
| 101 |
+
"<patch_index_0092>": 32107,
|
| 102 |
+
"<patch_index_0093>": 32108,
|
| 103 |
+
"<patch_index_0094>": 32109,
|
| 104 |
+
"<patch_index_0095>": 32110,
|
| 105 |
+
"<patch_index_0096>": 32111,
|
| 106 |
+
"<patch_index_0097>": 32112,
|
| 107 |
+
"<patch_index_0098>": 32113,
|
| 108 |
+
"<patch_index_0099>": 32114,
|
| 109 |
+
"<patch_index_0100>": 32115,
|
| 110 |
+
"<patch_index_0101>": 32116,
|
| 111 |
+
"<patch_index_0102>": 32117,
|
| 112 |
+
"<patch_index_0103>": 32118,
|
| 113 |
+
"<patch_index_0104>": 32119,
|
| 114 |
+
"<patch_index_0105>": 32120,
|
| 115 |
+
"<patch_index_0106>": 32121,
|
| 116 |
+
"<patch_index_0107>": 32122,
|
| 117 |
+
"<patch_index_0108>": 32123,
|
| 118 |
+
"<patch_index_0109>": 32124,
|
| 119 |
+
"<patch_index_0110>": 32125,
|
| 120 |
+
"<patch_index_0111>": 32126,
|
| 121 |
+
"<patch_index_0112>": 32127,
|
| 122 |
+
"<patch_index_0113>": 32128,
|
| 123 |
+
"<patch_index_0114>": 32129,
|
| 124 |
+
"<patch_index_0115>": 32130,
|
| 125 |
+
"<patch_index_0116>": 32131,
|
| 126 |
+
"<patch_index_0117>": 32132,
|
| 127 |
+
"<patch_index_0118>": 32133,
|
| 128 |
+
"<patch_index_0119>": 32134,
|
| 129 |
+
"<patch_index_0120>": 32135,
|
| 130 |
+
"<patch_index_0121>": 32136,
|
| 131 |
+
"<patch_index_0122>": 32137,
|
| 132 |
+
"<patch_index_0123>": 32138,
|
| 133 |
+
"<patch_index_0124>": 32139,
|
| 134 |
+
"<patch_index_0125>": 32140,
|
| 135 |
+
"<patch_index_0126>": 32141,
|
| 136 |
+
"<patch_index_0127>": 32142,
|
| 137 |
+
"<patch_index_0128>": 32143,
|
| 138 |
+
"<patch_index_0129>": 32144,
|
| 139 |
+
"<patch_index_0130>": 32145,
|
| 140 |
+
"<patch_index_0131>": 32146,
|
| 141 |
+
"<patch_index_0132>": 32147,
|
| 142 |
+
"<patch_index_0133>": 32148,
|
| 143 |
+
"<patch_index_0134>": 32149,
|
| 144 |
+
"<patch_index_0135>": 32150,
|
| 145 |
+
"<patch_index_0136>": 32151,
|
| 146 |
+
"<patch_index_0137>": 32152,
|
| 147 |
+
"<patch_index_0138>": 32153,
|
| 148 |
+
"<patch_index_0139>": 32154,
|
| 149 |
+
"<patch_index_0140>": 32155,
|
| 150 |
+
"<patch_index_0141>": 32156,
|
| 151 |
+
"<patch_index_0142>": 32157,
|
| 152 |
+
"<patch_index_0143>": 32158,
|
| 153 |
+
"<patch_index_0144>": 32159,
|
| 154 |
+
"<patch_index_0145>": 32160,
|
| 155 |
+
"<patch_index_0146>": 32161,
|
| 156 |
+
"<patch_index_0147>": 32162,
|
| 157 |
+
"<patch_index_0148>": 32163,
|
| 158 |
+
"<patch_index_0149>": 32164,
|
| 159 |
+
"<patch_index_0150>": 32165,
|
| 160 |
+
"<patch_index_0151>": 32166,
|
| 161 |
+
"<patch_index_0152>": 32167,
|
| 162 |
+
"<patch_index_0153>": 32168,
|
| 163 |
+
"<patch_index_0154>": 32169,
|
| 164 |
+
"<patch_index_0155>": 32170,
|
| 165 |
+
"<patch_index_0156>": 32171,
|
| 166 |
+
"<patch_index_0157>": 32172,
|
| 167 |
+
"<patch_index_0158>": 32173,
|
| 168 |
+
"<patch_index_0159>": 32174,
|
| 169 |
+
"<patch_index_0160>": 32175,
|
| 170 |
+
"<patch_index_0161>": 32176,
|
| 171 |
+
"<patch_index_0162>": 32177,
|
| 172 |
+
"<patch_index_0163>": 32178,
|
| 173 |
+
"<patch_index_0164>": 32179,
|
| 174 |
+
"<patch_index_0165>": 32180,
|
| 175 |
+
"<patch_index_0166>": 32181,
|
| 176 |
+
"<patch_index_0167>": 32182,
|
| 177 |
+
"<patch_index_0168>": 32183,
|
| 178 |
+
"<patch_index_0169>": 32184,
|
| 179 |
+
"<patch_index_0170>": 32185,
|
| 180 |
+
"<patch_index_0171>": 32186,
|
| 181 |
+
"<patch_index_0172>": 32187,
|
| 182 |
+
"<patch_index_0173>": 32188,
|
| 183 |
+
"<patch_index_0174>": 32189,
|
| 184 |
+
"<patch_index_0175>": 32190,
|
| 185 |
+
"<patch_index_0176>": 32191,
|
| 186 |
+
"<patch_index_0177>": 32192,
|
| 187 |
+
"<patch_index_0178>": 32193,
|
| 188 |
+
"<patch_index_0179>": 32194,
|
| 189 |
+
"<patch_index_0180>": 32195,
|
| 190 |
+
"<patch_index_0181>": 32196,
|
| 191 |
+
"<patch_index_0182>": 32197,
|
| 192 |
+
"<patch_index_0183>": 32198,
|
| 193 |
+
"<patch_index_0184>": 32199,
|
| 194 |
+
"<patch_index_0185>": 32200,
|
| 195 |
+
"<patch_index_0186>": 32201,
|
| 196 |
+
"<patch_index_0187>": 32202,
|
| 197 |
+
"<patch_index_0188>": 32203,
|
| 198 |
+
"<patch_index_0189>": 32204,
|
| 199 |
+
"<patch_index_0190>": 32205,
|
| 200 |
+
"<patch_index_0191>": 32206,
|
| 201 |
+
"<patch_index_0192>": 32207,
|
| 202 |
+
"<patch_index_0193>": 32208,
|
| 203 |
+
"<patch_index_0194>": 32209,
|
| 204 |
+
"<patch_index_0195>": 32210,
|
| 205 |
+
"<patch_index_0196>": 32211,
|
| 206 |
+
"<patch_index_0197>": 32212,
|
| 207 |
+
"<patch_index_0198>": 32213,
|
| 208 |
+
"<patch_index_0199>": 32214,
|
| 209 |
+
"<patch_index_0200>": 32215,
|
| 210 |
+
"<patch_index_0201>": 32216,
|
| 211 |
+
"<patch_index_0202>": 32217,
|
| 212 |
+
"<patch_index_0203>": 32218,
|
| 213 |
+
"<patch_index_0204>": 32219,
|
| 214 |
+
"<patch_index_0205>": 32220,
|
| 215 |
+
"<patch_index_0206>": 32221,
|
| 216 |
+
"<patch_index_0207>": 32222,
|
| 217 |
+
"<patch_index_0208>": 32223,
|
| 218 |
+
"<patch_index_0209>": 32224,
|
| 219 |
+
"<patch_index_0210>": 32225,
|
| 220 |
+
"<patch_index_0211>": 32226,
|
| 221 |
+
"<patch_index_0212>": 32227,
|
| 222 |
+
"<patch_index_0213>": 32228,
|
| 223 |
+
"<patch_index_0214>": 32229,
|
| 224 |
+
"<patch_index_0215>": 32230,
|
| 225 |
+
"<patch_index_0216>": 32231,
|
| 226 |
+
"<patch_index_0217>": 32232,
|
| 227 |
+
"<patch_index_0218>": 32233,
|
| 228 |
+
"<patch_index_0219>": 32234,
|
| 229 |
+
"<patch_index_0220>": 32235,
|
| 230 |
+
"<patch_index_0221>": 32236,
|
| 231 |
+
"<patch_index_0222>": 32237,
|
| 232 |
+
"<patch_index_0223>": 32238,
|
| 233 |
+
"<patch_index_0224>": 32239,
|
| 234 |
+
"<patch_index_0225>": 32240,
|
| 235 |
+
"<patch_index_0226>": 32241,
|
| 236 |
+
"<patch_index_0227>": 32242,
|
| 237 |
+
"<patch_index_0228>": 32243,
|
| 238 |
+
"<patch_index_0229>": 32244,
|
| 239 |
+
"<patch_index_0230>": 32245,
|
| 240 |
+
"<patch_index_0231>": 32246,
|
| 241 |
+
"<patch_index_0232>": 32247,
|
| 242 |
+
"<patch_index_0233>": 32248,
|
| 243 |
+
"<patch_index_0234>": 32249,
|
| 244 |
+
"<patch_index_0235>": 32250,
|
| 245 |
+
"<patch_index_0236>": 32251,
|
| 246 |
+
"<patch_index_0237>": 32252,
|
| 247 |
+
"<patch_index_0238>": 32253,
|
| 248 |
+
"<patch_index_0239>": 32254,
|
| 249 |
+
"<patch_index_0240>": 32255,
|
| 250 |
+
"<patch_index_0241>": 32256,
|
| 251 |
+
"<patch_index_0242>": 32257,
|
| 252 |
+
"<patch_index_0243>": 32258,
|
| 253 |
+
"<patch_index_0244>": 32259,
|
| 254 |
+
"<patch_index_0245>": 32260,
|
| 255 |
+
"<patch_index_0246>": 32261,
|
| 256 |
+
"<patch_index_0247>": 32262,
|
| 257 |
+
"<patch_index_0248>": 32263,
|
| 258 |
+
"<patch_index_0249>": 32264,
|
| 259 |
+
"<patch_index_0250>": 32265,
|
| 260 |
+
"<patch_index_0251>": 32266,
|
| 261 |
+
"<patch_index_0252>": 32267,
|
| 262 |
+
"<patch_index_0253>": 32268,
|
| 263 |
+
"<patch_index_0254>": 32269,
|
| 264 |
+
"<patch_index_0255>": 32270,
|
| 265 |
+
"<patch_index_0256>": 32271,
|
| 266 |
+
"<phrase>": 32009,
|
| 267 |
+
"[/IMG]": 32002,
|
| 268 |
+
"[/gIMG]": 32005,
|
| 269 |
+
"[EOC]": 32006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ding>",
|
| 11 |
+
"<phrase>",
|
| 12 |
+
"</phrase>",
|
| 13 |
+
"<object>",
|
| 14 |
+
"</object>",
|
| 15 |
+
"</delimiter_of_multi_objects/>",
|
| 16 |
+
"<REC>",
|
| 17 |
+
"<patch_index_0000>",
|
| 18 |
+
"<patch_index_0001>",
|
| 19 |
+
"<patch_index_0002>",
|
| 20 |
+
"<patch_index_0003>",
|
| 21 |
+
"<patch_index_0004>",
|
| 22 |
+
"<patch_index_0005>",
|
| 23 |
+
"<patch_index_0006>",
|
| 24 |
+
"<patch_index_0007>",
|
| 25 |
+
"<patch_index_0008>",
|
| 26 |
+
"<patch_index_0009>",
|
| 27 |
+
"<patch_index_0010>",
|
| 28 |
+
"<patch_index_0011>",
|
| 29 |
+
"<patch_index_0012>",
|
| 30 |
+
"<patch_index_0013>",
|
| 31 |
+
"<patch_index_0014>",
|
| 32 |
+
"<patch_index_0015>",
|
| 33 |
+
"<patch_index_0016>",
|
| 34 |
+
"<patch_index_0017>",
|
| 35 |
+
"<patch_index_0018>",
|
| 36 |
+
"<patch_index_0019>",
|
| 37 |
+
"<patch_index_0020>",
|
| 38 |
+
"<patch_index_0021>",
|
| 39 |
+
"<patch_index_0022>",
|
| 40 |
+
"<patch_index_0023>",
|
| 41 |
+
"<patch_index_0024>",
|
| 42 |
+
"<patch_index_0025>",
|
| 43 |
+
"<patch_index_0026>",
|
| 44 |
+
"<patch_index_0027>",
|
| 45 |
+
"<patch_index_0028>",
|
| 46 |
+
"<patch_index_0029>",
|
| 47 |
+
"<patch_index_0030>",
|
| 48 |
+
"<patch_index_0031>",
|
| 49 |
+
"<patch_index_0032>",
|
| 50 |
+
"<patch_index_0033>",
|
| 51 |
+
"<patch_index_0034>",
|
| 52 |
+
"<patch_index_0035>",
|
| 53 |
+
"<patch_index_0036>",
|
| 54 |
+
"<patch_index_0037>",
|
| 55 |
+
"<patch_index_0038>",
|
| 56 |
+
"<patch_index_0039>",
|
| 57 |
+
"<patch_index_0040>",
|
| 58 |
+
"<patch_index_0041>",
|
| 59 |
+
"<patch_index_0042>",
|
| 60 |
+
"<patch_index_0043>",
|
| 61 |
+
"<patch_index_0044>",
|
| 62 |
+
"<patch_index_0045>",
|
| 63 |
+
"<patch_index_0046>",
|
| 64 |
+
"<patch_index_0047>",
|
| 65 |
+
"<patch_index_0048>",
|
| 66 |
+
"<patch_index_0049>",
|
| 67 |
+
"<patch_index_0050>",
|
| 68 |
+
"<patch_index_0051>",
|
| 69 |
+
"<patch_index_0052>",
|
| 70 |
+
"<patch_index_0053>",
|
| 71 |
+
"<patch_index_0054>",
|
| 72 |
+
"<patch_index_0055>",
|
| 73 |
+
"<patch_index_0056>",
|
| 74 |
+
"<patch_index_0057>",
|
| 75 |
+
"<patch_index_0058>",
|
| 76 |
+
"<patch_index_0059>",
|
| 77 |
+
"<patch_index_0060>",
|
| 78 |
+
"<patch_index_0061>",
|
| 79 |
+
"<patch_index_0062>",
|
| 80 |
+
"<patch_index_0063>",
|
| 81 |
+
"<patch_index_0064>",
|
| 82 |
+
"<patch_index_0065>",
|
| 83 |
+
"<patch_index_0066>",
|
| 84 |
+
"<patch_index_0067>",
|
| 85 |
+
"<patch_index_0068>",
|
| 86 |
+
"<patch_index_0069>",
|
| 87 |
+
"<patch_index_0070>",
|
| 88 |
+
"<patch_index_0071>",
|
| 89 |
+
"<patch_index_0072>",
|
| 90 |
+
"<patch_index_0073>",
|
| 91 |
+
"<patch_index_0074>",
|
| 92 |
+
"<patch_index_0075>",
|
| 93 |
+
"<patch_index_0076>",
|
| 94 |
+
"<patch_index_0077>",
|
| 95 |
+
"<patch_index_0078>",
|
| 96 |
+
"<patch_index_0079>",
|
| 97 |
+
"<patch_index_0080>",
|
| 98 |
+
"<patch_index_0081>",
|
| 99 |
+
"<patch_index_0082>",
|
| 100 |
+
"<patch_index_0083>",
|
| 101 |
+
"<patch_index_0084>",
|
| 102 |
+
"<patch_index_0085>",
|
| 103 |
+
"<patch_index_0086>",
|
| 104 |
+
"<patch_index_0087>",
|
| 105 |
+
"<patch_index_0088>",
|
| 106 |
+
"<patch_index_0089>",
|
| 107 |
+
"<patch_index_0090>",
|
| 108 |
+
"<patch_index_0091>",
|
| 109 |
+
"<patch_index_0092>",
|
| 110 |
+
"<patch_index_0093>",
|
| 111 |
+
"<patch_index_0094>",
|
| 112 |
+
"<patch_index_0095>",
|
| 113 |
+
"<patch_index_0096>",
|
| 114 |
+
"<patch_index_0097>",
|
| 115 |
+
"<patch_index_0098>",
|
| 116 |
+
"<patch_index_0099>",
|
| 117 |
+
"<patch_index_0100>",
|
| 118 |
+
"<patch_index_0101>",
|
| 119 |
+
"<patch_index_0102>",
|
| 120 |
+
"<patch_index_0103>",
|
| 121 |
+
"<patch_index_0104>",
|
| 122 |
+
"<patch_index_0105>",
|
| 123 |
+
"<patch_index_0106>",
|
| 124 |
+
"<patch_index_0107>",
|
| 125 |
+
"<patch_index_0108>",
|
| 126 |
+
"<patch_index_0109>",
|
| 127 |
+
"<patch_index_0110>",
|
| 128 |
+
"<patch_index_0111>",
|
| 129 |
+
"<patch_index_0112>",
|
| 130 |
+
"<patch_index_0113>",
|
| 131 |
+
"<patch_index_0114>",
|
| 132 |
+
"<patch_index_0115>",
|
| 133 |
+
"<patch_index_0116>",
|
| 134 |
+
"<patch_index_0117>",
|
| 135 |
+
"<patch_index_0118>",
|
| 136 |
+
"<patch_index_0119>",
|
| 137 |
+
"<patch_index_0120>",
|
| 138 |
+
"<patch_index_0121>",
|
| 139 |
+
"<patch_index_0122>",
|
| 140 |
+
"<patch_index_0123>",
|
| 141 |
+
"<patch_index_0124>",
|
| 142 |
+
"<patch_index_0125>",
|
| 143 |
+
"<patch_index_0126>",
|
| 144 |
+
"<patch_index_0127>",
|
| 145 |
+
"<patch_index_0128>",
|
| 146 |
+
"<patch_index_0129>",
|
| 147 |
+
"<patch_index_0130>",
|
| 148 |
+
"<patch_index_0131>",
|
| 149 |
+
"<patch_index_0132>",
|
| 150 |
+
"<patch_index_0133>",
|
| 151 |
+
"<patch_index_0134>",
|
| 152 |
+
"<patch_index_0135>",
|
| 153 |
+
"<patch_index_0136>",
|
| 154 |
+
"<patch_index_0137>",
|
| 155 |
+
"<patch_index_0138>",
|
| 156 |
+
"<patch_index_0139>",
|
| 157 |
+
"<patch_index_0140>",
|
| 158 |
+
"<patch_index_0141>",
|
| 159 |
+
"<patch_index_0142>",
|
| 160 |
+
"<patch_index_0143>",
|
| 161 |
+
"<patch_index_0144>",
|
| 162 |
+
"<patch_index_0145>",
|
| 163 |
+
"<patch_index_0146>",
|
| 164 |
+
"<patch_index_0147>",
|
| 165 |
+
"<patch_index_0148>",
|
| 166 |
+
"<patch_index_0149>",
|
| 167 |
+
"<patch_index_0150>",
|
| 168 |
+
"<patch_index_0151>",
|
| 169 |
+
"<patch_index_0152>",
|
| 170 |
+
"<patch_index_0153>",
|
| 171 |
+
"<patch_index_0154>",
|
| 172 |
+
"<patch_index_0155>",
|
| 173 |
+
"<patch_index_0156>",
|
| 174 |
+
"<patch_index_0157>",
|
| 175 |
+
"<patch_index_0158>",
|
| 176 |
+
"<patch_index_0159>",
|
| 177 |
+
"<patch_index_0160>",
|
| 178 |
+
"<patch_index_0161>",
|
| 179 |
+
"<patch_index_0162>",
|
| 180 |
+
"<patch_index_0163>",
|
| 181 |
+
"<patch_index_0164>",
|
| 182 |
+
"<patch_index_0165>",
|
| 183 |
+
"<patch_index_0166>",
|
| 184 |
+
"<patch_index_0167>",
|
| 185 |
+
"<patch_index_0168>",
|
| 186 |
+
"<patch_index_0169>",
|
| 187 |
+
"<patch_index_0170>",
|
| 188 |
+
"<patch_index_0171>",
|
| 189 |
+
"<patch_index_0172>",
|
| 190 |
+
"<patch_index_0173>",
|
| 191 |
+
"<patch_index_0174>",
|
| 192 |
+
"<patch_index_0175>",
|
| 193 |
+
"<patch_index_0176>",
|
| 194 |
+
"<patch_index_0177>",
|
| 195 |
+
"<patch_index_0178>",
|
| 196 |
+
"<patch_index_0179>",
|
| 197 |
+
"<patch_index_0180>",
|
| 198 |
+
"<patch_index_0181>",
|
| 199 |
+
"<patch_index_0182>",
|
| 200 |
+
"<patch_index_0183>",
|
| 201 |
+
"<patch_index_0184>",
|
| 202 |
+
"<patch_index_0185>",
|
| 203 |
+
"<patch_index_0186>",
|
| 204 |
+
"<patch_index_0187>",
|
| 205 |
+
"<patch_index_0188>",
|
| 206 |
+
"<patch_index_0189>",
|
| 207 |
+
"<patch_index_0190>",
|
| 208 |
+
"<patch_index_0191>",
|
| 209 |
+
"<patch_index_0192>",
|
| 210 |
+
"<patch_index_0193>",
|
| 211 |
+
"<patch_index_0194>",
|
| 212 |
+
"<patch_index_0195>",
|
| 213 |
+
"<patch_index_0196>",
|
| 214 |
+
"<patch_index_0197>",
|
| 215 |
+
"<patch_index_0198>",
|
| 216 |
+
"<patch_index_0199>",
|
| 217 |
+
"<patch_index_0200>",
|
| 218 |
+
"<patch_index_0201>",
|
| 219 |
+
"<patch_index_0202>",
|
| 220 |
+
"<patch_index_0203>",
|
| 221 |
+
"<patch_index_0204>",
|
| 222 |
+
"<patch_index_0205>",
|
| 223 |
+
"<patch_index_0206>",
|
| 224 |
+
"<patch_index_0207>",
|
| 225 |
+
"<patch_index_0208>",
|
| 226 |
+
"<patch_index_0209>",
|
| 227 |
+
"<patch_index_0210>",
|
| 228 |
+
"<patch_index_0211>",
|
| 229 |
+
"<patch_index_0212>",
|
| 230 |
+
"<patch_index_0213>",
|
| 231 |
+
"<patch_index_0214>",
|
| 232 |
+
"<patch_index_0215>",
|
| 233 |
+
"<patch_index_0216>",
|
| 234 |
+
"<patch_index_0217>",
|
| 235 |
+
"<patch_index_0218>",
|
| 236 |
+
"<patch_index_0219>",
|
| 237 |
+
"<patch_index_0220>",
|
| 238 |
+
"<patch_index_0221>",
|
| 239 |
+
"<patch_index_0222>",
|
| 240 |
+
"<patch_index_0223>",
|
| 241 |
+
"<patch_index_0224>",
|
| 242 |
+
"<patch_index_0225>",
|
| 243 |
+
"<patch_index_0226>",
|
| 244 |
+
"<patch_index_0227>",
|
| 245 |
+
"<patch_index_0228>",
|
| 246 |
+
"<patch_index_0229>",
|
| 247 |
+
"<patch_index_0230>",
|
| 248 |
+
"<patch_index_0231>",
|
| 249 |
+
"<patch_index_0232>",
|
| 250 |
+
"<patch_index_0233>",
|
| 251 |
+
"<patch_index_0234>",
|
| 252 |
+
"<patch_index_0235>",
|
| 253 |
+
"<patch_index_0236>",
|
| 254 |
+
"<patch_index_0237>",
|
| 255 |
+
"<patch_index_0238>",
|
| 256 |
+
"<patch_index_0239>",
|
| 257 |
+
"<patch_index_0240>",
|
| 258 |
+
"<patch_index_0241>",
|
| 259 |
+
"<patch_index_0242>",
|
| 260 |
+
"<patch_index_0243>",
|
| 261 |
+
"<patch_index_0244>",
|
| 262 |
+
"<patch_index_0245>",
|
| 263 |
+
"<patch_index_0246>",
|
| 264 |
+
"<patch_index_0247>",
|
| 265 |
+
"<patch_index_0248>",
|
| 266 |
+
"<patch_index_0249>",
|
| 267 |
+
"<patch_index_0250>",
|
| 268 |
+
"<patch_index_0251>",
|
| 269 |
+
"<patch_index_0252>",
|
| 270 |
+
"<patch_index_0253>",
|
| 271 |
+
"<patch_index_0254>",
|
| 272 |
+
"<patch_index_0255>",
|
| 273 |
+
"<patch_index_0256>"
|
| 274 |
+
],
|
| 275 |
+
"bos_token": "<s>",
|
| 276 |
+
"eos_token": "</s>",
|
| 277 |
+
"pad_token": "[PAD]",
|
| 278 |
+
"unk_token": {
|
| 279 |
+
"content": "<unk>",
|
| 280 |
+
"lstrip": false,
|
| 281 |
+
"normalized": true,
|
| 282 |
+
"rstrip": false,
|
| 283 |
+
"single_word": false
|
| 284 |
+
}
|
| 285 |
+
}
|
diffusion-decoder/tokenizer/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffusion-decoder/tokenizer/tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
|
| 3 |
+
size 499723
|
diffusion-decoder/tokenizer/tokenizer_config.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": true,
|
| 3 |
+
"add_eos_token": false,
|
| 4 |
+
"bos_token": {
|
| 5 |
+
"__type": "AddedToken",
|
| 6 |
+
"content": "<s>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": true,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false
|
| 11 |
+
},
|
| 12 |
+
"clean_up_tokenization_spaces": false,
|
| 13 |
+
"eos_token": {
|
| 14 |
+
"__type": "AddedToken",
|
| 15 |
+
"content": "</s>",
|
| 16 |
+
"lstrip": false,
|
| 17 |
+
"normalized": true,
|
| 18 |
+
"rstrip": false,
|
| 19 |
+
"single_word": false
|
| 20 |
+
},
|
| 21 |
+
"legacy": true,
|
| 22 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 23 |
+
"pad_token": null,
|
| 24 |
+
"sp_model_kwargs": {},
|
| 25 |
+
"tokenizer_class": "LlamaTokenizer",
|
| 26 |
+
"unk_token": {
|
| 27 |
+
"__type": "AddedToken",
|
| 28 |
+
"content": "<unk>",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": true,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false
|
| 33 |
+
}
|
| 34 |
+
}
|
diffusion-decoder/unet/config.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "UNet2DConditionModel",
|
| 3 |
+
"_diffusers_version": "0.21.2",
|
| 4 |
+
"_name_or_path": "/share/project/quansun/release_hf/Emu2-VisualGeneration/unet",
|
| 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": 1792,
|
| 26 |
+
"cross_attention_norm": null,
|
| 27 |
+
"down_block_types": [
|
| 28 |
+
"DownBlock2D",
|
| 29 |
+
"CrossAttnDownBlock2D",
|
| 30 |
+
"CrossAttnDownBlock2D"
|
| 31 |
+
],
|
| 32 |
+
"downsample_padding": 1,
|
| 33 |
+
"dropout": 0.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": 3328,
|
| 51 |
+
"resnet_out_scale_factor": 1.0,
|
| 52 |
+
"resnet_skip_time_act": false,
|
| 53 |
+
"resnet_time_scale_shift": "default",
|
| 54 |
+
"sample_size": 128,
|
| 55 |
+
"time_cond_proj_dim": null,
|
| 56 |
+
"time_embedding_act_fn": null,
|
| 57 |
+
"time_embedding_dim": null,
|
| 58 |
+
"time_embedding_type": "positional",
|
| 59 |
+
"timestep_post_act": null,
|
| 60 |
+
"transformer_layers_per_block": [
|
| 61 |
+
1,
|
| 62 |
+
2,
|
| 63 |
+
10
|
| 64 |
+
],
|
| 65 |
+
"up_block_types": [
|
| 66 |
+
"CrossAttnUpBlock2D",
|
| 67 |
+
"CrossAttnUpBlock2D",
|
| 68 |
+
"UpBlock2D"
|
| 69 |
+
],
|
| 70 |
+
"upcast_attention": null,
|
| 71 |
+
"use_linear_projection": true
|
| 72 |
+
}
|
diffusion-decoder/unet/diffusion_pytorch_model.bf16.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:67215fe9e8e24202651fce2ff72203d21bdb7986a88ec062f72cc94f6040a314
|
| 3 |
+
size 5051265352
|
diffusion-decoder/vae/config.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "AutoencoderKL",
|
| 3 |
+
"_diffusers_version": "0.21.2",
|
| 4 |
+
"_name_or_path": "/share/project/quansun/release_hf/Emu2-VisualGeneration/vae",
|
| 5 |
+
"act_fn": "silu",
|
| 6 |
+
"block_out_channels": [
|
| 7 |
+
128,
|
| 8 |
+
256,
|
| 9 |
+
512,
|
| 10 |
+
512
|
| 11 |
+
],
|
| 12 |
+
"down_block_types": [
|
| 13 |
+
"DownEncoderBlock2D",
|
| 14 |
+
"DownEncoderBlock2D",
|
| 15 |
+
"DownEncoderBlock2D",
|
| 16 |
+
"DownEncoderBlock2D"
|
| 17 |
+
],
|
| 18 |
+
"force_upcast": true,
|
| 19 |
+
"in_channels": 3,
|
| 20 |
+
"latent_channels": 4,
|
| 21 |
+
"layers_per_block": 2,
|
| 22 |
+
"norm_num_groups": 32,
|
| 23 |
+
"out_channels": 3,
|
| 24 |
+
"sample_size": 1024,
|
| 25 |
+
"scaling_factor": 0.13025,
|
| 26 |
+
"up_block_types": [
|
| 27 |
+
"UpDecoderBlock2D",
|
| 28 |
+
"UpDecoderBlock2D",
|
| 29 |
+
"UpDecoderBlock2D",
|
| 30 |
+
"UpDecoderBlock2D"
|
| 31 |
+
]
|
| 32 |
+
}
|
diffusion-decoder/vae/diffusion_pytorch_model.bf16.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2741af7e84fe3b0a7aee02f89fa34c0858ed55f5782aab5931b94938983652da
|
| 3 |
+
size 167335590
|
generation_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attn_implementation": "flash_attention_2",
|
| 3 |
+
"bos_token_id": 151643,
|
| 4 |
+
"do_sample": true,
|
| 5 |
+
"eos_token_id": [
|
| 6 |
+
151645,
|
| 7 |
+
151643
|
| 8 |
+
],
|
| 9 |
+
"pad_token_id": 151643,
|
| 10 |
+
"repetition_penalty": 1.05,
|
| 11 |
+
"temperature": 1e-06,
|
| 12 |
+
"transformers_version": "4.51.3"
|
| 13 |
+
}
|
global_step1400/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:60a4196b8558c400d154dda4fe9d7add691b9c4a5450fc76209bf3031546b077
|
| 3 |
+
size 16348726092
|
global_step1400/mp_rank_00_model_states.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6128e1d508ced9f321bbb572e1465fda51c344b0a1d5f41a987d5d4c58fb97d5
|
| 3 |
+
size 18934248688
|
latest
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
global_step1400
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model-00001-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6ab4e02b1df4a3d27a9ae23b4f534318573c1e3f27c129b2b31bce5a3c47721
|
| 3 |
+
size 4996915272
|
model-00002-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3508125a89e376c78e8583c5814b75b127f7c61e9ebb1f5f92f0c2af0d173e5e
|
| 3 |
+
size 4988490264
|
model-00003-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dead7b0d328369211e344f81b9b95c11d38e0a68d20710564ba623b6f0cfc93b
|
| 3 |
+
size 4945870360
|
model-00004-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3d9ce9b5b0894ff19d98a836318581b874c210850f8e225ad5b0e9471de0b2e6
|
| 3 |
+
size 4623576184
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
rng_state.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a0efce065637df5ea1f0a02253f4de6da145affd4b5ab56df75e42af697e6a09
|
| 3 |
+
size 14244
|
scheduler.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d154ed8833a95231b13495341f4d5eda62192ea0a3a9aa2af2ce186e4e571f34
|
| 3 |
+
size 1064
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"[IMG]",
|
| 4 |
+
"[/IMG]",
|
| 5 |
+
"<image>"
|
| 6 |
+
],
|
| 7 |
+
"eos_token": {
|
| 8 |
+
"content": "<|im_end|>",
|
| 9 |
+
"lstrip": false,
|
| 10 |
+
"normalized": false,
|
| 11 |
+
"rstrip": false,
|
| 12 |
+
"single_word": false
|
| 13 |
+
},
|
| 14 |
+
"pad_token": {
|
| 15 |
+
"content": "<|endoftext|>",
|
| 16 |
+
"lstrip": false,
|
| 17 |
+
"normalized": false,
|
| 18 |
+
"rstrip": false,
|
| 19 |
+
"single_word": false
|
| 20 |
+
}
|
| 21 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:14f9ab052ece9afe1180aba8c156a452edb1b6610b4128668707c700acd43674
|
| 3 |
+
size 11422445
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": false
|
| 180 |
+
},
|
| 181 |
+
"151665": {
|
| 182 |
+
"content": "[IMG]",
|
| 183 |
+
"lstrip": false,
|
| 184 |
+
"normalized": false,
|
| 185 |
+
"rstrip": false,
|
| 186 |
+
"single_word": false,
|
| 187 |
+
"special": true
|
| 188 |
+
},
|
| 189 |
+
"151666": {
|
| 190 |
+
"content": "[/IMG]",
|
| 191 |
+
"lstrip": false,
|
| 192 |
+
"normalized": false,
|
| 193 |
+
"rstrip": false,
|
| 194 |
+
"single_word": false,
|
| 195 |
+
"special": true
|
| 196 |
+
},
|
| 197 |
+
"151667": {
|
| 198 |
+
"content": "<image>",
|
| 199 |
+
"lstrip": false,
|
| 200 |
+
"normalized": false,
|
| 201 |
+
"rstrip": false,
|
| 202 |
+
"single_word": false,
|
| 203 |
+
"special": true
|
| 204 |
+
}
|
| 205 |
+
},
|
| 206 |
+
"additional_special_tokens": [
|
| 207 |
+
"[IMG]",
|
| 208 |
+
"[/IMG]",
|
| 209 |
+
"<image>"
|
| 210 |
+
],
|
| 211 |
+
"bos_token": null,
|
| 212 |
+
"chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}",
|
| 213 |
+
"clean_up_tokenization_spaces": false,
|
| 214 |
+
"eos_token": "<|im_end|>",
|
| 215 |
+
"errors": "replace",
|
| 216 |
+
"extra_special_tokens": {},
|
| 217 |
+
"model_max_length": 512,
|
| 218 |
+
"pad_token": "<|endoftext|>",
|
| 219 |
+
"split_special_tokens": false,
|
| 220 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 221 |
+
"unk_token": null
|
| 222 |
+
}
|
trainer_state.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:87cac9652eb8a383c2a8e2da30c5e85a8c1de411e97da28f7aa234ed991cad7b
|
| 3 |
+
size 7096
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
zero_to_fp32.py
ADDED
|
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
# Copyright (c) Microsoft Corporation.
|
| 4 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
|
| 6 |
+
# DeepSpeed Team
|
| 7 |
+
|
| 8 |
+
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
|
| 9 |
+
# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
|
| 10 |
+
# the future. Once extracted, the weights don't require DeepSpeed and can be used in any
|
| 11 |
+
# application.
|
| 12 |
+
#
|
| 13 |
+
# example:
|
| 14 |
+
# python zero_to_fp32.py . output_dir/
|
| 15 |
+
# or
|
| 16 |
+
# python zero_to_fp32.py . output_dir/ --safe_serialization
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import torch
|
| 20 |
+
import glob
|
| 21 |
+
import math
|
| 22 |
+
import os
|
| 23 |
+
import re
|
| 24 |
+
import gc
|
| 25 |
+
import json
|
| 26 |
+
import numpy as np
|
| 27 |
+
from tqdm import tqdm
|
| 28 |
+
from collections import OrderedDict
|
| 29 |
+
from dataclasses import dataclass
|
| 30 |
+
|
| 31 |
+
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
|
| 32 |
+
# DeepSpeed data structures it has to be available in the current python environment.
|
| 33 |
+
from deepspeed.utils import logger
|
| 34 |
+
from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
|
| 35 |
+
FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
|
| 36 |
+
FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclass
|
| 40 |
+
class zero_model_state:
|
| 41 |
+
buffers: dict()
|
| 42 |
+
param_shapes: dict()
|
| 43 |
+
shared_params: list
|
| 44 |
+
ds_version: int
|
| 45 |
+
frozen_param_shapes: dict()
|
| 46 |
+
frozen_param_fragments: dict()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
debug = 0
|
| 50 |
+
|
| 51 |
+
# load to cpu
|
| 52 |
+
device = torch.device('cpu')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def atoi(text):
|
| 56 |
+
return int(text) if text.isdigit() else text
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def natural_keys(text):
|
| 60 |
+
'''
|
| 61 |
+
alist.sort(key=natural_keys) sorts in human order
|
| 62 |
+
http://nedbatchelder.com/blog/200712/human_sorting.html
|
| 63 |
+
(See Toothy's implementation in the comments)
|
| 64 |
+
'''
|
| 65 |
+
return [atoi(c) for c in re.split(r'(\d+)', text)]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def get_model_state_file(checkpoint_dir, zero_stage):
|
| 69 |
+
if not os.path.isdir(checkpoint_dir):
|
| 70 |
+
raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
|
| 71 |
+
|
| 72 |
+
# there should be only one file
|
| 73 |
+
if zero_stage <= 2:
|
| 74 |
+
file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
|
| 75 |
+
elif zero_stage == 3:
|
| 76 |
+
file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
|
| 77 |
+
|
| 78 |
+
if not os.path.exists(file):
|
| 79 |
+
raise FileNotFoundError(f"can't find model states file at '{file}'")
|
| 80 |
+
|
| 81 |
+
return file
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def get_checkpoint_files(checkpoint_dir, glob_pattern):
|
| 85 |
+
# XXX: need to test that this simple glob rule works for multi-node setup too
|
| 86 |
+
ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
|
| 87 |
+
|
| 88 |
+
if len(ckpt_files) == 0:
|
| 89 |
+
raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
|
| 90 |
+
|
| 91 |
+
return ckpt_files
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def get_optim_files(checkpoint_dir):
|
| 95 |
+
return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def get_model_state_files(checkpoint_dir):
|
| 99 |
+
return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def parse_model_states(files):
|
| 103 |
+
zero_model_states = []
|
| 104 |
+
for file in files:
|
| 105 |
+
state_dict = torch.load(file, map_location=device, weights_only=False)
|
| 106 |
+
|
| 107 |
+
if BUFFER_NAMES not in state_dict:
|
| 108 |
+
raise ValueError(f"{file} is not a model state checkpoint")
|
| 109 |
+
buffer_names = state_dict[BUFFER_NAMES]
|
| 110 |
+
if debug:
|
| 111 |
+
print("Found buffers:", buffer_names)
|
| 112 |
+
|
| 113 |
+
# recover just the buffers while restoring them to fp32 if they were saved in fp16
|
| 114 |
+
buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
|
| 115 |
+
param_shapes = state_dict[PARAM_SHAPES]
|
| 116 |
+
|
| 117 |
+
# collect parameters that are included in param_shapes
|
| 118 |
+
param_names = []
|
| 119 |
+
for s in param_shapes:
|
| 120 |
+
for name in s.keys():
|
| 121 |
+
param_names.append(name)
|
| 122 |
+
|
| 123 |
+
# update with frozen parameters
|
| 124 |
+
frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
|
| 125 |
+
if frozen_param_shapes is not None:
|
| 126 |
+
if debug:
|
| 127 |
+
print(f"Found frozen_param_shapes: {frozen_param_shapes}")
|
| 128 |
+
param_names += list(frozen_param_shapes.keys())
|
| 129 |
+
|
| 130 |
+
# handle shared params
|
| 131 |
+
shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
|
| 132 |
+
|
| 133 |
+
ds_version = state_dict.get(DS_VERSION, None)
|
| 134 |
+
|
| 135 |
+
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
|
| 136 |
+
|
| 137 |
+
z_model_state = zero_model_state(buffers=buffers,
|
| 138 |
+
param_shapes=param_shapes,
|
| 139 |
+
shared_params=shared_params,
|
| 140 |
+
ds_version=ds_version,
|
| 141 |
+
frozen_param_shapes=frozen_param_shapes,
|
| 142 |
+
frozen_param_fragments=frozen_param_fragments)
|
| 143 |
+
zero_model_states.append(z_model_state)
|
| 144 |
+
|
| 145 |
+
return zero_model_states
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def parse_optim_states(files, ds_checkpoint_dir):
|
| 149 |
+
total_files = len(files)
|
| 150 |
+
state_dicts = []
|
| 151 |
+
for f in tqdm(files, desc='Loading checkpoint shards'):
|
| 152 |
+
state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False)
|
| 153 |
+
# immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
|
| 154 |
+
# and also handle the case where it was already removed by another helper script
|
| 155 |
+
state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
|
| 156 |
+
state_dicts.append(state_dict)
|
| 157 |
+
|
| 158 |
+
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
|
| 159 |
+
raise ValueError(f"{files[0]} is not a zero checkpoint")
|
| 160 |
+
zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
|
| 161 |
+
world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
|
| 162 |
+
|
| 163 |
+
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert
|
| 164 |
+
# parameters can be different from data parallelism for non-expert parameters. So we can just
|
| 165 |
+
# use the max of the partition_count to get the dp world_size.
|
| 166 |
+
|
| 167 |
+
if type(world_size) is list:
|
| 168 |
+
world_size = max(world_size)
|
| 169 |
+
|
| 170 |
+
if world_size != total_files:
|
| 171 |
+
raise ValueError(
|
| 172 |
+
f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
|
| 173 |
+
"Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# the groups are named differently in each stage
|
| 177 |
+
if zero_stage <= 2:
|
| 178 |
+
fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
|
| 179 |
+
elif zero_stage == 3:
|
| 180 |
+
fp32_groups_key = FP32_FLAT_GROUPS
|
| 181 |
+
else:
|
| 182 |
+
raise ValueError(f"unknown zero stage {zero_stage}")
|
| 183 |
+
|
| 184 |
+
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
|
| 185 |
+
return zero_stage, world_size, fp32_flat_groups
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
|
| 189 |
+
"""
|
| 190 |
+
Returns fp32 state_dict reconstructed from ds checkpoint
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
- ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
|
| 194 |
+
|
| 195 |
+
"""
|
| 196 |
+
print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
|
| 197 |
+
|
| 198 |
+
optim_files = get_optim_files(ds_checkpoint_dir)
|
| 199 |
+
zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
|
| 200 |
+
print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
|
| 201 |
+
|
| 202 |
+
model_files = get_model_state_files(ds_checkpoint_dir)
|
| 203 |
+
|
| 204 |
+
zero_model_states = parse_model_states(model_files)
|
| 205 |
+
print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
|
| 206 |
+
|
| 207 |
+
if zero_stage <= 2:
|
| 208 |
+
return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
| 209 |
+
exclude_frozen_parameters)
|
| 210 |
+
elif zero_stage == 3:
|
| 211 |
+
return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
| 212 |
+
exclude_frozen_parameters)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _zero2_merge_frozen_params(state_dict, zero_model_states):
|
| 216 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
| 217 |
+
return
|
| 218 |
+
|
| 219 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
| 220 |
+
frozen_param_fragments = zero_model_states[0].frozen_param_fragments
|
| 221 |
+
|
| 222 |
+
if debug:
|
| 223 |
+
num_elem = sum(s.numel() for s in frozen_param_shapes.values())
|
| 224 |
+
print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
| 225 |
+
|
| 226 |
+
wanted_params = len(frozen_param_shapes)
|
| 227 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
| 228 |
+
avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
|
| 229 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
| 230 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
| 231 |
+
|
| 232 |
+
total_params = 0
|
| 233 |
+
total_numel = 0
|
| 234 |
+
for name, shape in frozen_param_shapes.items():
|
| 235 |
+
total_params += 1
|
| 236 |
+
unpartitioned_numel = shape.numel()
|
| 237 |
+
total_numel += unpartitioned_numel
|
| 238 |
+
|
| 239 |
+
state_dict[name] = frozen_param_fragments[name]
|
| 240 |
+
|
| 241 |
+
if debug:
|
| 242 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
| 243 |
+
|
| 244 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _has_callable(obj, fn):
|
| 248 |
+
attr = getattr(obj, fn, None)
|
| 249 |
+
return callable(attr)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
| 253 |
+
param_shapes = zero_model_states[0].param_shapes
|
| 254 |
+
|
| 255 |
+
# Reconstruction protocol:
|
| 256 |
+
#
|
| 257 |
+
# XXX: document this
|
| 258 |
+
|
| 259 |
+
if debug:
|
| 260 |
+
for i in range(world_size):
|
| 261 |
+
for j in range(len(fp32_flat_groups[0])):
|
| 262 |
+
print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
|
| 263 |
+
|
| 264 |
+
# XXX: memory usage doubles here (zero2)
|
| 265 |
+
num_param_groups = len(fp32_flat_groups[0])
|
| 266 |
+
merged_single_partition_of_fp32_groups = []
|
| 267 |
+
for i in range(num_param_groups):
|
| 268 |
+
merged_partitions = [sd[i] for sd in fp32_flat_groups]
|
| 269 |
+
full_single_fp32_vector = torch.cat(merged_partitions, 0)
|
| 270 |
+
merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
|
| 271 |
+
avail_numel = sum(
|
| 272 |
+
[full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
|
| 273 |
+
|
| 274 |
+
if debug:
|
| 275 |
+
wanted_params = sum([len(shapes) for shapes in param_shapes])
|
| 276 |
+
wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
|
| 277 |
+
# not asserting if there is a mismatch due to possible padding
|
| 278 |
+
print(f"Have {avail_numel} numels to process.")
|
| 279 |
+
print(f"Need {wanted_numel} numels in {wanted_params} params.")
|
| 280 |
+
|
| 281 |
+
# params
|
| 282 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
| 283 |
+
# out-of-core computing solution
|
| 284 |
+
total_numel = 0
|
| 285 |
+
total_params = 0
|
| 286 |
+
for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
|
| 287 |
+
offset = 0
|
| 288 |
+
avail_numel = full_single_fp32_vector.numel()
|
| 289 |
+
for name, shape in shapes.items():
|
| 290 |
+
|
| 291 |
+
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
|
| 292 |
+
total_numel += unpartitioned_numel
|
| 293 |
+
total_params += 1
|
| 294 |
+
|
| 295 |
+
if debug:
|
| 296 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
| 297 |
+
state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
|
| 298 |
+
offset += unpartitioned_numel
|
| 299 |
+
|
| 300 |
+
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
|
| 301 |
+
# avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
|
| 302 |
+
# paddings performed in the code it's almost impossible to predict the exact numbers w/o the
|
| 303 |
+
# live optimizer object, so we are checking that the numbers are within the right range
|
| 304 |
+
align_to = 2 * world_size
|
| 305 |
+
|
| 306 |
+
def zero2_align(x):
|
| 307 |
+
return align_to * math.ceil(x / align_to)
|
| 308 |
+
|
| 309 |
+
if debug:
|
| 310 |
+
print(f"original offset={offset}, avail_numel={avail_numel}")
|
| 311 |
+
|
| 312 |
+
offset = zero2_align(offset)
|
| 313 |
+
avail_numel = zero2_align(avail_numel)
|
| 314 |
+
|
| 315 |
+
if debug:
|
| 316 |
+
print(f"aligned offset={offset}, avail_numel={avail_numel}")
|
| 317 |
+
|
| 318 |
+
# Sanity check
|
| 319 |
+
if offset != avail_numel:
|
| 320 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
| 321 |
+
|
| 322 |
+
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
| 326 |
+
exclude_frozen_parameters):
|
| 327 |
+
state_dict = OrderedDict()
|
| 328 |
+
|
| 329 |
+
# buffers
|
| 330 |
+
buffers = zero_model_states[0].buffers
|
| 331 |
+
state_dict.update(buffers)
|
| 332 |
+
if debug:
|
| 333 |
+
print(f"added {len(buffers)} buffers")
|
| 334 |
+
|
| 335 |
+
if not exclude_frozen_parameters:
|
| 336 |
+
_zero2_merge_frozen_params(state_dict, zero_model_states)
|
| 337 |
+
|
| 338 |
+
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
| 339 |
+
|
| 340 |
+
# recover shared parameters
|
| 341 |
+
for pair in zero_model_states[0].shared_params:
|
| 342 |
+
if pair[1] in state_dict:
|
| 343 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
| 344 |
+
|
| 345 |
+
return state_dict
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def zero3_partitioned_param_info(unpartitioned_numel, world_size):
|
| 349 |
+
remainder = unpartitioned_numel % world_size
|
| 350 |
+
padding_numel = (world_size - remainder) if remainder else 0
|
| 351 |
+
partitioned_numel = math.ceil(unpartitioned_numel / world_size)
|
| 352 |
+
return partitioned_numel, padding_numel
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
|
| 356 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
| 357 |
+
return
|
| 358 |
+
|
| 359 |
+
if debug:
|
| 360 |
+
for i in range(world_size):
|
| 361 |
+
num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
|
| 362 |
+
print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
| 363 |
+
|
| 364 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
| 365 |
+
wanted_params = len(frozen_param_shapes)
|
| 366 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
| 367 |
+
avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
|
| 368 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
| 369 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
| 370 |
+
|
| 371 |
+
total_params = 0
|
| 372 |
+
total_numel = 0
|
| 373 |
+
for name, shape in zero_model_states[0].frozen_param_shapes.items():
|
| 374 |
+
total_params += 1
|
| 375 |
+
unpartitioned_numel = shape.numel()
|
| 376 |
+
total_numel += unpartitioned_numel
|
| 377 |
+
|
| 378 |
+
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
|
| 379 |
+
state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
|
| 380 |
+
|
| 381 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
| 382 |
+
|
| 383 |
+
if debug:
|
| 384 |
+
print(
|
| 385 |
+
f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class GatheredTensor:
|
| 392 |
+
"""
|
| 393 |
+
A pseudo tensor that collects partitioned weights.
|
| 394 |
+
It is more memory efficient when there are multiple groups.
|
| 395 |
+
"""
|
| 396 |
+
|
| 397 |
+
def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape):
|
| 398 |
+
self.flat_groups = flat_groups
|
| 399 |
+
self.flat_groups_offset = flat_groups_offset
|
| 400 |
+
self.offset = offset
|
| 401 |
+
self.partitioned_numel = partitioned_numel
|
| 402 |
+
self.shape = shape
|
| 403 |
+
self.dtype = self.flat_groups[0][0].dtype
|
| 404 |
+
|
| 405 |
+
def contiguous(self):
|
| 406 |
+
"""
|
| 407 |
+
Merge partitioned weights from flat_groups into a single tensor.
|
| 408 |
+
"""
|
| 409 |
+
end_idx = self.offset + self.partitioned_numel
|
| 410 |
+
world_size = len(self.flat_groups)
|
| 411 |
+
pad_flat_param_chunks = []
|
| 412 |
+
|
| 413 |
+
for rank_i in range(world_size):
|
| 414 |
+
# for each rank, we need to collect weights from related group/groups
|
| 415 |
+
flat_groups_at_rank_i = self.flat_groups[rank_i]
|
| 416 |
+
start_group_id = None
|
| 417 |
+
end_group_id = None
|
| 418 |
+
for group_id in range(len(self.flat_groups_offset)):
|
| 419 |
+
if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]:
|
| 420 |
+
start_group_id = group_id
|
| 421 |
+
if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]:
|
| 422 |
+
end_group_id = group_id
|
| 423 |
+
break
|
| 424 |
+
# collect weights from related group/groups
|
| 425 |
+
for group_id in range(start_group_id, end_group_id + 1):
|
| 426 |
+
flat_tensor = flat_groups_at_rank_i[group_id]
|
| 427 |
+
start_offset = self.offset - self.flat_groups_offset[group_id]
|
| 428 |
+
end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id]
|
| 429 |
+
pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
|
| 430 |
+
|
| 431 |
+
# collect weights from all ranks
|
| 432 |
+
pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0)
|
| 433 |
+
param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous()
|
| 434 |
+
return param
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
| 438 |
+
param_shapes = zero_model_states[0].param_shapes
|
| 439 |
+
avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
|
| 440 |
+
|
| 441 |
+
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
|
| 442 |
+
# param, re-consolidating each param, while dealing with padding if any
|
| 443 |
+
|
| 444 |
+
# merge list of dicts, preserving order
|
| 445 |
+
param_shapes = {k: v for d in param_shapes for k, v in d.items()}
|
| 446 |
+
|
| 447 |
+
if debug:
|
| 448 |
+
for i in range(world_size):
|
| 449 |
+
print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
|
| 450 |
+
|
| 451 |
+
wanted_params = len(param_shapes)
|
| 452 |
+
wanted_numel = sum(shape.numel() for shape in param_shapes.values())
|
| 453 |
+
# not asserting if there is a mismatch due to possible padding
|
| 454 |
+
avail_numel = fp32_flat_groups[0].numel() * world_size
|
| 455 |
+
print(f"Trainable params: Have {avail_numel} numels to process.")
|
| 456 |
+
print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
|
| 457 |
+
|
| 458 |
+
# params
|
| 459 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
| 460 |
+
# out-of-core computing solution
|
| 461 |
+
offset = 0
|
| 462 |
+
total_numel = 0
|
| 463 |
+
total_params = 0
|
| 464 |
+
flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]]))
|
| 465 |
+
for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'):
|
| 466 |
+
unpartitioned_numel = shape.numel()
|
| 467 |
+
total_numel += unpartitioned_numel
|
| 468 |
+
total_params += 1
|
| 469 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
| 470 |
+
|
| 471 |
+
if debug:
|
| 472 |
+
print(
|
| 473 |
+
f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
# memory efficient tensor
|
| 477 |
+
tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape)
|
| 478 |
+
state_dict[name] = tensor
|
| 479 |
+
offset += partitioned_numel
|
| 480 |
+
|
| 481 |
+
offset *= world_size
|
| 482 |
+
|
| 483 |
+
# Sanity check
|
| 484 |
+
if offset != avail_numel:
|
| 485 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
| 486 |
+
|
| 487 |
+
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
| 491 |
+
exclude_frozen_parameters):
|
| 492 |
+
state_dict = OrderedDict()
|
| 493 |
+
|
| 494 |
+
# buffers
|
| 495 |
+
buffers = zero_model_states[0].buffers
|
| 496 |
+
state_dict.update(buffers)
|
| 497 |
+
if debug:
|
| 498 |
+
print(f"added {len(buffers)} buffers")
|
| 499 |
+
|
| 500 |
+
if not exclude_frozen_parameters:
|
| 501 |
+
_zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
|
| 502 |
+
|
| 503 |
+
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
| 504 |
+
|
| 505 |
+
# recover shared parameters
|
| 506 |
+
for pair in zero_model_states[0].shared_params:
|
| 507 |
+
if pair[1] in state_dict:
|
| 508 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
| 509 |
+
|
| 510 |
+
return state_dict
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def to_torch_tensor(state_dict, return_empty_tensor=False):
|
| 514 |
+
"""
|
| 515 |
+
Convert state_dict of GatheredTensor to torch tensor
|
| 516 |
+
"""
|
| 517 |
+
torch_state_dict = {}
|
| 518 |
+
converted_tensors = {}
|
| 519 |
+
for name, tensor in state_dict.items():
|
| 520 |
+
tensor_id = id(tensor)
|
| 521 |
+
if tensor_id in converted_tensors: # shared tensors
|
| 522 |
+
shared_tensor = torch_state_dict[converted_tensors[tensor_id]]
|
| 523 |
+
torch_state_dict[name] = shared_tensor
|
| 524 |
+
else:
|
| 525 |
+
converted_tensors[tensor_id] = name
|
| 526 |
+
if return_empty_tensor:
|
| 527 |
+
torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype)
|
| 528 |
+
else:
|
| 529 |
+
torch_state_dict[name] = tensor.contiguous()
|
| 530 |
+
return torch_state_dict
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
| 534 |
+
tag=None,
|
| 535 |
+
exclude_frozen_parameters=False,
|
| 536 |
+
lazy_mode=False):
|
| 537 |
+
"""
|
| 538 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
|
| 539 |
+
``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
|
| 540 |
+
via a model hub.
|
| 541 |
+
|
| 542 |
+
Args:
|
| 543 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder
|
| 544 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
|
| 545 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
| 546 |
+
- ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient.
|
| 547 |
+
Convert the pesduo tensor to torch tensor by ``.contiguous()``
|
| 548 |
+
|
| 549 |
+
Returns:
|
| 550 |
+
- pytorch ``state_dict``
|
| 551 |
+
|
| 552 |
+
A typical usage might be ::
|
| 553 |
+
|
| 554 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
| 555 |
+
# do the training and checkpoint saving
|
| 556 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
|
| 557 |
+
model = model.cpu() # move to cpu
|
| 558 |
+
model.load_state_dict(state_dict)
|
| 559 |
+
# submit to model hub or save the model to share with others
|
| 560 |
+
|
| 561 |
+
In this example the ``model`` will no longer be usable in the deepspeed context of the same
|
| 562 |
+
application. i.e. you will need to re-initialize the deepspeed engine, since
|
| 563 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
| 564 |
+
|
| 565 |
+
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
|
| 566 |
+
|
| 567 |
+
Note: the above usage may not work if your application doesn't have sufficient free CPU memory.
|
| 568 |
+
You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
|
| 569 |
+
the checkpoint. Or you can load state_dict in lazy mode ::
|
| 570 |
+
|
| 571 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
| 572 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu
|
| 573 |
+
for name, lazy_tensor in state_dict.item():
|
| 574 |
+
tensor = lazy_tensor.contiguous() # to cpu
|
| 575 |
+
print(name, tensor)
|
| 576 |
+
# del tensor to release memory if it no longer in use
|
| 577 |
+
"""
|
| 578 |
+
if tag is None:
|
| 579 |
+
latest_path = os.path.join(checkpoint_dir, 'latest')
|
| 580 |
+
if os.path.isfile(latest_path):
|
| 581 |
+
with open(latest_path, 'r') as fd:
|
| 582 |
+
tag = fd.read().strip()
|
| 583 |
+
else:
|
| 584 |
+
raise ValueError(f"Unable to find 'latest' file at {latest_path}")
|
| 585 |
+
|
| 586 |
+
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
|
| 587 |
+
|
| 588 |
+
if not os.path.isdir(ds_checkpoint_dir):
|
| 589 |
+
raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
|
| 590 |
+
|
| 591 |
+
state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
|
| 592 |
+
if lazy_mode:
|
| 593 |
+
return state_dict
|
| 594 |
+
else:
|
| 595 |
+
return to_torch_tensor(state_dict)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir,
|
| 599 |
+
output_dir,
|
| 600 |
+
max_shard_size="5GB",
|
| 601 |
+
safe_serialization=False,
|
| 602 |
+
tag=None,
|
| 603 |
+
exclude_frozen_parameters=False):
|
| 604 |
+
"""
|
| 605 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
|
| 606 |
+
loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
|
| 607 |
+
|
| 608 |
+
Args:
|
| 609 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
| 610 |
+
- ``output_dir``: directory to the pytorch fp32 state_dict output files
|
| 611 |
+
- ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB
|
| 612 |
+
- ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
|
| 613 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
| 614 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
| 615 |
+
"""
|
| 616 |
+
|
| 617 |
+
# Dependency pre-check
|
| 618 |
+
if safe_serialization:
|
| 619 |
+
try:
|
| 620 |
+
from safetensors.torch import save_file
|
| 621 |
+
except ImportError:
|
| 622 |
+
print('If you want to use `safe_serialization`, please `pip install safetensors`')
|
| 623 |
+
raise
|
| 624 |
+
if max_shard_size is not None:
|
| 625 |
+
try:
|
| 626 |
+
from huggingface_hub import split_torch_state_dict_into_shards
|
| 627 |
+
except ImportError:
|
| 628 |
+
print('If you want to use `max_shard_size`, please `pip install huggingface_hub`')
|
| 629 |
+
raise
|
| 630 |
+
|
| 631 |
+
# Convert zero checkpoint to state_dict
|
| 632 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
| 633 |
+
tag,
|
| 634 |
+
exclude_frozen_parameters,
|
| 635 |
+
lazy_mode=True)
|
| 636 |
+
|
| 637 |
+
# Shard the model if it is too big.
|
| 638 |
+
weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin"
|
| 639 |
+
if max_shard_size is not None:
|
| 640 |
+
filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors")
|
| 641 |
+
# an memory-efficient approach for sharding
|
| 642 |
+
empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True)
|
| 643 |
+
state_dict_split = split_torch_state_dict_into_shards(empty_state_dict,
|
| 644 |
+
filename_pattern=filename_pattern,
|
| 645 |
+
max_shard_size=max_shard_size)
|
| 646 |
+
else:
|
| 647 |
+
from collections import namedtuple
|
| 648 |
+
StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"])
|
| 649 |
+
state_dict_split = StateDictSplit(is_sharded=False,
|
| 650 |
+
filename_to_tensors={weights_name: list(state_dict.keys())})
|
| 651 |
+
|
| 652 |
+
# Save the model by shard
|
| 653 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 654 |
+
filename_to_tensors = state_dict_split.filename_to_tensors.items()
|
| 655 |
+
for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"):
|
| 656 |
+
shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors}
|
| 657 |
+
shard_state_dict = to_torch_tensor(shard_state_dict)
|
| 658 |
+
output_path = os.path.join(output_dir, shard_file)
|
| 659 |
+
if safe_serialization:
|
| 660 |
+
save_file(shard_state_dict, output_path, metadata={"format": "pt"})
|
| 661 |
+
else:
|
| 662 |
+
torch.save(shard_state_dict, output_path)
|
| 663 |
+
# release the memory of current shard
|
| 664 |
+
for tensor_name in list(shard_state_dict.keys()):
|
| 665 |
+
del state_dict[tensor_name]
|
| 666 |
+
del shard_state_dict[tensor_name]
|
| 667 |
+
del shard_state_dict
|
| 668 |
+
gc.collect()
|
| 669 |
+
|
| 670 |
+
# Save index if sharded
|
| 671 |
+
if state_dict_split.is_sharded:
|
| 672 |
+
index = {
|
| 673 |
+
"metadata": state_dict_split.metadata,
|
| 674 |
+
"weight_map": state_dict_split.tensor_to_filename,
|
| 675 |
+
}
|
| 676 |
+
save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json"
|
| 677 |
+
save_index_file = os.path.join(output_dir, save_index_file)
|
| 678 |
+
with open(save_index_file, "w", encoding="utf-8") as f:
|
| 679 |
+
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
| 680 |
+
f.write(content)
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
|
| 684 |
+
"""
|
| 685 |
+
1. Put the provided model to cpu
|
| 686 |
+
2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
|
| 687 |
+
3. Load it into the provided model
|
| 688 |
+
|
| 689 |
+
Args:
|
| 690 |
+
- ``model``: the model object to update
|
| 691 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
| 692 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
| 693 |
+
|
| 694 |
+
Returns:
|
| 695 |
+
- ``model`: modified model
|
| 696 |
+
|
| 697 |
+
Make sure you have plenty of CPU memory available before you call this function. If you don't
|
| 698 |
+
have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
|
| 699 |
+
conveniently placed for you in the checkpoint folder.
|
| 700 |
+
|
| 701 |
+
A typical usage might be ::
|
| 702 |
+
|
| 703 |
+
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
|
| 704 |
+
model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
|
| 705 |
+
# submit to model hub or save the model to share with others
|
| 706 |
+
|
| 707 |
+
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
|
| 708 |
+
of the same application. i.e. you will need to re-initialize the deepspeed engine, since
|
| 709 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
| 710 |
+
|
| 711 |
+
"""
|
| 712 |
+
logger.info(f"Extracting fp32 weights")
|
| 713 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
|
| 714 |
+
|
| 715 |
+
logger.info(f"Overwriting model with fp32 weights")
|
| 716 |
+
model = model.cpu()
|
| 717 |
+
model.load_state_dict(state_dict, strict=False)
|
| 718 |
+
|
| 719 |
+
return model
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
if __name__ == "__main__":
|
| 723 |
+
parser = argparse.ArgumentParser()
|
| 724 |
+
parser.add_argument("checkpoint_dir",
|
| 725 |
+
type=str,
|
| 726 |
+
help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
|
| 727 |
+
parser.add_argument("output_dir",
|
| 728 |
+
type=str,
|
| 729 |
+
help="directory to the pytorch fp32 state_dict output files"
|
| 730 |
+
"(e.g. path/checkpoint-12-output/)")
|
| 731 |
+
parser.add_argument(
|
| 732 |
+
"--max_shard_size",
|
| 733 |
+
type=str,
|
| 734 |
+
default="5GB",
|
| 735 |
+
help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size"
|
| 736 |
+
"lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`"
|
| 737 |
+
"We default it to 5GB in order for models to be able to run easily on free-tier google colab instances"
|
| 738 |
+
"without CPU OOM issues.")
|
| 739 |
+
parser.add_argument(
|
| 740 |
+
"--safe_serialization",
|
| 741 |
+
default=False,
|
| 742 |
+
action='store_true',
|
| 743 |
+
help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).")
|
| 744 |
+
parser.add_argument("-t",
|
| 745 |
+
"--tag",
|
| 746 |
+
type=str,
|
| 747 |
+
default=None,
|
| 748 |
+
help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
|
| 749 |
+
parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
|
| 750 |
+
parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
|
| 751 |
+
args = parser.parse_args()
|
| 752 |
+
|
| 753 |
+
debug = args.debug
|
| 754 |
+
|
| 755 |
+
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
|
| 756 |
+
args.output_dir,
|
| 757 |
+
max_shard_size=args.max_shard_size,
|
| 758 |
+
safe_serialization=args.safe_serialization,
|
| 759 |
+
tag=args.tag,
|
| 760 |
+
exclude_frozen_parameters=args.exclude_frozen_parameters)
|