Add files using upload-large-folder tool
Browse files- .gitattributes +2 -0
- JiT-B-16/config.json +14 -0
- JiT-B-16/conversion_metadata.json +17 -0
- JiT-B-16/diffusion_pytorch_model.safetensors +3 -0
- JiT-B-16/model_index.json +8 -0
- JiT-B-16/scheduler_config.json +7 -0
- JiT-B-32/config.json +14 -0
- JiT-B-32/diffusion_pytorch_model.safetensors +3 -0
- JiT-B-32/model_index.json +8 -0
- JiT-B-32/scheduler_config.json +7 -0
- JiT-H-16/config.json +14 -0
- JiT-H-16/conversion_metadata.json +17 -0
- JiT-H-16/diffusion_pytorch_model.safetensors +3 -0
- JiT-H-16/model_index.json +8 -0
- JiT-H-16/scheduler_config.json +7 -0
- JiT-H-32/config.json +14 -0
- JiT-H-32/conversion_metadata.json +17 -0
- JiT-H-32/diffusion_pytorch_model.safetensors +3 -0
- JiT-H-32/model_index.json +8 -0
- JiT-H-32/scheduler_config.json +7 -0
- JiT-L-16/config.json +14 -0
- JiT-L-16/conversion_metadata.json +17 -0
- JiT-L-16/diffusion_pytorch_model.safetensors +3 -0
- JiT-L-16/model_index.json +8 -0
- JiT-L-16/scheduler_config.json +7 -0
- JiT-L-32/config.json +14 -0
- JiT-L-32/conversion_metadata.json +17 -0
- JiT-L-32/diffusion_pytorch_model.safetensors +3 -0
- JiT-L-32/model_index.json +8 -0
- JiT-L-32/scheduler_config.json +7 -0
- README.md +89 -0
- demo.png +3 -0
- demo_images/jit_h32_test_inference.png +3 -0
- jit_diffusers/__init__.py +11 -0
- jit_diffusers/modeling_jit_backbone.py +321 -0
- jit_diffusers/modeling_jit_transformer_2d.py +200 -0
- jit_diffusers/modeling_jit_utils.py +129 -0
- jit_diffusers/pipeline_jit.py +156 -0
- jit_diffusers/scheduling_jit.py +71 -0
- run_jit_diffusers_inference.py +96 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
demo.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
demo_images/jit_h32_test_inference.png filter=lfs diff=lfs merge=lfs -text
|
JiT-B-16/config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTTransformer2DModel",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"attention_dropout": 0.0,
|
| 5 |
+
"attn_dropout": null,
|
| 6 |
+
"dropout": 0.0,
|
| 7 |
+
"image_size": null,
|
| 8 |
+
"model_name": null,
|
| 9 |
+
"model_type": "JiT-B/16",
|
| 10 |
+
"num_class_embeds": 1000,
|
| 11 |
+
"num_classes": null,
|
| 12 |
+
"proj_dropout": null,
|
| 13 |
+
"sample_size": 256
|
| 14 |
+
}
|
JiT-B-16/conversion_metadata.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"source_checkpoint": "/root/worksapce/models/raw/jit-b-16/checkpoint-last.pth",
|
| 3 |
+
"weights": "ema1",
|
| 4 |
+
"epoch": null,
|
| 5 |
+
"jit_args": {
|
| 6 |
+
"model_type": "JiT-B/16",
|
| 7 |
+
"sample_size": 256,
|
| 8 |
+
"num_class_embeds": 1000,
|
| 9 |
+
"attention_dropout": 0.0,
|
| 10 |
+
"dropout": 0.0,
|
| 11 |
+
"model": "JiT-B/16",
|
| 12 |
+
"img_size": 256,
|
| 13 |
+
"class_num": 1000,
|
| 14 |
+
"attn_dropout": 0.0,
|
| 15 |
+
"proj_dropout": 0.0
|
| 16 |
+
}
|
| 17 |
+
}
|
JiT-B-16/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:53987d6142a3dd9b0a390bd987ebecf806f95cd7b52d64beb41a4fb21199fb6b
|
| 3 |
+
size 525301096
|
JiT-B-16/model_index.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTPipeline",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"transformer": [
|
| 5 |
+
"jit_diffusers",
|
| 6 |
+
"JiTTransformer2DModel"
|
| 7 |
+
]
|
| 8 |
+
}
|
JiT-B-16/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTScheduler",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"solver": "heun",
|
| 5 |
+
"timestep_start": 0.0,
|
| 6 |
+
"timestep_end": 1.0
|
| 7 |
+
}
|
JiT-B-32/config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTTransformer2DModel",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"attention_dropout": 0.0,
|
| 5 |
+
"attn_dropout": null,
|
| 6 |
+
"dropout": 0.0,
|
| 7 |
+
"image_size": null,
|
| 8 |
+
"model_name": null,
|
| 9 |
+
"model_type": "JiT-B/32",
|
| 10 |
+
"num_class_embeds": 1000,
|
| 11 |
+
"num_classes": null,
|
| 12 |
+
"proj_dropout": null,
|
| 13 |
+
"sample_size": 512
|
| 14 |
+
}
|
JiT-B-32/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3652a94f7815bd4b2a02575a4b004e4270a4ddbf5218c292c2cac6d16efb7399
|
| 3 |
+
size 533567848
|
JiT-B-32/model_index.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTPipeline",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"transformer": [
|
| 5 |
+
"jit_diffusers",
|
| 6 |
+
"JiTTransformer2DModel"
|
| 7 |
+
]
|
| 8 |
+
}
|
JiT-B-32/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTScheduler",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"solver": "heun",
|
| 5 |
+
"timestep_start": 0.0,
|
| 6 |
+
"timestep_end": 1.0
|
| 7 |
+
}
|
JiT-H-16/config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTTransformer2DModel",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"attention_dropout": 0.0,
|
| 5 |
+
"attn_dropout": null,
|
| 6 |
+
"dropout": 0.2,
|
| 7 |
+
"image_size": null,
|
| 8 |
+
"model_name": null,
|
| 9 |
+
"model_type": "JiT-H/16",
|
| 10 |
+
"num_class_embeds": 1000,
|
| 11 |
+
"num_classes": null,
|
| 12 |
+
"proj_dropout": null,
|
| 13 |
+
"sample_size": 256
|
| 14 |
+
}
|
JiT-H-16/conversion_metadata.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"source_checkpoint": "/root/worksapce/models/raw/jit-h-16/checkpoint-last.pth",
|
| 3 |
+
"weights": "ema1",
|
| 4 |
+
"epoch": null,
|
| 5 |
+
"jit_args": {
|
| 6 |
+
"model_type": "JiT-H/16",
|
| 7 |
+
"sample_size": 256,
|
| 8 |
+
"num_class_embeds": 1000,
|
| 9 |
+
"attention_dropout": 0.0,
|
| 10 |
+
"dropout": 0.2,
|
| 11 |
+
"model": "JiT-H/16",
|
| 12 |
+
"img_size": 256,
|
| 13 |
+
"class_num": 1000,
|
| 14 |
+
"attn_dropout": 0.0,
|
| 15 |
+
"proj_dropout": 0.2
|
| 16 |
+
}
|
| 17 |
+
}
|
JiT-H-16/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2723e68bceac95b153a01d3cc17cf10e727e8bfe7cdf3c38ee2f66adaa6e7b35
|
| 3 |
+
size 3811419656
|
JiT-H-16/model_index.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTPipeline",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"transformer": [
|
| 5 |
+
"jit_diffusers",
|
| 6 |
+
"JiTTransformer2DModel"
|
| 7 |
+
]
|
| 8 |
+
}
|
JiT-H-16/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTScheduler",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"solver": "heun",
|
| 5 |
+
"timestep_start": 0.0,
|
| 6 |
+
"timestep_end": 1.0
|
| 7 |
+
}
|
JiT-H-32/config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTTransformer2DModel",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"attention_dropout": 0.0,
|
| 5 |
+
"attn_dropout": null,
|
| 6 |
+
"dropout": 0.2,
|
| 7 |
+
"image_size": null,
|
| 8 |
+
"model_name": null,
|
| 9 |
+
"model_type": "JiT-H/32",
|
| 10 |
+
"num_class_embeds": 1000,
|
| 11 |
+
"num_classes": null,
|
| 12 |
+
"proj_dropout": null,
|
| 13 |
+
"sample_size": 512
|
| 14 |
+
}
|
JiT-H-32/conversion_metadata.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"source_checkpoint": "/root/worksapce/projects/JiT-diffusers/models/raw/jit-h-32/checkpoint-last.pth",
|
| 3 |
+
"weights": "ema1",
|
| 4 |
+
"epoch": null,
|
| 5 |
+
"jit_args": {
|
| 6 |
+
"model_type": "JiT-H/32",
|
| 7 |
+
"sample_size": 512,
|
| 8 |
+
"num_class_embeds": 1000,
|
| 9 |
+
"attention_dropout": 0.0,
|
| 10 |
+
"dropout": 0.2,
|
| 11 |
+
"model": "JiT-H/32",
|
| 12 |
+
"img_size": 512,
|
| 13 |
+
"class_num": 1000,
|
| 14 |
+
"attn_dropout": 0.0,
|
| 15 |
+
"proj_dropout": 0.2
|
| 16 |
+
}
|
| 17 |
+
}
|
JiT-H-32/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3693c9077ce262edf99fccbeff8e981ae1f7499a6d6148c0837081fe3dee15db
|
| 3 |
+
size 3825584616
|
JiT-H-32/model_index.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTPipeline",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"transformer": [
|
| 5 |
+
"jit_diffusers",
|
| 6 |
+
"JiTTransformer2DModel"
|
| 7 |
+
]
|
| 8 |
+
}
|
JiT-H-32/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTScheduler",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"solver": "heun",
|
| 5 |
+
"timestep_start": 0.0,
|
| 6 |
+
"timestep_end": 1.0
|
| 7 |
+
}
|
JiT-L-16/config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTTransformer2DModel",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"attention_dropout": 0.0,
|
| 5 |
+
"attn_dropout": null,
|
| 6 |
+
"dropout": 0.0,
|
| 7 |
+
"image_size": null,
|
| 8 |
+
"model_name": null,
|
| 9 |
+
"model_type": "JiT-L/16",
|
| 10 |
+
"num_class_embeds": 1000,
|
| 11 |
+
"num_classes": null,
|
| 12 |
+
"proj_dropout": null,
|
| 13 |
+
"sample_size": 256
|
| 14 |
+
}
|
JiT-L-16/conversion_metadata.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"source_checkpoint": "/root/worksapce/models/raw/jit-l-16/checkpoint-last.pth",
|
| 3 |
+
"weights": "ema1",
|
| 4 |
+
"epoch": null,
|
| 5 |
+
"jit_args": {
|
| 6 |
+
"model_type": "JiT-L/16",
|
| 7 |
+
"sample_size": 256,
|
| 8 |
+
"num_class_embeds": 1000,
|
| 9 |
+
"attention_dropout": 0.0,
|
| 10 |
+
"dropout": 0.0,
|
| 11 |
+
"model": "JiT-L/16",
|
| 12 |
+
"img_size": 256,
|
| 13 |
+
"class_num": 1000,
|
| 14 |
+
"attn_dropout": 0.0,
|
| 15 |
+
"proj_dropout": 0.0
|
| 16 |
+
}
|
| 17 |
+
}
|
JiT-L-16/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8d49cacb0751f4fc77d6578d71f992d65323b451fa194e35c77ebc49e21b9cbd
|
| 3 |
+
size 1836598016
|
JiT-L-16/model_index.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTPipeline",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"transformer": [
|
| 5 |
+
"jit_diffusers",
|
| 6 |
+
"JiTTransformer2DModel"
|
| 7 |
+
]
|
| 8 |
+
}
|
JiT-L-16/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTScheduler",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"solver": "heun",
|
| 5 |
+
"timestep_start": 0.0,
|
| 6 |
+
"timestep_end": 1.0
|
| 7 |
+
}
|
JiT-L-32/config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTTransformer2DModel",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"attention_dropout": 0.0,
|
| 5 |
+
"attn_dropout": null,
|
| 6 |
+
"dropout": 0.0,
|
| 7 |
+
"image_size": null,
|
| 8 |
+
"model_name": null,
|
| 9 |
+
"model_type": "JiT-L/32",
|
| 10 |
+
"num_class_embeds": 1000,
|
| 11 |
+
"num_classes": null,
|
| 12 |
+
"proj_dropout": null,
|
| 13 |
+
"sample_size": 512
|
| 14 |
+
}
|
JiT-L-32/conversion_metadata.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"source_checkpoint": "/root/worksapce/models/raw/jit-l-32/checkpoint-last.pth",
|
| 3 |
+
"weights": "ema1",
|
| 4 |
+
"epoch": null,
|
| 5 |
+
"jit_args": {
|
| 6 |
+
"model_type": "JiT-L/32",
|
| 7 |
+
"sample_size": 512,
|
| 8 |
+
"num_class_embeds": 1000,
|
| 9 |
+
"attention_dropout": 0.0,
|
| 10 |
+
"dropout": 0.0,
|
| 11 |
+
"model": "JiT-L/32",
|
| 12 |
+
"img_size": 512,
|
| 13 |
+
"class_num": 1000,
|
| 14 |
+
"attn_dropout": 0.0,
|
| 15 |
+
"proj_dropout": 0.0
|
| 16 |
+
}
|
| 17 |
+
}
|
JiT-L-32/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f46ad7ed33a27906245178451c724e40c33ad13832fd82e7ab751e9620e471e0
|
| 3 |
+
size 1847224072
|
JiT-L-32/model_index.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTPipeline",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"transformer": [
|
| 5 |
+
"jit_diffusers",
|
| 6 |
+
"JiTTransformer2DModel"
|
| 7 |
+
]
|
| 8 |
+
}
|
JiT-L-32/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "JiTScheduler",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"solver": "heun",
|
| 5 |
+
"timestep_start": 0.0,
|
| 6 |
+
"timestep_end": 1.0
|
| 7 |
+
}
|
README.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
library_name: diffusers
|
| 4 |
+
pipeline_tag: unconditional-image-generation
|
| 5 |
+
tags:
|
| 6 |
+
- diffusers
|
| 7 |
+
- jit
|
| 8 |
+
- image-generation
|
| 9 |
+
- class-conditional
|
| 10 |
+
widget:
|
| 11 |
+
- text: "ImageNet class 207 (golden retriever), JiT-H/32 test sample"
|
| 12 |
+
output:
|
| 13 |
+
url: demo.png
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# JiT-H/32 (Diffusers)
|
| 17 |
+
|
| 18 |
+
This repository is self-contained: model weights and a custom `diffusers` pipeline (`JiTPipeline`) are both included, so no external code repo is required.
|
| 19 |
+
|
| 20 |
+
## Available Checkpoints (All 6)
|
| 21 |
+
|
| 22 |
+
The JiT paper reports six ImageNet checkpoints across 256 and 512 resolutions. Use the following relative paths with `JiTPipeline.from_pretrained(...)`.
|
| 23 |
+
|
| 24 |
+
| Checkpoint | Relative path | Resolution | Pre-trained dataset | Recommended CFG | Recommended interval | Recommended noise_scale | FID-50K |
|
| 25 |
+
|---|---|---|---|---:|---|---:|---:|
|
| 26 |
+
| JiT-B/16 | `./JiT-B-16` | 256x256 | ImageNet 256x256 | 3.0 | `[0.1, 1.0]` | 1.0 | 3.66 |
|
| 27 |
+
| JiT-L/16 | `./JiT-L-16` | 256x256 | ImageNet 256x256 | 2.4 | `[0.1, 1.0]` | 1.0 | 2.36 |
|
| 28 |
+
| JiT-H/16 | `./JiT-H-16` | 256x256 | ImageNet 256x256 | 2.2 | `[0.1, 1.0]` | 1.0 | 1.86 |
|
| 29 |
+
| JiT-B/32 | `./JiT-B-32` | 512x512 | ImageNet 512x512 | 3.0 | `[0.1, 1.0]` | 2.0 | 4.02 |
|
| 30 |
+
| JiT-L/32 | `./JiT-L-32` | 512x512 | ImageNet 512x512 | 2.5 | `[0.1, 1.0]` | 2.0 | 2.53 |
|
| 31 |
+
| JiT-H/32 | `./JiT-H-32` | 512x512 | ImageNet 512x512 | 2.3 | `[0.1, 1.0]` | 2.0 | 1.94 |
|
| 32 |
+
|
| 33 |
+
Source: [Back to Basics: Let Denoising Generative Models Denoise (arXiv:2511.13720)](https://arxiv.org/html/2511.13720).
|
| 34 |
+
|
| 35 |
+
## Demo Image
|
| 36 |
+
|
| 37 |
+

|
| 38 |
+
|
| 39 |
+
## One-Stop Diffusers Inference
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
from pathlib import Path
|
| 43 |
+
import sys
|
| 44 |
+
import torch
|
| 45 |
+
|
| 46 |
+
repo_dir = Path(".").resolve()
|
| 47 |
+
sys.path.insert(0, str(repo_dir))
|
| 48 |
+
from jit_diffusers import JiTPipeline
|
| 49 |
+
|
| 50 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 51 |
+
pipe = JiTPipeline.from_pretrained("./JiT-H-32").to(device)
|
| 52 |
+
pipe.transformer = pipe.transformer.to(device=device, dtype=torch.bfloat16 if device == "cuda" else torch.float32)
|
| 53 |
+
pipe.transformer.eval()
|
| 54 |
+
|
| 55 |
+
generator = torch.Generator(device=device).manual_seed(42)
|
| 56 |
+
output = pipe(
|
| 57 |
+
class_labels=[207],
|
| 58 |
+
num_inference_steps=50,
|
| 59 |
+
guidance_scale=2.3,
|
| 60 |
+
guidance_interval_min=0.1,
|
| 61 |
+
guidance_interval_max=1.0,
|
| 62 |
+
noise_scale=2.0,
|
| 63 |
+
t_eps=5e-2,
|
| 64 |
+
sampling_method="heun",
|
| 65 |
+
generator=generator,
|
| 66 |
+
output_type="pil",
|
| 67 |
+
)
|
| 68 |
+
image = output.images[0]
|
| 69 |
+
output_path = Path("./demo_images/jit_h32_test_inference.png")
|
| 70 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 71 |
+
image.save(output_path)
|
| 72 |
+
print(f"Saved image to: {output_path}")
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
## Ready-to-Run Commands (All 6 Checkpoints)
|
| 76 |
+
|
| 77 |
+
Run these from this repository root (`models/BiliSakura/JiT-diffusers`).
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
# 256x256 checkpoints
|
| 81 |
+
python run_jit_diffusers_inference.py --model_path ./JiT-B-16 --output_path ./demo_images/jit_b16_test_inference.png --class_label 207 --seed 42 --steps 50 --cfg 3.0 --interval_min 0.1 --interval_max 1.0 --noise_scale 1.0 --t_eps 5e-2 --solver heun
|
| 82 |
+
python run_jit_diffusers_inference.py --model_path ./JiT-L-16 --output_path ./demo_images/jit_l16_test_inference.png --class_label 207 --seed 42 --steps 50 --cfg 2.4 --interval_min 0.1 --interval_max 1.0 --noise_scale 1.0 --t_eps 5e-2 --solver heun
|
| 83 |
+
python run_jit_diffusers_inference.py --model_path ./JiT-H-16 --output_path ./demo_images/jit_h16_test_inference.png --class_label 207 --seed 42 --steps 50 --cfg 2.2 --interval_min 0.1 --interval_max 1.0 --noise_scale 1.0 --t_eps 5e-2 --solver heun
|
| 84 |
+
|
| 85 |
+
# 512x512 checkpoints
|
| 86 |
+
python run_jit_diffusers_inference.py --model_path ./JiT-B-32 --output_path ./demo_images/jit_b32_test_inference.png --class_label 207 --seed 42 --steps 50 --cfg 3.0 --interval_min 0.1 --interval_max 1.0 --noise_scale 2.0 --t_eps 5e-2 --solver heun
|
| 87 |
+
python run_jit_diffusers_inference.py --model_path ./JiT-L-32 --output_path ./demo_images/jit_l32_test_inference.png --class_label 207 --seed 42 --steps 50 --cfg 2.5 --interval_min 0.1 --interval_max 1.0 --noise_scale 2.0 --t_eps 5e-2 --solver heun
|
| 88 |
+
python run_jit_diffusers_inference.py --model_path ./JiT-H-32 --output_path ./demo_images/jit_h32_test_inference.png --class_label 207 --seed 42 --steps 50 --cfg 2.3 --interval_min 0.1 --interval_max 1.0 --noise_scale 2.0 --t_eps 5e-2 --solver heun
|
| 89 |
+
```
|
demo.png
ADDED
|
Git LFS Details
|
demo_images/jit_h32_test_inference.png
ADDED
|
Git LFS Details
|
jit_diffusers/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .modeling_jit_transformer_2d import JiTTransformer2DModel, JiTDiffusersModel
|
| 2 |
+
from .pipeline_jit import JiTPipeline, JiTPipelineOutput
|
| 3 |
+
from .scheduling_jit import JiTScheduler
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
"JiTTransformer2DModel",
|
| 7 |
+
"JiTDiffusersModel",
|
| 8 |
+
"JiTPipeline",
|
| 9 |
+
"JiTPipelineOutput",
|
| 10 |
+
"JiTScheduler",
|
| 11 |
+
]
|
jit_diffusers/modeling_jit_backbone.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from .modeling_jit_utils import VisionRotaryEmbeddingFast, get_2d_sincos_pos_embed, RMSNorm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def modulate(x, shift, scale):
|
| 11 |
+
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BottleneckPatchEmbed(nn.Module):
|
| 15 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, pca_dim=768, embed_dim=768, bias=True):
|
| 16 |
+
super().__init__()
|
| 17 |
+
img_size = (img_size, img_size)
|
| 18 |
+
patch_size = (patch_size, patch_size)
|
| 19 |
+
num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
|
| 20 |
+
self.img_size = img_size
|
| 21 |
+
self.patch_size = patch_size
|
| 22 |
+
self.num_patches = num_patches
|
| 23 |
+
|
| 24 |
+
self.proj1 = nn.Conv2d(in_chans, pca_dim, kernel_size=patch_size, stride=patch_size, bias=False)
|
| 25 |
+
self.proj2 = nn.Conv2d(pca_dim, embed_dim, kernel_size=1, stride=1, bias=bias)
|
| 26 |
+
|
| 27 |
+
def forward(self, x):
|
| 28 |
+
_, _, height, width = x.shape
|
| 29 |
+
assert height == self.img_size[0] and width == self.img_size[1], (
|
| 30 |
+
f"Input image size ({height}*{width}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
|
| 31 |
+
)
|
| 32 |
+
x = self.proj2(self.proj1(x)).flatten(2).transpose(1, 2)
|
| 33 |
+
return x
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TimestepEmbedder(nn.Module):
|
| 37 |
+
def __init__(self, hidden_size, frequency_embedding_size=256):
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.mlp = nn.Sequential(
|
| 40 |
+
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
| 41 |
+
nn.SiLU(),
|
| 42 |
+
nn.Linear(hidden_size, hidden_size, bias=True),
|
| 43 |
+
)
|
| 44 |
+
self.frequency_embedding_size = frequency_embedding_size
|
| 45 |
+
|
| 46 |
+
@staticmethod
|
| 47 |
+
def timestep_embedding(t, dim, max_period=10000):
|
| 48 |
+
half = dim // 2
|
| 49 |
+
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
|
| 50 |
+
device=t.device
|
| 51 |
+
)
|
| 52 |
+
args = t[:, None].float() * freqs[None]
|
| 53 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 54 |
+
if dim % 2:
|
| 55 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 56 |
+
return embedding
|
| 57 |
+
|
| 58 |
+
def forward(self, t):
|
| 59 |
+
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
| 60 |
+
t_freq = t_freq.to(dtype=self.mlp[0].weight.dtype)
|
| 61 |
+
t_emb = self.mlp(t_freq)
|
| 62 |
+
return t_emb
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class LabelEmbedder(nn.Module):
|
| 66 |
+
def __init__(self, num_classes, hidden_size):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.embedding_table = nn.Embedding(num_classes + 1, hidden_size)
|
| 69 |
+
self.num_classes = num_classes
|
| 70 |
+
|
| 71 |
+
def forward(self, labels):
|
| 72 |
+
embeddings = self.embedding_table(labels)
|
| 73 |
+
return embeddings
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def scaled_dot_product_attention(query, key, value, dropout_p=0.0) -> torch.Tensor:
|
| 77 |
+
query_len, key_len = query.size(-2), key.size(-2)
|
| 78 |
+
scale_factor = 1 / math.sqrt(query.size(-1))
|
| 79 |
+
attn_bias = torch.zeros(query.size(0), 1, query_len, key_len, dtype=query.dtype, device=query.device)
|
| 80 |
+
|
| 81 |
+
with torch.amp.autocast("cuda", enabled=False):
|
| 82 |
+
attn_weight = query.float() @ key.float().transpose(-2, -1) * scale_factor
|
| 83 |
+
attn_weight += attn_bias
|
| 84 |
+
attn_weight = torch.softmax(attn_weight, dim=-1)
|
| 85 |
+
attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
|
| 86 |
+
out = attn_weight @ value.float()
|
| 87 |
+
return out.to(query.dtype)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class Attention(nn.Module):
|
| 91 |
+
def __init__(self, dim, num_heads=8, qkv_bias=True, qk_norm=True, attn_drop=0.0, proj_drop=0.0):
|
| 92 |
+
super().__init__()
|
| 93 |
+
self.num_heads = num_heads
|
| 94 |
+
head_dim = dim // num_heads
|
| 95 |
+
|
| 96 |
+
self.q_norm = RMSNorm(head_dim) if qk_norm else nn.Identity()
|
| 97 |
+
self.k_norm = RMSNorm(head_dim) if qk_norm else nn.Identity()
|
| 98 |
+
|
| 99 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 100 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 101 |
+
self.proj = nn.Linear(dim, dim)
|
| 102 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 103 |
+
|
| 104 |
+
def forward(self, x, rope):
|
| 105 |
+
batch_size, num_tokens, channels = x.shape
|
| 106 |
+
qkv = self.qkv(x).reshape(batch_size, num_tokens, 3, self.num_heads, channels // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 107 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
| 108 |
+
|
| 109 |
+
q = self.q_norm(q)
|
| 110 |
+
k = self.k_norm(k)
|
| 111 |
+
q = rope(q)
|
| 112 |
+
k = rope(k)
|
| 113 |
+
|
| 114 |
+
x = scaled_dot_product_attention(q, k, v, dropout_p=self.attn_drop.p if self.training else 0.0)
|
| 115 |
+
x = x.transpose(1, 2).reshape(batch_size, num_tokens, channels)
|
| 116 |
+
x = x.to(self.proj.weight.dtype)
|
| 117 |
+
x = self.proj(x)
|
| 118 |
+
x = self.proj_drop(x)
|
| 119 |
+
return x
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class SwiGLUFFN(nn.Module):
|
| 123 |
+
def __init__(self, dim: int, hidden_dim: int, drop=0.0, bias=True) -> None:
|
| 124 |
+
super().__init__()
|
| 125 |
+
hidden_dim = int(hidden_dim * 2 / 3)
|
| 126 |
+
self.w12 = nn.Linear(dim, 2 * hidden_dim, bias=bias)
|
| 127 |
+
self.w3 = nn.Linear(hidden_dim, dim, bias=bias)
|
| 128 |
+
self.ffn_dropout = nn.Dropout(drop)
|
| 129 |
+
|
| 130 |
+
def forward(self, x):
|
| 131 |
+
x12 = self.w12(x)
|
| 132 |
+
x1, x2 = x12.chunk(2, dim=-1)
|
| 133 |
+
hidden = F.silu(x1) * x2
|
| 134 |
+
return self.w3(self.ffn_dropout(hidden))
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class FinalLayer(nn.Module):
|
| 138 |
+
def __init__(self, hidden_size, patch_size, out_channels):
|
| 139 |
+
super().__init__()
|
| 140 |
+
self.norm_final = RMSNorm(hidden_size)
|
| 141 |
+
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
|
| 142 |
+
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
|
| 143 |
+
|
| 144 |
+
def forward(self, x, c):
|
| 145 |
+
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
|
| 146 |
+
x = modulate(self.norm_final(x), shift, scale)
|
| 147 |
+
x = self.linear(x)
|
| 148 |
+
return x
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class JiTBlock(nn.Module):
|
| 152 |
+
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, attn_drop=0.0, proj_drop=0.0):
|
| 153 |
+
super().__init__()
|
| 154 |
+
self.norm1 = RMSNorm(hidden_size, eps=1e-6)
|
| 155 |
+
self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, qk_norm=True, attn_drop=attn_drop, proj_drop=proj_drop)
|
| 156 |
+
self.norm2 = RMSNorm(hidden_size, eps=1e-6)
|
| 157 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 158 |
+
self.mlp = SwiGLUFFN(hidden_size, mlp_hidden_dim, drop=proj_drop)
|
| 159 |
+
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True))
|
| 160 |
+
|
| 161 |
+
def forward(self, x, c, feat_rope=None):
|
| 162 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=-1)
|
| 163 |
+
x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope)
|
| 164 |
+
x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
|
| 165 |
+
return x
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class JiT(nn.Module):
|
| 169 |
+
def __init__(
|
| 170 |
+
self,
|
| 171 |
+
input_size=256,
|
| 172 |
+
patch_size=16,
|
| 173 |
+
in_channels=3,
|
| 174 |
+
hidden_size=1024,
|
| 175 |
+
depth=24,
|
| 176 |
+
num_heads=16,
|
| 177 |
+
mlp_ratio=4.0,
|
| 178 |
+
attn_drop=0.0,
|
| 179 |
+
proj_drop=0.0,
|
| 180 |
+
num_classes=1000,
|
| 181 |
+
bottleneck_dim=128,
|
| 182 |
+
in_context_len=32,
|
| 183 |
+
in_context_start=8,
|
| 184 |
+
):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.in_channels = in_channels
|
| 187 |
+
self.out_channels = in_channels
|
| 188 |
+
self.patch_size = patch_size
|
| 189 |
+
self.num_heads = num_heads
|
| 190 |
+
self.hidden_size = hidden_size
|
| 191 |
+
self.input_size = input_size
|
| 192 |
+
self.in_context_len = in_context_len
|
| 193 |
+
self.in_context_start = in_context_start
|
| 194 |
+
self.num_classes = num_classes
|
| 195 |
+
|
| 196 |
+
self.t_embedder = TimestepEmbedder(hidden_size)
|
| 197 |
+
self.y_embedder = LabelEmbedder(num_classes, hidden_size)
|
| 198 |
+
self.x_embedder = BottleneckPatchEmbed(input_size, patch_size, in_channels, bottleneck_dim, hidden_size, bias=True)
|
| 199 |
+
|
| 200 |
+
num_patches = self.x_embedder.num_patches
|
| 201 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
|
| 202 |
+
|
| 203 |
+
if self.in_context_len > 0:
|
| 204 |
+
self.in_context_posemb = nn.Parameter(torch.zeros(1, self.in_context_len, hidden_size), requires_grad=True)
|
| 205 |
+
torch.nn.init.normal_(self.in_context_posemb, std=0.02)
|
| 206 |
+
|
| 207 |
+
half_head_dim = hidden_size // num_heads // 2
|
| 208 |
+
hw_seq_len = input_size // patch_size
|
| 209 |
+
self.feat_rope = VisionRotaryEmbeddingFast(dim=half_head_dim, pt_seq_len=hw_seq_len, num_cls_token=0)
|
| 210 |
+
self.feat_rope_incontext = VisionRotaryEmbeddingFast(dim=half_head_dim, pt_seq_len=hw_seq_len, num_cls_token=self.in_context_len)
|
| 211 |
+
|
| 212 |
+
self.blocks = nn.ModuleList(
|
| 213 |
+
[
|
| 214 |
+
JiTBlock(
|
| 215 |
+
hidden_size,
|
| 216 |
+
num_heads,
|
| 217 |
+
mlp_ratio=mlp_ratio,
|
| 218 |
+
attn_drop=attn_drop if (depth // 4 * 3 > i >= depth // 4) else 0.0,
|
| 219 |
+
proj_drop=proj_drop if (depth // 4 * 3 > i >= depth // 4) else 0.0,
|
| 220 |
+
)
|
| 221 |
+
for i in range(depth)
|
| 222 |
+
]
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels)
|
| 226 |
+
self.initialize_weights()
|
| 227 |
+
|
| 228 |
+
def initialize_weights(self):
|
| 229 |
+
def _basic_init(module):
|
| 230 |
+
if isinstance(module, nn.Linear):
|
| 231 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
| 232 |
+
if module.bias is not None:
|
| 233 |
+
nn.init.constant_(module.bias, 0)
|
| 234 |
+
|
| 235 |
+
self.apply(_basic_init)
|
| 236 |
+
|
| 237 |
+
pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches**0.5))
|
| 238 |
+
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 239 |
+
|
| 240 |
+
w1 = self.x_embedder.proj1.weight.data
|
| 241 |
+
nn.init.xavier_uniform_(w1.view([w1.shape[0], -1]))
|
| 242 |
+
w2 = self.x_embedder.proj2.weight.data
|
| 243 |
+
nn.init.xavier_uniform_(w2.view([w2.shape[0], -1]))
|
| 244 |
+
nn.init.constant_(self.x_embedder.proj2.bias, 0)
|
| 245 |
+
|
| 246 |
+
nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
|
| 247 |
+
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
|
| 248 |
+
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
|
| 249 |
+
|
| 250 |
+
for block in self.blocks:
|
| 251 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
| 252 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
| 253 |
+
|
| 254 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
|
| 255 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
|
| 256 |
+
nn.init.constant_(self.final_layer.linear.weight, 0)
|
| 257 |
+
nn.init.constant_(self.final_layer.linear.bias, 0)
|
| 258 |
+
|
| 259 |
+
def unpatchify(self, x, patch_size):
|
| 260 |
+
channels = self.out_channels
|
| 261 |
+
height = width = int(x.shape[1] ** 0.5)
|
| 262 |
+
assert height * width == x.shape[1]
|
| 263 |
+
|
| 264 |
+
x = x.reshape(shape=(x.shape[0], height, width, patch_size, patch_size, channels))
|
| 265 |
+
x = torch.einsum("nhwpqc->nchpwq", x)
|
| 266 |
+
images = x.reshape(shape=(x.shape[0], channels, height * patch_size, height * patch_size))
|
| 267 |
+
return images
|
| 268 |
+
|
| 269 |
+
def forward(self, x, t, y):
|
| 270 |
+
t_emb = self.t_embedder(t)
|
| 271 |
+
y_emb = self.y_embedder(y)
|
| 272 |
+
c = t_emb + y_emb
|
| 273 |
+
|
| 274 |
+
x = self.x_embedder(x)
|
| 275 |
+
x += self.pos_embed
|
| 276 |
+
|
| 277 |
+
for i, block in enumerate(self.blocks):
|
| 278 |
+
if self.in_context_len > 0 and i == self.in_context_start:
|
| 279 |
+
in_context_tokens = y_emb.unsqueeze(1).repeat(1, self.in_context_len, 1)
|
| 280 |
+
in_context_tokens += self.in_context_posemb
|
| 281 |
+
x = torch.cat([in_context_tokens, x], dim=1)
|
| 282 |
+
x = block(x, c, self.feat_rope if i < self.in_context_start else self.feat_rope_incontext)
|
| 283 |
+
|
| 284 |
+
x = x[:, self.in_context_len :]
|
| 285 |
+
x = self.final_layer(x, c)
|
| 286 |
+
output = self.unpatchify(x, self.patch_size)
|
| 287 |
+
return output
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def JiT_B_16(**kwargs):
|
| 291 |
+
return JiT(depth=12, hidden_size=768, num_heads=12, bottleneck_dim=128, in_context_len=32, in_context_start=4, patch_size=16, **kwargs)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def JiT_B_32(**kwargs):
|
| 295 |
+
return JiT(depth=12, hidden_size=768, num_heads=12, bottleneck_dim=128, in_context_len=32, in_context_start=4, patch_size=32, **kwargs)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def JiT_L_16(**kwargs):
|
| 299 |
+
return JiT(depth=24, hidden_size=1024, num_heads=16, bottleneck_dim=128, in_context_len=32, in_context_start=8, patch_size=16, **kwargs)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def JiT_L_32(**kwargs):
|
| 303 |
+
return JiT(depth=24, hidden_size=1024, num_heads=16, bottleneck_dim=128, in_context_len=32, in_context_start=8, patch_size=32, **kwargs)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def JiT_H_16(**kwargs):
|
| 307 |
+
return JiT(depth=32, hidden_size=1280, num_heads=16, bottleneck_dim=256, in_context_len=32, in_context_start=10, patch_size=16, **kwargs)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def JiT_H_32(**kwargs):
|
| 311 |
+
return JiT(depth=32, hidden_size=1280, num_heads=16, bottleneck_dim=256, in_context_len=32, in_context_start=10, patch_size=32, **kwargs)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
JiT_models = {
|
| 315 |
+
"JiT-B/16": JiT_B_16,
|
| 316 |
+
"JiT-B/32": JiT_B_32,
|
| 317 |
+
"JiT-L/16": JiT_L_16,
|
| 318 |
+
"JiT-L/32": JiT_L_32,
|
| 319 |
+
"JiT-H/16": JiT_H_16,
|
| 320 |
+
"JiT-H/32": JiT_H_32,
|
| 321 |
+
}
|
jit_diffusers/modeling_jit_transformer_2d.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from collections.abc import Mapping
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Any, Dict, Literal, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from diffusers import ConfigMixin, ModelMixin
|
| 10 |
+
from diffusers.configuration_utils import register_to_config
|
| 11 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 12 |
+
|
| 13 |
+
from .modeling_jit_backbone import JiT_models
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _extract_module_state_dict(
|
| 17 |
+
state_dict: Dict[str, torch.Tensor], prefixes: Tuple[str, ...] = ("transformer.", "net.")
|
| 18 |
+
) -> Dict[str, torch.Tensor]:
|
| 19 |
+
"""Extract module state by stripping the first fully-matching prefix.
|
| 20 |
+
|
| 21 |
+
Prefix precedence is left-to-right; `"transformer."` is preferred over legacy `"net."`.
|
| 22 |
+
"""
|
| 23 |
+
for prefix in prefixes:
|
| 24 |
+
if all(key.startswith(prefix) for key in state_dict.keys()):
|
| 25 |
+
return {k[len(prefix):]: v for k, v in state_dict.items()}
|
| 26 |
+
return state_dict
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _build_jit_kwargs(
|
| 30 |
+
image_size: int,
|
| 31 |
+
num_classes: int,
|
| 32 |
+
attn_dropout: float,
|
| 33 |
+
proj_dropout: float,
|
| 34 |
+
model_name: str | None = None,
|
| 35 |
+
) -> Dict[str, object]:
|
| 36 |
+
# Keep model_name for backward-compatible internal call signatures.
|
| 37 |
+
_ = model_name
|
| 38 |
+
return {
|
| 39 |
+
"input_size": image_size,
|
| 40 |
+
"in_channels": 3,
|
| 41 |
+
"num_classes": num_classes,
|
| 42 |
+
"attn_drop": attn_dropout,
|
| 43 |
+
"proj_drop": proj_dropout,
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class JiTCheckpointConfig:
|
| 49 |
+
model_name: str
|
| 50 |
+
image_size: int
|
| 51 |
+
num_classes: int
|
| 52 |
+
attn_dropout: float
|
| 53 |
+
proj_dropout: float
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _config_from_checkpoint(ckpt_args: argparse.Namespace | Mapping[str, Any]) -> JiTCheckpointConfig:
|
| 57 |
+
if isinstance(ckpt_args, argparse.Namespace):
|
| 58 |
+
args_dict = vars(ckpt_args)
|
| 59 |
+
elif isinstance(ckpt_args, Mapping):
|
| 60 |
+
args_dict = ckpt_args
|
| 61 |
+
else:
|
| 62 |
+
raise TypeError(f"Unsupported checkpoint args type: {type(ckpt_args)}")
|
| 63 |
+
|
| 64 |
+
def _get_first_available(*keys: str, default=None):
|
| 65 |
+
for key in keys:
|
| 66 |
+
if key in args_dict and args_dict[key] is not None:
|
| 67 |
+
return args_dict[key]
|
| 68 |
+
return default
|
| 69 |
+
|
| 70 |
+
model_name = _get_first_available("model", "model_name", "model_type")
|
| 71 |
+
image_size = _get_first_available("img_size", "image_size", "sample_size")
|
| 72 |
+
num_classes = _get_first_available("class_num", "num_classes", "num_class_embeds")
|
| 73 |
+
if model_name is None or image_size is None or num_classes is None:
|
| 74 |
+
raise ValueError("Checkpoint args are missing model/image_size/num_classes information.")
|
| 75 |
+
|
| 76 |
+
return JiTCheckpointConfig(
|
| 77 |
+
model_name=str(model_name),
|
| 78 |
+
image_size=int(image_size),
|
| 79 |
+
num_classes=int(num_classes),
|
| 80 |
+
attn_dropout=float(_get_first_available("attn_dropout", "attention_dropout", default=0.0)),
|
| 81 |
+
proj_dropout=float(_get_first_available("proj_dropout", "dropout", default=0.0)),
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class JiTTransformer2DModel(ModelMixin, ConfigMixin):
|
| 86 |
+
@register_to_config
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
model_type: str = "JiT-B/16",
|
| 90 |
+
sample_size: int = 256,
|
| 91 |
+
num_class_embeds: int = 1000,
|
| 92 |
+
attention_dropout: float = 0.0,
|
| 93 |
+
dropout: float = 0.0,
|
| 94 |
+
model_name: str | None = None,
|
| 95 |
+
image_size: int | None = None,
|
| 96 |
+
num_classes: int | None = None,
|
| 97 |
+
attn_dropout: float | None = None,
|
| 98 |
+
proj_dropout: float | None = None,
|
| 99 |
+
):
|
| 100 |
+
super().__init__()
|
| 101 |
+
resolved_model_type = model_type if model_name is None else model_name
|
| 102 |
+
resolved_sample_size = sample_size if image_size is None else image_size
|
| 103 |
+
resolved_num_class_embeds = num_class_embeds if num_classes is None else num_classes
|
| 104 |
+
resolved_attention_dropout = attention_dropout if attn_dropout is None else attn_dropout
|
| 105 |
+
resolved_dropout = dropout if proj_dropout is None else proj_dropout
|
| 106 |
+
|
| 107 |
+
if resolved_model_type not in JiT_models:
|
| 108 |
+
raise ValueError(f"Unknown model '{resolved_model_type}'. Available: {list(JiT_models.keys())}")
|
| 109 |
+
|
| 110 |
+
self.transformer = JiT_models[resolved_model_type](
|
| 111 |
+
**_build_jit_kwargs(
|
| 112 |
+
image_size=resolved_sample_size,
|
| 113 |
+
num_classes=resolved_num_class_embeds,
|
| 114 |
+
attn_dropout=resolved_attention_dropout,
|
| 115 |
+
proj_dropout=resolved_dropout,
|
| 116 |
+
model_name=resolved_model_type,
|
| 117 |
+
)
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
def forward(
|
| 121 |
+
self,
|
| 122 |
+
sample: torch.Tensor,
|
| 123 |
+
timestep: torch.Tensor,
|
| 124 |
+
class_labels: torch.Tensor,
|
| 125 |
+
return_dict: bool = True,
|
| 126 |
+
):
|
| 127 |
+
timestep = torch.as_tensor(timestep, device=sample.device)
|
| 128 |
+
if timestep.ndim == 0:
|
| 129 |
+
timestep = timestep.repeat(sample.shape[0])
|
| 130 |
+
else:
|
| 131 |
+
timestep = timestep.reshape(-1)
|
| 132 |
+
if timestep.shape[0] == 1 and sample.shape[0] > 1:
|
| 133 |
+
timestep = timestep.repeat(sample.shape[0])
|
| 134 |
+
|
| 135 |
+
denoised = self.transformer(sample, timestep, class_labels)
|
| 136 |
+
if not return_dict:
|
| 137 |
+
return (denoised,)
|
| 138 |
+
return Transformer2DModelOutput(sample=denoised)
|
| 139 |
+
|
| 140 |
+
@classmethod
|
| 141 |
+
def from_jit_checkpoint(
|
| 142 |
+
cls,
|
| 143 |
+
checkpoint_path: str,
|
| 144 |
+
weights: Literal["model", "ema1", "ema2"] = "ema1",
|
| 145 |
+
map_location: str = "cpu",
|
| 146 |
+
strict: bool = True,
|
| 147 |
+
) -> Tuple["JiTTransformer2DModel", Dict[str, object]]:
|
| 148 |
+
checkpoint = torch.load(checkpoint_path, map_location=map_location)
|
| 149 |
+
if "args" not in checkpoint:
|
| 150 |
+
raise ValueError("Checkpoint is missing 'args', cannot infer JiT architecture config.")
|
| 151 |
+
|
| 152 |
+
config = _config_from_checkpoint(checkpoint["args"])
|
| 153 |
+
model = cls(
|
| 154 |
+
model_type=config.model_name,
|
| 155 |
+
sample_size=config.image_size,
|
| 156 |
+
num_class_embeds=config.num_classes,
|
| 157 |
+
attention_dropout=config.attn_dropout,
|
| 158 |
+
dropout=config.proj_dropout,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
key = "model" if weights == "model" else f"model_{weights}"
|
| 162 |
+
if key not in checkpoint:
|
| 163 |
+
raise ValueError(f"Checkpoint key '{key}' not found. Available keys: {list(checkpoint.keys())}")
|
| 164 |
+
|
| 165 |
+
model_state = _extract_module_state_dict(checkpoint[key])
|
| 166 |
+
model.transformer.load_state_dict(model_state, strict=strict)
|
| 167 |
+
|
| 168 |
+
metadata = {
|
| 169 |
+
"checkpoint_path": checkpoint_path,
|
| 170 |
+
"weights": weights,
|
| 171 |
+
"epoch": checkpoint.get("epoch"),
|
| 172 |
+
"source_args": checkpoint.get("args"),
|
| 173 |
+
}
|
| 174 |
+
return model, metadata
|
| 175 |
+
|
| 176 |
+
def to_jit_checkpoint(
|
| 177 |
+
self,
|
| 178 |
+
ema_mode: Literal["none", "copy_to_both"] = "copy_to_both",
|
| 179 |
+
prefix: str = "net.",
|
| 180 |
+
) -> Dict[str, object]:
|
| 181 |
+
base_state = {f"{prefix}{k}": v.detach().cpu() for k, v in self.transformer.state_dict().items()}
|
| 182 |
+
checkpoint = {"model": base_state}
|
| 183 |
+
if ema_mode == "copy_to_both":
|
| 184 |
+
checkpoint["model_ema1"] = {k: v.clone() for k, v in base_state.items()}
|
| 185 |
+
checkpoint["model_ema2"] = {k: v.clone() for k, v in base_state.items()}
|
| 186 |
+
elif ema_mode != "none":
|
| 187 |
+
raise ValueError(f"Unsupported ema_mode='{ema_mode}'.")
|
| 188 |
+
return checkpoint
|
| 189 |
+
|
| 190 |
+
@property
|
| 191 |
+
def net(self):
|
| 192 |
+
return self.transformer
|
| 193 |
+
|
| 194 |
+
@net.setter
|
| 195 |
+
def net(self, module):
|
| 196 |
+
self.transformer = module
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# Backward-compatible alias.
|
| 200 |
+
JiTDiffusersModel = JiTTransformer2DModel
|
jit_diffusers/modeling_jit_utils.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import pi
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from einops import rearrange, repeat
|
| 6 |
+
from torch import nn
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def broadcat(tensors, dim=-1):
|
| 10 |
+
num_tensors = len(tensors)
|
| 11 |
+
shape_lens = set(list(map(lambda tensor: len(tensor.shape), tensors)))
|
| 12 |
+
assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
|
| 13 |
+
shape_len = list(shape_lens)[0]
|
| 14 |
+
dim = (dim + shape_len) if dim < 0 else dim
|
| 15 |
+
dims = list(zip(*map(lambda tensor: list(tensor.shape), tensors)))
|
| 16 |
+
expandable_dims = [(index, val) for index, val in enumerate(dims) if index != dim]
|
| 17 |
+
assert all([*map(lambda tensor: len(set(tensor[1])) <= 2, expandable_dims)]), "invalid dimensions for broadcastable concatenation"
|
| 18 |
+
max_dims = list(map(lambda tensor: (tensor[0], max(tensor[1])), expandable_dims))
|
| 19 |
+
expanded_dims = list(map(lambda tensor: (tensor[0], (tensor[1],) * num_tensors), max_dims))
|
| 20 |
+
expanded_dims.insert(dim, (dim, dims[dim]))
|
| 21 |
+
expandable_shapes = list(zip(*map(lambda tensor: tensor[1], expanded_dims)))
|
| 22 |
+
tensors = list(map(lambda tensor: tensor[0].expand(*tensor[1]), zip(tensors, expandable_shapes)))
|
| 23 |
+
return torch.cat(tensors, dim=dim)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def rotate_half(x):
|
| 27 |
+
x = rearrange(x, "... (d r) -> ... d r", r=2)
|
| 28 |
+
x1, x2 = x.unbind(dim=-1)
|
| 29 |
+
x = torch.stack((-x2, x1), dim=-1)
|
| 30 |
+
return rearrange(x, "... d r -> ... (d r)")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class VisionRotaryEmbeddingFast(nn.Module):
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
dim,
|
| 37 |
+
pt_seq_len=16,
|
| 38 |
+
ft_seq_len=None,
|
| 39 |
+
custom_freqs=None,
|
| 40 |
+
freqs_for="lang",
|
| 41 |
+
theta=10000,
|
| 42 |
+
max_freq=10,
|
| 43 |
+
num_freqs=1,
|
| 44 |
+
num_cls_token=0,
|
| 45 |
+
):
|
| 46 |
+
super().__init__()
|
| 47 |
+
if custom_freqs:
|
| 48 |
+
freqs = custom_freqs
|
| 49 |
+
elif freqs_for == "lang":
|
| 50 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
| 51 |
+
elif freqs_for == "pixel":
|
| 52 |
+
freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
|
| 53 |
+
elif freqs_for == "constant":
|
| 54 |
+
freqs = torch.ones(num_freqs).float()
|
| 55 |
+
else:
|
| 56 |
+
raise ValueError(f"unknown modality {freqs_for}")
|
| 57 |
+
|
| 58 |
+
if ft_seq_len is None:
|
| 59 |
+
ft_seq_len = pt_seq_len
|
| 60 |
+
t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
|
| 61 |
+
|
| 62 |
+
freqs = torch.einsum("..., f -> ... f", t, freqs)
|
| 63 |
+
freqs = repeat(freqs, "... n -> ... (n r)", r=2)
|
| 64 |
+
freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
|
| 65 |
+
|
| 66 |
+
if num_cls_token > 0:
|
| 67 |
+
freqs_flat = freqs.view(-1, freqs.shape[-1])
|
| 68 |
+
cos_img = freqs_flat.cos()
|
| 69 |
+
sin_img = freqs_flat.sin()
|
| 70 |
+
_, dim_freq = cos_img.shape
|
| 71 |
+
cos_pad = torch.ones(num_cls_token, dim_freq, dtype=cos_img.dtype, device=cos_img.device)
|
| 72 |
+
sin_pad = torch.zeros(num_cls_token, dim_freq, dtype=sin_img.dtype, device=sin_img.device)
|
| 73 |
+
self.register_buffer("freqs_cos", torch.cat([cos_pad, cos_img], dim=0), persistent=False)
|
| 74 |
+
self.register_buffer("freqs_sin", torch.cat([sin_pad, sin_img], dim=0), persistent=False)
|
| 75 |
+
else:
|
| 76 |
+
self.register_buffer("freqs_cos", freqs.cos().view(-1, freqs.shape[-1]), persistent=False)
|
| 77 |
+
self.register_buffer("freqs_sin", freqs.sin().view(-1, freqs.shape[-1]), persistent=False)
|
| 78 |
+
|
| 79 |
+
def forward(self, tensor):
|
| 80 |
+
freqs_cos = self.freqs_cos.to(device=tensor.device, dtype=tensor.dtype)
|
| 81 |
+
freqs_sin = self.freqs_sin.to(device=tensor.device, dtype=tensor.dtype)
|
| 82 |
+
return tensor * freqs_cos + rotate_half(tensor) * freqs_sin
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class RMSNorm(nn.Module):
|
| 86 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 89 |
+
self.variance_epsilon = eps
|
| 90 |
+
|
| 91 |
+
def forward(self, hidden_states):
|
| 92 |
+
input_dtype = hidden_states.dtype
|
| 93 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 94 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 95 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 96 |
+
return (self.weight * hidden_states).to(input_dtype)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
|
| 100 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 101 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 102 |
+
grid = np.meshgrid(grid_w, grid_h)
|
| 103 |
+
grid = np.stack(grid, axis=0)
|
| 104 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 105 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 106 |
+
if cls_token and extra_tokens > 0:
|
| 107 |
+
pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
|
| 108 |
+
return pos_embed
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 112 |
+
assert embed_dim % 2 == 0
|
| 113 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0])
|
| 114 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1])
|
| 115 |
+
emb = np.concatenate([emb_h, emb_w], axis=1)
|
| 116 |
+
return emb
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 120 |
+
assert embed_dim % 2 == 0
|
| 121 |
+
omega = np.arange(embed_dim // 2, dtype=np.float64)
|
| 122 |
+
omega /= embed_dim / 2.0
|
| 123 |
+
omega = 1.0 / 10000**omega
|
| 124 |
+
pos = pos.reshape(-1)
|
| 125 |
+
out = np.einsum("m,d->md", pos, omega)
|
| 126 |
+
emb_sin = np.sin(out)
|
| 127 |
+
emb_cos = np.cos(out)
|
| 128 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1)
|
| 129 |
+
return emb
|
jit_diffusers/pipeline_jit.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import List, Tuple
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from diffusers import DiffusionPipeline
|
| 8 |
+
from diffusers.pipelines.pipeline_utils import ImagePipelineOutput
|
| 9 |
+
from diffusers.utils import BaseOutput
|
| 10 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 11 |
+
|
| 12 |
+
from .modeling_jit_transformer_2d import JiTTransformer2DModel
|
| 13 |
+
from .scheduling_jit import JiTScheduler
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass
|
| 17 |
+
class JiTPipelineOutput(BaseOutput):
|
| 18 |
+
images: List["PIL.Image.Image"] | np.ndarray | torch.Tensor
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class JiTPipeline(DiffusionPipeline):
|
| 22 |
+
model_cpu_offload_seq = "transformer"
|
| 23 |
+
|
| 24 |
+
def __init__(self, transformer: JiTTransformer2DModel, scheduler: JiTScheduler | None = None):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.register_modules(transformer=transformer, scheduler=scheduler or JiTScheduler())
|
| 27 |
+
|
| 28 |
+
@classmethod
|
| 29 |
+
def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
|
| 30 |
+
model_kwargs = dict(kwargs)
|
| 31 |
+
transformer_subfolder = model_kwargs.pop("transformer_subfolder", None)
|
| 32 |
+
scheduler_subfolder = model_kwargs.pop("scheduler_subfolder", None)
|
| 33 |
+
scheduler_kwargs = model_kwargs.pop("scheduler_kwargs", {})
|
| 34 |
+
if transformer_subfolder is not None:
|
| 35 |
+
transformer_path = str(Path(pretrained_model_name_or_path) / transformer_subfolder)
|
| 36 |
+
else:
|
| 37 |
+
transformer_path = pretrained_model_name_or_path
|
| 38 |
+
transformer = JiTTransformer2DModel.from_pretrained(transformer_path, **model_kwargs)
|
| 39 |
+
try:
|
| 40 |
+
scheduler = JiTScheduler.from_pretrained(
|
| 41 |
+
pretrained_model_name_or_path,
|
| 42 |
+
subfolder=scheduler_subfolder,
|
| 43 |
+
**scheduler_kwargs,
|
| 44 |
+
)
|
| 45 |
+
except Exception:
|
| 46 |
+
scheduler = JiTScheduler(**scheduler_kwargs)
|
| 47 |
+
return cls(transformer=transformer, scheduler=scheduler)
|
| 48 |
+
|
| 49 |
+
@torch.no_grad()
|
| 50 |
+
def __call__(
|
| 51 |
+
self,
|
| 52 |
+
class_labels: int | List[int] | torch.Tensor,
|
| 53 |
+
num_inference_steps: int = 50,
|
| 54 |
+
guidance_scale: float = 2.9,
|
| 55 |
+
guidance_interval_min: float = 0.1,
|
| 56 |
+
guidance_interval_max: float = 1.0,
|
| 57 |
+
noise_scale: float = 2.0,
|
| 58 |
+
t_eps: float = 5e-2,
|
| 59 |
+
sampling_method: str | None = None,
|
| 60 |
+
generator: torch.Generator | List[torch.Generator] | None = None,
|
| 61 |
+
output_type: str = "pil",
|
| 62 |
+
return_dict: bool = True,
|
| 63 |
+
) -> JiTPipelineOutput | ImagePipelineOutput | Tuple:
|
| 64 |
+
if output_type not in {"pil", "np", "pt"}:
|
| 65 |
+
raise ValueError("output_type must be one of: 'pil', 'np', 'pt'.")
|
| 66 |
+
if sampling_method is not None and sampling_method not in {"heun", "euler"}:
|
| 67 |
+
raise ValueError("sampling_method must be one of: 'heun', 'euler'.")
|
| 68 |
+
if num_inference_steps < 2:
|
| 69 |
+
raise ValueError("num_inference_steps must be >= 2.")
|
| 70 |
+
if sampling_method is not None and sampling_method != self.scheduler.config.solver:
|
| 71 |
+
self.scheduler = JiTScheduler.from_config(self.scheduler.config, solver=sampling_method)
|
| 72 |
+
|
| 73 |
+
if isinstance(class_labels, int):
|
| 74 |
+
class_labels = [class_labels]
|
| 75 |
+
if isinstance(class_labels, list):
|
| 76 |
+
class_labels = torch.tensor(class_labels, device=self._execution_device, dtype=torch.long)
|
| 77 |
+
else:
|
| 78 |
+
class_labels = class_labels.to(self._execution_device, dtype=torch.long).reshape(-1)
|
| 79 |
+
|
| 80 |
+
batch_size = class_labels.shape[0]
|
| 81 |
+
latent_size = int(self.transformer.config.sample_size)
|
| 82 |
+
latent_channels = int(getattr(self.transformer.config, "in_channels", 3))
|
| 83 |
+
num_classes = int(self.transformer.config.num_class_embeds)
|
| 84 |
+
|
| 85 |
+
class_labels = class_labels.clamp(0, num_classes - 1)
|
| 86 |
+
class_null = torch.full_like(class_labels, num_classes)
|
| 87 |
+
|
| 88 |
+
latents = randn_tensor(
|
| 89 |
+
shape=(batch_size, latent_channels, latent_size, latent_size),
|
| 90 |
+
generator=generator,
|
| 91 |
+
device=self._execution_device,
|
| 92 |
+
dtype=self.transformer.dtype,
|
| 93 |
+
) * noise_scale
|
| 94 |
+
self.scheduler.set_timesteps(num_inference_steps=num_inference_steps, device=self._execution_device)
|
| 95 |
+
timesteps = self.scheduler.timesteps.to(device=self._execution_device, dtype=latents.dtype)
|
| 96 |
+
|
| 97 |
+
def forward_cfg(z_value: torch.Tensor, t: torch.Tensor | float) -> torch.Tensor:
|
| 98 |
+
t = torch.as_tensor(t, device=self._execution_device, dtype=latents.dtype)
|
| 99 |
+
x_cond = self.transformer(sample=z_value, timestep=t.flatten(), class_labels=class_labels).sample
|
| 100 |
+
v_cond = (x_cond - z_value) / (1.0 - t).clamp_min(t_eps)
|
| 101 |
+
|
| 102 |
+
x_uncond = self.transformer(sample=z_value, timestep=t.flatten(), class_labels=class_null).sample
|
| 103 |
+
v_uncond = (x_uncond - z_value) / (1.0 - t).clamp_min(t_eps)
|
| 104 |
+
|
| 105 |
+
interval_mask = (t < guidance_interval_max) & (t > guidance_interval_min)
|
| 106 |
+
scale = torch.where(
|
| 107 |
+
interval_mask,
|
| 108 |
+
torch.tensor(guidance_scale, device=self._execution_device, dtype=latents.dtype),
|
| 109 |
+
torch.tensor(1.0, device=self._execution_device, dtype=latents.dtype),
|
| 110 |
+
)
|
| 111 |
+
return v_uncond + scale * (v_cond - v_uncond)
|
| 112 |
+
|
| 113 |
+
for i in self.progress_bar(range(num_inference_steps - 1)):
|
| 114 |
+
t, t_next = timesteps[i], timesteps[i + 1]
|
| 115 |
+
model_output = forward_cfg(latents, t)
|
| 116 |
+
if self.scheduler.config.solver == "heun":
|
| 117 |
+
latents = self.scheduler.step(
|
| 118 |
+
model_output=model_output,
|
| 119 |
+
timestep=t,
|
| 120 |
+
next_timestep=t_next,
|
| 121 |
+
sample=latents,
|
| 122 |
+
model_fn=forward_cfg,
|
| 123 |
+
).prev_sample
|
| 124 |
+
else:
|
| 125 |
+
latents = self.scheduler.step(
|
| 126 |
+
model_output=model_output,
|
| 127 |
+
timestep=t,
|
| 128 |
+
next_timestep=t_next,
|
| 129 |
+
sample=latents,
|
| 130 |
+
).prev_sample
|
| 131 |
+
|
| 132 |
+
# Match the original JiT implementation: always use Euler for the final step.
|
| 133 |
+
t, t_next = timesteps[-2], timesteps[-1]
|
| 134 |
+
model_output = forward_cfg(latents, t)
|
| 135 |
+
latents = self.scheduler.euler_step(
|
| 136 |
+
model_output=model_output,
|
| 137 |
+
timestep=t,
|
| 138 |
+
next_timestep=t_next,
|
| 139 |
+
sample=latents,
|
| 140 |
+
).prev_sample
|
| 141 |
+
|
| 142 |
+
images_pt = ((latents.float().clamp(-1, 1) + 1.0) / 2.0).cpu()
|
| 143 |
+
if output_type == "pt":
|
| 144 |
+
images = images_pt
|
| 145 |
+
else:
|
| 146 |
+
images_np = images_pt.permute(0, 2, 3, 1).numpy()
|
| 147 |
+
if output_type == "np":
|
| 148 |
+
images = images_np
|
| 149 |
+
else:
|
| 150 |
+
images = self.numpy_to_pil(images_np)
|
| 151 |
+
|
| 152 |
+
self.maybe_free_model_hooks()
|
| 153 |
+
|
| 154 |
+
if not return_dict:
|
| 155 |
+
return (images,)
|
| 156 |
+
return JiTPipelineOutput(images=images)
|
jit_diffusers/scheduling_jit.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Callable
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 7 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin, SchedulerOutput
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class JiTScheduler(SchedulerMixin, ConfigMixin):
|
| 11 |
+
order = 1
|
| 12 |
+
|
| 13 |
+
@register_to_config
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
solver: str = "heun",
|
| 17 |
+
timestep_start: float = 0.0,
|
| 18 |
+
timestep_end: float = 1.0,
|
| 19 |
+
):
|
| 20 |
+
if solver not in {"heun", "euler"}:
|
| 21 |
+
raise ValueError("solver must be one of: 'heun', 'euler'.")
|
| 22 |
+
if timestep_end <= timestep_start:
|
| 23 |
+
raise ValueError("timestep_end must be greater than timestep_start.")
|
| 24 |
+
self.timesteps = torch.tensor([])
|
| 25 |
+
|
| 26 |
+
def set_timesteps(self, num_inference_steps: int, device: str | torch.device | None = None):
|
| 27 |
+
if num_inference_steps < 2:
|
| 28 |
+
raise ValueError("num_inference_steps must be >= 2.")
|
| 29 |
+
self.timesteps = torch.linspace(
|
| 30 |
+
self.config.timestep_start,
|
| 31 |
+
self.config.timestep_end,
|
| 32 |
+
num_inference_steps + 1,
|
| 33 |
+
device=device,
|
| 34 |
+
dtype=torch.float32,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
def euler_step(
|
| 38 |
+
self,
|
| 39 |
+
model_output: torch.Tensor,
|
| 40 |
+
timestep: torch.Tensor,
|
| 41 |
+
next_timestep: torch.Tensor,
|
| 42 |
+
sample: torch.Tensor,
|
| 43 |
+
return_dict: bool = True,
|
| 44 |
+
) -> SchedulerOutput | tuple[torch.Tensor]:
|
| 45 |
+
prev_sample = sample + (next_timestep - timestep) * model_output
|
| 46 |
+
if not return_dict:
|
| 47 |
+
return (prev_sample,)
|
| 48 |
+
return SchedulerOutput(prev_sample=prev_sample)
|
| 49 |
+
|
| 50 |
+
def step(
|
| 51 |
+
self,
|
| 52 |
+
model_output: torch.Tensor,
|
| 53 |
+
timestep: torch.Tensor,
|
| 54 |
+
next_timestep: torch.Tensor,
|
| 55 |
+
sample: torch.Tensor,
|
| 56 |
+
model_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
|
| 57 |
+
return_dict: bool = True,
|
| 58 |
+
) -> SchedulerOutput | tuple[torch.Tensor]:
|
| 59 |
+
if self.config.solver == "euler":
|
| 60 |
+
return self.euler_step(model_output, timestep, next_timestep, sample, return_dict=return_dict)
|
| 61 |
+
|
| 62 |
+
if model_fn is None:
|
| 63 |
+
raise ValueError("model_fn is required when solver='heun'.")
|
| 64 |
+
|
| 65 |
+
sample_euler = sample + (next_timestep - timestep) * model_output
|
| 66 |
+
model_output_next = model_fn(sample_euler, next_timestep)
|
| 67 |
+
prev_sample = sample + (next_timestep - timestep) * 0.5 * (model_output + model_output_next)
|
| 68 |
+
|
| 69 |
+
if not return_dict:
|
| 70 |
+
return (prev_sample,)
|
| 71 |
+
return SchedulerOutput(prev_sample=prev_sample)
|
run_jit_diffusers_inference.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
SCRIPT_DIR = Path(__file__).resolve().parent
|
| 8 |
+
if str(SCRIPT_DIR) not in sys.path:
|
| 9 |
+
sys.path.insert(0, str(SCRIPT_DIR))
|
| 10 |
+
|
| 11 |
+
from jit_diffusers import JiTPipeline
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args() -> argparse.Namespace:
|
| 15 |
+
parser = argparse.ArgumentParser(description="Run single-image JiT diffusers inference.")
|
| 16 |
+
parser.add_argument("--model_path", type=str, required=True, help="Path to converted diffusers model directory.")
|
| 17 |
+
parser.add_argument("--output_path", type=str, required=True, help="Path to save output PNG image.")
|
| 18 |
+
parser.add_argument("--class_label", type=int, default=207, help="ImageNet class id for conditional generation.")
|
| 19 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed.")
|
| 20 |
+
parser.add_argument("--steps", type=int, default=50, help="Number of ODE sampling steps.")
|
| 21 |
+
parser.add_argument("--cfg", type=float, default=2.9, help="Classifier-free guidance scale.")
|
| 22 |
+
parser.add_argument("--interval_min", type=float, default=0.1, help="CFG interval min.")
|
| 23 |
+
parser.add_argument("--interval_max", type=float, default=1.0, help="CFG interval max.")
|
| 24 |
+
parser.add_argument("--noise_scale", type=float, default=2.0, help="Initial Gaussian noise scale.")
|
| 25 |
+
parser.add_argument("--t_eps", type=float, default=5e-2, help="Small epsilon for timestep denominator.")
|
| 26 |
+
parser.add_argument(
|
| 27 |
+
"--device",
|
| 28 |
+
type=str,
|
| 29 |
+
default="auto",
|
| 30 |
+
choices=["auto", "cuda", "cpu"],
|
| 31 |
+
help="Inference device.",
|
| 32 |
+
)
|
| 33 |
+
parser.add_argument(
|
| 34 |
+
"--dtype",
|
| 35 |
+
type=str,
|
| 36 |
+
default="bf16",
|
| 37 |
+
choices=["bf16", "fp32"],
|
| 38 |
+
help="Inference dtype. Defaults to bf16 on CUDA.",
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument(
|
| 41 |
+
"--solver",
|
| 42 |
+
type=str,
|
| 43 |
+
default="scheduler",
|
| 44 |
+
choices=["scheduler", "heun", "euler"],
|
| 45 |
+
help="Sampling solver. Use scheduler to keep pipeline default.",
|
| 46 |
+
)
|
| 47 |
+
return parser.parse_args()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def resolve_device(name: str) -> torch.device:
|
| 51 |
+
if name == "auto":
|
| 52 |
+
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 53 |
+
return torch.device(name)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def resolve_dtype(name: str, device: torch.device) -> torch.dtype:
|
| 57 |
+
if name == "bf16":
|
| 58 |
+
return torch.bfloat16 if device.type == "cuda" else torch.float32
|
| 59 |
+
return torch.float32
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def main() -> None:
|
| 63 |
+
args = parse_args()
|
| 64 |
+
device = resolve_device(args.device)
|
| 65 |
+
dtype = resolve_dtype(args.dtype, device)
|
| 66 |
+
if device.type == "cuda":
|
| 67 |
+
torch.set_float32_matmul_precision("high")
|
| 68 |
+
|
| 69 |
+
pipe = JiTPipeline.from_pretrained(args.model_path).to(device)
|
| 70 |
+
pipe.transformer = pipe.transformer.to(device=device, dtype=dtype)
|
| 71 |
+
pipe.transformer.eval()
|
| 72 |
+
sampling_method = None if args.solver == "scheduler" else args.solver
|
| 73 |
+
|
| 74 |
+
generator = torch.Generator(device=device).manual_seed(args.seed)
|
| 75 |
+
output = pipe(
|
| 76 |
+
class_labels=[args.class_label],
|
| 77 |
+
num_inference_steps=args.steps,
|
| 78 |
+
guidance_scale=args.cfg,
|
| 79 |
+
guidance_interval_min=args.interval_min,
|
| 80 |
+
guidance_interval_max=args.interval_max,
|
| 81 |
+
noise_scale=args.noise_scale,
|
| 82 |
+
t_eps=args.t_eps,
|
| 83 |
+
sampling_method=sampling_method,
|
| 84 |
+
generator=generator,
|
| 85 |
+
output_type="pil",
|
| 86 |
+
)
|
| 87 |
+
image = output.images[0]
|
| 88 |
+
|
| 89 |
+
output_path = Path(args.output_path)
|
| 90 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 91 |
+
image.save(output_path)
|
| 92 |
+
print(f"Saved image to: {output_path}")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
if __name__ == "__main__":
|
| 96 |
+
main()
|