Ouzhang commited on
Commit
14153ec
·
verified ·
1 Parent(s): d14e4c4

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Ditto_models/.gitattributes +35 -0
  2. Ditto_models/README.md +137 -0
  3. GENERanno-eukaryote-0.5b-base/.gitattributes +35 -0
  4. GENERanno-eukaryote-0.5b-base/README.md +92 -0
  5. GENERanno-eukaryote-0.5b-base/config.json +36 -0
  6. GENERanno-eukaryote-0.5b-base/configuration_generanno.py +190 -0
  7. GENERanno-eukaryote-0.5b-base/modeling_generanno.py +1273 -0
  8. GENERanno-eukaryote-0.5b-base/special_tokens_map.json +7 -0
  9. GENERanno-eukaryote-0.5b-base/tokenizer.py +192 -0
  10. GENERanno-eukaryote-0.5b-base/tokenizer_config.json +59 -0
  11. GENERanno-eukaryote-0.5b-base/vocab.txt +43 -0
  12. SSD-1B/scheduler/scheduler_config.json +18 -0
  13. SSD-1B/text_encoder/config.json +24 -0
  14. SSD-1B/text_encoder_2/config.json +24 -0
  15. SSD-1B/tokenizer/merges.txt +0 -0
  16. SSD-1B/tokenizer/special_tokens_map.json +24 -0
  17. SSD-1B/tokenizer/tokenizer_config.json +33 -0
  18. SSD-1B/tokenizer/vocab.json +0 -0
  19. SSD-1B/tokenizer_2/merges.txt +0 -0
  20. SSD-1B/tokenizer_2/special_tokens_map.json +24 -0
  21. SSD-1B/tokenizer_2/tokenizer_config.json +33 -0
  22. SSD-1B/tokenizer_2/vocab.json +0 -0
  23. SSD-1B/unet/config.json +74 -0
  24. SSD-1B/vae/config.json +31 -0
  25. bk-sdm-tiny/.gitattributes +35 -0
  26. bk-sdm-tiny/README.md +216 -0
  27. bk-sdm-tiny/feature_extractor/preprocessor_config.json +20 -0
  28. bk-sdm-tiny/model_index.json +32 -0
  29. bk-sdm-tiny/safety_checker/config.json +171 -0
  30. bk-sdm-tiny/scheduler/.ipynb_checkpoints/scheduler_config-checkpoint.json +9 -0
  31. bk-sdm-tiny/scheduler/scheduler_config.json +13 -0
  32. bk-sdm-tiny/text_encoder/config.json +24 -0
  33. bk-sdm-tiny/tokenizer/merges.txt +0 -0
  34. bk-sdm-tiny/tokenizer/special_tokens_map.json +24 -0
  35. bk-sdm-tiny/tokenizer/tokenizer_config.json +34 -0
  36. bk-sdm-tiny/tokenizer/vocab.json +0 -0
  37. bk-sdm-tiny/unet/config.json +55 -0
  38. bk-sdm-tiny/vae/config.json +29 -0
  39. controlnet-canny-sdxl-1.0/.gitattributes +41 -0
  40. controlnet-canny-sdxl-1.0/README.md +106 -0
  41. controlnet-canny-sdxl-1.0/config.json +57 -0
  42. controlnet-openpose-sdxl-1.0/.gitattributes +37 -0
  43. controlnet-openpose-sdxl-1.0/README.md +99 -0
  44. controlnet-openpose-sdxl-1.0/config.json +56 -0
  45. lcm-lora-ssd-1b/.gitattributes +36 -0
  46. lcm-lora-ssd-1b/README.md +87 -0
  47. stable-diffusion-v1-4/.gitattributes +32 -0
  48. stable-diffusion-v1-4/README.md +324 -0
  49. stable-diffusion-v1-4/feature_extractor/preprocessor_config.json +20 -0
  50. stable-diffusion-v1-4/model_index.json +32 -0
Ditto_models/.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
Ditto_models/README.md ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model:
3
+ - Wan-AI/Wan2.1-T2V-14B
4
+ - Wan-AI/Wan2.1-VACE-14B
5
+ datasets:
6
+ - QingyanBai/Ditto-1M
7
+ language:
8
+ - en
9
+ license: cc-by-nc-sa-4.0
10
+ pipeline_tag: video-to-video
11
+ ---
12
+
13
+ # Ditto: Scaling Instruction-Based Video Editing with a High-Quality Synthetic Dataset
14
+
15
+ This repository contains the **Ditto** framework and the **Editto** model, which are introduced in the paper [Scaling Instruction-Based Video Editing with a High-Quality Synthetic Dataset](https://huggingface.co/papers/2510.15742). Ditto provides a holistic approach to address the scarcity of high-quality training data for instruction-based video editing, enabling the creation of the Ditto-1M dataset and the training of the state-of-the-art Editto model.
16
+
17
+ - 📄 [Paper](https://huggingface.co/papers/2510.15742)
18
+ - 🌐 [Project Page](https://ezioby.github.io/Ditto_page)
19
+ - 💻 [GitHub Repository](https://github.com/EzioBy/Ditto)
20
+ - 📦 [Model Weights (on HF)](https://huggingface.co/QingyanBai/Ditto_models/tree/main)
21
+ - 📊 [Dataset (on HF)](https://huggingface.co/datasets/QingyanBai/Ditto-1M)
22
+
23
+ ## Abstract
24
+ Instruction-based video editing promises to democratize content creation, yet its progress is severely hampered by the scarcity of large-scale, high-quality training data. We introduce Ditto, a holistic framework designed to tackle this fundamental challenge. At its heart, Ditto features a novel data generation pipeline that fuses the creative diversity of a leading image editor with an in-context video generator, overcoming the limited scope of existing models. To make this process viable, our framework resolves the prohibitive cost-quality trade-off by employing an efficient, distilled model architecture augmented by a temporal enhancer, which simultaneously reduces computational overhead and improves temporal coherence. Finally, to achieve full scalability, this entire pipeline is driven by an intelligent agent that crafts diverse instructions and rigorously filters the output, ensuring quality control at scale. Using this framework, we invested over 12,000 GPU-days to build Ditto-1M, a new dataset of one million high-fidelity video editing examples. We trained our model, Editto, on Ditto-1M with a curriculum learning strategy. The results demonstrate superior instruction-following ability and establish a new state-of-the-art in instruction-based video editing.
25
+
26
+ ## Model Usage
27
+
28
+ ### 1. Using with DiffSynth
29
+
30
+ #### *Environment Setup*
31
+
32
+ ```bash
33
+ # Create conda environment (if you already have a DiffSynth conda environment, you can reuse it)
34
+ conda create -n ditto python=3.10
35
+ conda activate ditto
36
+ pip install -e .
37
+ ```
38
+
39
+ #### *Download Models*
40
+
41
+ Download the base model and our models from [Google Drive](https://drive.google.com/drive/folders/1SCsD-r-8QtQUNZSXdz0ALYd_Z_xXyN_6?usp=sharing) or [Hugging Face](https://huggingface.co/QingyanBai/Ditto_models/tree/main/models):
42
+ ```bash
43
+ # Download Wan-AI/Wan2.1-VACE-14B from Hugging Face to models/Wan-AI/
44
+ huggingface-cli download Wan-AI/Wan2.1-VACE-14B --local-dir models/Wan-AI/
45
+
46
+ # Download Ditto models
47
+ huggingface-cli download QingyanBai/Ditto_models --include="models/*" --local-dir ./
48
+ ```
49
+
50
+ #### *Usage*
51
+
52
+ You can either use the provided script or run Python directly:
53
+
54
+ ```bash
55
+ # Option 1: Use the provided script
56
+ bash infer.sh
57
+
58
+ # Option 2: Run Python directly
59
+ python inference/infer_ditto.py \
60
+ --input_video /path/to/input_video.mp4 \
61
+ --output_video /path/to/output_video.mp4 \
62
+ --prompt "Editing instruction." \
63
+ --lora_path /path/to/model.safetensors \
64
+ --num_frames 73 \
65
+ --device_id 0
66
+ ```
67
+
68
+ Some test cases could be found at [HF Dataset](https://huggingface.co/datasets/QingyanBai/Ditto-1M/tree/main/mini_test_videos). You can also find some reference editing prompts in `inference/example_prompts.txt`.
69
+
70
+ ### 2. Using with ComfyUI
71
+ <sub>Note: While ComfyUI runs faster with lower computational requirements (832×480x73 videos need 11G GPU memory and ~4min on A6000), please note that due to the use of quantized and distilled models, there may be some quality degradation.</sub>
72
+
73
+ #### *Environment Setup*
74
+
75
+ First, follow the [ComfyUI installation guide](https://github.com/comfyanonymous/ComfyUI) to set up the base ComfyUI environment.
76
+ We strongly recommend installing [ComfyUI-Manager](https://github.com/Comfy-Org/ComfyUI-Manager) for easy custom node management:
77
+
78
+ ```bash
79
+ # Install ComfyUI-Manager
80
+ cd ComfyUI/custom_nodes
81
+ git clone https://github.com/Comfy-Org/ComfyUI-Manager.git
82
+ ```
83
+
84
+ After installing ComfyUI, you can either:
85
+
86
+ Option 1 (Recommended): Use ComfyUI-Manager to automatically install all required custom nodes with the function Install Missing Custom Nodes.
87
+
88
+ Option 2: Manually install the required custom nodes (you can refer to [this page](https://docs.comfy.org/installation/install_custom_node)):
89
+ <sub>
90
+ - [ComfyUI-WanVideoWrapper](https://github.com/kijai/ComfyUI-WanVideoWrapper)
91
+ - [KJNodes for ComfyUI](https://github.com/kijai/ComfyUI-KJNodes)
92
+ - [comfyui-mixlab-nodes](https://github.com/MixLabPro/comfyui-mixlab-nodes)
93
+ - [ComfyUI-VideoHelperSuite](https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite)
94
+ </sub>
95
+
96
+ #### *Download Models*
97
+
98
+ Download the required model weights from: [Kijai/WanVideo_comfy](https://huggingface.co/Kijai/WanVideo_comfy/tree/main) to subfolders of `models/`. Required files include:
99
+ - [Wan2_1-T2V-14B_fp8_e4m3fn.safetensors](https://huggingface.co/Kijai/WanVideo_comfy/blob/main/Wan2_1-T2V-14B_fp8_e4m3fn.safetensors) to `diffusion_models/`
100
+ - [Wan21_CausVid_14B_T2V_lora_rank32_v2.safetensors](https://huggingface.co/Kijai/WanVideo_comfy/blob/main/Wan21_CausVid_14B_T2V_lora_rank32_v2.safetensors) to `loras/` for inference acceleration
101
+ - [Wan2_1_VAE_bf16.safetensors](https://huggingface.co/Kijai/WanVideo_comfy/blob/main/Wan2_1_VAE_bf16.safetensors) to `vae/wan/`
102
+ - [umt5-xxl-enc-bf16.safetensors](https://huggingface.co/Kijai/WanVideo_comfy/blob/main/umt5-xxl-enc-bf16.safetensors) to `text_encoders/`
103
+
104
+ Download our models from [Google Drive](https://drive.google.com/drive/folders/1SCsD-r-8QtQUNZSXdz0ALYd_Z_xXyN_6?usp=sharing) or [Hugging Face](https://huggingface.co/QingyanBai/Ditto_models/tree/main/models_comfy) to `diffusion_models/` (use VACE Module Select node for loading).
105
+
106
+ #### *Usage*
107
+
108
+ Use the workflow `ditto_comfyui_workflow.json` in this repo to get started.
109
+ We provided some reference prompts in the note.
110
+ Some test cases could be found at [HF Dataset](https://huggingface.co/datasets/QingyanBai/Ditto-1M/tree/main/mini_test_videos).
111
+
112
+ <sub>Note: If you want to test sim2real cases, you can try prompts like 'Turn it into the real domain'.</sub>
113
+
114
+ ## Citation
115
+
116
+ If you find this work useful, please consider citing our paper:
117
+
118
+ ```bibtex
119
+ @article{bai2025ditto,
120
+ title={Scaling Instruction-Based Video Editing with a High-Quality Synthetic Dataset},
121
+ author={Bai, Qingyan and Wang, Qiuyu and Ouyang, Hao and Yu, Yue and Wang, Hanlin and Wang, Wen and Cheng, Ka Leong and Ma, Shuailei and Zeng, Yanhong and Liu, Zichen and Xu, Yinghao and Shen, Yujun and Chen, Qifeng},
122
+ journal={arXiv preprint arXiv:2510.15742},
123
+ year={2025}
124
+ }
125
+ ```
126
+
127
+ ## Acknowledgments
128
+
129
+ We thank [Wan](https://github.com/Wan-Video/Wan2.1) & [VACE](https://github.com/ali-vilab/VACE) & [Qwen-Image](https://github.com/QwenLM/Qwen-Image) for providing the powerful foundation model, and [QwenVL](https://github.com/QwenLM/Qwen2.5-VL) for the advanced visual understanding capabilities. We also thank [DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio) serving as the codebase for this repository.
130
+
131
+ ## License
132
+
133
+ This project is licensed under the CC BY-NC-SA 4.0([Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-nc-sa/4.0/)).
134
+
135
+ The code is provided for academic research purposes only.
136
+
137
+ For any questions, please contact qingyanbai@hotmail.com.
GENERanno-eukaryote-0.5b-base/.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
GENERanno-eukaryote-0.5b-base/README.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ pipeline_tag: fill-mask
4
+ tags:
5
+ - biology
6
+ - genomics
7
+ - long-context
8
+ library_name: transformers
9
+ ---
10
+ # GENERanno-eukaryote-0.5b-base model
11
+
12
+ ## Abouts
13
+ In this repository, we present GENERanno, a genomic foundation model featuring a context length of 8k base pairs and 500M parameters, trained on an expansive dataset comprising 386 billion base pairs of eukaryotic DNA. Our evaluations demonstrate that the GENERanno achieves comparable performance with [GENERator](https://huggingface.co/GenerTeam/GENERator-eukaryote-1.2b-base) in benchmark evaluations, including [Genomic Benchmarks](https://huggingface.co/datasets/katielink/genomic-benchmarks/tree/main), [NT tasks](https://huggingface.co/datasets/InstaDeepAI/nucleotide_transformer_downstream_tasks_revised), and our newly proposed [Gener tasks](https://huggingface.co/GenerTeam), making them the top genomic foundation models in the field (2025-02).
14
+
15
+ Beyond benchmark performance, the GENERanno model is meticulously designed with its specialization in gene annotation. The model efficiently and accurately identifies gene locations, predicts gene function, and annotates gene structure, highlighting its potential to revolutionize genomic research by significantly enhancing the precision and efficiency of gene annotation processes.
16
+
17
+ The code and implementation details are available on Github: [https://github.com/GenerTeam/GENERanno](https://github.com/GenerTeam/GENERanno).
18
+
19
+ Please note that the GENERanno-eukaryote is currently in the developmental phase. We are actively refining the model and will release more technical details soon. Stay tuned for updates!
20
+
21
+ ## How to use
22
+ ### Simple example: embedding
23
+
24
+ ```python
25
+
26
+ import torch
27
+ from transformers import AutoTokenizer, AutoModel
28
+
29
+ # Load the tokenizer and model using the pretrained model name
30
+ tokenizer = AutoTokenizer.from_pretrained("GenerTeam/GENERanno-eukaryote-0.5b-base")
31
+ model = AutoModel.from_pretrained("GenerTeam/GENERanno-eukaryote-0.5b-base", trust_remote_code=True)
32
+
33
+ # Get model configuration and maximum sequence length
34
+ config = model.config
35
+ max_length = config.max_position_embeddings
36
+
37
+ # Define input sequences
38
+ sequences = [
39
+ "ATGAGGTGGCAAGAAATGGGCTAC",
40
+ "GAATTCCATGAGGCTATAGAATAATCTAAGAGAAAT"
41
+ ]
42
+
43
+ # Tokenize the sequences
44
+ # The add_special_tokens=True adds special tokens
45
+ tokenizer.padding_side = "right"
46
+ inputs = tokenizer(
47
+ sequences,
48
+ add_special_tokens=True,
49
+ return_tensors="pt",
50
+ padding=True,
51
+ truncation=True,
52
+ max_length=max_length
53
+ )
54
+
55
+ # Perform a forward pass through the model to obtain the outputs, including hidden states
56
+ with torch.inference_mode():
57
+ outputs = model(**inputs, output_hidden_states=True)
58
+
59
+ # Retrieve the hidden states from the last layer
60
+ # hidden_states shape: (batch_size, sequence_length, hidden_size)
61
+ hidden_states = outputs.hidden_states[-1]
62
+
63
+ # Option 1: Use the first token (BOS) as the sentence embedding
64
+ cls_embeddings = hidden_states[:, 0, :]
65
+
66
+ # Option 2: Use mean pooling over the token embeddings
67
+ # Use the attention mask to take care of the padded tokens
68
+ attention_mask = inputs["attention_mask"] # Shape: (batch_size, sequence_length)
69
+ # Expand the attention mask dimensions so that it matches the hidden_states dimensions
70
+ expanded_mask = attention_mask.unsqueeze(-1).expand(hidden_states.size()).to(torch.float32)
71
+ # Sum the token embeddings, taking the mask into account
72
+ sum_embeddings = torch.sum(hidden_states * expanded_mask, dim=1)
73
+ # Compute the average by dividing with the sum of the attention mask
74
+ mean_embeddings = sum_embeddings / expanded_mask.sum(dim=1)
75
+
76
+ print("BOS Embeddings:", cls_embeddings)
77
+ print("Mean Embeddings:", mean_embeddings)
78
+ ```
79
+
80
+ ## Citation
81
+ ```
82
+ @article{li2025generanno,
83
+ author = {Li, Qiuyi and Wu, Wei and Zhu, Yiheng and Feng, Fuli and Ye, Jieping and Wang, Zheng},
84
+ title = {GENERanno: A Genomic Foundation Model for Metagenomic Annotation},
85
+ elocation-id = {2025.06.04.656517},
86
+ year = {2025},
87
+ doi = {10.1101/2025.06.04.656517},
88
+ publisher = {Cold Spring Harbor Laboratory},
89
+ URL = {https://www.biorxiv.org/content/early/2025/06/05/2025.06.04.656517},
90
+ journal = {bioRxiv}
91
+ }
92
+ ```
GENERanno-eukaryote-0.5b-base/config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GenerannoForMaskedLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_generanno.GenerannoConfig",
7
+ "AutoModel": "modeling_generanno.GenerannoModel",
8
+ "AutoModelForMaskedLM": "modeling_generanno.GenerannoForMaskedLM",
9
+ "AutoModelForSequenceClassification": "modeling_generanno.GenerannoForSequenceClassification",
10
+ "AutoModelForTokenClassification": "modeling_generanno.GenerannoForTokenClassification"
11
+ },
12
+ "attention_bias": false,
13
+ "attention_dropout": 0.0,
14
+ "bos_token_id": 1,
15
+ "eos_token_id": 2,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 1280,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 3520,
20
+ "mask_token_id": 4,
21
+ "max_position_embeddings": 8192,
22
+ "mlp_bias": false,
23
+ "model_type": "generanno",
24
+ "num_attention_heads": 16,
25
+ "num_hidden_layers": 28,
26
+ "num_key_value_heads": 4,
27
+ "pad_token_id": 3,
28
+ "pretraining_tp": 1,
29
+ "rms_norm_eps": 1e-05,
30
+ "rope_scaling": null,
31
+ "rope_theta": 500000.0,
32
+ "tie_word_embeddings": false,
33
+ "dtype": "float32",
34
+ "transformers_version": "4.44.0",
35
+ "vocab_size": 64
36
+ }
GENERanno-eukaryote-0.5b-base/configuration_generanno.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class GenerannoConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`GenerannoModel`]. It is used to instantiate an LLaMA
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the LLaMA-7B.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 32000):
38
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`GenerannoModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 11008):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer decoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer decoder.
48
+ num_key_value_heads (`int`, *optional*):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
55
+ `num_attention_heads`.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
57
+ The non-linear activation function (function or string) in the decoder.
58
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
59
+ The maximum sequence length that this model might ever be used with. Generanno 1 supports up to 2048 tokens,
60
+ Generanno 2 up to 4096, CodeGeneranno up to 16384.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ pad_token_id (`int`, *optional*):
69
+ Padding token id.
70
+ bos_token_id (`int`, *optional*, defaults to 1):
71
+ Beginning of stream token id.
72
+ eos_token_id (`int`, *optional*, defaults to 2):
73
+ End of stream token id.
74
+ pretraining_tp (`int`, *optional*, defaults to 1):
75
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
76
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
77
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
78
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
79
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
80
+ Whether to tie weight embeddings
81
+ rope_theta (`float`, *optional*, defaults to 10000.0):
82
+ The base period of the RoPE embeddings.
83
+ rope_scaling (`Dict`, *optional*):
84
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
85
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
86
+ accordingly.
87
+ Expected contents:
88
+ `rope_type` (`str`):
89
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
90
+ 'llama3'], with 'default' being the original RoPE implementation.
91
+ `factor` (`float`, *optional*):
92
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
93
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
94
+ original maximum pre-trained length.
95
+ `original_max_position_embeddings` (`int`, *optional*):
96
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
97
+ pretraining.
98
+ `attention_factor` (`float`, *optional*):
99
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
100
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
101
+ `factor` field to infer the suggested value.
102
+ `beta_fast` (`float`, *optional*):
103
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
104
+ ramp function. If unspecified, it defaults to 32.
105
+ `beta_slow` (`float`, *optional*):
106
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
107
+ ramp function. If unspecified, it defaults to 1.
108
+ `short_factor` (`List[float]`, *optional*):
109
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
110
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
111
+ size divided by the number of attention heads divided by 2
112
+ `long_factor` (`List[float]`, *optional*):
113
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
114
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
115
+ size divided by the number of attention heads divided by 2
116
+ `low_freq_factor` (`float`, *optional*):
117
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
118
+ `high_freq_factor` (`float`, *optional*):
119
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
120
+ attention_bias (`bool`, *optional*, defaults to `False`):
121
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
122
+ attention_dropout (`float`, *optional*, defaults to 0.0):
123
+ The dropout ratio for the attention probabilities.
124
+ mlp_bias (`bool`, *optional*, defaults to `False`):
125
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
126
+ """
127
+
128
+ model_type = "generanno"
129
+
130
+ def __init__(
131
+ self,
132
+ vocab_size=32000,
133
+ hidden_size=4096,
134
+ intermediate_size=11008,
135
+ num_hidden_layers=32,
136
+ num_attention_heads=32,
137
+ num_key_value_heads=None,
138
+ hidden_act="silu",
139
+ max_position_embeddings=2048,
140
+ initializer_range=0.02,
141
+ rms_norm_eps=1e-6,
142
+ pad_token_id=None,
143
+ bos_token_id=1,
144
+ eos_token_id=2,
145
+ mask_token_id=4,
146
+ pretraining_tp=1,
147
+ tie_word_embeddings=False,
148
+ rope_theta=10000.0,
149
+ rope_scaling=None,
150
+ attention_bias=False,
151
+ attention_dropout=0.0,
152
+ mlp_bias=False,
153
+ **kwargs,
154
+ ):
155
+ self.vocab_size = vocab_size
156
+ self.max_position_embeddings = max_position_embeddings
157
+ self.hidden_size = hidden_size
158
+ self.intermediate_size = intermediate_size
159
+ self.num_hidden_layers = num_hidden_layers
160
+ self.num_attention_heads = num_attention_heads
161
+
162
+ # for backward compatibility
163
+ if num_key_value_heads is None:
164
+ num_key_value_heads = num_attention_heads
165
+
166
+ self.num_key_value_heads = num_key_value_heads
167
+ self.hidden_act = hidden_act
168
+ self.initializer_range = initializer_range
169
+ self.rms_norm_eps = rms_norm_eps
170
+ self.pretraining_tp = pretraining_tp
171
+ self.rope_theta = rope_theta
172
+ self.rope_scaling = rope_scaling
173
+ self.attention_bias = attention_bias
174
+ self.attention_dropout = attention_dropout
175
+ self.mlp_bias = mlp_bias
176
+
177
+ # Validate the correctness of rotary position embeddings parameters
178
+ # BC: if there is a 'type' field, move it to 'rope_type'.
179
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
180
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
181
+ rope_config_validation(self)
182
+
183
+ super().__init__(
184
+ pad_token_id=pad_token_id,
185
+ bos_token_id=bos_token_id,
186
+ eos_token_id=eos_token_id,
187
+ mask_token_id=mask_token_id,
188
+ tie_word_embeddings=tie_word_embeddings,
189
+ **kwargs,
190
+ )
GENERanno-eukaryote-0.5b-base/modeling_generanno.py ADDED
@@ -0,0 +1,1273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ import math
21
+ import random
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple, Union, List, Any
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn, Tensor
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+ from transformers.activations import ACT2FN
31
+ from transformers.modeling_attn_mask_utils import (
32
+ _prepare_4d_attention_mask_for_sdpa,
33
+ _prepare_4d_attention_mask
34
+ )
35
+
36
+ from transformers.modeling_outputs import (
37
+ ModelOutput,
38
+ TokenClassifierOutput,
39
+ BaseModelOutput,
40
+ MaskedLMOutput,
41
+ SequenceClassifierOutput,
42
+ )
43
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
44
+ from transformers.modeling_utils import PreTrainedModel
45
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
46
+ from transformers.utils import (
47
+ logging,
48
+ )
49
+
50
+ from .configuration_generanno import GenerannoConfig
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+ _CONFIG_FOR_DOC = "GenerannoConfig"
55
+
56
+ try:
57
+ from flash_attn import flash_attn_func
58
+ FLASH_ATTN_AVAILABLE = True
59
+ except ImportError:
60
+ FLASH_ATTN_AVAILABLE = False
61
+
62
+
63
+ class GenerannoRMSNorm(nn.Module):
64
+ def __init__(self, hidden_size, eps=1e-6):
65
+ """
66
+ GenerannoRMSNorm is equivalent to T5LayerNorm
67
+ """
68
+ super().__init__()
69
+ self.weight = nn.Parameter(torch.ones(hidden_size))
70
+ self.variance_epsilon = eps
71
+
72
+ def forward(self, hidden_states):
73
+ input_dtype = hidden_states.dtype
74
+ hidden_states = hidden_states.to(torch.float32)
75
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
76
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
77
+ return self.weight * hidden_states.to(input_dtype)
78
+
79
+ def extra_repr(self):
80
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
81
+
82
+
83
+ ALL_LAYERNORM_LAYERS.append(GenerannoRMSNorm)
84
+
85
+
86
+ class GenerannoRotaryEmbedding(nn.Module):
87
+ def __init__(
88
+ self,
89
+ dim=None,
90
+ max_position_embeddings=2048,
91
+ base=10000,
92
+ device=None,
93
+ scaling_factor=1.0,
94
+ rope_type="default",
95
+ config: Optional[GenerannoConfig] = None,
96
+ ):
97
+ super().__init__()
98
+ # TODO (joao): remove the `if` below, only used for BC
99
+ self.rope_kwargs = {}
100
+ if config is None:
101
+ logger.warning_once(
102
+ "`GenerannoRotaryEmbedding` can now be fully parameterized by passing the model config through the "
103
+ "`config` argument. All other arguments will be removed in v4.45"
104
+ )
105
+ self.rope_kwargs = {
106
+ "rope_type": rope_type,
107
+ "factor": scaling_factor,
108
+ "dim": dim,
109
+ "base": base,
110
+ "max_position_embeddings": max_position_embeddings,
111
+ }
112
+ self.rope_type = rope_type
113
+ self.max_seq_len_cached = max_position_embeddings
114
+ self.original_max_seq_len = max_position_embeddings
115
+ else:
116
+ # BC: "rope_type" was originally "type"
117
+ if config.rope_scaling is not None:
118
+ self.rope_type = config.rope_scaling.get(
119
+ "rope_type", config.rope_scaling.get("type")
120
+ )
121
+ else:
122
+ self.rope_type = "default"
123
+ self.max_seq_len_cached = config.max_position_embeddings
124
+ self.original_max_seq_len = config.max_position_embeddings
125
+
126
+ self.config = config
127
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
128
+
129
+ inv_freq, self.attention_scaling = self.rope_init_fn(
130
+ self.config, device, **self.rope_kwargs
131
+ )
132
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
133
+ self.original_inv_freq = self.inv_freq
134
+
135
+ def _dynamic_frequency_update(self, position_ids, device):
136
+ """
137
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
138
+ 1 - growing beyond the cached sequence length (allow scaling)
139
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
140
+ """
141
+ seq_len = torch.max(position_ids) + 1
142
+ if seq_len > self.max_seq_len_cached: # growth
143
+ inv_freq, self.attention_scaling = self.rope_init_fn(
144
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
145
+ )
146
+ self.register_buffer(
147
+ "inv_freq", inv_freq, persistent=False
148
+ ) # TODO joao: may break with compilation
149
+ self.max_seq_len_cached = seq_len
150
+
151
+ if (
152
+ seq_len < self.original_max_seq_len
153
+ and self.max_seq_len_cached > self.original_max_seq_len
154
+ ): # reset
155
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
156
+ self.max_seq_len_cached = self.original_max_seq_len
157
+
158
+ @torch.no_grad()
159
+ def forward(self, x, position_ids):
160
+ if "dynamic" in self.rope_type:
161
+ self._dynamic_frequency_update(position_ids, device=x.device)
162
+
163
+ # Core RoPE block
164
+ inv_freq_expanded = (
165
+ self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
166
+ )
167
+ position_ids_expanded = position_ids[:, None, :].float()
168
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
169
+ device_type = x.device.type
170
+ device_type = (
171
+ device_type
172
+ if isinstance(device_type, str) and device_type != "mps"
173
+ else "cpu"
174
+ )
175
+ with torch.autocast(device_type=device_type, enabled=False):
176
+ freqs = (
177
+ inv_freq_expanded.float() @ position_ids_expanded.float()
178
+ ).transpose(1, 2)
179
+ emb = torch.cat((freqs, freqs), dim=-1)
180
+ cos = emb.cos()
181
+ sin = emb.sin()
182
+
183
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
184
+ cos = cos * self.attention_scaling
185
+ sin = sin * self.attention_scaling
186
+
187
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
188
+
189
+
190
+ class GenerannoLinearScalingRotaryEmbedding(GenerannoRotaryEmbedding):
191
+ """GenerannoRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
192
+
193
+ def __init__(self, *args, **kwargs):
194
+ logger.warning_once(
195
+ "`GenerannoLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
196
+ "`GenerannoRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
197
+ )
198
+ kwargs["rope_type"] = "linear"
199
+ super().__init__(*args, **kwargs)
200
+
201
+
202
+ class GenerannoDynamicNTKScalingRotaryEmbedding(GenerannoRotaryEmbedding):
203
+ """GenerannoRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
204
+
205
+ def __init__(self, *args, **kwargs):
206
+ logger.warning_once(
207
+ "`GenerannoDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
208
+ "`GenerannoRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
209
+ "__init__)."
210
+ )
211
+ kwargs["rope_type"] = "dynamic"
212
+ super().__init__(*args, **kwargs)
213
+
214
+
215
+ def rotate_half(x):
216
+ """Rotates half the hidden dims of the input."""
217
+ x1 = x[..., : x.shape[-1] // 2]
218
+ x2 = x[..., x.shape[-1] // 2 :]
219
+ return torch.cat((-x2, x1), dim=-1)
220
+
221
+
222
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
223
+ """Applies Rotary Position Embedding to the query and key tensors.
224
+
225
+ Args:
226
+ q (`torch.Tensor`): The query tensor.
227
+ k (`torch.Tensor`): The key tensor.
228
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
229
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
230
+ position_ids (`torch.Tensor`, *optional*):
231
+ Deprecated and unused.
232
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
233
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
234
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
235
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
236
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
237
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
238
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
239
+ Returns:
240
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
241
+ """
242
+ cos = cos.unsqueeze(unsqueeze_dim)
243
+ sin = sin.unsqueeze(unsqueeze_dim)
244
+ q_embed = (q * cos) + (rotate_half(q) * sin)
245
+ k_embed = (k * cos) + (rotate_half(k) * sin)
246
+ return q_embed, k_embed
247
+
248
+
249
+ class GenerannoMLP(nn.Module):
250
+ def __init__(self, config):
251
+ super().__init__()
252
+ self.config = config
253
+ self.hidden_size = config.hidden_size
254
+ self.intermediate_size = config.intermediate_size
255
+ self.gate_proj = nn.Linear(
256
+ self.hidden_size, self.intermediate_size, bias=config.mlp_bias
257
+ )
258
+ self.up_proj = nn.Linear(
259
+ self.hidden_size, self.intermediate_size, bias=config.mlp_bias
260
+ )
261
+ self.down_proj = nn.Linear(
262
+ self.intermediate_size, self.hidden_size, bias=config.mlp_bias
263
+ )
264
+ self.act_fn = ACT2FN[config.hidden_act]
265
+
266
+ def forward(self, x):
267
+ if self.config.pretraining_tp > 1:
268
+ slice = self.intermediate_size // self.config.pretraining_tp
269
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
270
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
271
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
272
+
273
+ gate_proj = torch.cat(
274
+ [
275
+ F.linear(x, gate_proj_slices[i])
276
+ for i in range(self.config.pretraining_tp)
277
+ ],
278
+ dim=-1,
279
+ )
280
+ up_proj = torch.cat(
281
+ [
282
+ F.linear(x, up_proj_slices[i])
283
+ for i in range(self.config.pretraining_tp)
284
+ ],
285
+ dim=-1,
286
+ )
287
+
288
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
289
+ down_proj = [
290
+ F.linear(intermediate_states[i], down_proj_slices[i])
291
+ for i in range(self.config.pretraining_tp)
292
+ ]
293
+ down_proj = sum(down_proj)
294
+ else:
295
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
296
+
297
+ return down_proj
298
+
299
+
300
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
301
+ """
302
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
303
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
304
+ """
305
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
306
+ if n_rep == 1:
307
+ return hidden_states
308
+ hidden_states = hidden_states[:, :, None, :, :].expand(
309
+ batch, num_key_value_heads, n_rep, slen, head_dim
310
+ )
311
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
312
+
313
+
314
+ class GenerannoAttention(nn.Module):
315
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
316
+
317
+ def __init__(self, config: GenerannoConfig, layer_idx: Optional[int] = None):
318
+ super().__init__()
319
+ self.config = config
320
+ self.layer_idx = layer_idx
321
+ if layer_idx is None:
322
+ logger.warning_once(
323
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
324
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
325
+ "when creating this class."
326
+ )
327
+
328
+ self.attention_dropout = config.attention_dropout
329
+ self.hidden_size = config.hidden_size
330
+ self.num_heads = config.num_attention_heads
331
+ self.head_dim = self.hidden_size // self.num_heads
332
+ self.num_key_value_heads = config.num_key_value_heads
333
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
334
+ self.max_position_embeddings = config.max_position_embeddings
335
+ self.rope_theta = config.rope_theta
336
+
337
+ if (self.head_dim * self.num_heads) != self.hidden_size:
338
+ raise ValueError(
339
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
340
+ f" and `num_heads`: {self.num_heads})."
341
+ )
342
+
343
+ self.q_proj = nn.Linear(
344
+ self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
345
+ )
346
+ self.k_proj = nn.Linear(
347
+ self.hidden_size,
348
+ self.num_key_value_heads * self.head_dim,
349
+ bias=config.attention_bias,
350
+ )
351
+ self.v_proj = nn.Linear(
352
+ self.hidden_size,
353
+ self.num_key_value_heads * self.head_dim,
354
+ bias=config.attention_bias,
355
+ )
356
+ self.o_proj = nn.Linear(
357
+ self.hidden_size, self.hidden_size, bias=config.attention_bias
358
+ )
359
+
360
+ # TODO (joao): remove in v4.45 (RoPE is computed in the model, not in the encoder layers)
361
+ self.rotary_emb = GenerannoRotaryEmbedding(config=self.config)
362
+
363
+ def forward(
364
+ self,
365
+ hidden_states: torch.Tensor,
366
+ attention_mask: Optional[torch.Tensor] = None,
367
+ position_ids: Optional[torch.LongTensor] = None,
368
+ output_attentions: bool = False,
369
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
370
+ is_causal: bool = False,
371
+ **kwargs,
372
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
373
+ bsz, q_len, _ = hidden_states.size()
374
+
375
+ if self.config.pretraining_tp > 1:
376
+ key_value_slicing = (
377
+ self.num_key_value_heads * self.head_dim
378
+ ) // self.config.pretraining_tp
379
+ query_slices = self.q_proj.weight.split(
380
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
381
+ )
382
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
383
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
384
+
385
+ query_states = [
386
+ F.linear(hidden_states, query_slices[i])
387
+ for i in range(self.config.pretraining_tp)
388
+ ]
389
+ query_states = torch.cat(query_states, dim=-1)
390
+
391
+ key_states = [
392
+ F.linear(hidden_states, key_slices[i])
393
+ for i in range(self.config.pretraining_tp)
394
+ ]
395
+ key_states = torch.cat(key_states, dim=-1)
396
+
397
+ value_states = [
398
+ F.linear(hidden_states, value_slices[i])
399
+ for i in range(self.config.pretraining_tp)
400
+ ]
401
+ value_states = torch.cat(value_states, dim=-1)
402
+
403
+ else:
404
+ query_states = self.q_proj(hidden_states)
405
+ key_states = self.k_proj(hidden_states)
406
+ value_states = self.v_proj(hidden_states)
407
+
408
+ query_states = query_states.view(
409
+ bsz, q_len, self.num_heads, self.head_dim
410
+ ).transpose(1, 2)
411
+ key_states = key_states.view(
412
+ bsz, q_len, self.num_key_value_heads, self.head_dim
413
+ ).transpose(1, 2)
414
+ value_states = value_states.view(
415
+ bsz, q_len, self.num_key_value_heads, self.head_dim
416
+ ).transpose(1, 2)
417
+
418
+ if position_embeddings is None:
419
+ logger.warning_once(
420
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
421
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
422
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
423
+ "removed and `position_embeddings` will be mandatory."
424
+ )
425
+ cos, sin = self.rotary_emb(value_states, position_ids)
426
+ else:
427
+ cos, sin = position_embeddings
428
+ query_states, key_states = apply_rotary_pos_emb(
429
+ query_states, key_states, cos, sin
430
+ )
431
+
432
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
433
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
434
+
435
+ attn_weights = torch.matmul(
436
+ query_states, key_states.transpose(2, 3)
437
+ ) / math.sqrt(self.head_dim)
438
+
439
+ if attention_mask is not None:
440
+ attn_weights = attn_weights + attention_mask
441
+
442
+ # upcast attention to fp32
443
+ attn_weights = nn.functional.softmax(
444
+ attn_weights, dim=-1, dtype=torch.float32
445
+ ).to(query_states.dtype)
446
+ attn_weights = nn.functional.dropout(
447
+ attn_weights, p=self.attention_dropout, training=self.training
448
+ )
449
+ attn_output = torch.matmul(attn_weights, value_states)
450
+
451
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
452
+ raise ValueError(
453
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
454
+ f" {attn_output.size()}"
455
+ )
456
+
457
+ attn_output = attn_output.transpose(1, 2).contiguous()
458
+
459
+ attn_output = attn_output.reshape(bsz, q_len, -1)
460
+
461
+ if self.config.pretraining_tp > 1:
462
+ attn_output = attn_output.split(
463
+ self.hidden_size // self.config.pretraining_tp, dim=2
464
+ )
465
+ o_proj_slices = self.o_proj.weight.split(
466
+ self.hidden_size // self.config.pretraining_tp, dim=1
467
+ )
468
+ attn_output = sum(
469
+ [
470
+ F.linear(attn_output[i], o_proj_slices[i])
471
+ for i in range(self.config.pretraining_tp)
472
+ ]
473
+ )
474
+ else:
475
+ attn_output = self.o_proj(attn_output)
476
+
477
+ if not output_attentions:
478
+ attn_weights = None
479
+
480
+ return attn_output, attn_weights
481
+
482
+
483
+ class GenerannoSdpaAttention(GenerannoAttention):
484
+ """
485
+ Generanno attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
486
+ `GenerannoAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
487
+ SDPA API.
488
+ """
489
+
490
+ # Adapted from GenerannoAttention.forward
491
+ def forward(
492
+ self,
493
+ hidden_states: torch.Tensor,
494
+ attention_mask: Optional[torch.Tensor] = None,
495
+ position_ids: Optional[torch.LongTensor] = None,
496
+ output_attentions: bool = False,
497
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
498
+ is_causal: bool = False,
499
+ **kwargs,
500
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
501
+ if output_attentions:
502
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
503
+ logger.warning_once(
504
+ "GenerannoModel is using GenerannoSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
505
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
506
+ )
507
+ return super().forward(
508
+ hidden_states=hidden_states,
509
+ attention_mask=attention_mask,
510
+ position_ids=position_ids,
511
+ output_attentions=output_attentions,
512
+ position_embeddings=position_embeddings,
513
+ )
514
+
515
+ bsz, q_len, _ = hidden_states.size()
516
+
517
+ query_states = self.q_proj(hidden_states)
518
+ key_states = self.k_proj(hidden_states)
519
+ value_states = self.v_proj(hidden_states)
520
+
521
+ query_states = query_states.view(
522
+ bsz, q_len, self.num_heads, self.head_dim
523
+ ).transpose(1, 2)
524
+ key_states = key_states.view(
525
+ bsz, q_len, self.num_key_value_heads, self.head_dim
526
+ ).transpose(1, 2)
527
+ value_states = value_states.view(
528
+ bsz, q_len, self.num_key_value_heads, self.head_dim
529
+ ).transpose(1, 2)
530
+
531
+ if position_embeddings is None:
532
+ logger.warning_once(
533
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
534
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
535
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
536
+ "removed and `position_embeddings` will be mandatory."
537
+ )
538
+ cos, sin = self.rotary_emb(value_states, position_ids)
539
+ else:
540
+ cos, sin = position_embeddings
541
+ query_states, key_states = apply_rotary_pos_emb(
542
+ query_states, key_states, cos, sin
543
+ )
544
+
545
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
546
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
547
+
548
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
549
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
550
+ if query_states.device.type == "cuda" and attention_mask is not None:
551
+ query_states = query_states.contiguous()
552
+ key_states = key_states.contiguous()
553
+ value_states = value_states.contiguous()
554
+ attention_mask = attention_mask.bool()
555
+
556
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
557
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
558
+
559
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
560
+ query_states,
561
+ key_states,
562
+ value_states,
563
+ attn_mask=attention_mask,
564
+ dropout_p=self.attention_dropout if self.training else 0.0,
565
+ is_causal=is_causal,
566
+ )
567
+
568
+ attn_output = attn_output.transpose(1, 2).contiguous()
569
+ attn_output = attn_output.view(bsz, q_len, -1)
570
+
571
+ attn_output = self.o_proj(attn_output)
572
+
573
+ return attn_output, None
574
+
575
+ class GenerannoFlashAttention2(GenerannoSdpaAttention):
576
+ """
577
+ Generanno attention module using Flash Attention 2. This module inherits from
578
+ `GenerannoSdpaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
579
+ Flash Attention 2 API.
580
+ """
581
+
582
+ def forward(
583
+ self,
584
+ hidden_states: torch.Tensor,
585
+ attention_mask: Optional[torch.Tensor] = None,
586
+ position_ids: Optional[torch.LongTensor] = None,
587
+ output_attentions: bool = False,
588
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
589
+ is_causal: bool = False,
590
+ **kwargs,
591
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
592
+ if output_attentions:
593
+ logger.warning_once(
594
+ "GenerannoModel is using GenerannoFlashAttention2, but `flash_attn_func` does not support `output_attentions=True`. Falling back to the manual attention implementation."
595
+ )
596
+ return super().forward( # 现在会回退到SDPA!
597
+ hidden_states=hidden_states,
598
+ attention_mask=attention_mask,
599
+ position_ids=position_ids,
600
+ output_attentions=output_attentions,
601
+ position_embeddings=position_embeddings,
602
+ is_causal=is_causal,
603
+ )
604
+
605
+ if not FLASH_ATTN_AVAILABLE:
606
+ raise ImportError("Flash Attention 2 is not available. Please install it via `pip install flash-attn --no-build-isolation`")
607
+
608
+ # 检查是否需要回退到SDPA(有padding的情况)
609
+ if attention_mask is not None:
610
+ # 检查是否有真正的padding
611
+ if not torch.all(attention_mask == 1):
612
+ logger.warning_once(
613
+ "GenerannoModel is using GenerannoFlashAttention2, but `flash_attn_func` does not support `attention_mask`. Falling back to the manual attention implementation."
614
+ )
615
+ return super().forward( # 调用父类SDPA的实现
616
+ hidden_states=hidden_states,
617
+ attention_mask=attention_mask,
618
+ position_ids=position_ids,
619
+ output_attentions=output_attentions,
620
+ position_embeddings=position_embeddings,
621
+ is_causal=is_causal,
622
+ )
623
+
624
+ # flash attenton 2 只处理不带padding的情况
625
+ bsz, q_len, _ = hidden_states.size()
626
+
627
+ query_states = self.q_proj(hidden_states)
628
+ key_states = self.k_proj(hidden_states)
629
+ value_states = self.v_proj(hidden_states)
630
+
631
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
632
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
633
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
634
+
635
+ if position_embeddings is None:
636
+ cos, sin = self.rotary_emb(value_states, position_ids)
637
+ else:
638
+ cos, sin = position_embeddings
639
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
640
+
641
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
642
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
643
+
644
+ # Flash Attention 2 expects (batch_size, seqlen, nheads, headdim)
645
+ query_states = query_states.transpose(1, 2)
646
+ key_states = key_states.transpose(1, 2)
647
+ value_states = value_states.transpose(1, 2)
648
+
649
+ # 确保张量是连续的
650
+ query_states = query_states.contiguous()
651
+ key_states = key_states.contiguous()
652
+ value_states = value_states.contiguous()
653
+
654
+ attn_output = flash_attn_func(
655
+ query_states,
656
+ key_states,
657
+ value_states,
658
+ dropout_p=self.attention_dropout if self.training else 0.0,
659
+ softmax_scale=1.0 / math.sqrt(self.head_dim),
660
+ causal=is_causal,
661
+ )
662
+
663
+ attn_output = attn_output.reshape(bsz, q_len, -1)
664
+ attn_output = self.o_proj(attn_output)
665
+
666
+ return attn_output, None
667
+
668
+ GENERANNO_ATTENTION_CLASSES = {
669
+ "eager": GenerannoAttention,
670
+ "sdpa": GenerannoSdpaAttention,
671
+ "flash_attention_2": GenerannoFlashAttention2,
672
+ }
673
+
674
+ class GenerannoEncoderLayer(nn.Module):
675
+ def __init__(self, config: GenerannoConfig, layer_idx: int):
676
+ super().__init__()
677
+ self.hidden_size = config.hidden_size
678
+
679
+ self.self_attn = GENERANNO_ATTENTION_CLASSES[config._attn_implementation](
680
+ config=config, layer_idx=layer_idx
681
+ )
682
+
683
+ self.mlp = GenerannoMLP(config)
684
+ self.input_layernorm = GenerannoRMSNorm(
685
+ config.hidden_size, eps=config.rms_norm_eps
686
+ )
687
+ self.post_attention_layernorm = GenerannoRMSNorm(
688
+ config.hidden_size, eps=config.rms_norm_eps
689
+ )
690
+
691
+ def forward(
692
+ self,
693
+ hidden_states: torch.Tensor,
694
+ attention_mask: Optional[torch.Tensor] = None,
695
+ position_ids: Optional[torch.LongTensor] = None,
696
+ output_attentions: Optional[bool] = False,
697
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
698
+ is_causal: bool = False,
699
+ **kwargs,
700
+ ) -> tuple[Tensor | Any]:
701
+ """
702
+ Args:
703
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
704
+ attention_mask (`torch.FloatTensor`, *optional*):
705
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
706
+ query_sequence_length, key_sequence_length)` if default attention is used.
707
+ output_attentions (`bool`, *optional*):
708
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
709
+ returned tensors for more detail.
710
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
711
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
712
+ with `head_dim` being the embedding dimension of each attention head.
713
+ kwargs (`dict`, *optional*):
714
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
715
+ into the model
716
+ """
717
+ residual = hidden_states
718
+
719
+ hidden_states = self.input_layernorm(hidden_states)
720
+
721
+ # Self Attention
722
+ hidden_states, self_attn_weights = self.self_attn(
723
+ hidden_states=hidden_states,
724
+ attention_mask=attention_mask,
725
+ position_ids=position_ids,
726
+ output_attentions=output_attentions,
727
+ position_embeddings=position_embeddings,
728
+ is_causal=is_causal,
729
+ **kwargs,
730
+ )
731
+ hidden_states = residual + hidden_states
732
+
733
+ # Fully Connected
734
+ residual = hidden_states
735
+ hidden_states = self.post_attention_layernorm(hidden_states)
736
+ hidden_states = self.mlp(hidden_states)
737
+ hidden_states = residual + hidden_states
738
+
739
+ outputs = (hidden_states,)
740
+
741
+ if output_attentions:
742
+ outputs += (self_attn_weights,)
743
+
744
+ return outputs
745
+
746
+
747
+ class GenerannoPreTrainedModel(PreTrainedModel):
748
+ config_class = GenerannoConfig
749
+ base_model_prefix = "model"
750
+ supports_gradient_checkpointing = True
751
+ _no_split_modules = ["GenerannoEncoderLayer"]
752
+ _supports_flash_attn_2 = True
753
+ _supports_sdpa = True
754
+
755
+ def _init_weights(self, module):
756
+
757
+ std = self.config.initializer_range
758
+ if isinstance(module, nn.Linear):
759
+ module.weight.data.normal_(mean=0.0, std=std)
760
+ if module.bias is not None:
761
+ module.bias.data.zero_()
762
+ elif isinstance(module, nn.Embedding):
763
+ module.weight.data.normal_(mean=0.0, std=std)
764
+ if module.padding_idx is not None:
765
+ module.weight.data[module.padding_idx].zero_()
766
+
767
+
768
+ class GenerannoModel(GenerannoPreTrainedModel):
769
+ """
770
+ Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GenerannoEncoderLayer`]
771
+
772
+ Args:
773
+ config: GenerannoConfig
774
+ """
775
+
776
+ def __init__(self, config: GenerannoConfig):
777
+ super().__init__(config)
778
+ self.padding_idx = config.pad_token_id
779
+ self.vocab_size = config.vocab_size
780
+
781
+ self.embed_tokens = nn.Embedding(
782
+ config.vocab_size, config.hidden_size, self.padding_idx
783
+ )
784
+ self.layers = nn.ModuleList(
785
+ [
786
+ GenerannoEncoderLayer(config, layer_idx)
787
+ for layer_idx in range(config.num_hidden_layers)
788
+ ]
789
+ )
790
+ self.norm = GenerannoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
791
+ self.rotary_emb = GenerannoRotaryEmbedding(config=config)
792
+ self.gradient_checkpointing = getattr(config, "gradient_checkpointing", False)
793
+ self.target_dtype = self.embed_tokens.weight.dtype
794
+
795
+ # Initialize weights and apply final processing
796
+ self.post_init()
797
+
798
+ # 添加gradient_checkpointing_enable方法供Trainer调用
799
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
800
+ if gradient_checkpointing_kwargs is None:
801
+ gradient_checkpointing_kwargs = {}
802
+
803
+ self.gradient_checkpointing = True
804
+ # 确保配置一致性
805
+ self.config.gradient_checkpointing = True
806
+
807
+ # 调用父类的方法来设置_gradient_checkpointing_func
808
+ if hasattr(super(), 'gradient_checkpointing_enable'):
809
+ super().gradient_checkpointing_enable(gradient_checkpointing_kwargs=gradient_checkpointing_kwargs)
810
+
811
+ def get_input_embeddings(self):
812
+ return self.embed_tokens
813
+
814
+ def set_input_embeddings(self, value):
815
+ self.embed_tokens = value
816
+
817
+ def _prepare_attention_mask(self, attention_mask, inputs_embeds):
818
+ attn_impl = self.config._attn_implementation
819
+
820
+ # 情况1: 标准Transformer - 总是需要mask
821
+ if attn_impl == "eager":
822
+ if attention_mask is None:
823
+ attention_mask = torch.ones_like(inputs_embeds[:, :, 0])
824
+ return _prepare_4d_attention_mask(
825
+ attention_mask, self.target_dtype,
826
+ tgt_len=inputs_embeds.shape[1]
827
+ )
828
+
829
+ # 情况2: SDPA 和 Flash Attention 2
830
+ elif attn_impl in ["sdpa", "flash_attention_2"]:
831
+ if (attention_mask is None) or torch.all(attention_mask == 1):
832
+ # ✅ 没有padding,让SDPA/Flash Attention通过is_causal参数处理
833
+ return None
834
+ else:
835
+ # 有外部提供的mask,正常转换
836
+ return _prepare_4d_attention_mask_for_sdpa(
837
+ attention_mask, self.target_dtype,
838
+ tgt_len=inputs_embeds.shape[1]
839
+ )
840
+
841
+ else:
842
+ raise ValueError(f"Unsupported attention implementation: {attn_impl}")
843
+
844
+ def forward(
845
+ self,
846
+ input_ids: torch.LongTensor = None,
847
+ attention_mask: Optional[torch.Tensor] = None,
848
+ position_ids: Optional[torch.LongTensor] = None,
849
+ inputs_embeds: Optional[torch.FloatTensor] = None,
850
+ output_attentions: Optional[bool] = None,
851
+ output_hidden_states: Optional[bool] = None,
852
+ token_type_ids: Optional[torch.LongTensor] = None,
853
+ return_dict: Optional[bool] = None,
854
+ is_causal: bool = False,
855
+ ) -> tuple[tuple, ...] | BaseModelOutput:
856
+ output_attentions = (
857
+ output_attentions
858
+ if output_attentions is not None
859
+ else self.config.output_attentions
860
+ )
861
+ output_hidden_states = (
862
+ output_hidden_states
863
+ if output_hidden_states is not None
864
+ else self.config.output_hidden_states
865
+ )
866
+ return_dict = (
867
+ return_dict if return_dict is not None else self.config.use_return_dict
868
+ )
869
+
870
+ if (input_ids is None) ^ (inputs_embeds is not None):
871
+ raise ValueError(
872
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
873
+ )
874
+
875
+ if inputs_embeds is None:
876
+ inputs_embeds = self.embed_tokens(input_ids)
877
+
878
+ if position_ids is None:
879
+ position_ids = torch.arange(
880
+ 0, inputs_embeds.shape[1], device=inputs_embeds.device
881
+ ).unsqueeze(0)
882
+
883
+ attention_mask = self._prepare_attention_mask(attention_mask, inputs_embeds)
884
+
885
+ hidden_states = inputs_embeds
886
+
887
+ # create position embeddings to be shared across the encoder layers
888
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
889
+
890
+ # encoder layers
891
+ all_hidden_states = () if output_hidden_states else None
892
+ all_self_attns = () if output_attentions else None
893
+
894
+ for encoder_layer in self.layers:
895
+ if output_hidden_states:
896
+ all_hidden_states += (hidden_states,)
897
+
898
+ if self.gradient_checkpointing and self.training:
899
+ layer_outputs = self._gradient_checkpointing_func(
900
+ encoder_layer.__call__,
901
+ hidden_states,
902
+ attention_mask,
903
+ position_ids,
904
+ output_attentions,
905
+ position_embeddings,
906
+ is_causal, # 传递参数
907
+ )
908
+ else:
909
+ layer_outputs = encoder_layer(
910
+ hidden_states,
911
+ attention_mask=attention_mask,
912
+ position_ids=position_ids,
913
+ output_attentions=output_attentions,
914
+ position_embeddings=position_embeddings,
915
+ is_causal=is_causal, # 传递参数
916
+ )
917
+
918
+ hidden_states = layer_outputs[0]
919
+
920
+ if output_attentions:
921
+ all_self_attns += (layer_outputs[1],)
922
+
923
+ hidden_states = self.norm(hidden_states)
924
+
925
+ # add hidden states from the last encoder layer
926
+ if output_hidden_states:
927
+ all_hidden_states += (hidden_states,)
928
+
929
+ if not return_dict:
930
+ return tuple(
931
+ v
932
+ for v in [hidden_states, all_hidden_states, all_self_attns]
933
+ if v is not None
934
+ )
935
+ return BaseModelOutput(
936
+ last_hidden_state=hidden_states,
937
+ hidden_states=all_hidden_states,
938
+ attentions=all_self_attns,
939
+ )
940
+
941
+
942
+ class GenerannoForMaskedLM(GenerannoPreTrainedModel):
943
+ _tied_weights_keys = ["lm_head.weight"]
944
+
945
+ def __init__(self, config):
946
+ super().__init__(config)
947
+
948
+ self.model = GenerannoModel(config)
949
+ self.vocab_size = config.vocab_size
950
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
951
+
952
+ self.init_weights()
953
+
954
+ def get_input_embeddings(self):
955
+ return self.model.embed_tokens
956
+
957
+ def set_input_embeddings(self, value):
958
+ self.model.embed_tokens = value
959
+
960
+ def get_output_embeddings(self):
961
+ return self.lm_head
962
+
963
+ def set_output_embeddings(self, new_embeddings):
964
+ self.lm_head = new_embeddings
965
+
966
+ def set_encoder(self, encoder):
967
+ self.model = encoder
968
+
969
+ def get_encoder(self):
970
+ return self.model
971
+
972
+ def forward(
973
+ self,
974
+ input_ids: torch.LongTensor = None,
975
+ attention_mask: Optional[torch.Tensor] = None,
976
+ position_ids: Optional[torch.LongTensor] = None,
977
+ inputs_embeds: Optional[torch.FloatTensor] = None,
978
+ labels: Optional[torch.LongTensor] = None,
979
+ output_attentions: Optional[bool] = None,
980
+ output_hidden_states: Optional[bool] = None,
981
+ return_dict: Optional[bool] = None,
982
+ ) -> Union[Tuple, MaskedLMOutput]:
983
+ r"""
984
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
985
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
986
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
987
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
988
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
989
+ Used to hide legacy arguments that have been deprecated.
990
+ """
991
+ return_dict = (
992
+ return_dict if return_dict is not None else self.config.use_return_dict
993
+ )
994
+
995
+ outputs = self.model(
996
+ input_ids,
997
+ attention_mask=attention_mask,
998
+ position_ids=position_ids,
999
+ inputs_embeds=inputs_embeds,
1000
+ output_attentions=output_attentions,
1001
+ output_hidden_states=output_hidden_states,
1002
+ return_dict=return_dict,
1003
+ )
1004
+ hidden_states = outputs[0]
1005
+ if self.config.pretraining_tp > 1:
1006
+ lm_head_slices = self.lm_head.weight.split(
1007
+ self.vocab_size // self.config.pretraining_tp, dim=0
1008
+ )
1009
+ logits = [
1010
+ F.linear(hidden_states, lm_head_slices[i])
1011
+ for i in range(self.config.pretraining_tp)
1012
+ ]
1013
+ logits = torch.cat(logits, dim=-1)
1014
+ else:
1015
+ logits = self.lm_head(hidden_states)
1016
+
1017
+ masked_lm_loss = None
1018
+ if labels is not None:
1019
+ loss_fct = CrossEntropyLoss()
1020
+
1021
+ labels = labels.to(logits.device)
1022
+ masked_lm_loss = loss_fct(
1023
+ logits.view(-1, self.config.vocab_size).float(), labels.view(-1)
1024
+ )
1025
+
1026
+ if not return_dict:
1027
+ output = (logits,) + outputs[2:]
1028
+ return (
1029
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1030
+ )
1031
+
1032
+ return MaskedLMOutput(
1033
+ loss=masked_lm_loss,
1034
+ logits=logits,
1035
+ hidden_states=outputs.hidden_states,
1036
+ attentions=outputs.attentions,
1037
+ )
1038
+
1039
+
1040
+ class GenerannoForSequenceClassification(GenerannoPreTrainedModel):
1041
+ def __init__(self, config):
1042
+ super().__init__(config)
1043
+ self.num_labels = config.num_labels
1044
+ self.config = config
1045
+
1046
+ self.model = GenerannoModel(config)
1047
+ self.feature_layer = getattr(config, "feature_layer", -1)
1048
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1049
+ if getattr(config, "use_mlp_classifier", False):
1050
+ self.score = nn.Sequential(
1051
+ nn.Linear(config.hidden_size, config.hidden_size),
1052
+ nn.GELU(),
1053
+ nn.Dropout(0.1),
1054
+ nn.Linear(config.hidden_size, self.num_labels, bias=False),
1055
+ )
1056
+
1057
+ # Initialize weights and apply final processing
1058
+ self.post_init()
1059
+
1060
+ def forward(
1061
+ self,
1062
+ input_ids: Optional[torch.LongTensor] = None,
1063
+ attention_mask: Optional[torch.Tensor] = None,
1064
+ position_ids: Optional[torch.LongTensor] = None,
1065
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1066
+ labels: Optional[torch.LongTensor] = None,
1067
+ output_attentions: Optional[bool] = None,
1068
+ output_hidden_states: Optional[bool] = None,
1069
+ return_dict: Optional[bool] = None,
1070
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1071
+ r"""
1072
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1073
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1074
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1075
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1076
+ """
1077
+ return_dict = (
1078
+ return_dict if return_dict is not None else self.config.use_return_dict
1079
+ )
1080
+
1081
+ if self.feature_layer == -1:
1082
+ outputs = self.model(
1083
+ input_ids,
1084
+ attention_mask=attention_mask,
1085
+ position_ids=position_ids,
1086
+ inputs_embeds=inputs_embeds,
1087
+ output_attentions=output_attentions,
1088
+ output_hidden_states=output_hidden_states,
1089
+ return_dict=return_dict,
1090
+ )
1091
+ hidden_states = outputs[0]
1092
+ else:
1093
+ outputs = self.model(
1094
+ input_ids,
1095
+ attention_mask=attention_mask,
1096
+ position_ids=position_ids,
1097
+ inputs_embeds=inputs_embeds,
1098
+ output_attentions=output_attentions,
1099
+ output_hidden_states=True,
1100
+ return_dict=return_dict,
1101
+ )
1102
+ hidden_states = outputs.hidden_states[self.feature_layer]
1103
+
1104
+ pooled_hidden_states = hidden_states[:, 0]
1105
+ logits = self.score(pooled_hidden_states)
1106
+
1107
+ loss = None
1108
+ if labels is not None:
1109
+ labels = labels.to(logits.device)
1110
+
1111
+ if self.config.problem_type is None:
1112
+ if self.num_labels == 1:
1113
+ self.config.problem_type = "regression"
1114
+ elif self.num_labels > 1 and (
1115
+ labels.dtype == torch.long or labels.dtype == torch.int
1116
+ ):
1117
+ self.config.problem_type = "single_label_classification"
1118
+ else:
1119
+ self.config.problem_type = "multi_label_classification"
1120
+
1121
+ if self.config.problem_type == "regression":
1122
+ loss_fct = MSELoss()
1123
+ if self.num_labels == 1:
1124
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1125
+ else:
1126
+ loss = loss_fct(logits, labels)
1127
+ elif self.config.problem_type == "single_label_classification":
1128
+ loss_fct = CrossEntropyLoss()
1129
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1130
+ elif self.config.problem_type == "multi_label_classification":
1131
+ loss_fct = BCEWithLogitsLoss()
1132
+ loss = loss_fct(logits, labels)
1133
+ if not return_dict:
1134
+ output = (logits,)
1135
+ return ((loss,) + output) if loss is not None else output
1136
+
1137
+ return SequenceClassifierOutput(loss=loss, logits=logits)
1138
+
1139
+
1140
+ class GenerannoForTokenClassification(GenerannoPreTrainedModel):
1141
+ def __init__(self, config):
1142
+ super().__init__(config)
1143
+ self.num_labels = config.num_labels
1144
+ self.num_prediction_heads = getattr(config, "num_prediction_heads", 2)
1145
+ self.k = getattr(config, "k", 1)
1146
+
1147
+ self.model = GenerannoModel(config)
1148
+ self.feature_layer = getattr(config, "feature_layer", -1)
1149
+
1150
+ if self.num_prediction_heads > 1:
1151
+ self.score = nn.ModuleList()
1152
+ for _ in range(self.num_prediction_heads):
1153
+ if getattr(config, "use_mlp_classifier", False):
1154
+ head = nn.Sequential(
1155
+ nn.Linear(config.hidden_size, config.hidden_size),
1156
+ nn.GELU(),
1157
+ nn.Dropout(0.1),
1158
+ nn.Linear(config.hidden_size, self.num_labels * self.k, bias=False),
1159
+ )
1160
+ else:
1161
+ head = nn.Linear(config.hidden_size, self.num_labels * self.k, bias=False)
1162
+ self.score.append(head)
1163
+ else:
1164
+ if getattr(config, "use_mlp_classifier", False):
1165
+ self.score = nn.Sequential(
1166
+ nn.Linear(config.hidden_size, config.hidden_size),
1167
+ nn.GELU(),
1168
+ nn.Dropout(0.1),
1169
+ nn.Linear(config.hidden_size, self.num_labels * self.k, bias=False),
1170
+ )
1171
+ else:
1172
+ self.score = nn.Linear(config.hidden_size, self.num_labels * self.k, bias=False)
1173
+
1174
+ self.label_weights = (
1175
+ torch.tensor(config.label_weights)
1176
+ if hasattr(config, "label_weights")
1177
+ else None
1178
+ )
1179
+
1180
+ self.post_init()
1181
+
1182
+ def forward(
1183
+ self,
1184
+ input_ids: Optional[torch.LongTensor] = None,
1185
+ attention_mask: Optional[torch.Tensor] = None,
1186
+ position_ids: Optional[torch.LongTensor] = None,
1187
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1188
+ labels: Optional[torch.LongTensor] = None,
1189
+ output_attentions: Optional[bool] = None,
1190
+ output_hidden_states: Optional[bool] = None,
1191
+ return_dict: Optional[bool] = None,
1192
+ ) -> Union[Tuple, TokenClassifierOutput]:
1193
+ return_dict = (
1194
+ return_dict if return_dict is not None else self.config.use_return_dict
1195
+ )
1196
+
1197
+ if self.feature_layer == -1:
1198
+ outputs = self.model(
1199
+ input_ids,
1200
+ attention_mask=attention_mask,
1201
+ position_ids=position_ids,
1202
+ inputs_embeds=inputs_embeds,
1203
+ output_attentions=output_attentions,
1204
+ output_hidden_states=output_hidden_states,
1205
+ return_dict=return_dict,
1206
+ )
1207
+ hidden_states = outputs[0]
1208
+ else:
1209
+ outputs = self.model(
1210
+ input_ids,
1211
+ attention_mask=attention_mask,
1212
+ position_ids=position_ids,
1213
+ inputs_embeds=inputs_embeds,
1214
+ output_attentions=output_attentions,
1215
+ output_hidden_states=True,
1216
+ return_dict=return_dict,
1217
+ )
1218
+ hidden_states = outputs.hidden_states[self.feature_layer]
1219
+
1220
+ batch_size, padded_token_len, hidden_size = hidden_states.shape
1221
+
1222
+ if self.num_prediction_heads > 1:
1223
+ unpadded_token_lengths = attention_mask.sum(dim=1)
1224
+ all_logits_list = [head(hidden_states) for head in self.score]
1225
+
1226
+ # 最终预测位置数量 = padded_token_len * k * 头数
1227
+ total_prediction_positions = padded_token_len * self.k * self.num_prediction_heads
1228
+
1229
+ logits = hidden_states.new_full(
1230
+ (batch_size, total_prediction_positions, self.num_labels),
1231
+ fill_value=float("-inf"),
1232
+ )
1233
+
1234
+ for i in range(batch_size):
1235
+ actual_token_len = unpadded_token_lengths[i].item() # 当前样本的实际token数
1236
+ head_outputs = [
1237
+ logits_head[i, :actual_token_len] for logits_head in all_logits_list
1238
+ ]
1239
+
1240
+ reshaped_outputs = []
1241
+ for head_out in head_outputs:
1242
+ # head_out形状: [actual_token_len, num_labels * k]
1243
+ # 重塑为: [actual_token_len * k, num_labels]
1244
+ head_reshaped = head_out.view(actual_token_len * self.k, self.num_labels)
1245
+ reshaped_outputs.append(head_reshaped)
1246
+
1247
+ combined = torch.cat(reshaped_outputs, dim=0)
1248
+ total_combined_len = actual_token_len * self.k * self.num_prediction_heads
1249
+ logits[i, :total_combined_len] = combined
1250
+
1251
+ else:
1252
+ # 单头情况
1253
+ raw_logits = self.score(hidden_states)
1254
+ # raw_logits形状: [batch_size, padded_token_len, num_labels * k]
1255
+ # reshape为: [batch_size, padded_token_len * k, num_labels]
1256
+ logits = raw_logits.view(batch_size, padded_token_len * self.k, self.num_labels)
1257
+
1258
+ loss = None
1259
+ if labels is not None:
1260
+ if self.label_weights is not None:
1261
+ self.label_weights = self.label_weights.to(
1262
+ device=logits.device, dtype=logits.dtype
1263
+ )
1264
+ loss_fct = CrossEntropyLoss(weight=self.label_weights)
1265
+ else:
1266
+ loss_fct = CrossEntropyLoss()
1267
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1268
+
1269
+ if not return_dict:
1270
+ output = (logits,)
1271
+ return ((loss,) + output) if loss is not None else output
1272
+
1273
+ return TokenClassifierOutput(loss=loss, logits=logits)
GENERanno-eukaryote-0.5b-base/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "eos_token": "</s>",
4
+ "mask_token": "<mask>",
5
+ "pad_token": "<pad>",
6
+ "unk_token": "N"
7
+ }
GENERanno-eukaryote-0.5b-base/tokenizer.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import re
4
+ from typing import List, Optional, Tuple, Dict
5
+ from transformers import PreTrainedTokenizer
6
+
7
+ class SingleNucleotideTokenizer(PreTrainedTokenizer):
8
+ def __init__(self, **kwargs):
9
+ # 定义词表
10
+ self.vocab_list = [
11
+ "<oov>", "<s>", "</s>", "<pad>", "<mask>",
12
+ "<bog>", "<eog>", "<bok>", "<eok>", "<+>", "<->",
13
+ "<mam>", "<vrt>", "<inv>", "<pln>", "<fng>", "<prt>",
14
+ "<arc>", "<bct>", "<mit>", "<plt>", "<plm>", "<vir>",
15
+ "<cds>", "<pseudo>", "<tRNA>", "<rRNA>", "<ncRNA>",
16
+ "<sp0>", "<sp1>", "<sp2>", "<sp3>",
17
+ "A", "C", "G", "<K>", "<M>", "N", "<R>", "<S>", "T", "<W>", "<Y>"
18
+ ]
19
+
20
+ # 创建词汇映射
21
+ self.vocab = {token: idx for idx, token in enumerate(self.vocab_list)}
22
+ self.ids_to_tokens = {idx: token for token, idx in self.vocab.items()}
23
+ self.tokens_to_ids = {token: idx for token, idx in self.vocab.items()}
24
+
25
+ # 设置特殊token
26
+ self.unk_token = "N"
27
+ self.bos_token = "<s>"
28
+ self.eos_token = "</s>"
29
+ self.pad_token = "<pad>"
30
+ self.mask_token = "<mask>"
31
+
32
+ # 编译正则表达式以匹配特殊token
33
+ special_tokens_pattern = "|".join(re.escape(token) for token in self.vocab_list if token.startswith("<") and token.endswith(">"))
34
+ self.special_token_re = re.compile(f"({special_tokens_pattern})")
35
+
36
+ # 编译正则表达式以匹配普通token
37
+ self.normal_token_re = re.compile(r"[ACGTN]")
38
+
39
+ # 设置特殊token ID
40
+ self.unk_token_id = self.vocab[self.unk_token]
41
+ self.bos_token_id = self.vocab[self.bos_token]
42
+ self.eos_token_id = self.vocab[self.eos_token]
43
+ self.pad_token_id = self.vocab[self.pad_token]
44
+ self.mask_token_id = self.vocab[self.mask_token]
45
+
46
+ # 调用父类初始化
47
+ super().__init__(
48
+ unk_token=self.unk_token,
49
+ bos_token=self.bos_token,
50
+ eos_token=self.eos_token,
51
+ pad_token=self.pad_token,
52
+ mask_token=self.mask_token,
53
+ **kwargs
54
+ )
55
+ self.clean_up_tokenization_spaces = True
56
+
57
+ @property
58
+ def vocab_size(self) -> int:
59
+ return len(self.vocab)
60
+
61
+ def get_vocab(self) -> Dict[str, int]:
62
+ return self.vocab
63
+
64
+ def _tokenize(self, text: str, **kwargs) -> List[str]:
65
+ tokens = []
66
+ pos = 0
67
+ text_length = len(text)
68
+
69
+ while pos < text_length:
70
+ # 首先尝试匹配特殊token
71
+ special_match = self.special_token_re.match(text, pos)
72
+ if special_match:
73
+ token = special_match.group()
74
+ tokens.append(token)
75
+ pos = special_match.end()
76
+ continue
77
+
78
+ # 然后尝试匹配普通token
79
+ normal_match = self.normal_token_re.match(text, pos)
80
+ if normal_match:
81
+ token = normal_match.group()
82
+ # 确保token在词汇表中
83
+ if token in self.vocab:
84
+ tokens.append(token)
85
+ else:
86
+ tokens.append(self.unk_token)
87
+ pos = normal_match.end()
88
+ continue
89
+
90
+ # 如果都不匹配,跳过字符并使用unk_token
91
+ tokens.append(self.unk_token)
92
+ pos += 1
93
+
94
+ return tokens
95
+
96
+ def _convert_token_to_id(self, token: str) -> int:
97
+ return self.vocab.get(token, self.unk_token_id)
98
+
99
+ def _convert_id_to_token(self, index: int) -> str:
100
+ return self.ids_to_tokens.get(index, self.unk_token)
101
+
102
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
103
+ # 简单地连接所有token
104
+ return "".join(tokens)
105
+
106
+ def build_inputs_with_special_tokens(
107
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
108
+ ) -> List[int]:
109
+ if token_ids_1 is None:
110
+ return [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
111
+ return [self.bos_token_id] + token_ids_0 + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
112
+
113
+ def get_special_tokens_mask(
114
+ self,
115
+ token_ids_0: List[int],
116
+ token_ids_1: Optional[List[int]] = None,
117
+ already_has_special_tokens: bool = False
118
+ ) -> List[int]:
119
+ if already_has_special_tokens:
120
+ return super().get_special_tokens_mask(
121
+ token_ids_0=token_ids_0,
122
+ token_ids_1=token_ids_1,
123
+ already_has_special_tokens=True
124
+ )
125
+
126
+ if token_ids_1 is None:
127
+ return [1] + ([0] * len(token_ids_0)) + [1]
128
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
129
+
130
+ def create_token_type_ids_from_sequences(
131
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
132
+ ) -> List[int]:
133
+ # Llama通常不使用token类型ID
134
+ if token_ids_1 is None:
135
+ return [0] * (len(token_ids_0) + 2) # +2 for [CLS] and [SEP]
136
+ return [0] * (len(token_ids_0) + 1) + [1] * (len(token_ids_1) + 1)
137
+
138
+ def save_pretrained(self, save_directory: str, **kwargs):
139
+ """重写save_pretrained以包含auto_map配置"""
140
+ # 先调用父类方法保存词汇表等
141
+ vocab_files = super().save_pretrained(save_directory, **kwargs)
142
+
143
+ # 创建或更新tokenizer_config.json
144
+ tokenizer_config_path = os.path.join(save_directory, "tokenizer_config.json")
145
+
146
+ # 读取现有的配置或创建新的
147
+ if os.path.exists(tokenizer_config_path):
148
+ with open(tokenizer_config_path, "r", encoding="utf-8") as f:
149
+ config = json.load(f)
150
+ else:
151
+ config = {}
152
+
153
+ # 添加auto_map配置
154
+ config.update({
155
+ "auto_map": {
156
+ "AutoTokenizer": [
157
+ "tokenizer.SingleNucleotideTokenizer", # 如果是直接运行的脚本
158
+ None
159
+ ]
160
+ },
161
+ })
162
+
163
+ # 保存配置
164
+ with open(tokenizer_config_path, "w", encoding="utf-8") as f:
165
+ json.dump(config, f, ensure_ascii=False, indent=2)
166
+
167
+ return vocab_files
168
+
169
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
170
+ import os
171
+
172
+ # 确保目录存在
173
+ if not os.path.exists(save_directory):
174
+ os.makedirs(save_directory)
175
+
176
+ # 创建词汇文件路径
177
+ vocab_file = os.path.join(
178
+ save_directory,
179
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.txt"
180
+ )
181
+
182
+ # 写入词汇表
183
+ with open(vocab_file, "w", encoding="utf-8") as f:
184
+ for token, idx in sorted(self.vocab.items(), key=lambda x: x[1]):
185
+ f.write(f"{token} {idx}\n")
186
+
187
+ return (vocab_file,)
188
+
189
+ @classmethod
190
+ def from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs):
191
+ # 直接创建新的tokenizer实例
192
+ return cls(**kwargs)
GENERanno-eukaryote-0.5b-base/tokenizer_config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "1": {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "2": {
12
+ "content": "</s>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "3": {
20
+ "content": "<pad>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "4": {
28
+ "content": "<mask>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "37": {
36
+ "content": "N",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "bos_token": "<s>",
45
+ "clean_up_tokenization_spaces": true,
46
+ "eos_token": "</s>",
47
+ "extra_special_tokens": {},
48
+ "mask_token": "<mask>",
49
+ "model_max_length": 1000000000000000019884624838656,
50
+ "pad_token": "<pad>",
51
+ "tokenizer_class": "SingleNucleotideTokenizer",
52
+ "unk_token": "N",
53
+ "auto_map": {
54
+ "AutoTokenizer": [
55
+ "tokenizer.SingleNucleotideTokenizer",
56
+ null
57
+ ]
58
+ }
59
+ }
GENERanno-eukaryote-0.5b-base/vocab.txt ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <oov> 0
2
+ <s> 1
3
+ </s> 2
4
+ <pad> 3
5
+ <mask> 4
6
+ <bog> 5
7
+ <eog> 6
8
+ <bok> 7
9
+ <eok> 8
10
+ <+> 9
11
+ <-> 10
12
+ <mam> 11
13
+ <vrt> 12
14
+ <inv> 13
15
+ <pln> 14
16
+ <fng> 15
17
+ <prt> 16
18
+ <arc> 17
19
+ <bct> 18
20
+ <mit> 19
21
+ <plt> 20
22
+ <plm> 21
23
+ <vir> 22
24
+ <cds> 23
25
+ <pseudo> 24
26
+ <tRNA> 25
27
+ <rRNA> 26
28
+ <ncRNA> 27
29
+ <sp0> 28
30
+ <sp1> 29
31
+ <sp2> 30
32
+ <sp3> 31
33
+ A 32
34
+ C 33
35
+ G 34
36
+ <K> 35
37
+ <M> 36
38
+ N 37
39
+ <R> 38
40
+ <S> 39
41
+ T 40
42
+ <W> 41
43
+ <Y> 42
SSD-1B/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "EulerDiscreteScheduler",
3
+ "_diffusers_version": "0.19.0",
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
+ }
SSD-1B/text_encoder/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CLIPTextModel"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 0,
7
+ "dropout": 0.0,
8
+ "eos_token_id": 2,
9
+ "hidden_act": "quick_gelu",
10
+ "hidden_size": 768,
11
+ "initializer_factor": 1.0,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 3072,
14
+ "layer_norm_eps": 1e-05,
15
+ "max_position_embeddings": 77,
16
+ "model_type": "clip_text_model",
17
+ "num_attention_heads": 12,
18
+ "num_hidden_layers": 12,
19
+ "pad_token_id": 1,
20
+ "projection_dim": 768,
21
+ "torch_dtype": "float32",
22
+ "transformers_version": "4.29.2",
23
+ "vocab_size": 49408
24
+ }
SSD-1B/text_encoder_2/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CLIPTextModelWithProjection"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 0,
7
+ "dropout": 0.0,
8
+ "eos_token_id": 2,
9
+ "hidden_act": "gelu",
10
+ "hidden_size": 1280,
11
+ "initializer_factor": 1.0,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 5120,
14
+ "layer_norm_eps": 1e-05,
15
+ "max_position_embeddings": 77,
16
+ "model_type": "clip_text_model",
17
+ "num_attention_heads": 20,
18
+ "num_hidden_layers": 32,
19
+ "pad_token_id": 1,
20
+ "projection_dim": 1280,
21
+ "torch_dtype": "float32",
22
+ "transformers_version": "4.29.2",
23
+ "vocab_size": 49408
24
+ }
SSD-1B/tokenizer/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
SSD-1B/tokenizer/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "<|endoftext|>",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
SSD-1B/tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "bos_token": {
4
+ "__type": "AddedToken",
5
+ "content": "<|startoftext|>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "clean_up_tokenization_spaces": true,
12
+ "do_lower_case": true,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|endoftext|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "errors": "replace",
22
+ "model_max_length": 77,
23
+ "pad_token": "<|endoftext|>",
24
+ "tokenizer_class": "CLIPTokenizer",
25
+ "unk_token": {
26
+ "__type": "AddedToken",
27
+ "content": "<|endoftext|>",
28
+ "lstrip": false,
29
+ "normalized": true,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
SSD-1B/tokenizer/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
SSD-1B/tokenizer_2/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
SSD-1B/tokenizer_2/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "!",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
SSD-1B/tokenizer_2/tokenizer_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "bos_token": {
4
+ "__type": "AddedToken",
5
+ "content": "<|startoftext|>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "clean_up_tokenization_spaces": true,
12
+ "do_lower_case": true,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|endoftext|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "errors": "replace",
22
+ "model_max_length": 77,
23
+ "pad_token": "!",
24
+ "tokenizer_class": "CLIPTokenizer",
25
+ "unk_token": {
26
+ "__type": "AddedToken",
27
+ "content": "<|endoftext|>",
28
+ "lstrip": false,
29
+ "normalized": true,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
SSD-1B/tokenizer_2/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
SSD-1B/unet/config.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UNet2DConditionModel",
3
+ "_diffusers_version": "0.19.0.dev0",
4
+ "act_fn": "silu",
5
+ "addition_embed_type": "text_time",
6
+ "addition_embed_type_num_heads": 64,
7
+ "addition_time_embed_dim": 256,
8
+ "attention_head_dim": [
9
+ 5,
10
+ 10,
11
+ 20
12
+ ],
13
+ "block_out_channels": [
14
+ 320,
15
+ 640,
16
+ 1280
17
+ ],
18
+ "center_input_sample": false,
19
+ "class_embed_type": null,
20
+ "class_embeddings_concat": false,
21
+ "conv_in_kernel": 3,
22
+ "conv_out_kernel": 3,
23
+ "cross_attention_dim": 2048,
24
+ "cross_attention_norm": null,
25
+ "down_block_types": [
26
+ "DownBlock2D",
27
+ "CrossAttnDownBlock2D",
28
+ "CrossAttnDownBlock2D"
29
+ ],
30
+ "downsample_padding": 1,
31
+ "dual_cross_attention": false,
32
+ "encoder_hid_dim": null,
33
+ "encoder_hid_dim_type": null,
34
+ "flip_sin_to_cos": true,
35
+ "freq_shift": 0,
36
+ "in_channels": 4,
37
+ "layers_per_block": 2,
38
+ "mid_block_only_cross_attention": null,
39
+ "mid_block_scale_factor": 1,
40
+ "mid_block_type": "UNetMidBlock2D",
41
+ "norm_eps": 1e-05,
42
+ "norm_num_groups": 32,
43
+ "num_attention_heads": null,
44
+ "num_class_embeds": null,
45
+ "only_cross_attention": false,
46
+ "out_channels": 4,
47
+ "projection_class_embeddings_input_dim": 2816,
48
+ "resnet_out_scale_factor": 1.0,
49
+ "resnet_skip_time_act": false,
50
+ "resnet_time_scale_shift": "default",
51
+ "sample_size": 128,
52
+ "time_cond_proj_dim": null,
53
+ "time_embedding_act_fn": null,
54
+ "time_embedding_dim": null,
55
+ "time_embedding_type": "positional",
56
+ "timestep_post_act": null,
57
+ "transformer_layers_per_block": [
58
+ [1],
59
+ [2,2],
60
+ [4,4]
61
+ ],
62
+ "reverse_transformer_layers_per_block": [
63
+ [4,4,10],
64
+ [2,1,1],
65
+ 1
66
+ ],
67
+ "up_block_types": [
68
+ "CrossAttnUpBlock2D",
69
+ "CrossAttnUpBlock2D",
70
+ "UpBlock2D"
71
+ ],
72
+ "upcast_attention": null,
73
+ "use_linear_projection": true
74
+ }
SSD-1B/vae/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.19.0",
4
+ "act_fn": "silu",
5
+ "block_out_channels": [
6
+ 128,
7
+ 256,
8
+ 512,
9
+ 512
10
+ ],
11
+ "down_block_types": [
12
+ "DownEncoderBlock2D",
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D"
16
+ ],
17
+ "force_upcast": true,
18
+ "in_channels": 3,
19
+ "latent_channels": 4,
20
+ "layers_per_block": 2,
21
+ "norm_num_groups": 32,
22
+ "out_channels": 3,
23
+ "sample_size": 1024,
24
+ "scaling_factor": 0.13025,
25
+ "up_block_types": [
26
+ "UpDecoderBlock2D",
27
+ "UpDecoderBlock2D",
28
+ "UpDecoderBlock2D",
29
+ "UpDecoderBlock2D"
30
+ ]
31
+ }
bk-sdm-tiny/.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
bk-sdm-tiny/README.md ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: creativeml-openrail-m
3
+ tags:
4
+ - stable-diffusion
5
+ - stable-diffusion-diffusers
6
+ - text-to-image
7
+ datasets:
8
+ - ChristophSchuhmann/improved_aesthetics_6.5plus
9
+ library_name: diffusers
10
+ pipeline_tag: text-to-image
11
+ extra_gated_prompt: >-
12
+ This model is open access and available to all, with a CreativeML OpenRAIL-M
13
+ license further specifying rights and usage.
14
+
15
+ The CreativeML OpenRAIL License specifies:
16
+
17
+
18
+ 1. You can't use the model to deliberately produce nor share illegal or
19
+ harmful outputs or content
20
+
21
+ 2. The authors claim no rights on the outputs you generate, you are free to
22
+ use them and are accountable for their use which must not go against the
23
+ provisions set in the license
24
+
25
+ 3. You may re-distribute the weights and use the model commercially and/or as
26
+ a service. If you do, please be aware you have to include the same use
27
+ restrictions as the ones in the license and share a copy of the CreativeML
28
+ OpenRAIL-M to all your users (please read the license entirely and carefully)
29
+
30
+ Please read the full license carefully here:
31
+ https://huggingface.co/spaces/CompVis/stable-diffusion-license
32
+
33
+ extra_gated_heading: Please read the LICENSE to access this model
34
+
35
+ ---
36
+
37
+ # BK-SDM Model Card
38
+ Block-removed Knowledge-distilled Stable Diffusion Model (BK-SDM) is an architecturally compressed SDM for efficient general-purpose text-to-image synthesis. This model is bulit with (i) removing several residual and attention blocks from the U-Net of [Stable Diffusion v1.4]( https://huggingface.co/CompVis/stable-diffusion-v1-4) and (ii) distillation pretraining on only 0.22M LAION pairs (fewer than 0.1% of the full training set). Despite being trained with very limited resources, our compact model can imitate the original SDM by benefiting from transferred knowledge.
39
+ - **Resources for more information**: [Paper](https://arxiv.org/abs/2305.15798), [GitHub](https://github.com/Nota-NetsPresso/BK-SDM), [Demo]( https://huggingface.co/spaces/nota-ai/compressed-stable-diffusion).
40
+
41
+
42
+
43
+ ## Examples with 🤗[Diffusers library](https://github.com/huggingface/diffusers).
44
+
45
+ An inference code with the default PNDM scheduler and 50 denoising steps is as follows.
46
+
47
+ ```python
48
+ import torch
49
+ from diffusers import StableDiffusionPipeline
50
+
51
+ pipe = StableDiffusionPipeline.from_pretrained("nota-ai/bk-sdm-tiny", torch_dtype=torch.float16)
52
+ pipe = pipe.to("cuda")
53
+
54
+ prompt = "a tropical bird sitting on a branch of a tree"
55
+ image = pipe(prompt).images[0]
56
+
57
+ image.save("example.png")
58
+ ```
59
+
60
+ The following code is also runnable, because we compressed the U-Net of [Stable Diffusion v1.4]( https://huggingface.co/CompVis/stable-diffusion-v1-4) while keeping the other parts (i.e., Text Encoder and Image Decoder) unchanged:
61
+
62
+ ```python
63
+ import torch
64
+ from diffusers import StableDiffusionPipeline, UNet2DConditionModel
65
+
66
+ pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16)
67
+ pipe.unet = UNet2DConditionModel.from_pretrained("nota-ai/bk-sdm-tiny", subfolder="unet", torch_dtype=torch.float16)
68
+ pipe = pipe.to("cuda")
69
+
70
+ prompt = "a tropical bird sitting on a branch of a tree"
71
+ image = pipe(prompt).images[0]
72
+
73
+ image.save("example.png")
74
+ ```
75
+
76
+ ## Compression Method
77
+
78
+ ### U-Net Architecture
79
+ Certain residual and attention blocks were eliminated from the U-Net of SDM-v1.4:
80
+
81
+ - 1.04B-param [SDM-v1.4](https://huggingface.co/CompVis/stable-diffusion-v1-4) (0.86B-param U-Net): the original source model.
82
+ - 0.76B-param [**BK-SDM-Base**](https://huggingface.co/nota-ai/bk-sdm-base) (0.58B-param U-Net): obtained with ① fewer blocks in outer stages.
83
+ - 0.66B-param [**BK-SDM-Small**](https://huggingface.co/nota-ai/bk-sdm-small) (0.49B-param U-Net): obtained with ① and ② mid-stage removal.
84
+ - 0.50B-param [**BK-SDM-Tiny**](https://huggingface.co/nota-ai/bk-sdm-tiny) (0.33B-param U-Net): obtained with ①, ②, and ③ further inner-stage removal.
85
+
86
+
87
+ <center>
88
+ <img alt="U-Net architectures" img src="https://netspresso-research-code-release.s3.us-east-2.amazonaws.com/assets-bk-sdm/fig_arch.png" width="100%">
89
+ </center>
90
+
91
+
92
+
93
+
94
+ ### Distillation Pretraining
95
+ The compact U-Net was trained to mimic the behavior of the original U-Net. We leveraged feature-level and output-level distillation, along with the denoising task loss.
96
+
97
+
98
+ <center>
99
+ <img alt="KD-based pretraining" img src="https://netspresso-research-code-release.s3.us-east-2.amazonaws.com/assets-bk-sdm/fig_kd_bksdm.png" width="100%">
100
+ </center>
101
+
102
+
103
+
104
+ <br/>
105
+
106
+ - **Training Data**: 212,776 image-text pairs (i.e., 0.22M pairs) from [LAION-Aesthetics V2 6.5+](https://laion.ai/blog/laion-aesthetics/).
107
+ - **Hardware:** A single NVIDIA A100 80GB GPU
108
+ - **Gradient Accumulations**: 4
109
+ - **Batch:** 256 (=4×64)
110
+ - **Optimizer:** AdamW
111
+ - **Learning Rate:** a constant learning rate of 5e-5 for 50K-iteration pretraining
112
+
113
+
114
+ ## Experimental Results
115
+
116
+ The following table shows the zero-shot results on 30K samples from the MS-COCO validation split. After generating 512×512 images with the PNDM scheduler and 25 denoising steps, we downsampled them to 256×256 for evaluating generation scores. Our models were drawn at the 50K-th training iteration.
117
+
118
+ | Model | FID↓ | IS↑ | CLIP Score↑<br>(ViT-g/14) | # Params,<br>U-Net | # Params,<br>Whole SDM |
119
+ |---|:---:|:---:|:---:|:---:|:---:|
120
+ | [Stable Diffusion v1.4](https://huggingface.co/CompVis/stable-diffusion-v1-4) | 13.05 | 36.76 | 0.2958 | 0.86B | 1.04B |
121
+ | [BK-SDM-Base](https://huggingface.co/nota-ai/bk-sdm-base) (Ours) | 15.76 | 33.79 | 0.2878 | 0.58B | 0.76B |
122
+ | [BK-SDM-Small](https://huggingface.co/nota-ai/bk-sdm-small) (Ours) | 16.98 | 31.68 | 0.2677 | 0.49B | 0.66B |
123
+ | [BK-SDM-Tiny](https://huggingface.co/nota-ai/bk-sdm-tiny) (Ours) | 17.12 | 30.09 | 0.2653 | 0.33B | 0.50B |
124
+
125
+ <br/>
126
+
127
+ The following figure depicts synthesized images with some MS-COCO captions.
128
+
129
+ <center>
130
+ <img alt="Visual results" img src="https://netspresso-research-code-release.s3.us-east-2.amazonaws.com/assets-bk-sdm/fig_results.png" width="100%">
131
+ </center>
132
+
133
+
134
+ <br/>
135
+
136
+
137
+ # Uses
138
+ _Note: This section is taken from the [Stable Diffusion v1 model card]( https://huggingface.co/CompVis/stable-diffusion-v1-4) (which was based on the [DALLE-MINI model card](https://huggingface.co/dalle-mini/dalle-mini)) and applies in the same way to BK-SDMs_.
139
+
140
+ ## Direct Use
141
+ The model is intended for research purposes only. Possible research areas and tasks include
142
+ - Safe deployment of models which have the potential to generate harmful content.
143
+ - Probing and understanding the limitations and biases of generative models.
144
+ - Generation of artworks and use in design and other artistic processes.
145
+ - Applications in educational or creative tools.
146
+ - Research on generative models.
147
+
148
+ Excluded uses are described below.
149
+
150
+ ### Misuse, Malicious Use, and Out-of-Scope Use
151
+ The model should not be used to intentionally create or disseminate images that create hostile or alienating environments for people. This includes generating images that people would foreseeably find disturbing, distressing, or offensive; or content that propagates historical or current stereotypes.
152
+
153
+ #### Out-of-Scope Use
154
+ The model was not trained to be factual or true representations of people or events, and therefore using the model to generate such content is out-of-scope for the abilities of this model.
155
+
156
+ #### Misuse and Malicious Use
157
+ Using the model to generate content that is cruel to individuals is a misuse of this model. This includes, but is not limited to:
158
+
159
+ - Generating demeaning, dehumanizing, or otherwise harmful representations of people or their environments, cultures, religions, etc.
160
+ - Intentionally promoting or propagating discriminatory content or harmful stereotypes.
161
+ - Impersonating individuals without their consent.
162
+ - Sexual content without consent of the people who might see it.
163
+ - Mis- and disinformation
164
+ - Representations of egregious violence and gore
165
+ - Sharing of copyrighted or licensed material in violation of its terms of use.
166
+ - Sharing content that is an alteration of copyrighted or licensed material in violation of its terms of use.
167
+
168
+ ## Limitations and Bias
169
+
170
+ ### Limitations
171
+
172
+ - The model does not achieve perfect photorealism
173
+ - The model cannot render legible text
174
+ - The model does not perform well on more difficult tasks which involve compositionality, such as rendering an image corresponding to “A red cube on top of a blue sphere”
175
+ - Faces and people in general may not be generated properly.
176
+ - The model was trained mainly with English captions and will not work as well in other languages.
177
+ - The autoencoding part of the model is lossy
178
+ - The model was trained on a large-scale dataset [LAION-5B](https://laion.ai/blog/laion-5b/) which contains adult material and is not fit for product use without additional safety mechanisms and considerations.
179
+ - No additional measures were used to deduplicate the dataset. As a result, we observe some degree of memorization for images that are duplicated in the training data. The training data can be searched at [https://rom1504.github.io/clip-retrieval/](https://rom1504.github.io/clip-retrieval/) to possibly assist in the detection of memorized images.
180
+
181
+ ### Bias
182
+
183
+ While the capabilities of image generation models are impressive, they can also reinforce or exacerbate social biases. Stable Diffusion v1 was trained on subsets of [LAION-2B(en)](https://laion.ai/blog/laion-5b/), which consists of images that are primarily limited to English descriptions. Texts and images from communities and cultures that use other languages are likely to be insufficiently accounted for. This affects the overall output of the model, as white and western cultures are often set as the default. Further, the ability of the model to generate content with non-English prompts is significantly worse than with English-language prompts.
184
+
185
+ ### Safety Module
186
+
187
+ The intended use of this model is with the [Safety Checker](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py) in Diffusers. This checker works by checking model outputs against known hard-coded NSFW concepts. The concepts are intentionally hidden to reduce the likelihood of reverse-engineering this filter. Specifically, the checker compares the class probability of harmful concepts in the embedding space of the `CLIPTextModel` *after generation* of the images. The concepts are passed into the model with the generated image and compared to a hand-engineered weight for each NSFW concept.
188
+
189
+
190
+ # Acknowledgments
191
+ - We express our gratitude to [Microsoft for Startups Founders Hub](https://www.microsoft.com/en-us/startups) for generously providing the Azure credits used during pretraining.
192
+ - We deeply appreciate the pioneering research on Latent/Stable Diffusion conducted by [CompVis](https://github.com/CompVis/latent-diffusion), [Runway](https://runwayml.com/), and [Stability AI](https://stability.ai/).
193
+ - Special thanks to the contributors to [LAION](https://laion.ai/), [Diffusers](https://github.com/huggingface/diffusers), and [Gradio](https://www.gradio.app/) for their valuable support.
194
+
195
+
196
+ # Citation
197
+ ```bibtex
198
+ @article{kim2023architectural,
199
+ title={BK-SDM: A Lightweight, Fast, and Cheap Version of Stable Diffusion},
200
+ author={Kim, Bo-Kyeong and Song, Hyoung-Kyu and Castells, Thibault and Choi, Shinkook},
201
+ journal={arXiv preprint arXiv:2305.15798},
202
+ year={2023},
203
+ url={https://arxiv.org/abs/2305.15798}
204
+ }
205
+ ```
206
+ ```bibtex
207
+ @article{kim2023bksdm,
208
+ title={BK-SDM: Architecturally Compressed Stable Diffusion for Efficient Text-to-Image Generation},
209
+ author={Kim, Bo-Kyeong and Song, Hyoung-Kyu and Castells, Thibault and Choi, Shinkook},
210
+ journal={ICML Workshop on Efficient Systems for Foundation Models (ES-FoMo)},
211
+ year={2023},
212
+ url={https://openreview.net/forum?id=bOVydU0XKC}
213
+ }
214
+ ```
215
+
216
+ *This model card was written by Bo-Kyeong Kim and is based on the [Stable Diffusion v1 model card]( https://huggingface.co/CompVis/stable-diffusion-v1-4).*
bk-sdm-tiny/feature_extractor/preprocessor_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": 224,
3
+ "do_center_crop": true,
4
+ "do_convert_rgb": true,
5
+ "do_normalize": true,
6
+ "do_resize": true,
7
+ "feature_extractor_type": "CLIPFeatureExtractor",
8
+ "image_mean": [
9
+ 0.48145466,
10
+ 0.4578275,
11
+ 0.40821073
12
+ ],
13
+ "image_std": [
14
+ 0.26862954,
15
+ 0.26130258,
16
+ 0.27577711
17
+ ],
18
+ "resample": 3,
19
+ "size": 224
20
+ }
bk-sdm-tiny/model_index.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "StableDiffusionPipeline",
3
+ "_diffusers_version": "0.2.2",
4
+ "feature_extractor": [
5
+ "transformers",
6
+ "CLIPImageProcessor"
7
+ ],
8
+ "safety_checker": [
9
+ "stable_diffusion",
10
+ "StableDiffusionSafetyChecker"
11
+ ],
12
+ "scheduler": [
13
+ "diffusers",
14
+ "PNDMScheduler"
15
+ ],
16
+ "text_encoder": [
17
+ "transformers",
18
+ "CLIPTextModel"
19
+ ],
20
+ "tokenizer": [
21
+ "transformers",
22
+ "CLIPTokenizer"
23
+ ],
24
+ "unet": [
25
+ "diffusers",
26
+ "UNet2DConditionModel"
27
+ ],
28
+ "vae": [
29
+ "diffusers",
30
+ "AutoencoderKL"
31
+ ]
32
+ }
bk-sdm-tiny/safety_checker/config.json ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./safety_module",
3
+ "architectures": [
4
+ "StableDiffusionSafetyChecker"
5
+ ],
6
+ "initializer_factor": 1.0,
7
+ "logit_scale_init_value": 2.6592,
8
+ "model_type": "clip",
9
+ "projection_dim": 768,
10
+ "text_config": {
11
+ "_name_or_path": "",
12
+ "add_cross_attention": false,
13
+ "architectures": null,
14
+ "attention_dropout": 0.0,
15
+ "bad_words_ids": null,
16
+ "bos_token_id": 0,
17
+ "chunk_size_feed_forward": 0,
18
+ "cross_attention_hidden_size": null,
19
+ "decoder_start_token_id": null,
20
+ "diversity_penalty": 0.0,
21
+ "do_sample": false,
22
+ "dropout": 0.0,
23
+ "early_stopping": false,
24
+ "encoder_no_repeat_ngram_size": 0,
25
+ "eos_token_id": 2,
26
+ "exponential_decay_length_penalty": null,
27
+ "finetuning_task": null,
28
+ "forced_bos_token_id": null,
29
+ "forced_eos_token_id": null,
30
+ "hidden_act": "quick_gelu",
31
+ "hidden_size": 768,
32
+ "id2label": {
33
+ "0": "LABEL_0",
34
+ "1": "LABEL_1"
35
+ },
36
+ "initializer_factor": 1.0,
37
+ "initializer_range": 0.02,
38
+ "intermediate_size": 3072,
39
+ "is_decoder": false,
40
+ "is_encoder_decoder": false,
41
+ "label2id": {
42
+ "LABEL_0": 0,
43
+ "LABEL_1": 1
44
+ },
45
+ "layer_norm_eps": 1e-05,
46
+ "length_penalty": 1.0,
47
+ "max_length": 20,
48
+ "max_position_embeddings": 77,
49
+ "min_length": 0,
50
+ "model_type": "clip_text_model",
51
+ "no_repeat_ngram_size": 0,
52
+ "num_attention_heads": 12,
53
+ "num_beam_groups": 1,
54
+ "num_beams": 1,
55
+ "num_hidden_layers": 12,
56
+ "num_return_sequences": 1,
57
+ "output_attentions": false,
58
+ "output_hidden_states": false,
59
+ "output_scores": false,
60
+ "pad_token_id": 1,
61
+ "prefix": null,
62
+ "problem_type": null,
63
+ "pruned_heads": {},
64
+ "remove_invalid_values": false,
65
+ "repetition_penalty": 1.0,
66
+ "return_dict": true,
67
+ "return_dict_in_generate": false,
68
+ "sep_token_id": null,
69
+ "task_specific_params": null,
70
+ "temperature": 1.0,
71
+ "tie_encoder_decoder": false,
72
+ "tie_word_embeddings": true,
73
+ "tokenizer_class": null,
74
+ "top_k": 50,
75
+ "top_p": 1.0,
76
+ "torch_dtype": null,
77
+ "torchscript": false,
78
+ "transformers_version": "4.21.0.dev0",
79
+ "typical_p": 1.0,
80
+ "use_bfloat16": false,
81
+ "vocab_size": 49408
82
+ },
83
+ "text_config_dict": {
84
+ "hidden_size": 768,
85
+ "intermediate_size": 3072,
86
+ "num_attention_heads": 12,
87
+ "num_hidden_layers": 12
88
+ },
89
+ "torch_dtype": "float32",
90
+ "transformers_version": null,
91
+ "vision_config": {
92
+ "_name_or_path": "",
93
+ "add_cross_attention": false,
94
+ "architectures": null,
95
+ "attention_dropout": 0.0,
96
+ "bad_words_ids": 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_hidden_layers": 24,
137
+ "num_return_sequences": 1,
138
+ "output_attentions": false,
139
+ "output_hidden_states": false,
140
+ "output_scores": false,
141
+ "pad_token_id": null,
142
+ "patch_size": 14,
143
+ "prefix": null,
144
+ "problem_type": null,
145
+ "pruned_heads": {},
146
+ "remove_invalid_values": false,
147
+ "repetition_penalty": 1.0,
148
+ "return_dict": true,
149
+ "return_dict_in_generate": false,
150
+ "sep_token_id": null,
151
+ "task_specific_params": null,
152
+ "temperature": 1.0,
153
+ "tie_encoder_decoder": false,
154
+ "tie_word_embeddings": true,
155
+ "tokenizer_class": null,
156
+ "top_k": 50,
157
+ "top_p": 1.0,
158
+ "torch_dtype": null,
159
+ "torchscript": false,
160
+ "transformers_version": "4.21.0.dev0",
161
+ "typical_p": 1.0,
162
+ "use_bfloat16": false
163
+ },
164
+ "vision_config_dict": {
165
+ "hidden_size": 1024,
166
+ "intermediate_size": 4096,
167
+ "num_attention_heads": 16,
168
+ "num_hidden_layers": 24,
169
+ "patch_size": 14
170
+ }
171
+ }
bk-sdm-tiny/scheduler/.ipynb_checkpoints/scheduler_config-checkpoint.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "PNDMScheduler",
3
+ "_diffusers_version": "0.2.2",
4
+ "beta_end": 0.012,
5
+ "beta_schedule": "scaled_linear",
6
+ "beta_start": 0.00085,
7
+ "num_train_timesteps": 1000,
8
+ "skip_prk_steps": true
9
+ }
bk-sdm-tiny/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "PNDMScheduler",
3
+ "_diffusers_version": "0.7.0.dev0",
4
+ "beta_end": 0.012,
5
+ "beta_schedule": "scaled_linear",
6
+ "beta_start": 0.00085,
7
+ "num_train_timesteps": 1000,
8
+ "set_alpha_to_one": false,
9
+ "skip_prk_steps": true,
10
+ "steps_offset": 1,
11
+ "trained_betas": null,
12
+ "clip_sample": false
13
+ }
bk-sdm-tiny/text_encoder/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "openai/clip-vit-large-patch14",
3
+ "architectures": [
4
+ "CLIPTextModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "dropout": 0.0,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "quick_gelu",
11
+ "hidden_size": 768,
12
+ "initializer_factor": 1.0,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 3072,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 77,
17
+ "model_type": "clip_text_model",
18
+ "num_attention_heads": 12,
19
+ "num_hidden_layers": 12,
20
+ "pad_token_id": 1,
21
+ "torch_dtype": "float32",
22
+ "transformers_version": "4.21.0.dev0",
23
+ "vocab_size": 49408
24
+ }
bk-sdm-tiny/tokenizer/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
bk-sdm-tiny/tokenizer/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "<|endoftext|>",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
bk-sdm-tiny/tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "bos_token": {
4
+ "__type": "AddedToken",
5
+ "content": "<|startoftext|>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "do_lower_case": true,
12
+ "eos_token": {
13
+ "__type": "AddedToken",
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": true,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "errors": "replace",
21
+ "model_max_length": 77,
22
+ "name_or_path": "openai/clip-vit-large-patch14",
23
+ "pad_token": "<|endoftext|>",
24
+ "special_tokens_map_file": "./special_tokens_map.json",
25
+ "tokenizer_class": "CLIPTokenizer",
26
+ "unk_token": {
27
+ "__type": "AddedToken",
28
+ "content": "<|endoftext|>",
29
+ "lstrip": false,
30
+ "normalized": true,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ }
34
+ }
bk-sdm-tiny/tokenizer/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
bk-sdm-tiny/unet/config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UNet2DConditionModel",
3
+ "_diffusers_version": "0.15.0",
4
+ "_name_or_path": "/ssd2/bkkim/sdm_paper_checkpoints/BK-SDM-Tiny/checkpoint-50000",
5
+ "act_fn": "silu",
6
+ "attention_head_dim": 8,
7
+ "block_out_channels": [
8
+ 320,
9
+ 640,
10
+ 1280
11
+ ],
12
+ "center_input_sample": false,
13
+ "class_embed_type": null,
14
+ "class_embeddings_concat": false,
15
+ "conv_in_kernel": 3,
16
+ "conv_out_kernel": 3,
17
+ "cross_attention_dim": 768,
18
+ "cross_attention_norm": null,
19
+ "down_block_types": [
20
+ "CrossAttnDownBlock2D",
21
+ "CrossAttnDownBlock2D",
22
+ "CrossAttnDownBlock2D"
23
+ ],
24
+ "downsample_padding": 1,
25
+ "dual_cross_attention": false,
26
+ "encoder_hid_dim": null,
27
+ "flip_sin_to_cos": true,
28
+ "freq_shift": 0,
29
+ "in_channels": 4,
30
+ "layers_per_block": 1,
31
+ "mid_block_only_cross_attention": null,
32
+ "mid_block_scale_factor": 1,
33
+ "mid_block_type": null,
34
+ "norm_eps": 1e-05,
35
+ "norm_num_groups": 32,
36
+ "num_class_embeds": null,
37
+ "only_cross_attention": false,
38
+ "out_channels": 4,
39
+ "projection_class_embeddings_input_dim": null,
40
+ "resnet_out_scale_factor": 1.0,
41
+ "resnet_skip_time_act": false,
42
+ "resnet_time_scale_shift": "default",
43
+ "sample_size": 64,
44
+ "time_cond_proj_dim": null,
45
+ "time_embedding_act_fn": null,
46
+ "time_embedding_type": "positional",
47
+ "timestep_post_act": null,
48
+ "up_block_types": [
49
+ "CrossAttnUpBlock2D",
50
+ "CrossAttnUpBlock2D",
51
+ "CrossAttnUpBlock2D"
52
+ ],
53
+ "upcast_attention": false,
54
+ "use_linear_projection": false
55
+ }
bk-sdm-tiny/vae/config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.2.2",
4
+ "act_fn": "silu",
5
+ "block_out_channels": [
6
+ 128,
7
+ 256,
8
+ 512,
9
+ 512
10
+ ],
11
+ "down_block_types": [
12
+ "DownEncoderBlock2D",
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D"
16
+ ],
17
+ "in_channels": 3,
18
+ "latent_channels": 4,
19
+ "layers_per_block": 2,
20
+ "out_channels": 3,
21
+ "sample_size": 512,
22
+ "scaling_factor": 0.18215,
23
+ "up_block_types": [
24
+ "UpDecoderBlock2D",
25
+ "UpDecoderBlock2D",
26
+ "UpDecoderBlock2D",
27
+ "UpDecoderBlock2D"
28
+ ]
29
+ }
controlnet-canny-sdxl-1.0/.gitattributes ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
+ out_bird.png filter=lfs diff=lfs merge=lfs -text
37
+ out_couple.png filter=lfs diff=lfs merge=lfs -text
38
+ out_room.png filter=lfs diff=lfs merge=lfs -text
39
+ out_tornado.png filter=lfs diff=lfs merge=lfs -text
40
+ out_women.png filter=lfs diff=lfs merge=lfs -text
41
+ out_hug_lab_7.png filter=lfs diff=lfs merge=lfs -text
controlnet-canny-sdxl-1.0/README.md ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: openrail++
3
+ base_model: runwayml/stable-diffusion-v1-5
4
+ tags:
5
+ - stable-diffusion-xl
6
+ - stable-diffusion-xl-diffusers
7
+ - text-to-image
8
+ - diffusers
9
+ inference: false
10
+ ---
11
+
12
+ # SDXL-controlnet: Canny
13
+
14
+ These are controlnet weights trained on [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) with canny conditioning. You can find some example images in the following.
15
+
16
+ prompt: a couple watching a romantic sunset, 4k photo
17
+ ![images_0)](./out_couple.png)
18
+
19
+ prompt: ultrarealistic shot of a furry blue bird
20
+ ![images_1)](./out_bird.png)
21
+
22
+ prompt: a woman, close up, detailed, beautiful, street photography, photorealistic, detailed, Kodak ektar 100, natural, candid shot
23
+ ![images_2)](./out_women.png)
24
+
25
+ prompt: Cinematic, neoclassical table in the living room, cinematic, contour, lighting, highly detailed, winter, golden hour
26
+ ![images_3)](./out_room.png)
27
+
28
+ prompt: a tornado hitting grass field, 1980's film grain. overcast, muted colors.
29
+ ![images_0)](./out_tornado.png)
30
+
31
+ ## Usage
32
+
33
+ Make sure to first install the libraries:
34
+
35
+ ```bash
36
+ pip install accelerate transformers safetensors opencv-python diffusers
37
+ ```
38
+
39
+ And then we're ready to go:
40
+
41
+ ```python
42
+ from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline, AutoencoderKL
43
+ from diffusers.utils import load_image
44
+ from PIL import Image
45
+ import torch
46
+ import numpy as np
47
+ import cv2
48
+
49
+ prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
50
+ negative_prompt = 'low quality, bad quality, sketches'
51
+
52
+ image = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png")
53
+
54
+ controlnet_conditioning_scale = 0.5 # recommended for good generalization
55
+
56
+ controlnet = ControlNetModel.from_pretrained(
57
+ "diffusers/controlnet-canny-sdxl-1.0",
58
+ torch_dtype=torch.float16
59
+ )
60
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
61
+ pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
62
+ "stabilityai/stable-diffusion-xl-base-1.0",
63
+ controlnet=controlnet,
64
+ vae=vae,
65
+ torch_dtype=torch.float16,
66
+ )
67
+ pipe.enable_model_cpu_offload()
68
+
69
+ image = np.array(image)
70
+ image = cv2.Canny(image, 100, 200)
71
+ image = image[:, :, None]
72
+ image = np.concatenate([image, image, image], axis=2)
73
+ image = Image.fromarray(image)
74
+
75
+ images = pipe(
76
+ prompt, negative_prompt=negative_prompt, image=image, controlnet_conditioning_scale=controlnet_conditioning_scale,
77
+ ).images
78
+
79
+ images[0].save(f"hug_lab.png")
80
+ ```
81
+
82
+ ![images_10)](./out_hug_lab_7.png)
83
+
84
+ To more details, check out the official documentation of [`StableDiffusionXLControlNetPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/controlnet_sdxl).
85
+
86
+ ### Training
87
+
88
+ Our training script was built on top of the official training script that we provide [here](https://github.com/huggingface/diffusers/blob/main/examples/controlnet/README_sdxl.md).
89
+
90
+ #### Training data
91
+ This checkpoint was first trained for 20,000 steps on laion 6a resized to a max minimum dimension of 384.
92
+ It was then further trained for 20,000 steps on laion 6a resized to a max minimum dimension of 1024 and
93
+ then filtered to contain only minimum 1024 images. We found the further high resolution finetuning was
94
+ necessary for image quality.
95
+
96
+ #### Compute
97
+ one 8xA100 machine
98
+
99
+ #### Batch size
100
+ Data parallel with a single gpu batch size of 8 for a total batch size of 64.
101
+
102
+ #### Hyper Parameters
103
+ Constant learning rate of 1e-4 scaled by batch size for total learning rate of 64e-4
104
+
105
+ #### Mixed precision
106
+ fp16
controlnet-canny-sdxl-1.0/config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ControlNetModel",
3
+ "_diffusers_version": "0.20.0.dev0",
4
+ "_name_or_path": "../controlnet-1-0-canny/checkpoint-20000/controlnet",
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
+ "block_out_channels": [
15
+ 320,
16
+ 640,
17
+ 1280
18
+ ],
19
+ "class_embed_type": null,
20
+ "conditioning_channels": 3,
21
+ "conditioning_embedding_out_channels": [
22
+ 16,
23
+ 32,
24
+ 96,
25
+ 256
26
+ ],
27
+ "controlnet_conditioning_channel_order": "rgb",
28
+ "cross_attention_dim": 2048,
29
+ "down_block_types": [
30
+ "DownBlock2D",
31
+ "CrossAttnDownBlock2D",
32
+ "CrossAttnDownBlock2D"
33
+ ],
34
+ "downsample_padding": 1,
35
+ "encoder_hid_dim": null,
36
+ "encoder_hid_dim_type": null,
37
+ "flip_sin_to_cos": true,
38
+ "freq_shift": 0,
39
+ "global_pool_conditions": false,
40
+ "in_channels": 4,
41
+ "layers_per_block": 2,
42
+ "mid_block_scale_factor": 1,
43
+ "norm_eps": 1e-05,
44
+ "norm_num_groups": 32,
45
+ "num_attention_heads": null,
46
+ "num_class_embeds": null,
47
+ "only_cross_attention": false,
48
+ "projection_class_embeddings_input_dim": 2816,
49
+ "resnet_time_scale_shift": "default",
50
+ "transformer_layers_per_block": [
51
+ 1,
52
+ 2,
53
+ 10
54
+ ],
55
+ "upcast_attention": null,
56
+ "use_linear_projection": true
57
+ }
controlnet-openpose-sdxl-1.0/.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
+ out_ballerina.png filter=lfs diff=lfs merge=lfs -text
37
+ darth_vader_grid.png filter=lfs diff=lfs merge=lfs -text
controlnet-openpose-sdxl-1.0/README.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ base_model: stabilityai/stable-diffusion-xl-base-1.0
4
+ tags:
5
+ - stable-diffusion-xl
6
+ - stable-diffusion-xl-diffusers
7
+ - text-to-image
8
+ - diffusers
9
+ - controlnet
10
+ inference: false
11
+ ---
12
+
13
+ # SDXL-controlnet: OpenPose (v2)
14
+
15
+ These are controlnet weights trained on stabilityai/stable-diffusion-xl-base-1.0 with OpenPose (v2) conditioning. You can find some example images in the following.
16
+
17
+ prompt: a ballerina, romantic sunset, 4k photo
18
+ ![images_0)](./screenshot_ballerina.png)
19
+
20
+
21
+ ### Comfy Workflow
22
+ ![images_0)](./out_ballerina.png)
23
+
24
+
25
+ (Image is from ComfyUI, you can drag and drop in Comfy to use it as workflow)
26
+
27
+ License: refers to the OpenPose's one.
28
+
29
+ ### Using in 🧨 diffusers
30
+
31
+ First, install all the libraries:
32
+
33
+ ```bash
34
+ pip install -q controlnet_aux transformers accelerate
35
+ pip install -q git+https://github.com/huggingface/diffusers
36
+ ```
37
+
38
+ Now, we're ready to make Darth Vader dance:
39
+
40
+ ```python
41
+ from diffusers import AutoencoderKL, StableDiffusionXLControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
42
+ import torch
43
+ from controlnet_aux import OpenposeDetector
44
+ from diffusers.utils import load_image
45
+
46
+
47
+ # Compute openpose conditioning image.
48
+ openpose = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
49
+
50
+ image = load_image(
51
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/person.png"
52
+ )
53
+ openpose_image = openpose(image)
54
+
55
+ # Initialize ControlNet pipeline.
56
+ controlnet = ControlNetModel.from_pretrained("thibaud/controlnet-openpose-sdxl-1.0", torch_dtype=torch.float16)
57
+ pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
58
+ "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
59
+ )
60
+ pipe.enable_model_cpu_offload()
61
+
62
+
63
+ # Infer.
64
+ prompt = "Darth vader dancing in a desert, high quality"
65
+ negative_prompt = "low quality, bad quality"
66
+ images = pipe(
67
+ prompt,
68
+ negative_prompt=negative_prompt,
69
+ num_inference_steps=25,
70
+ num_images_per_prompt=4,
71
+ image=openpose_image.resize((1024, 1024)),
72
+ generator=torch.manual_seed(97),
73
+ ).images
74
+ images[0]
75
+ ```
76
+
77
+ Here are some gemerated examples:
78
+
79
+ ![](./darth_vader_grid.png)
80
+
81
+
82
+ ### Training
83
+
84
+ Use of the training script by HF🤗 [here](https://github.com/huggingface/diffusers/blob/main/examples/controlnet/README_sdxl.md).
85
+
86
+ #### Training data
87
+ This checkpoint was first trained for 15,000 steps on laion 6a resized to a max minimum dimension of 768.
88
+
89
+ #### Compute
90
+ one 1xA100 machine (Thanks a lot HF🤗 to provide the compute!)
91
+
92
+ #### Batch size
93
+ Data parallel with a single gpu batch size of 2 with gradient accumulation 8.
94
+
95
+ #### Hyper Parameters
96
+ Constant learning rate of 8e-5
97
+
98
+ #### Mixed precision
99
+ fp16
controlnet-openpose-sdxl-1.0/config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ControlNetModel",
3
+ "_diffusers_version": "0.20.0.dev0",
4
+ "act_fn": "silu",
5
+ "addition_embed_type": "text_time",
6
+ "addition_embed_type_num_heads": 64,
7
+ "addition_time_embed_dim": 256,
8
+ "attention_head_dim": [
9
+ 5,
10
+ 10,
11
+ 20
12
+ ],
13
+ "block_out_channels": [
14
+ 320,
15
+ 640,
16
+ 1280
17
+ ],
18
+ "class_embed_type": null,
19
+ "conditioning_channels": 3,
20
+ "conditioning_embedding_out_channels": [
21
+ 16,
22
+ 32,
23
+ 96,
24
+ 256
25
+ ],
26
+ "controlnet_conditioning_channel_order": "rgb",
27
+ "cross_attention_dim": 2048,
28
+ "down_block_types": [
29
+ "DownBlock2D",
30
+ "CrossAttnDownBlock2D",
31
+ "CrossAttnDownBlock2D"
32
+ ],
33
+ "downsample_padding": 1,
34
+ "encoder_hid_dim": null,
35
+ "encoder_hid_dim_type": null,
36
+ "flip_sin_to_cos": true,
37
+ "freq_shift": 0,
38
+ "global_pool_conditions": false,
39
+ "in_channels": 4,
40
+ "layers_per_block": 2,
41
+ "mid_block_scale_factor": 1,
42
+ "norm_eps": 1e-05,
43
+ "norm_num_groups": 32,
44
+ "num_attention_heads": null,
45
+ "num_class_embeds": null,
46
+ "only_cross_attention": false,
47
+ "projection_class_embeddings_input_dim": 2816,
48
+ "resnet_time_scale_shift": "default",
49
+ "transformer_layers_per_block": [
50
+ 1,
51
+ 2,
52
+ 10
53
+ ],
54
+ "upcast_attention": null,
55
+ "use_linear_projection": true
56
+ }
lcm-lora-ssd-1b/.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
+ image.png filter=lfs diff=lfs merge=lfs -text
lcm-lora-ssd-1b/README.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: diffusers
3
+ base_model: segmind/SSD-1B
4
+ tags:
5
+ - lora
6
+ - text-to-image
7
+ license: openrail++
8
+ inference: false
9
+ ---
10
+
11
+ # Latent Consistency Model (LCM) LoRA: SSD-1B
12
+
13
+ Latent Consistency Model (LCM) LoRA was proposed in [LCM-LoRA: A universal Stable-Diffusion Acceleration Module](https://arxiv.org/abs/2311.05556)
14
+ by *Simian Luo, Yiqin Tan, Suraj Patil, Daniel Gu et al.*
15
+
16
+ It is a distilled consistency adapter for [`segmind/SSD-1B`](https://huggingface.co/segmind/SSD-1B) that allows
17
+ to reduce the number of inference steps to only between **2 - 8 steps**.
18
+
19
+ | Model | Params / M |
20
+ |----------------------------------------------------------------------------|------------|
21
+ | [lcm-lora-sdv1-5](https://huggingface.co/latent-consistency/lcm-lora-sdv1-5) | 67.5 |
22
+ | [**lcm-lora-ssd-1b**](https://huggingface.co/latent-consistency/lcm-lora-ssd-1b) | **105** |
23
+ | [lcm-lora-sdxl](https://huggingface.co/latent-consistency/lcm-lora-sdxl) | 197M |
24
+
25
+ ## Usage
26
+
27
+ LCM-LoRA is supported in 🤗 Hugging Face Diffusers library from version v0.23.0 onwards. To run the model, first
28
+ install the latest version of the Diffusers library as well as `peft`, `accelerate` and `transformers`.
29
+ audio dataset from the Hugging Face Hub:
30
+
31
+ ```bash
32
+ pip install --upgrade pip
33
+ pip install --upgrade diffusers transformers accelerate peft
34
+ ```
35
+
36
+ ### Text-to-Image
37
+
38
+ Let's load the base model `segmind/SSD-1B` first. Next, the scheduler needs to be changed to [`LCMScheduler`](https://huggingface.co/docs/diffusers/v0.22.3/en/api/schedulers/lcm#diffusers.LCMScheduler) and we can reduce the number of inference steps to just 2 to 8 steps.
39
+ Please make sure to either disable `guidance_scale` or use values between 1.0 and 2.0.
40
+
41
+ ```python
42
+ import torch
43
+ from diffusers import LCMScheduler, AutoPipelineForText2Image
44
+
45
+ model_id = "segmind/SSD-1B"
46
+ adapter_id = "latent-consistency/lcm-lora-ssd-1b"
47
+
48
+ pipe = AutoPipelineForText2Image.from_pretrained(model_id, torch_dtype=torch.float16, variant="fp16")
49
+ pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
50
+ pipe.to("cuda")
51
+
52
+ # load and fuse lcm lora
53
+ pipe.load_lora_weights(adapter_id)
54
+ pipe.fuse_lora()
55
+
56
+
57
+ prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k"
58
+
59
+ # disable guidance_scale by passing 0
60
+ image = pipe(prompt=prompt, num_inference_steps=4, guidance_scale=0).images[0]
61
+ ```
62
+
63
+ ![](./image.png)
64
+
65
+ ### Image-to-Image
66
+
67
+ Works as well! TODO docs
68
+
69
+ ### Inpainting
70
+
71
+ Works as well! TODO docs
72
+
73
+ ### ControlNet
74
+
75
+ Works as well! TODO docs
76
+
77
+ ### T2I Adapter
78
+
79
+ Works as well! TODO docs
80
+
81
+ ## Speed Benchmark
82
+
83
+ TODO
84
+
85
+ ## Training
86
+
87
+ TODO
stable-diffusion-v1-4/.gitattributes ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pb filter=lfs diff=lfs merge=lfs -text
18
+ *.pickle filter=lfs diff=lfs merge=lfs -text
19
+ *.pkl filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz filter=lfs diff=lfs merge=lfs -text
29
+ *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zst filter=lfs diff=lfs merge=lfs -text
31
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
32
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
stable-diffusion-v1-4/README.md ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: creativeml-openrail-m
3
+ tags:
4
+ - stable-diffusion
5
+ - stable-diffusion-diffusers
6
+ - text-to-image
7
+ widget:
8
+ - text: "A high tech solarpunk utopia in the Amazon rainforest"
9
+ example_title: Amazon rainforest
10
+ - text: "A pikachu fine dining with a view to the Eiffel Tower"
11
+ example_title: Pikachu in Paris
12
+ - text: "A mecha robot in a favela in expressionist style"
13
+ example_title: Expressionist robot
14
+ - text: "an insect robot preparing a delicious meal"
15
+ example_title: Insect robot
16
+ - text: "A small cabin on top of a snowy mountain in the style of Disney, artstation"
17
+ example_title: Snowy disney cabin
18
+ extra_gated_prompt: |-
19
+ This model is open access and available to all, with a CreativeML OpenRAIL-M license further specifying rights and usage.
20
+ The CreativeML OpenRAIL License specifies:
21
+
22
+ 1. You can't use the model to deliberately produce nor share illegal or harmful outputs or content
23
+ 2. The authors claim no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in the license
24
+ 3. You may re-distribute the weights and use the model commercially and/or as a service. If you do, please be aware you have to include the same use restrictions as the ones in the license and share a copy of the CreativeML OpenRAIL-M to all your users (please read the license entirely and carefully)
25
+ Please read the full license carefully here: https://huggingface.co/spaces/CompVis/stable-diffusion-license
26
+
27
+ extra_gated_heading: Please read the LICENSE to access this model
28
+ ---
29
+
30
+ # Stable Diffusion v1-4 Model Card
31
+
32
+ Stable Diffusion is a latent text-to-image diffusion model capable of generating photo-realistic images given any text input.
33
+ For more information about how Stable Diffusion functions, please have a look at [🤗's Stable Diffusion with 🧨Diffusers blog](https://huggingface.co/blog/stable_diffusion).
34
+
35
+ The **Stable-Diffusion-v1-4** checkpoint was initialized with the weights of the [Stable-Diffusion-v1-2](https:/steps/huggingface.co/CompVis/stable-diffusion-v1-2)
36
+ checkpoint and subsequently fine-tuned on 225k steps at resolution 512x512 on "laion-aesthetics v2 5+" and 10% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
37
+
38
+ This weights here are intended to be used with the 🧨 Diffusers library. If you are looking for the weights to be loaded into the CompVis Stable Diffusion codebase, [come here](https://huggingface.co/CompVis/stable-diffusion-v-1-4-original)
39
+
40
+ ## Model Details
41
+ - **Developed by:** Robin Rombach, Patrick Esser
42
+ - **Model type:** Diffusion-based text-to-image generation model
43
+ - **Language(s):** English
44
+ - **License:** [The CreativeML OpenRAIL M license](https://huggingface.co/spaces/CompVis/stable-diffusion-license) is an [Open RAIL M license](https://www.licenses.ai/blog/2022/8/18/naming-convention-of-responsible-ai-licenses), adapted from the work that [BigScience](https://bigscience.huggingface.co/) and [the RAIL Initiative](https://www.licenses.ai/) are jointly carrying in the area of responsible AI licensing. See also [the article about the BLOOM Open RAIL license](https://bigscience.huggingface.co/blog/the-bigscience-rail-license) on which our license is based.
45
+ - **Model Description:** This is a model that can be used to generate and modify images based on text prompts. It is a [Latent Diffusion Model](https://arxiv.org/abs/2112.10752) that uses a fixed, pretrained text encoder ([CLIP ViT-L/14](https://arxiv.org/abs/2103.00020)) as suggested in the [Imagen paper](https://arxiv.org/abs/2205.11487).
46
+ - **Resources for more information:** [GitHub Repository](https://github.com/CompVis/stable-diffusion), [Paper](https://arxiv.org/abs/2112.10752).
47
+ - **Cite as:**
48
+
49
+ @InProceedings{Rombach_2022_CVPR,
50
+ author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn},
51
+ title = {High-Resolution Image Synthesis With Latent Diffusion Models},
52
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
53
+ month = {June},
54
+ year = {2022},
55
+ pages = {10684-10695}
56
+ }
57
+
58
+ ## Examples
59
+
60
+ We recommend using [🤗's Diffusers library](https://github.com/huggingface/diffusers) to run Stable Diffusion.
61
+
62
+ ### PyTorch
63
+
64
+ ```bash
65
+ pip install --upgrade diffusers transformers scipy
66
+ ```
67
+
68
+ Running the pipeline with the default PNDM scheduler:
69
+
70
+ ```python
71
+ import torch
72
+ from diffusers import StableDiffusionPipeline
73
+
74
+ model_id = "CompVis/stable-diffusion-v1-4"
75
+ device = "cuda"
76
+
77
+
78
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
79
+ pipe = pipe.to(device)
80
+
81
+ prompt = "a photo of an astronaut riding a horse on mars"
82
+ image = pipe(prompt).images[0]
83
+
84
+ image.save("astronaut_rides_horse.png")
85
+ ```
86
+
87
+ **Note**:
88
+ If you are limited by GPU memory and have less than 4GB of GPU RAM available, please make sure to load the StableDiffusionPipeline in float16 precision instead of the default float32 precision as done above. You can do so by telling diffusers to expect the weights to be in float16 precision:
89
+
90
+
91
+ ```py
92
+ import torch
93
+
94
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
95
+ pipe = pipe.to(device)
96
+ pipe.enable_attention_slicing()
97
+
98
+ prompt = "a photo of an astronaut riding a horse on mars"
99
+ image = pipe(prompt).images[0]
100
+
101
+ image.save("astronaut_rides_horse.png")
102
+ ```
103
+
104
+ To swap out the noise scheduler, pass it to `from_pretrained`:
105
+
106
+ ```python
107
+ from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler
108
+
109
+ model_id = "CompVis/stable-diffusion-v1-4"
110
+
111
+ # Use the Euler scheduler here instead
112
+ scheduler = EulerDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler")
113
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, scheduler=scheduler, torch_dtype=torch.float16)
114
+ pipe = pipe.to("cuda")
115
+
116
+ prompt = "a photo of an astronaut riding a horse on mars"
117
+ image = pipe(prompt).images[0]
118
+
119
+ image.save("astronaut_rides_horse.png")
120
+ ```
121
+
122
+ ### JAX/Flax
123
+
124
+ To use StableDiffusion on TPUs and GPUs for faster inference you can leverage JAX/Flax.
125
+
126
+ Running the pipeline with default PNDMScheduler
127
+
128
+ ```python
129
+ import jax
130
+ import numpy as np
131
+ from flax.jax_utils import replicate
132
+ from flax.training.common_utils import shard
133
+
134
+ from diffusers import FlaxStableDiffusionPipeline
135
+
136
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
137
+ "CompVis/stable-diffusion-v1-4", revision="flax", dtype=jax.numpy.bfloat16
138
+ )
139
+
140
+ prompt = "a photo of an astronaut riding a horse on mars"
141
+
142
+ prng_seed = jax.random.PRNGKey(0)
143
+ num_inference_steps = 50
144
+
145
+ num_samples = jax.device_count()
146
+ prompt = num_samples * [prompt]
147
+ prompt_ids = pipeline.prepare_inputs(prompt)
148
+
149
+ # shard inputs and rng
150
+ params = replicate(params)
151
+ prng_seed = jax.random.split(prng_seed, num_samples)
152
+ prompt_ids = shard(prompt_ids)
153
+
154
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
155
+ images = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
156
+ ```
157
+
158
+ **Note**:
159
+ If you are limited by TPU memory, please make sure to load the `FlaxStableDiffusionPipeline` in `bfloat16` precision instead of the default `float32` precision as done above. You can do so by telling diffusers to load the weights from "bf16" branch.
160
+
161
+ ```python
162
+ import jax
163
+ import numpy as np
164
+ from flax.jax_utils import replicate
165
+ from flax.training.common_utils import shard
166
+
167
+ from diffusers import FlaxStableDiffusionPipeline
168
+
169
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
170
+ "CompVis/stable-diffusion-v1-4", revision="bf16", dtype=jax.numpy.bfloat16
171
+ )
172
+
173
+ prompt = "a photo of an astronaut riding a horse on mars"
174
+
175
+ prng_seed = jax.random.PRNGKey(0)
176
+ num_inference_steps = 50
177
+
178
+ num_samples = jax.device_count()
179
+ prompt = num_samples * [prompt]
180
+ prompt_ids = pipeline.prepare_inputs(prompt)
181
+
182
+ # shard inputs and rng
183
+ params = replicate(params)
184
+ prng_seed = jax.random.split(prng_seed, num_samples)
185
+ prompt_ids = shard(prompt_ids)
186
+
187
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
188
+ images = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
189
+ ```
190
+
191
+ # Uses
192
+
193
+ ## Direct Use
194
+ The model is intended for research purposes only. Possible research areas and
195
+ tasks include
196
+
197
+ - Safe deployment of models which have the potential to generate harmful content.
198
+ - Probing and understanding the limitations and biases of generative models.
199
+ - Generation of artworks and use in design and other artistic processes.
200
+ - Applications in educational or creative tools.
201
+ - Research on generative models.
202
+
203
+ Excluded uses are described below.
204
+
205
+ ### Misuse, Malicious Use, and Out-of-Scope Use
206
+ _Note: This section is taken from the [DALLE-MINI model card](https://huggingface.co/dalle-mini/dalle-mini), but applies in the same way to Stable Diffusion v1_.
207
+
208
+
209
+ The model should not be used to intentionally create or disseminate images that create hostile or alienating environments for people. This includes generating images that people would foreseeably find disturbing, distressing, or offensive; or content that propagates historical or current stereotypes.
210
+
211
+ #### Out-of-Scope Use
212
+ The model was not trained to be factual or true representations of people or events, and therefore using the model to generate such content is out-of-scope for the abilities of this model.
213
+
214
+ #### Misuse and Malicious Use
215
+ Using the model to generate content that is cruel to individuals is a misuse of this model. This includes, but is not limited to:
216
+
217
+ - Generating demeaning, dehumanizing, or otherwise harmful representations of people or their environments, cultures, religions, etc.
218
+ - Intentionally promoting or propagating discriminatory content or harmful stereotypes.
219
+ - Impersonating individuals without their consent.
220
+ - Sexual content without consent of the people who might see it.
221
+ - Mis- and disinformation
222
+ - Representations of egregious violence and gore
223
+ - Sharing of copyrighted or licensed material in violation of its terms of use.
224
+ - Sharing content that is an alteration of copyrighted or licensed material in violation of its terms of use.
225
+
226
+ ## Limitations and Bias
227
+
228
+ ### Limitations
229
+
230
+ - The model does not achieve perfect photorealism
231
+ - The model cannot render legible text
232
+ - The model does not perform well on more difficult tasks which involve compositionality, such as rendering an image corresponding to “A red cube on top of a blue sphere”
233
+ - Faces and people in general may not be generated properly.
234
+ - The model was trained mainly with English captions and will not work as well in other languages.
235
+ - The autoencoding part of the model is lossy
236
+ - The model was trained on a large-scale dataset
237
+ [LAION-5B](https://laion.ai/blog/laion-5b/) which contains adult material
238
+ and is not fit for product use without additional safety mechanisms and
239
+ considerations.
240
+ - No additional measures were used to deduplicate the dataset. As a result, we observe some degree of memorization for images that are duplicated in the training data.
241
+ The training data can be searched at [https://rom1504.github.io/clip-retrieval/](https://rom1504.github.io/clip-retrieval/) to possibly assist in the detection of memorized images.
242
+
243
+ ### Bias
244
+
245
+ While the capabilities of image generation models are impressive, they can also reinforce or exacerbate social biases.
246
+ Stable Diffusion v1 was trained on subsets of [LAION-2B(en)](https://laion.ai/blog/laion-5b/),
247
+ which consists of images that are primarily limited to English descriptions.
248
+ Texts and images from communities and cultures that use other languages are likely to be insufficiently accounted for.
249
+ This affects the overall output of the model, as white and western cultures are often set as the default. Further, the
250
+ ability of the model to generate content with non-English prompts is significantly worse than with English-language prompts.
251
+
252
+ ### Safety Module
253
+
254
+ The intended use of this model is with the [Safety Checker](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py) in Diffusers.
255
+ This checker works by checking model outputs against known hard-coded NSFW concepts.
256
+ The concepts are intentionally hidden to reduce the likelihood of reverse-engineering this filter.
257
+ Specifically, the checker compares the class probability of harmful concepts in the embedding space of the `CLIPTextModel` *after generation* of the images.
258
+ The concepts are passed into the model with the generated image and compared to a hand-engineered weight for each NSFW concept.
259
+
260
+
261
+ ## Training
262
+
263
+ **Training Data**
264
+ The model developers used the following dataset for training the model:
265
+
266
+ - LAION-2B (en) and subsets thereof (see next section)
267
+
268
+ **Training Procedure**
269
+ Stable Diffusion v1-4 is a latent diffusion model which combines an autoencoder with a diffusion model that is trained in the latent space of the autoencoder. During training,
270
+
271
+ - Images are encoded through an encoder, which turns images into latent representations. The autoencoder uses a relative downsampling factor of 8 and maps images of shape H x W x 3 to latents of shape H/f x W/f x 4
272
+ - Text prompts are encoded through a ViT-L/14 text-encoder.
273
+ - The non-pooled output of the text encoder is fed into the UNet backbone of the latent diffusion model via cross-attention.
274
+ - The loss is a reconstruction objective between the noise that was added to the latent and the prediction made by the UNet.
275
+
276
+ We currently provide four checkpoints, which were trained as follows.
277
+ - [`stable-diffusion-v1-1`](https://huggingface.co/CompVis/stable-diffusion-v1-1): 237,000 steps at resolution `256x256` on [laion2B-en](https://huggingface.co/datasets/laion/laion2B-en).
278
+ 194,000 steps at resolution `512x512` on [laion-high-resolution](https://huggingface.co/datasets/laion/laion-high-resolution) (170M examples from LAION-5B with resolution `>= 1024x1024`).
279
+ - [`stable-diffusion-v1-2`](https://huggingface.co/CompVis/stable-diffusion-v1-2): Resumed from `stable-diffusion-v1-1`.
280
+ 515,000 steps at resolution `512x512` on "laion-improved-aesthetics" (a subset of laion2B-en,
281
+ filtered to images with an original size `>= 512x512`, estimated aesthetics score `> 5.0`, and an estimated watermark probability `< 0.5`. The watermark estimate is from the LAION-5B metadata, the aesthetics score is estimated using an [improved aesthetics estimator](https://github.com/christophschuhmann/improved-aesthetic-predictor)).
282
+ - [`stable-diffusion-v1-3`](https://huggingface.co/CompVis/stable-diffusion-v1-3): Resumed from `stable-diffusion-v1-2`. 195,000 steps at resolution `512x512` on "laion-improved-aesthetics" and 10 % dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
283
+ - [`stable-diffusion-v1-4`](https://huggingface.co/CompVis/stable-diffusion-v1-4) Resumed from `stable-diffusion-v1-2`.225,000 steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10 % dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
284
+
285
+ - **Hardware:** 32 x 8 x A100 GPUs
286
+ - **Optimizer:** AdamW
287
+ - **Gradient Accumulations**: 2
288
+ - **Batch:** 32 x 8 x 2 x 4 = 2048
289
+ - **Learning rate:** warmup to 0.0001 for 10,000 steps and then kept constant
290
+
291
+ ## Evaluation Results
292
+ Evaluations with different classifier-free guidance scales (1.5, 2.0, 3.0, 4.0,
293
+ 5.0, 6.0, 7.0, 8.0) and 50 PLMS sampling
294
+ steps show the relative improvements of the checkpoints:
295
+
296
+ ![pareto](https://huggingface.co/CompVis/stable-diffusion/resolve/main/v1-variants-scores.jpg)
297
+
298
+ Evaluated using 50 PLMS steps and 10000 random prompts from the COCO2017 validation set, evaluated at 512x512 resolution. Not optimized for FID scores.
299
+ ## Environmental Impact
300
+
301
+ **Stable Diffusion v1** **Estimated Emissions**
302
+ Based on that information, we estimate the following CO2 emissions using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). The hardware, runtime, cloud provider, and compute region were utilized to estimate the carbon impact.
303
+
304
+ - **Hardware Type:** A100 PCIe 40GB
305
+ - **Hours used:** 150000
306
+ - **Cloud Provider:** AWS
307
+ - **Compute Region:** US-east
308
+ - **Carbon Emitted (Power consumption x Time x Carbon produced based on location of power grid):** 11250 kg CO2 eq.
309
+
310
+
311
+ ## Citation
312
+
313
+ ```bibtex
314
+ @InProceedings{Rombach_2022_CVPR,
315
+ author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn},
316
+ title = {High-Resolution Image Synthesis With Latent Diffusion Models},
317
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
318
+ month = {June},
319
+ year = {2022},
320
+ pages = {10684-10695}
321
+ }
322
+ ```
323
+
324
+ *This model card was written by: Robin Rombach and Patrick Esser and is based on the [DALL-E Mini model card](https://huggingface.co/dalle-mini/dalle-mini).*
stable-diffusion-v1-4/feature_extractor/preprocessor_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": 224,
3
+ "do_center_crop": true,
4
+ "do_convert_rgb": true,
5
+ "do_normalize": true,
6
+ "do_resize": true,
7
+ "feature_extractor_type": "CLIPFeatureExtractor",
8
+ "image_mean": [
9
+ 0.48145466,
10
+ 0.4578275,
11
+ 0.40821073
12
+ ],
13
+ "image_std": [
14
+ 0.26862954,
15
+ 0.26130258,
16
+ 0.27577711
17
+ ],
18
+ "resample": 3,
19
+ "size": 224
20
+ }
stable-diffusion-v1-4/model_index.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "StableDiffusionPipeline",
3
+ "_diffusers_version": "0.2.2",
4
+ "feature_extractor": [
5
+ "transformers",
6
+ "CLIPImageProcessor"
7
+ ],
8
+ "safety_checker": [
9
+ "stable_diffusion",
10
+ "StableDiffusionSafetyChecker"
11
+ ],
12
+ "scheduler": [
13
+ "diffusers",
14
+ "PNDMScheduler"
15
+ ],
16
+ "text_encoder": [
17
+ "transformers",
18
+ "CLIPTextModel"
19
+ ],
20
+ "tokenizer": [
21
+ "transformers",
22
+ "CLIPTokenizer"
23
+ ],
24
+ "unet": [
25
+ "diffusers",
26
+ "UNet2DConditionModel"
27
+ ],
28
+ "vae": [
29
+ "diffusers",
30
+ "AutoencoderKL"
31
+ ]
32
+ }