diff --git a/Helios/checkpoints/Helios-Base/transformer/diffusion_pytorch_model.safetensors.index.json b/Helios/checkpoints/Helios-Base/transformer/diffusion_pytorch_model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..4f2c224baaf020b84a93f1631271d778373791b0 --- /dev/null +++ b/Helios/checkpoints/Helios-Base/transformer/diffusion_pytorch_model.safetensors.index.json @@ -0,0 +1,1108 @@ +{ + "metadata": { + "total_size": 57249710336 + }, + "weight_map": { + "blocks.0.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.10.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.14.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.2.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.20.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.21.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.28.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.3.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.30.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.35.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.4.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.7.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "proj_out.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "proj_out.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "norm_out.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors" + } +} \ No newline at end of file diff --git a/Helios/checkpoints/Helios-Base/transformer_init/config.json b/Helios/checkpoints/Helios-Base/transformer_init/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5b75c593f158ec44325422ef1f258a5649633546 --- /dev/null +++ b/Helios/checkpoints/Helios-Base/transformer_init/config.json @@ -0,0 +1,32 @@ +{ + "_class_name": "HeliosTransformer3DModel", + "_diffusers_version": "0.37.0.dev0", + "added_kv_proj_dim": null, + "attention_head_dim": 128, + "cross_attn_norm": true, + "eps": 1e-06, + "ffn_dim": 13824, + "freq_dim": 256, + "has_multi_term_memory_patch": true, + "history_scale_mode": "per_head", + "in_channels": 16, + "is_amplify_history": false, + "num_attention_heads": 40, + "num_layers": 40, + "out_channels": 16, + "patch_size": [ + 1, + 2, + 2 + ], + "qk_norm": "rms_norm_across_heads", + "rope_dim": [ + 44, + 42, + 42 + ], + "rope_theta": 10000.0, + "guidance_cross_attn": true, + "text_dim": 4096, + "zero_history_timestep": true +} diff --git a/Helios/checkpoints/Helios-Base/transformer_init/diffusion_pytorch_model.safetensors.index.json b/Helios/checkpoints/Helios-Base/transformer_init/diffusion_pytorch_model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..4f2c224baaf020b84a93f1631271d778373791b0 --- /dev/null +++ b/Helios/checkpoints/Helios-Base/transformer_init/diffusion_pytorch_model.safetensors.index.json @@ -0,0 +1,1108 @@ +{ + "metadata": { + "total_size": 57249710336 + }, + "weight_map": { + "blocks.0.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.10.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.14.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.2.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.20.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.21.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.28.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.3.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.30.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.35.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.4.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.7.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "proj_out.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "proj_out.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "norm_out.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors" + } +} \ No newline at end of file diff --git a/Helios/checkpoints/Helios-Base/vae/config.json b/Helios/checkpoints/Helios-Base/vae/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8db4fa5e82e5ce2fc9b2a1ae9b8dadeb61f027ab --- /dev/null +++ b/Helios/checkpoints/Helios-Base/vae/config.json @@ -0,0 +1,56 @@ +{ + "_class_name": "AutoencoderKLWan", + "_diffusers_version": "0.37.0.dev0", + "attn_scales": [], + "base_dim": 96, + "dim_mult": [ + 1, + 2, + 4, + 4 + ], + "dropout": 0.0, + "latents_mean": [ + -0.7571, + -0.7089, + -0.9113, + 0.1075, + -0.1745, + 0.9653, + -0.1517, + 1.5508, + 0.4134, + -0.0715, + 0.5517, + -0.3632, + -0.1922, + -0.9497, + 0.2503, + -0.2921 + ], + "latents_std": [ + 2.8184, + 1.4541, + 2.3275, + 2.6558, + 1.2196, + 1.7708, + 2.6052, + 2.0743, + 3.2687, + 2.1526, + 2.8652, + 1.5579, + 1.6382, + 1.1253, + 2.8251, + 1.916 + ], + "num_res_blocks": 2, + "temperal_downsample": [ + false, + true, + true + ], + "z_dim": 16 +} diff --git a/Helios/checkpoints/Helios-Distilled/guider/guider_config.json b/Helios/checkpoints/Helios-Distilled/guider/guider_config.json new file mode 100644 index 0000000000000000000000000000000000000000..426be42dd29f4d76da525584a00913a0eeef3fa1 --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/guider/guider_config.json @@ -0,0 +1,10 @@ +{ + "_class_name": "ClassifierFreeGuidance", + "_diffusers_version": "0.38.0.dev0", + "enabled": true, + "guidance_rescale": 0.0, + "guidance_scale": 1.0, + "start": 0.0, + "stop": 1.0, + "use_original_formulation": false +} diff --git a/Helios/checkpoints/Helios-Distilled/scheduler/scheduler_config.json b/Helios/checkpoints/Helios-Distilled/scheduler/scheduler_config.json new file mode 100644 index 0000000000000000000000000000000000000000..f458d3c42d236b243880948f0f0f98978df7a9a3 --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/scheduler/scheduler_config.json @@ -0,0 +1,19 @@ +{ + "_class_name": "HeliosDMDScheduler", + "_diffusers_version": "0.37.0.dev0", + "gamma": 0.3333333333333333, + "num_train_timesteps": 1000, + "prediction_type": "flow_prediction", + "scheduler_type": "dmd", + "shift": 1.0, + "stage_range": [ + 0, + 0.3333333333333333, + 0.6666666666666666, + 1 + ], + "stages": 3, + "time_shift_type": "linear", + "use_dynamic_shifting": true, + "use_flow_sigmas": true +} diff --git a/Helios/checkpoints/Helios-Distilled/text_encoder/config.json b/Helios/checkpoints/Helios-Distilled/text_encoder/config.json new file mode 100644 index 0000000000000000000000000000000000000000..6fe481f3ea36816769f28b5a146d1349071e0fcd --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/text_encoder/config.json @@ -0,0 +1,34 @@ +{ + "_name_or_path": "google/umt5-xxl", + "architectures": [ + "UMT5EncoderModel" + ], + "classifier_dropout": 0.0, + "d_ff": 10240, + "d_kv": 64, + "d_model": 4096, + "decoder_start_token_id": 0, + "dense_act_fn": "gelu_new", + "dropout_rate": 0.1, + "eos_token_id": 1, + "feed_forward_proj": "gated-gelu", + "initializer_factor": 1.0, + "is_encoder_decoder": true, + "is_gated_act": true, + "layer_norm_epsilon": 1e-06, + "model_type": "umt5", + "num_decoder_layers": 24, + "num_heads": 64, + "num_layers": 24, + "output_past": true, + "pad_token_id": 0, + "relative_attention_max_distance": 128, + "relative_attention_num_buckets": 32, + "scalable_attention": true, + "tie_word_embeddings": true, + "tokenizer_class": "T5Tokenizer", + "torch_dtype": "float32", + "transformers_version": "4.48.0.dev0", + "use_cache": true, + "vocab_size": 256384 +} diff --git a/Helios/checkpoints/Helios-Distilled/text_encoder/model.safetensors.index.json b/Helios/checkpoints/Helios-Distilled/text_encoder/model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..60ece61b46ecb3e6a5b705ea304bc97535317c2a --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/text_encoder/model.safetensors.index.json @@ -0,0 +1,249 @@ +{ + "metadata": { + "total_size": 22723641344 + }, + "weight_map": { + "encoder.block.0.layer.0.SelfAttention.k.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.SelfAttention.o.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.SelfAttention.q.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.SelfAttention.v.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.layer_norm.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.1.DenseReluDense.wo.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.1.layer_norm.weight": "model-00001-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.13.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.o.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.relative_attention_bias.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.20.layer.0.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.1.DenseReluDense.wi_0.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.1.DenseReluDense.wi_1.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.1.DenseReluDense.wo.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.1.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.k.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.o.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.q.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.relative_attention_bias.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.v.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.1.DenseReluDense.wi_0.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.1.DenseReluDense.wi_1.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.1.DenseReluDense.wo.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.1.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.k.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.o.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.q.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.relative_attention_bias.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.v.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.1.DenseReluDense.wi_0.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.1.DenseReluDense.wi_1.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.1.DenseReluDense.wo.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.1.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.k.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.o.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.q.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.relative_attention_bias.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.v.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.1.DenseReluDense.wi_0.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.1.DenseReluDense.wi_1.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.1.DenseReluDense.wo.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.1.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.7.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.7.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.7.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.final_layer_norm.weight": "model-00005-of-00005.safetensors", + "shared.weight": "model-00001-of-00005.safetensors" + } +} diff --git a/Helios/checkpoints/Helios-Distilled/tokenizer/special_tokens_map.json b/Helios/checkpoints/Helios-Distilled/tokenizer/special_tokens_map.json new file mode 100644 index 0000000000000000000000000000000000000000..2ed25bf989a28d20b5d4b5822fbc24666d12a6f7 --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/tokenizer/special_tokens_map.json @@ -0,0 +1,332 @@ +{ + "additional_special_tokens": [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" + ], + "bos_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + }, + "eos_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + }, + "pad_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + }, + "unk_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + } +} diff --git a/Helios/checkpoints/Helios-Distilled/tokenizer/tokenizer_config.json b/Helios/checkpoints/Helios-Distilled/tokenizer/tokenizer_config.json new file mode 100644 index 0000000000000000000000000000000000000000..09d434f9457238f697f4c208aab47f58caa15bfe --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/tokenizer/tokenizer_config.json @@ -0,0 +1,2749 @@ +{ + "added_tokens_decoder": { + "0": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "1": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "2": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "3": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256000": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256001": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256002": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256003": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256004": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256005": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256006": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256007": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256008": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256009": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256010": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256011": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256012": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256013": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256014": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256015": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256016": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256017": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256018": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256019": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256020": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256021": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256022": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256023": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256024": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256025": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256026": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256027": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256028": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256029": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256030": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256031": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256032": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256033": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256034": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256035": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256036": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256037": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256038": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256039": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256040": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256041": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256042": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256043": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256044": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256045": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256046": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256047": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256048": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256049": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256050": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256051": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256052": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256053": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256054": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256055": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256056": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256057": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256058": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256059": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256060": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256061": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256062": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256063": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256064": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256065": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256066": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256067": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256068": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256069": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256070": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256071": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256072": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256073": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256074": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256075": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256076": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256077": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256078": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256079": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256080": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256081": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256082": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256083": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256084": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256085": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256086": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256087": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256088": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256089": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256090": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256091": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256092": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256093": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256094": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256095": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256096": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256097": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256098": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256099": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256100": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256101": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256102": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256103": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256104": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256105": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256106": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256107": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256108": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256109": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256110": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256111": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256112": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256113": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256114": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256115": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256116": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256117": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256118": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256119": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256120": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256121": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256122": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256123": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256124": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256125": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256126": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256127": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256128": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256129": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256130": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256131": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256132": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256133": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256134": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256135": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256136": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256137": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256138": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256139": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256140": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256141": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256142": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256143": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256144": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256145": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256146": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256147": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256148": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256149": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256150": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256151": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256152": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256153": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256154": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256155": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256156": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256157": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256158": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256159": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256160": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256161": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256162": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256163": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256164": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256165": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256166": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256167": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256168": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256169": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256170": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256171": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256172": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256173": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256174": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256175": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256176": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256177": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256178": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256179": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256180": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256181": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256182": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256183": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256184": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256185": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256186": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256187": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256188": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256189": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256190": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256191": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256192": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256193": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256194": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256195": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256196": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256197": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256198": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256199": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256200": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256201": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256202": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256203": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256204": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256205": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256206": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256207": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256208": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256209": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256210": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256211": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256212": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256213": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256214": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256215": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256216": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256217": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256218": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256219": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256220": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256221": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256222": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256223": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256224": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256225": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256226": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256227": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256228": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256229": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256230": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256231": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256232": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256233": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256234": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256235": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256236": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256237": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256238": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256239": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256240": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256241": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256242": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256243": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256244": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256245": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256246": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256247": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256248": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256249": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256250": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256251": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256252": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256253": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256254": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256255": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256256": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256257": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256258": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256259": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256260": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256261": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256262": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256263": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256264": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256265": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256266": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256267": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256268": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256269": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256270": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256271": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256272": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256273": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256274": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256275": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256276": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256277": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256278": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256279": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256280": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256281": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256282": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256283": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256284": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256285": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256286": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256287": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256288": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256289": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256290": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256291": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256292": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256293": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256294": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256295": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256296": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256297": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256298": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256299": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + } + }, + "additional_special_tokens": [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" + ], + "bos_token": "", + "clean_up_tokenization_spaces": true, + "eos_token": "", + "extra_ids": 300, + "extra_special_tokens": {}, + "model_max_length": 1000000000000000019884624838656, + "pad_token": "", + "sp_model_kwargs": {}, + "spaces_between_special_tokens": false, + "tokenizer_class": "T5Tokenizer", + "unk_token": "" +} diff --git a/Helios/checkpoints/Helios-Distilled/transformer/config.json b/Helios/checkpoints/Helios-Distilled/transformer/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5b75c593f158ec44325422ef1f258a5649633546 --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/transformer/config.json @@ -0,0 +1,32 @@ +{ + "_class_name": "HeliosTransformer3DModel", + "_diffusers_version": "0.37.0.dev0", + "added_kv_proj_dim": null, + "attention_head_dim": 128, + "cross_attn_norm": true, + "eps": 1e-06, + "ffn_dim": 13824, + "freq_dim": 256, + "has_multi_term_memory_patch": true, + "history_scale_mode": "per_head", + "in_channels": 16, + "is_amplify_history": false, + "num_attention_heads": 40, + "num_layers": 40, + "out_channels": 16, + "patch_size": [ + 1, + 2, + 2 + ], + "qk_norm": "rms_norm_across_heads", + "rope_dim": [ + 44, + 42, + 42 + ], + "rope_theta": 10000.0, + "guidance_cross_attn": true, + "text_dim": 4096, + "zero_history_timestep": true +} diff --git a/Helios/checkpoints/Helios-Distilled/transformer/diffusion_pytorch_model.safetensors.index.json b/Helios/checkpoints/Helios-Distilled/transformer/diffusion_pytorch_model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..4f2c224baaf020b84a93f1631271d778373791b0 --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/transformer/diffusion_pytorch_model.safetensors.index.json @@ -0,0 +1,1108 @@ +{ + "metadata": { + "total_size": 57249710336 + }, + "weight_map": { + "blocks.0.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.10.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.14.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.2.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.20.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.21.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.28.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.3.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.30.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.35.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.4.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.7.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "proj_out.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "proj_out.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "norm_out.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors" + } +} \ No newline at end of file diff --git a/Helios/checkpoints/Helios-Distilled/transformer_ode/config.json b/Helios/checkpoints/Helios-Distilled/transformer_ode/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5b75c593f158ec44325422ef1f258a5649633546 --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/transformer_ode/config.json @@ -0,0 +1,32 @@ +{ + "_class_name": "HeliosTransformer3DModel", + "_diffusers_version": "0.37.0.dev0", + "added_kv_proj_dim": null, + "attention_head_dim": 128, + "cross_attn_norm": true, + "eps": 1e-06, + "ffn_dim": 13824, + "freq_dim": 256, + "has_multi_term_memory_patch": true, + "history_scale_mode": "per_head", + "in_channels": 16, + "is_amplify_history": false, + "num_attention_heads": 40, + "num_layers": 40, + "out_channels": 16, + "patch_size": [ + 1, + 2, + 2 + ], + "qk_norm": "rms_norm_across_heads", + "rope_dim": [ + 44, + 42, + 42 + ], + "rope_theta": 10000.0, + "guidance_cross_attn": true, + "text_dim": 4096, + "zero_history_timestep": true +} diff --git a/Helios/checkpoints/Helios-Distilled/transformer_ode/diffusion_pytorch_model.safetensors.index.json b/Helios/checkpoints/Helios-Distilled/transformer_ode/diffusion_pytorch_model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..4f2c224baaf020b84a93f1631271d778373791b0 --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/transformer_ode/diffusion_pytorch_model.safetensors.index.json @@ -0,0 +1,1108 @@ +{ + "metadata": { + "total_size": 57249710336 + }, + "weight_map": { + "blocks.0.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.10.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.14.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.2.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.20.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.21.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.28.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.3.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.30.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.35.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.4.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.7.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "proj_out.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "proj_out.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "norm_out.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors" + } +} \ No newline at end of file diff --git a/Helios/checkpoints/Helios-Distilled/vae/config.json b/Helios/checkpoints/Helios-Distilled/vae/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8db4fa5e82e5ce2fc9b2a1ae9b8dadeb61f027ab --- /dev/null +++ b/Helios/checkpoints/Helios-Distilled/vae/config.json @@ -0,0 +1,56 @@ +{ + "_class_name": "AutoencoderKLWan", + "_diffusers_version": "0.37.0.dev0", + "attn_scales": [], + "base_dim": 96, + "dim_mult": [ + 1, + 2, + 4, + 4 + ], + "dropout": 0.0, + "latents_mean": [ + -0.7571, + -0.7089, + -0.9113, + 0.1075, + -0.1745, + 0.9653, + -0.1517, + 1.5508, + 0.4134, + -0.0715, + 0.5517, + -0.3632, + -0.1922, + -0.9497, + 0.2503, + -0.2921 + ], + "latents_std": [ + 2.8184, + 1.4541, + 2.3275, + 2.6558, + 1.2196, + 1.7708, + 2.6052, + 2.0743, + 3.2687, + 2.1526, + 2.8652, + 1.5579, + 1.6382, + 1.1253, + 2.8251, + 1.916 + ], + "num_res_blocks": 2, + "temperal_downsample": [ + false, + true, + true + ], + "z_dim": 16 +} diff --git a/Helios/checkpoints/Helios-Mid/guider/guider_config.json b/Helios/checkpoints/Helios-Mid/guider/guider_config.json new file mode 100644 index 0000000000000000000000000000000000000000..81ce7b9d80de934984906b8f7f7728a7229d8ff9 --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/guider/guider_config.json @@ -0,0 +1,11 @@ +{ + "_class_name": "ClassifierFreeZeroStarGuidance", + "_diffusers_version": "0.38.0.dev0", + "enabled": true, + "guidance_rescale": 0.0, + "guidance_scale": 5.0, + "start": 0.0, + "stop": 1.0, + "use_original_formulation": false, + "zero_init_steps": 2 +} diff --git a/Helios/checkpoints/Helios-Mid/scheduler/scheduler_config.json b/Helios/checkpoints/Helios-Mid/scheduler/scheduler_config.json new file mode 100644 index 0000000000000000000000000000000000000000..4988814fe7adc03d38ebde78279eae4395270d78 --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/scheduler/scheduler_config.json @@ -0,0 +1,26 @@ +{ + "_class_name": "HeliosScheduler", + "_diffusers_version": "0.37.0.dev0", + "disable_corrector": [], + "gamma": 0.3333333333333333, + "lower_order_final": true, + "num_train_timesteps": 1000, + "predict_x0": true, + "prediction_type": "flow_prediction", + "scheduler_type": "unipc", + "shift": 1.0, + "solver_order": 2, + "solver_p": null, + "solver_type": "bh2", + "stage_range": [ + 0, + 0.3333333333333333, + 0.6666666666666666, + 1 + ], + "stages": 3, + "time_shift_type": "exponential", + "thresholding": false, + "use_dynamic_shifting": true, + "use_flow_sigmas": true +} diff --git a/Helios/checkpoints/Helios-Mid/text_encoder/config.json b/Helios/checkpoints/Helios-Mid/text_encoder/config.json new file mode 100644 index 0000000000000000000000000000000000000000..6fe481f3ea36816769f28b5a146d1349071e0fcd --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/text_encoder/config.json @@ -0,0 +1,34 @@ +{ + "_name_or_path": "google/umt5-xxl", + "architectures": [ + "UMT5EncoderModel" + ], + "classifier_dropout": 0.0, + "d_ff": 10240, + "d_kv": 64, + "d_model": 4096, + "decoder_start_token_id": 0, + "dense_act_fn": "gelu_new", + "dropout_rate": 0.1, + "eos_token_id": 1, + "feed_forward_proj": "gated-gelu", + "initializer_factor": 1.0, + "is_encoder_decoder": true, + "is_gated_act": true, + "layer_norm_epsilon": 1e-06, + "model_type": "umt5", + "num_decoder_layers": 24, + "num_heads": 64, + "num_layers": 24, + "output_past": true, + "pad_token_id": 0, + "relative_attention_max_distance": 128, + "relative_attention_num_buckets": 32, + "scalable_attention": true, + "tie_word_embeddings": true, + "tokenizer_class": "T5Tokenizer", + "torch_dtype": "float32", + "transformers_version": "4.48.0.dev0", + "use_cache": true, + "vocab_size": 256384 +} diff --git a/Helios/checkpoints/Helios-Mid/text_encoder/model.safetensors.index.json b/Helios/checkpoints/Helios-Mid/text_encoder/model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..60ece61b46ecb3e6a5b705ea304bc97535317c2a --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/text_encoder/model.safetensors.index.json @@ -0,0 +1,249 @@ +{ + "metadata": { + "total_size": 22723641344 + }, + "weight_map": { + "encoder.block.0.layer.0.SelfAttention.k.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.SelfAttention.o.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.SelfAttention.q.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.SelfAttention.v.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.0.layer_norm.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.1.DenseReluDense.wo.weight": "model-00001-of-00005.safetensors", + "encoder.block.0.layer.1.layer_norm.weight": "model-00001-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.1.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.10.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.11.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.12.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.13.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.13.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.14.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.15.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.16.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.17.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.18.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.o.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.relative_attention_bias.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.0.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.1.DenseReluDense.wi_0.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.1.DenseReluDense.wi_1.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.1.DenseReluDense.wo.weight": "model-00004-of-00005.safetensors", + "encoder.block.19.layer.1.layer_norm.weight": "model-00004-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.2.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.k.weight": "model-00004-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.o.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.q.weight": "model-00004-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.relative_attention_bias.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.0.SelfAttention.v.weight": "model-00004-of-00005.safetensors", + "encoder.block.20.layer.0.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.1.DenseReluDense.wi_0.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.1.DenseReluDense.wi_1.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.1.DenseReluDense.wo.weight": "model-00005-of-00005.safetensors", + "encoder.block.20.layer.1.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.k.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.o.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.q.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.relative_attention_bias.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.SelfAttention.v.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.0.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.1.DenseReluDense.wi_0.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.1.DenseReluDense.wi_1.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.1.DenseReluDense.wo.weight": "model-00005-of-00005.safetensors", + "encoder.block.21.layer.1.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.k.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.o.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.q.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.relative_attention_bias.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.SelfAttention.v.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.0.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.1.DenseReluDense.wi_0.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.1.DenseReluDense.wi_1.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.1.DenseReluDense.wo.weight": "model-00005-of-00005.safetensors", + "encoder.block.22.layer.1.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.k.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.o.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.q.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.relative_attention_bias.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.SelfAttention.v.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.0.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.1.DenseReluDense.wi_0.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.1.DenseReluDense.wi_1.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.1.DenseReluDense.wo.weight": "model-00005-of-00005.safetensors", + "encoder.block.23.layer.1.layer_norm.weight": "model-00005-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.3.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.4.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.5.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.1.DenseReluDense.wo.weight": "model-00002-of-00005.safetensors", + "encoder.block.6.layer.1.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.k.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.o.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.q.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.relative_attention_bias.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.SelfAttention.v.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.0.layer_norm.weight": "model-00002-of-00005.safetensors", + "encoder.block.7.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.7.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.7.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.7.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.8.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.k.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.o.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.q.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.relative_attention_bias.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.SelfAttention.v.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.0.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.1.DenseReluDense.wi_0.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.1.DenseReluDense.wi_1.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.1.DenseReluDense.wo.weight": "model-00003-of-00005.safetensors", + "encoder.block.9.layer.1.layer_norm.weight": "model-00003-of-00005.safetensors", + "encoder.final_layer_norm.weight": "model-00005-of-00005.safetensors", + "shared.weight": "model-00001-of-00005.safetensors" + } +} diff --git a/Helios/checkpoints/Helios-Mid/tokenizer/special_tokens_map.json b/Helios/checkpoints/Helios-Mid/tokenizer/special_tokens_map.json new file mode 100644 index 0000000000000000000000000000000000000000..2ed25bf989a28d20b5d4b5822fbc24666d12a6f7 --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/tokenizer/special_tokens_map.json @@ -0,0 +1,332 @@ +{ + "additional_special_tokens": [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" + ], + "bos_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + }, + "eos_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + }, + "pad_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + }, + "unk_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + } +} diff --git a/Helios/checkpoints/Helios-Mid/tokenizer/tokenizer_config.json b/Helios/checkpoints/Helios-Mid/tokenizer/tokenizer_config.json new file mode 100644 index 0000000000000000000000000000000000000000..09d434f9457238f697f4c208aab47f58caa15bfe --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/tokenizer/tokenizer_config.json @@ -0,0 +1,2749 @@ +{ + "added_tokens_decoder": { + "0": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "1": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "2": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "3": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256000": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256001": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256002": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256003": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256004": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256005": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256006": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256007": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256008": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256009": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256010": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256011": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256012": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256013": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256014": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256015": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256016": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256017": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256018": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256019": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256020": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256021": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256022": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256023": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256024": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256025": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256026": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256027": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256028": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256029": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256030": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256031": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256032": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256033": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256034": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256035": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256036": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256037": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256038": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256039": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256040": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256041": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256042": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256043": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256044": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256045": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256046": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256047": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256048": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256049": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256050": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256051": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256052": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256053": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256054": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256055": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256056": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256057": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256058": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256059": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256060": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256061": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256062": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256063": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256064": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256065": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256066": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256067": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256068": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256069": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256070": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256071": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256072": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256073": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256074": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256075": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256076": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256077": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256078": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256079": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256080": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256081": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256082": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256083": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256084": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256085": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256086": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256087": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256088": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256089": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256090": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256091": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256092": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256093": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256094": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256095": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256096": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256097": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256098": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256099": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256100": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256101": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256102": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256103": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256104": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256105": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256106": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256107": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256108": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256109": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256110": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256111": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256112": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256113": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256114": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256115": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256116": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256117": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256118": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256119": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256120": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256121": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256122": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256123": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256124": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256125": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256126": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256127": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256128": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256129": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256130": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256131": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256132": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256133": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256134": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256135": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256136": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256137": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256138": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256139": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256140": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256141": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256142": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256143": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256144": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256145": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256146": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256147": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256148": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256149": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256150": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256151": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256152": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256153": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256154": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256155": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256156": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256157": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256158": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256159": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256160": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256161": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256162": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256163": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256164": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256165": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256166": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256167": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256168": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256169": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256170": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256171": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256172": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256173": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256174": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256175": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256176": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256177": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256178": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256179": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256180": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256181": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256182": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256183": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256184": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256185": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256186": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256187": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256188": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256189": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256190": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256191": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256192": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256193": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256194": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256195": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256196": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256197": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256198": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256199": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256200": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256201": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256202": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256203": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256204": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256205": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256206": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256207": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256208": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256209": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256210": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256211": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256212": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256213": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256214": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256215": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256216": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256217": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256218": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256219": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256220": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256221": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256222": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256223": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256224": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256225": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256226": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256227": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256228": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256229": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256230": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256231": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256232": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256233": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256234": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256235": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256236": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256237": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256238": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256239": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256240": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256241": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256242": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256243": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256244": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256245": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256246": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256247": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256248": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256249": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256250": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256251": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256252": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256253": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256254": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256255": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256256": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256257": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256258": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256259": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256260": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256261": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256262": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256263": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256264": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256265": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256266": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256267": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256268": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256269": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256270": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256271": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256272": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256273": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256274": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256275": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256276": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256277": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256278": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256279": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256280": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256281": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256282": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256283": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256284": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256285": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256286": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256287": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256288": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256289": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256290": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256291": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256292": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256293": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256294": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256295": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256296": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256297": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256298": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "256299": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + } + }, + "additional_special_tokens": [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" + ], + "bos_token": "", + "clean_up_tokenization_spaces": true, + "eos_token": "", + "extra_ids": 300, + "extra_special_tokens": {}, + "model_max_length": 1000000000000000019884624838656, + "pad_token": "", + "sp_model_kwargs": {}, + "spaces_between_special_tokens": false, + "tokenizer_class": "T5Tokenizer", + "unk_token": "" +} diff --git a/Helios/checkpoints/Helios-Mid/transformer/config.json b/Helios/checkpoints/Helios-Mid/transformer/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5b75c593f158ec44325422ef1f258a5649633546 --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/transformer/config.json @@ -0,0 +1,32 @@ +{ + "_class_name": "HeliosTransformer3DModel", + "_diffusers_version": "0.37.0.dev0", + "added_kv_proj_dim": null, + "attention_head_dim": 128, + "cross_attn_norm": true, + "eps": 1e-06, + "ffn_dim": 13824, + "freq_dim": 256, + "has_multi_term_memory_patch": true, + "history_scale_mode": "per_head", + "in_channels": 16, + "is_amplify_history": false, + "num_attention_heads": 40, + "num_layers": 40, + "out_channels": 16, + "patch_size": [ + 1, + 2, + 2 + ], + "qk_norm": "rms_norm_across_heads", + "rope_dim": [ + 44, + 42, + 42 + ], + "rope_theta": 10000.0, + "guidance_cross_attn": true, + "text_dim": 4096, + "zero_history_timestep": true +} diff --git a/Helios/checkpoints/Helios-Mid/transformer/diffusion_pytorch_model.safetensors.index.json b/Helios/checkpoints/Helios-Mid/transformer/diffusion_pytorch_model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..4f2c224baaf020b84a93f1631271d778373791b0 --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/transformer/diffusion_pytorch_model.safetensors.index.json @@ -0,0 +1,1108 @@ +{ + "metadata": { + "total_size": 57249710336 + }, + "weight_map": { + "blocks.0.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.10.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.14.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.2.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.20.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.21.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.28.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.3.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.30.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.35.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.4.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.7.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "proj_out.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "proj_out.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "norm_out.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors" + } +} \ No newline at end of file diff --git a/Helios/checkpoints/Helios-Mid/transformer_init/config.json b/Helios/checkpoints/Helios-Mid/transformer_init/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5b75c593f158ec44325422ef1f258a5649633546 --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/transformer_init/config.json @@ -0,0 +1,32 @@ +{ + "_class_name": "HeliosTransformer3DModel", + "_diffusers_version": "0.37.0.dev0", + "added_kv_proj_dim": null, + "attention_head_dim": 128, + "cross_attn_norm": true, + "eps": 1e-06, + "ffn_dim": 13824, + "freq_dim": 256, + "has_multi_term_memory_patch": true, + "history_scale_mode": "per_head", + "in_channels": 16, + "is_amplify_history": false, + "num_attention_heads": 40, + "num_layers": 40, + "out_channels": 16, + "patch_size": [ + 1, + 2, + 2 + ], + "qk_norm": "rms_norm_across_heads", + "rope_dim": [ + 44, + 42, + 42 + ], + "rope_theta": 10000.0, + "guidance_cross_attn": true, + "text_dim": 4096, + "zero_history_timestep": true +} diff --git a/Helios/checkpoints/Helios-Mid/transformer_init/diffusion_pytorch_model.safetensors.index.json b/Helios/checkpoints/Helios-Mid/transformer_init/diffusion_pytorch_model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..4f2c224baaf020b84a93f1631271d778373791b0 --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/transformer_init/diffusion_pytorch_model.safetensors.index.json @@ -0,0 +1,1108 @@ +{ + "metadata": { + "total_size": 57249710336 + }, + "weight_map": { + "blocks.0.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.0.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.1.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.10.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.10.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.11.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.12.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.13.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.14.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.14.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.15.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.16.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.17.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.18.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.0.proj.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.ffn.net.2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.19.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.2.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.2.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.20.attn1.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn1.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.norm_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_k.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_out.0.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_q.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.attn2.to_v.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.20.norm2.bias": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.norm2.weight": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.20.scale_shift_table": "diffusion_pytorch_model-00003-of-00006.safetensors", + "blocks.21.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.21.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.22.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.23.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.24.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.25.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.0.proj.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.ffn.net.2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.26.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn1.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.norm_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_k.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_out.0.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_q.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.attn2.to_v.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.27.norm2.bias": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.norm2.weight": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.27.scale_shift_table": "diffusion_pytorch_model-00004-of-00006.safetensors", + "blocks.28.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.28.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.29.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.3.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.3.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.30.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.30.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.31.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.32.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.0.proj.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.ffn.net.2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.33.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn1.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.norm_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_k.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_out.0.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_q.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.attn2.to_v.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.34.norm2.bias": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.norm2.weight": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.34.scale_shift_table": "diffusion_pytorch_model-00005-of-00006.safetensors", + "blocks.35.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.35.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.36.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.37.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.38.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn1.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.norm_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_k.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_out.0.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_q.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.attn2.to_v.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.0.proj.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.ffn.net.2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.norm2.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.39.scale_shift_table": "diffusion_pytorch_model-00006-of-00006.safetensors", + "blocks.4.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.4.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.attn2.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.0.proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.ffn.net.2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.norm2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.5.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.norm_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_out.0.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn1.to_v.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_k.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_k.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_q.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_q.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.6.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.6.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors", + "blocks.7.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.7.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.8.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn1.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.norm_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_k.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_out.0.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_q.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.attn2.to_v.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.0.proj.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.ffn.net.2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.bias": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.norm2.weight": "diffusion_pytorch_model-00002-of-00006.safetensors", + "blocks.9.scale_shift_table": "diffusion_pytorch_model-00002-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.text_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_1.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_embedder.linear_2.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "condition_embedder.time_proj.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.bias": "diffusion_pytorch_model-00001-of-00006.safetensors", + "patch_embedding.weight": "diffusion_pytorch_model-00001-of-00006.safetensors", + "proj_out.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "proj_out.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_short.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_mid.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.bias": "diffusion_pytorch_model-00006-of-00006.safetensors", + "patch_long.weight": "diffusion_pytorch_model-00006-of-00006.safetensors", + "norm_out.scale_shift_table": "diffusion_pytorch_model-00001-of-00006.safetensors" + } +} \ No newline at end of file diff --git a/Helios/checkpoints/Helios-Mid/vae/config.json b/Helios/checkpoints/Helios-Mid/vae/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8db4fa5e82e5ce2fc9b2a1ae9b8dadeb61f027ab --- /dev/null +++ b/Helios/checkpoints/Helios-Mid/vae/config.json @@ -0,0 +1,56 @@ +{ + "_class_name": "AutoencoderKLWan", + "_diffusers_version": "0.37.0.dev0", + "attn_scales": [], + "base_dim": 96, + "dim_mult": [ + 1, + 2, + 4, + 4 + ], + "dropout": 0.0, + "latents_mean": [ + -0.7571, + -0.7089, + -0.9113, + 0.1075, + -0.1745, + 0.9653, + -0.1517, + 1.5508, + 0.4134, + -0.0715, + 0.5517, + -0.3632, + -0.1922, + -0.9497, + 0.2503, + -0.2921 + ], + "latents_std": [ + 2.8184, + 1.4541, + 2.3275, + 2.6558, + 1.2196, + 1.7708, + 2.6052, + 2.0743, + 3.2687, + 2.1526, + 2.8652, + 1.5579, + 1.6382, + 1.1253, + 2.8251, + 1.916 + ], + "num_res_blocks": 2, + "temperal_downsample": [ + false, + true, + true + ], + "z_dim": 16 +} diff --git a/Helios/eval/checkpoints/get_checkpoints.sh b/Helios/eval/checkpoints/get_checkpoints.sh new file mode 100644 index 0000000000000000000000000000000000000000..473c4970f5f9d1be6effd7f0dd8414eff4118604 --- /dev/null +++ b/Helios/eval/checkpoints/get_checkpoints.sh @@ -0,0 +1 @@ +hf download BestWishYsh/HeliosBench-Weights --local-dir ./ \ No newline at end of file diff --git a/Helios/eval/playground/helios_t2v_prompts.csv b/Helios/eval/playground/helios_t2v_prompts.csv new file mode 100644 index 0000000000000000000000000000000000000000..0e8a10943b3e9d06b82f5e6c567cdd80b99ed088 --- /dev/null +++ b/Helios/eval/playground/helios_t2v_prompts.csv @@ -0,0 +1,241 @@ +id,prompt,duration +1,"A stylish woman strolls down a bustling Tokyo street, the warm glow of neon lights and animated city signs casting vibrant reflections. She wears a sleek black leather jacket paired with a flowing red dress and black boots, her black purse slung over her shoulder. Sunglasses perched on her nose and a bold red lipstick add to her confident, casual demeanor. The street is damp and reflective, creating a mirror-like effect that enhances the colorful lights and shadows. Pedestrians move about, adding to the lively atmosphere. The scene is captured in a dynamic medium shot with the woman walking slightly to one side, highlighting her graceful strides.",1440 +2,"A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity.",240 +3,"A movie trailer in a classic cinematic style, featuring the adventurous journey of a 30-year-old space man wearing a vibrant red wool knitted motorcycle helmet. The scene unfolds against a vast blue sky and a desolate salt desert landscape. Shot on 35mm film, the trailer showcases vivid and rich colors, capturing the hero as he navigates through the harsh terrain with determination. His helmet glints under the sun, adding to the dramatic effect. The background is a mix of sweeping desert vistas and distant horizons, with the occasional shimmer of light reflecting off the salt flats. A dynamic medium shot with a sweeping overhead angle, emphasizing the hero's resilience and the vastness of his adventure.",1440 +4,"A drone view of waves crashing against the rugged cliffs along Big Sur’s Garay Point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore, casting long shadows. In the distance, a small island with a lighthouse stands tall, its beam piercing the twilight. Green shrubbery covers the cliff’s edge, and the steep drop from the road down to the beach is a dramatic feat, with the cliff’s edges jutting out over the sea. The camera angle provides a bird's-eye view, capturing the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway. The scene is bathed in a warm, golden hue, highlighting the textures and details of the rocky terrain.",240 +5,"A close-up 3D animated scene of a short, fluffy monster kneeling beside a melting red candle. The monster has large, wide eyes and an open mouth, gazing at the flame with a look of wonder and curiosity. Its soft, fluffy fur contrasts with the warm, dramatic lighting that highlights every detail of its gentle, innocent expression. The pose conveys a sense of playfulness and exploration, as if the creature is discovering the world for the first time. The background features a cozy, warmly lit room with subtle hints of a fireplace and soft furnishings, enhancing the overall atmosphere. The use of warm colors and dramatic lighting creates a captivating and inviting scene.",240 +6,"A beautifully detailed papercraft illustration of a vibrant coral reef teeming with colorful fish and sea creatures. The coral formations are intricately designed, with each polyp and branch meticulously crafted. Schools of tropical fish swim gracefully among the corals, their scales shimmering in hues of turquoise, orange, and purple. Sea turtles glide smoothly over the reef, while a school of clownfish dart playfully around an anemone. The background features a soft, pastel-colored ocean with gentle waves and a hint of sunlight breaking through. The entire scene is rendered with a lifelike and textured papercraft style, capturing the essence of a thriving underwater ecosystem. A close-up view from a slightly elevated angle.",720 +7,"A close-up shot of a Victoria crowned pigeon in a naturalistic wildlife photography style, showcasing its striking blue plumage and red chest. The bird’s crest is adorned with delicate, lacy feathers, and its eye is a striking red color, adding to its regal and majestic appearance. The pigeon’s head is tilted slightly to the side, giving it a regal gaze. The background is blurred, emphasizing the bird’s striking beauty against a soft, muted backdrop. The lighting highlights the bird’s feathers, creating a vibrant and lifelike image.",720 +8,"A photorealistic closeup video of two pirate ships battling each other as they sail inside a steaming cup of coffee. The ships are intricately detailed, with wooden planks, sails flapping in the breeze, and cannons aimed at each other. The crew members, wearing authentic pirate attire, brandish swords and pistols, their expressions fierce and determined. The coffee foam creates a frothy, turbulent sea, with ripples and waves realistically depicted. The background is a blurred, warm brown coffee surface, with steam rising gently. The camera angle is slightly elevated, capturing the intense action from above.",240 +9,"A vibrant anime illustration in a thick painting style featuring a young man in his 20s sitting on a fluffy white cloud in the sky, engrossed in reading a classic leather-bound book. He has short, messy black hair and expressive brown eyes, wearing a casual white t-shirt and blue jeans. His posture is relaxed yet attentive, with one leg crossed over the other. The background is a vivid sky with cotton-like clouds and a soft sunset glow, casting a warm orange hue. The scene has a dreamy and ethereal quality. A medium shot with a slightly downward angle.",1440 +10,"A historical footage style photograph depicting a bustling gold rush town in California. The scene captures miners panning for gold in a stream, their faces weathered and determined. Behind them, makeshift wooden shacks and tents line the streets, with smoke rising from chimneys. A man in a dusty hat and tattered clothes stands near a sluice box, his hand on his hip, looking out towards the camera with a mix of hope and hardship. The background features rolling hills and dense forests, with a few oxen-drawn wagons in the distance. The photo has a sepia tone and a grainy texture, capturing the essence of the era. A medium shot with a slightly tilted angle.",1440 +11,"A close-up view of a glass sphere containing a tranquil Zen garden. Inside, a small Eastern dwarf with weathered skin and a serene expression is raking the sand, meticulously creating intricate patterns with a bamboo rake. His movements are deliberate and meditative, enhancing the peaceful atmosphere of the scene. The background is blurred, revealing only hints of greenery and rocks, adding to the serene setting. The sphere itself is polished, reflecting the surroundings subtly. The camera angle captures the dwarf from a slightly elevated position, emphasizing his focused and contemplative pose.",240 +12,"A cinematic film shot in 70mm, capturing an extreme close-up of a 24-year-old woman's eye as it blinks. The scene takes place during magic hour in Marrakech, with the vibrant colors of the setting sun casting warm hues over the bustling streets. The depth of field emphasizes the intricate details of her almond-shaped eyes, which reflect the lively atmosphere of the city. Her eyes, framed by long, dark lashes, are set against a backdrop of bustling market stalls, ornate architecture, and the soft shadows of the setting sun. The background features a blend of rich textures and vibrant colors, creating a sense of depth and immersion. A medium shot with a slightly elevated perspective, highlighting the natural movement of her eye.",240 +13,"A vibrant cartoon-style illustration depicting a kangaroo performing a lively disco dance. The kangaroo has a joyful expression, with large, expressive eyes and a mischievous grin. It wears a colorful sequined outfit with sparkles, including a glittery top and matching pants. Its tail is fluffed out and swaying rhythmically. The kangaroo moves with natural fluidity, one foot lifted and the other stepping forward. The background features a blurred dance floor with colorful lights and dancing figures, creating a festive atmosphere. The illustration has a smooth, hand-drawn style with exaggerated proportions. A dynamic close-up shot from a slightly elevated angle.",1440 +14,"A beautifully crafted homemade video set in Lagos, Nigeria in the year 2056, captured with a mobile phone camera. The footage showcases diverse people going about their daily lives in a vibrant and bustling urban environment. The camera captures various individuals: a group of young Nigerian women in colorful traditional attire walking down a crowded street, a man in a smart business suit hurrying past a futuristic billboard, and a family gathered around a street vendor selling fresh fruits. The background features modern skyscrapers, traditional market stalls, and electric vehicles zipping by. The video has a warm, nostalgic feel, with occasional blurs and graininess reminiscent of mobile phone recording. A series of handheld shots and close-ups capture the dynamic energy of the city.",720 +15,"A high-resolution digital artwork in a realistic botanical style, showcasing a petri dish where a miniature bamboo forest thrives, complete with tiny red pandas running around. The bamboo stalks are slender and green, with delicate leaves swaying gently. The red pandas, with their distinctive reddish-brown fur and black legs, move playfully among the bamboo, sometimes climbing up the stalks or nibbling on leaves. The petri dish is filled with nutrient-rich soil, and the background is a blurred but recognizable forest landscape, with hints of distant mountains and clear blue skies. The entire scene exudes a sense of harmony and tranquility, capturing the wonder of nature in a microscopic world. A macro shot from a low angle, emphasizing the intricate details of the red pandas and the bamboo.",1440 +16,"A rotating camera view inside a large New York museum gallery, showcasing a towering stack of vintage televisions, each displaying different programs from the 1950s and 1970s. The televisions show a mix of 1950s sci-fi movies, horror films, news broadcasts, static, and a 1970s sitcom. The gallery space is filled with the nostalgic glow of the old TV screens, their edges worn and frames aged. The background features other vintage exhibits and artifacts, adding to the historical ambiance. The televisions are arranged in a dynamic, almost chaotic pattern, creating a sense of visual interest and movement. A wide-angle shot capturing the entire stack and the surrounding gallery space.",720 +17,"A 3D animation of a small, round, fluffy creature with big, expressive eyes exploring a vibrant, enchanted forest. The creature, a whimsical blend of a rabbit and a squirrel, has soft blue fur and a bushy, striped tail. It hops along a sparkling stream, its eyes wide with wonder. The forest is alive with magical elements: flowers that glow and change colors, trees with leaves in shades of purple and silver, and small floating lights that resemble fireflies. The creature stops to interact playfully with a group of tiny, fairy-like beings dancing around a mushroom ring. The creature looks up in awe at a large, glowing tree that seems to be the heart of the forest. The scene is rendered in a detailed, fantasy style, with a soft, ethereal lighting that enhances the enchantment. The camera follows the creature as it moves, capturing its playful interactions and the magical ambiance of the forest. A medium shot with a dynamic angle that highlights the creature's expressions and the enchanting environment.",1440 +18,"A dynamic shot from behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by towering redwood trees on a rugged mountain slope. Dust kicks up from its tires, and the sunlight shines on the SUV, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other vehicles in sight. The trees on either side are dense redwoods, with patches of greenery scattered throughout. The car navigates the curve with ease, making it seem as if it is on a thrilling drive through the rugged terrain. The dirt road is framed by steep hills and mountains, with a clear blue sky above and wispy clouds drifting by. The camera captures the vehicle from the rear, emphasizing its powerful and adventurous journey.",1440 +19,"A detailed digital painting in the style of a realistic Japanese manga, capturing reflections in the window of a train traveling through the Tokyo suburbs. The train moves smoothly, passing through lush green fields and dense forests. Outside the window, the scenery blurs into a series of vivid colors—emerald greens, deep browns, and vibrant yellows. Inside the train, a young woman with long black hair and traditional Japanese clothing sits with a contemplative expression, gazing out the window. Her kimono is adorned with intricate patterns, and she wears a simple obi sash tied neatly. The train cabin is dimly lit, with soft shadows playing across the wooden seats. The background features a blurred yet recognizable landscape, with hints of Tokyo skyscrapers and cherry blossoms in the distance. A medium shot from a slightly tilted angle, emphasizing the reflection and the woman's serene expression.",720 +20,"A stunning aerial photograph captured from a drone, circling around a majestic historic church perched atop a rocky outcropping along the Amalfi Coast. The camera captures the intricate architectural details and tiered pathways and patios that adorn the church, with waves crashing against the rocks below. The view extends to the horizon, showcasing the coastal waters and the rolling hills of the Amalfi Coast in Italy. Distant figures can be seen leisurely walking and enjoying the dramatic ocean views from the patios. The warm glow of the afternoon sun bathes the scene in a magical and romantic light, creating a breathtaking and serene atmosphere. The photo has a high-resolution, detailed quality that highlights every texture and color of the landscape. A wide-angle shot from a dynamic aerial perspective.",240 +21,"A wide-angle underwater photograph captures a large orange octopus resting on the ocean floor, its tentacles spread out around its body and eyes closed. The octopus blends seamlessly with the sandy and rocky terrain. Behind a rock, a brown and spiny king crab is crawling towards it, its claws raised and ready to strike. The crab has long legs and antennae, adding to its menacing appearance. The scene is set in a clear, blue ocean with rays of sunlight filtering through, creating a vivid contrast. The photo is sharp and crisp, with a high dynamic range, emphasizing the octopus and the crab in focus while the background is slightly blurred, enhancing the sense of depth.",1440 +22,"A vibrant illustration in a whimsical cartoon style depicting a flock of paper airplanes fluttering through a dense jungle. The airplanes, resembling small birds, weave gracefully around towering trees, their wings fluttering gently. The jungle is lush and vibrant, with a variety of exotic plants and colorful flowers. The airplanes seem to migrate through the forest, creating a mesmerizing aerial dance. The background is rich with detailed textures, including sunlight filtering through the canopy, casting dappled shadows on the ground. A dynamic overhead view capturing the mid-flight action of the airplanes.",240 +23,"A charming comic-style illustration depicting a cozy living room scene where a fluffy gray cat is waking up its sleeping owner, who lies on the couch with a sleepy, resigned expression. The cat, with large, round eyes and a mischievous look, is pawing at the owner's face and meowing insistently. The owner attempts to ignore the cat, turning away slightly, but the cat persists, jumping onto the owner's chest and nuzzling their hand. Finally, the owner, unable to resist, reaches under the pillow and pulls out a small bag of treats, offering it to the cat with a playful smile. The background shows soft, warm lighting from a nearby lamp, with scattered books and a blanket on the couch. A medium shot from a slightly elevated angle, capturing both the cat and the owner's interaction.",240 +24,"A nature photography style photo capturing a family of orangutans along the Kinabatangan River in Borneo. The mother orangutan, with long reddish-brown fur and expressive brown eyes, is holding her baby tightly. The baby orangutan, with smaller size and lighter fur, is clinging to its mother’s chest, both gazing curiously at the camera. The father orangutan, larger and more muscular, is standing nearby, looking contemplative. The riverbank is lush with green foliage, and the water reflects the surrounding tropical rainforest. The photo has a vivid and naturalistic style, with the orangutans in focus against a slightly blurred background of dense jungle. A medium shot from a slightly elevated angle, capturing the interaction between the family.",720 +25,"A vibrant and lively Chinese Lunar New Year celebration video featuring a majestic Chinese dragon performing traditional dance moves. The dragon, made of colorful silk and adorned with intricate patterns, has flowing scales and a fierce expression, moving gracefully with fluid movements. It dances amidst a sea of joyful people in festive red and gold attire, accompanied by drummers and musicians playing traditional instruments. The background showcases bustling streets filled with lanterns, paper decorations, and colorful stalls. The video has a dynamic and energetic feel, capturing the essence of the festival. A wide-angle shot with dynamic camera movements following the dragon's path.",1440 +26,"A dynamic and lively tour through an art gallery, showcasing a diverse array of beautiful works in various styles. The gallery is filled with paintings, sculptures, and installations, each piece telling its own story. One section features impressionistic landscapes with soft brushstrokes and vibrant colors, capturing serene lakes and rolling hills. Nearby, there are realistic portraits with intricate details and lifelike expressions. In another corner, abstract artworks with bold colors and geometric shapes create a sense of movement and energy. The gallery itself has a modern, open design with high ceilings and large windows allowing natural light to flood in. Visitors move gracefully through the space, pausing occasionally to admire the works. The camera captures the gallery from multiple angles—wide shots of the entire room, close-ups of individual pieces, and sweeping pans to show the flow of visitors. The overall atmosphere is one of inspiration and wonder.",720 +27,"A dynamic and vibrant anime illustration in a flowing watercolor style, capturing the bustling snowy streets of Tokyo. The camera moves smoothly through the city, following several people joyfully enjoying the snow and shopping at nearby stalls. Gorgeous sakura petals dance through the air, swirling with snowflakes. The scene features traditional Japanese architecture, with shops and lanterns illuminated by the soft winter light. People are bundled up in warm coats and scarves, their faces lit with smiles. The background shows blurred, snowy rooftops and distant cherry blossom trees, creating a serene yet lively atmosphere. A medium shot with a sweeping camera motion, highlighting the natural movement of both people and petals.",1440 +28,"A stop motion animation in a charming hand-drawn style, depicting a flower slowly growing out of the windowsill of a suburban house. The flower is a vibrant sunflower, with its petals unfurling gracefully. The windowsill is adorned with small potted plants and a few scattered books. The house has a cozy exterior, with a red door and white shutters, and the surrounding area features neatly trimmed bushes and a small garden path. The animation captures the natural growth process, with the sunflower stem bending slightly as it stretches upward. A close-up shot from a low angle, emphasizing the delicate details of the flower's growth.",240 +29,"A cyberpunk-style illustration depicting a lone robot navigating a neon-lit cityscape. The robot stands tall with sleek, metallic armor, adorned with blinking lights and wires. Its eyes, glowing with a deep blue hue, scan the surroundings with curiosity. The background features towering skyscrapers, holographic advertisements, and crowded streets filled with various cyborgs and humans. The air is thick with smoke and the hum of technology. A medium shot from a high-angle perspective, capturing both the robot and the bustling city environment.",720 +30,"A cinematic 35mm film-style extreme close-up of a gray-haired man in his 60s, deeply engrossed in thought about the history of the universe as he sits at a Parisian café. His weathered face, adorned with a full beard, conveys a professorial air. His eyes are fixed on people walking off-screen, lost in contemplation. He is dressed in a woolen suit coat and a button-down shirt, wearing a brown beret and glasses. The background showcases the bustling Parisian streets and cityscape, with golden light illuminating the scene. The depth of field creates a sense of depth, and the lighting is cinematic, highlighting his subtle, closed-mouth smile as if he has just discovered the answer to life's mysteries. A medium shot with a slight overhead angle.",720 +31,"A beautifully animated silhouette scene depicts a lone wolf standing on a rocky hilltop, howling at the full moon, its expression filled with loneliness and longing. As the wolf's howl echoes across the night, it suddenly notices a distant silhouette of another wolf, signaling the beginning of its journey to rejoin its pack. The background is a detailed, moonlit landscape with rolling hills, dense forests, and a clear, starry sky. The animation has a smooth, fluid motion, capturing the natural movements of the wolves. The camera starts with a close-up of the lone wolf, then gradually pans out to show the entire scene, creating a sense of connection and movement.",720 +32,"A surreal and dreamlike scene in the style of a cyberpunk film, depicting New York City submerged underwater, resembling the mythical city of Atlantis. Fish, whales, sea turtles, and sharks swim through the bustling streets, which now resemble underwater landscapes. The buildings are partially submerged, their facades covered in algae and marine growth. The water is murky and filled with sunlight filtering through from above, casting colorful hues. Pedestrians, now merfolk, move gracefully through the water, interacting with the aquatic creatures. The camera angle is from a low, sweeping shot, capturing the vast expanse of this submerged metropolis.",240 +33,"A winter scene in a snowy forest, where a litter of playful golden retriever puppies emerge from the snow. Their heads pop out, their fluffy fur glistening in the sunlight, and they wag their tails joyfully. They are covered in snow, with some paw prints leading away into the deep snow. One puppy is burying its nose in the snow, while another chases a small ball that has rolled nearby. The background shows dense evergreen trees and a gentle slope leading up to a clearing. The air is crisp and cold, with tiny snowflakes falling gently. A close-up shot from a slightly elevated angle, capturing the lively and energetic moment.",720 +34,"A cinematic film shot in 35mm capturing a dynamic step-printing scene of a person running. The runner is a young man with short, tousled brown hair and determined eyes, sprinting down a city street lined with tall buildings and neon signs. His arms are pumped vigorously, and he looks focused and energetic. The background features blurred motion with the cityscape gradually fading into a soft, sepia tone. The camera follows him closely, capturing his every stride and movement. The scene has a nostalgic and vintage film texture, enhancing the dramatic intensity of the run. A close-up shot from a slightly behind-the-subject angle.",720 +35,"A nature-inspired illustration in a soft watercolor style depicting five playful gray wolf pups frolicking and chasing each other along a remote gravel road. The pups run and leap, their tails wagging joyfully as they chase and nip at one another. They are covered in a fine layer of dirt and grass, adding to their lively energy. The background is filled with tall grass swaying gently in the breeze, with a few wildflowers scattered about. The sun casts warm, golden light over the scene, creating a serene and natural atmosphere. A dynamic close-up from a low angle, capturing the wolves' playful antics.",240 +36,"A dynamic and explosive basketball moment captured in a high-energy action style, showcasing a basketball flying through the hoop with a burst of fireworks exploding behind it. The basketball is vividly depicted, with realistic textures and reflections. The hoop is made of shiny black metal, and the net is taut and stretched. Behind the hoop, a spectacular explosion of fireworks fills the sky, creating a dazzling display of colors and sparks. The camera angle is from the side, capturing the intense moment with a sense of movement and excitement. The background features blurred spectators and a sports arena with standing figures, adding to the lively atmosphere. A medium shot with a slight upward angle.",720 +37,"A realistic archaeological excavation scene in a vast desert, where archeologists meticulously uncover a generic plastic chair buried under layers of sand. They carefully brush away the dust, their focused expressions conveying the importance of their discovery. The chair, though simple, appears slightly worn and faded. The background showcases the harsh, barren landscape of the desert, with dunes stretching into the distance. The sun is setting, casting long shadows and adding a sense of timelessness to the scene. A close-up shot from a slightly lower angle, emphasizing the detailed work of the archeologists and the weathered chair.",240 +38,"A cinematic photograph in the style of a warm family moment, capturing a grandmother with neatly combed grey hair standing behind a colorful birthday cake adorned with numerous pink frosting candles and sprinkles. She leans forward with a gentle puff, extinguishing the flickering candles with a joyful expression, her eyes sparkling with happiness. The grandmother wears a light blue blouse adorned with delicate floral patterns, and the scene is filled with several happy friends and family members gathered at the wooden dining room table, their faces illuminated by soft, warm lighting. The background is slightly out of focus, emphasizing the intimate and celebratory atmosphere. A 3/4 view shot, highlighting the grandmother's warm and loving demeanor, with a beautiful blend of natural light and color tones.",240 +39,"A vibrant and lively scene in Burano, Italy, captured in a direct camera angle. The colorful buildings with their distinctive pastel hues dominate the background, creating a picturesque Venetian atmosphere. On the ground floor, a cute Dalmatian peers out through a window, its curious gaze catching the attention of passersby. Pedestrians and cyclists move gracefully along the canal streets in front of the buildings, adding to the bustling yet charming ambiance. The photo has a warm, nostalgic feel, with the Dalmatian standing out against the vivid backdrop. A medium shot capturing the street life and the building details.",240 +40,"A scenic photograph capturing the moment a steam train departs from the Glenfinnan Viaduct, a historic railway bridge in Scotland. The train moves gracefully over the arch-covered viaduct, its smoke billowing into the air. The landscape is lush with greenery, and towering rocky mountains frame the scene, creating a picturesque backdrop. The sky is a clear, bright blue with the sun shining down, casting a warm glow on the train and the surrounding scenery. The viaduct itself is a striking feature, with intricate ironwork and a verdant setting. The photo has a classic, nostalgic feel, emphasizing the natural beauty and historical charm of the location. A wide-angle shot from a slightly elevated angle, capturing both the train and the expansive landscape.",720 +41,"A charming 3D digital render art style image showcasing an adorable and happy otter confidently standing on a surfboard, wearing a bright yellow lifejacket. The otter is depicted with a joyful expression, its fur soft and detailed, and it appears to glide gracefully through turquoise tropical waters. The background features lush tropical islands with vibrant green foliage and palm trees, creating a serene and picturesque setting. The water is crystal clear, with gentle waves and sunlight filtering through, adding a sense of tranquility and vibrancy to the scene. A medium shot capturing the otter mid-glide, with a slight tilt to the camera angle emphasizing its playful and adventurous spirit.",1440 +42,"A close-up shot in the style of a nature documentary, featuring a chameleon with its body contorted in an intriguing pose, showcasing its striking color-changing capabilities. The chameleon's skin shifts between vibrant shades of green, blue, and yellow, with intricate patterns and textures. Its large, round eyes focus intently on the viewer, and its long, sticky tongue is partially extended, ready to catch prey. The background is blurred, emphasizing the chameleon's vivid colors and detailed patterns, with hints of a lush, tropical forest environment. The photo has a crisp, high-resolution quality, highlighting the reptile's natural movements and vibrant hues. A close-up shot from a slightly elevated angle.",1440 +43,"A vibrant and lively vlog-style photo of a corgi in tropical Maui, showcasing the dog energetically filming itself on a sandy beach. The corgi stands on the shore, one paw slightly lifted, with a joyful and curious expression. It wears a colorful collar and a small backpack camera slung over its neck. The background features a lush, palm-fringed beach with clear turquoise waters and a bright blue sky. The photo has a warm, natural lighting effect, capturing the corgi from a slightly elevated angle, emphasizing its playful and adventurous spirit.",240 +44,"A cinematic and grainy photograph captures a white and orange tabby cat joyfully darting through a dense garden, as if chasing something. The cat’s eyes are wide and filled with happiness as it jogs forward, scanning the branches, flowers, and leaves. The narrow path winds between the lush greenery, and the scene is captured from a ground-level angle, providing a low and intimate perspective. The image has warm tones and a subtle grainy texture, with scattered daylight filtering through the leaves and plants above, creating a warm contrast that highlights the cat’s orange fur. The shot is clear and sharp, with a shallow depth of field that focuses solely on the cat’s movements and expressions.",240 +45,"An aerial view of Santorini during the blue hour, capturing the stunning architecture of white Cycladic buildings with blue domes against the twilight sky. The caldera views are breathtaking, with the volcanic cliffs and sea below creating a dramatic contrast. The lighting casts a soft, warm glow, enhancing the serene atmosphere. The image has a dreamy, almost ethereal quality, emphasizing the beauty of the setting. A bird's-eye view with a wide-angle lens, focusing on the intricate details of the buildings and the vast expanse of the caldera.",1440 +46,"A tilt-shift photograph of a bustling construction site, capturing the essence of a busy work environment. Workers in hard hats and safety gear are scattered throughout the scene, operating various pieces of heavy machinery and equipment. The site is filled with cranes, bulldozers, and excavators, each piece of machinery adding to the dynamic atmosphere. The background features partially constructed buildings and scaffolding, creating a sense of progress and ongoing development. The overall texture of the photo gives it a miniature-like quality, emphasizing the scale and activity of the site. A medium shot with a slightly downward angle, highlighting the intricate details and movements of the workers and machines.",240 +47,"A dramatic, epic fantasy-style illustration depicting a towering, giant cloud shaped like a man, with thunderous lightning bolts emanating from his outstretched arms and striking the ground below. The cloud-man has a fierce, determined expression, with stormy gray clouds cascading down his form, giving him a menacing presence. His eyes glow with an intense, electric blue light, and his arms are spread wide, ready to unleash more bolts. The background shows a dark, stormy sky with heavy rain and distant lightning, creating a foreboding atmosphere. The scene is rendered in a dynamic, high-detailed style with a mix of realistic and fantastical elements. A high-angle shot capturing the full figure of the cloud-man in action.",1440 +48,"A vibrant and dynamic illustration in the style of a futuristic sci-fi comic, depicting two playful dogs, a Samoyed and a Golden Retriever, running through a neon-lit city at night. The dogs' fur gleams under the vibrant glow of the city's neon lights, casting colorful reflections. They move energetically, tails wagging, with the Samoyed having a fluffy white coat and the Golden Retriever sporting a golden one. The cityscape is filled with towering skyscrapers adorned with flickering neon signs, creating a mesmerizing visual spectacle. The background features blurred outlines of the city's architecture, with hints of glowing streets and distant buildings. The camera angle captures a medium shot of the dogs from a slightly elevated perspective, emphasizing their joyful movements.",240 +49,"A dynamic scene captured in the style of a vibrant food photography, showcasing a chef skillfully chopping onions in a bustling kitchen. The chef, a middle-aged man with a weathered face and determined expression, skillfully slices the onions with quick, practiced movements. He wears a white apron tied neatly around his waist and a chef's hat perched atop his head. The background is a well-equipped kitchen, with stainless steel appliances and countertops cluttered with various cooking tools and ingredients. Steam rises from a pot on the stove, and sunlight filters through the window, casting a warm glow. A medium shot with the chef at the center, capturing the intensity of his work.",720 +50,"A detailed digital painting style illustration of a small man with a cheerful expression, holding several colorful building blocks, visiting an art gallery. He has round glasses and a warm smile, with his hands gently holding the blocks. The gallery features various paintings on the walls, with a mix of modern abstract and classic artworks. The floor is covered in polished wooden tiles, and there are comfortable chairs and tables nearby. The man is standing near a large painting of a serene landscape, with his gaze focused on it. The background has a soft, warm lighting, highlighting the textures of the artwork and the man's clothes. A medium shot from a slightly lower angle, capturing both the man and the gallery scene.",720 +51,"A vibrant and dynamic illustration in a cartoon style depicting a white cat sitting comfortably behind the wheel of a toy car, driving through a bustling downtown street. The cat has large, round eyes and a mischievous grin, with fur that appears soft and fluffy. Tall skyscrapers and a mix of people walking briskly fill the background, adding to the lively urban setting. The car's tires spin as it moves, and the wind flows through the cat's ears. The illustration has a bright color palette and a smooth, cartoony texture. The camera angle is slightly elevated, capturing both the cat and the vibrant street scene below.",240 +52,"A macro shot of a volcanic eruption in a coffee cup, capturing the dramatic moment in vivid detail. The coffee cup is filled with rich, dark brown liquid, and the surface is suddenly disrupted by a burst of foam and steam, mimicking the intense heat and pressure of a real volcanic eruption. The foam rises and spreads across the surface, creating a chaotic yet mesmerizing pattern. The cup itself is made of ceramic, with intricate patterns etched into the sides, adding texture and depth to the scene. The background is a blurred gradient of warm browns and grays, enhancing the focus on the erupting foam. The lighting is dramatic, casting shadows and highlighting the dynamic movement of the foam. A close-up shot from a low angle, emphasizing the explosive nature of the eruption.",1440 +53,"A highly detailed close-up shot in HD, focusing on dew droplets glistening on the delicate petals of a blue rose. The petals are soft and velvety, with intricate patterns and subtle color gradients. Each dew drop sparkles like tiny diamonds, catching the light and creating a mesmerizing effect. The background is blurred, emphasizing the dew and petals, with a soft focus on the edges. The photo has a clear, crisp texture, highlighting the beauty and fragility of nature.",720 +54,"A Chinese boy wearing glasses sits in a fast food restaurant, enjoying a delicious cheeseburger with his eyes closed. His hair is neatly combed, and he has a slightly dreamy expression. He holds the cheeseburger with both hands, taking a big bite. The background shows other diners and a colorful menu board with various fast food items. The lighting is warm and inviting, creating a cozy atmosphere. A close-up shot from a slightly lower angle, capturing the boy's joyful moment.",720 +55,"A tropical island beach scene in a vibrant and lively illustration style, featuring a corgi wearing stylish sunglasses walking along the sandy shore. The corgi has a playful expression, its fur glistening in the bright sunlight. It strides confidently, its tail wagging as it explores the soft sand. The background showcases a clear turquoise sea with palm trees swaying gently in the breeze. A few seagulls fly overhead, adding to the serene yet lively atmosphere. The corgi’s sunglasses add a touch of whimsy and fun to the scene. A medium shot with the corgi at the center, captured from a slightly elevated angle.",1440 +56,"A traditional Chinese dining scene in a dimly lit restaurant, capturing a middle-aged Chinese man sitting at a small round table. He is attentively eating noodles with chopsticks, his face reflecting contentment and focus. His attire is casual yet neat, with a light blue shirt and black pants. The background features blurred details of other diners and tables, hinting at a bustling yet cozy atmosphere. The lighting casts soft shadows, enhancing the warm and inviting ambiance. A close-up shot from a slightly overhead angle, emphasizing the man's engaged expression and the textures of the food.",720 +57,"A romantic scene in a nighttime cityscape where a man and a woman walk hand in hand under a starry sky, their faces illuminated by the soft glow of streetlights. They are dressed in casual yet elegant attire, the man in a dark blue suit and the woman in a light green dress. A wooden bucket is placed on the ground nearby, adding a touch of rustic charm. The couple’s expressions are filled with happiness and affection, as they gaze into each other’s eyes. The background features tall buildings with windows lit up, creating a warm and cozy atmosphere. The stars above twinkle brightly, enhancing the serene and intimate mood. The scene is captured in a medium shot with a slightly upward angle, capturing both the couple and the surrounding environment.",1440 +58,"A close-up shot of a steaming cappuccino in a ceramic cup, with a rich brown foam on top and a slight milk swirl pattern. The cup has a simple yet elegant design, with a white handle and a light brown body. The background is a cozy café with warm lighting, wooden tables, and a few patrons chatting in the corner. The cappuccino is freshly made, with a hint of steam rising from the surface, capturing the essence of a perfect morning beverage.",1440 +59,"A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement.",240 +60,"A photograph in a warm and nostalgic style, capturing chimneys against a setting sun. The chimneys stand tall and sturdy, casting long shadows across a peaceful rural landscape. The sun is low in the sky, painting the scene in soft orange and pink hues. The background features a serene countryside with fields, trees, and distant hills. The chimneys are surrounded by a haze of golden light, creating a sense of warmth and tranquility. A wide-angle shot with the chimneys in the foreground, capturing the entire sunset scene.",720 +61,"An astronaut runs smoothly and appears almost weightless on the lunar surface, as seen from a low-angle shot that highlights the vast, desolate background of the moon. The moon's craters and rocky terrain are clearly visible, creating a stark contrast against the running astronaut who moves with graceful, fluid motions. The background features a muted, grayscale texture with subtle shadows and highlights, emphasizing the lunar landscape's rugged beauty. The astronaut wears a classic spacesuit with reflective fabric, adding to the sense of lightness and movement. A dynamic medium shot capturing the astronaut's forward momentum.",240 +62,"A dynamic photograph capturing a little boy riding his bike through a garden that transitions through the changing seasons—fall leaves crunch underfoot, winter snow blankets the ground, spring flowers bloom, and summer sunshine sparkles through the foliage. The boy, with curly brown hair and a joyful smile, pedals energetically, his arms outstretched in excitement. The garden backdrop features trees with branches adorned in each season’s distinctive foliage. A series of shots taken from various angles, starting with a wide shot of the boy entering the garden in spring, transitioning to a mid-shot of him biking through the colorful autumn leaves, then a close-up of him riding through a snowy path, and finally a wide-angle view of him enjoying the warm summer sun. The photo has a natural, documentary style, emphasizing the boy’s natural movements and the vibrant colors of the changing seasons.",720 +63,"A close-up shot of someone carefully pouring milk into a cup, with the milk flowing smoothly and filling the cup with a milky white color. The person's hand is steady, guiding the milk into the cup with precision. The background is blurred, showing a subtle kitchen setting with hints of cabinets and countertops. The photo has a soft, natural lighting effect, emphasizing the smoothness and elegance of the pouring action.",240 +64,"A detailed oil painting in a romantic style, showcasing a young woman standing amidst a vibrant garden filled with blooming flowers. She wears a floral-patterned dress, her hair loosely tied with wildflowers adorning it. Her expression is one of serene joy, with a gentle smile on her lips. She is framed by a variety of colorful blooms, including roses, tulips, and daisies, which surround her in a natural, organic arrangement. The background features a soft, pastel-colored sky with fluffy clouds, and a gentle breeze rustling through the petals. A medium shot with a slightly tilted angle, capturing the essence of spring and renewal.",240 +65,"A cinematic scene from a classic western movie, featuring a rugged man riding a powerful horse through the vast Gobi Desert at sunset. The man, dressed in a dusty cowboy hat and a worn leather jacket, reins tightly on the horse's neck as he gallops across the golden sands. The sun sets dramatically behind them, casting long shadows and warm hues across the landscape. The background is filled with rolling dunes and sparse, rocky outcrops, emphasizing the harsh beauty of the desert. A dynamic wide shot from a low angle, capturing both the man and the expansive desert vista.",1440 +66,"A vibrant and lively illustration in a cartoon style of a panda playing the guitar. The panda has black and white fur, with round eyes and a friendly expression. It sits comfortably on a small stool, strumming the guitar with one paw while the other rests on its knee. The guitar is a small acoustic model, and the strings are plucked with precision. The background features a cozy room with a few plants and colorful decorations, adding a warm and inviting atmosphere. The camera angle is slightly from above, capturing the panda's joyful and focused performance.",720 +67,"A dramatic sunset landscape photograph captured in a cinematic style, featuring a car with its side mirrors reflecting the vibrant hues of the setting sun. The car is parked on a winding road, with one of its side mirrors perfectly capturing the warm orange and pink tones of the sky. The sun is just below the horizon, casting long shadows and creating a golden glow over the landscape. The background includes rolling hills and a few trees silhouetted against the sky. The photo has a rich, film noir texture, enhancing the mood and atmosphere. A wide-angle shot from a low angle, emphasizing the reflection in the mirror and the vastness of the landscape.",240 +68,"A dynamic rally car speeding through a tight turn on a winding track, tires screeching as it navigates the curves with precision. The car is a sleek, racing machine with a vibrant red body and black accents, its headlights glowing brightly in the night. The driver, a determined-looking man with focused eyes, grips the steering wheel tightly, his muscles tensed. The background is blurred, showing glimpses of the track ahead and behind, with lights reflecting off the wet pavement. The camera angle is from slightly above, capturing the car's movement and the intense energy of the moment.",240 +69,"A charming illustration in a watercolor style of a young white rabbit wearing glasses and reading a newspaper. The rabbit has soft fur, large round ears, and gentle, curious eyes. It sits upright on a cozy armchair, one paw holding the newspaper and the other resting on its knee. The background features a warm living room with a fireplace, a few books on a side table, and a blurred view of a window with falling leaves. The rabbit's expression is one of focused interest, with a slight smile playing on its lips. A close-up shot from a slightly elevated angle, capturing the rabbit's detailed features and the newspaper's headlines.",240 +70,"A close-up shot of a bright blue parrot's shimmering feathers, capturing the unique and vibrant colors in the light. The parrot's feathers glisten with a metallic sheen, showcasing a mix of deep indigos, vivid greens, and rich blues. Its eyes sparkle with curiosity, and it appears lively and alert, perched on a branch. The background is blurred, highlighting the parrot against a soft, warm environment. The photo has a naturalistic and lifelike quality, emphasizing the bird's detailed plumage and natural movements.",1440 +71,"A subtle and elegant photograph in a Japanese style, capturing a woman with gentle, contemplative eyes and flowing dark hair sitting by the window of a high-speed train. The train moves rapidly through a bustling cityscape, with blurred reflections of the city lights and buildings on the window pane. The woman appears serene, her hands resting gently on her lap. The background features a blend of traditional Japanese architecture and modern skyscrapers, with a soft, muted color palette. The photo has a vintage film texture, emphasizing the movement and energy of the scene. A medium shot from a slightly angled perspective, highlighting the woman's thoughtful gaze and the dynamic motion of the train.",1440 +72,"An astronaut running through a narrow alley in Rio de Janeiro, Brazil. The astronaut is dressed in a bright white spacesuit with a helmet that reflects sunlight. The spacesuit is adorned with various technical patches and has a reflective texture. The astronaut's movements are energetic and dynamic, with one hand on their hip and the other reaching forward for balance. The background features colorful street art, vibrant buildings, and people bustling about. The alley is dimly lit, with shadows cast by the narrow walls. A mid-shot with the astronaut running from a low-angle perspective, capturing the excitement and contrast between the urban environment and the space exploration gear.",240 +73,"A dynamic FPV aerial view of a vibrant underwater suburban neighborhood, where colorful corals line the streets. The camera moves swiftly, capturing the intricate details of the coral formations and the diverse marine life swimming around. The streets are bustling with colorful fish and schools of tropical fish, creating a lively and energetic atmosphere. The water is crystal clear, with sunlight filtering through, casting a warm glow on the scene. The camera angle shifts slightly, providing a sense of depth and movement, as if the viewer is flying through this underwater world. A fast-paced, first-person view shot with a vivid and lifelike underwater setting.",720 +74,"A dynamic and surreal scene from a conceptual digital art piece, showcasing an empty warehouse where flora suddenly bursts forth from the ground, transforming the space. The warehouse walls remain exposed brick, but green vines and flowers rapidly cover the floors and walls, creating a chaotic yet vibrant explosion of nature. The camera angle is from a low, sweeping perspective, capturing the full extent of the transformation. The background features a mix of old machinery and newer plant life, with sunlight filtering through gaps in the roof, casting a dappled light pattern on the scene. The overall style is hyper-realistic with a touch of magical realism, emphasizing the sudden and dramatic change.",1440 +75,"A close-up shot of a living flame wisp darting through a bustling fantasy market at night. The wisp, flickering with an ethereal glow, moves swiftly among the stalls and vendors. The market is filled with colorful lanterns, glowing signs, and various magical items. The background features a crowded scene with people in exotic attire, bustling about their business under the soft light of the full moon. The air is filled with the scent of spices and incense. The camera angle is slightly elevated, capturing the dynamic movement of the wisp as it weaves through the market, creating a sense of wonder and enchantment.",720 +76,"A handheld tracking shot following a red balloon floating above the ground in an abandoned street. The balloon drifts gracefully, its bright red color contrasting sharply against the decaying urban backdrop. The street is littered with debris and graffiti-covered walls, with broken windows and rusted cars scattered about. Shadows dance across the scene as sunlight filters through gaps in the buildings. The camera moves fluidly, capturing the balloon's gentle ascent and descent, emphasizing its playful motion. A close-up of the balloon transitions to a wider shot, showcasing the desolate environment.",1440 +77,"A first-person view (FPV) shot zooming through a narrow tunnel, transitioning into a vibrant underwater world. The tunnel walls are illuminated by colorful lights, creating a mesmerizing effect. Inside the tunnel, bubbles rise gently, and seaweed sways gracefully. The underwater space is filled with a variety of colorful fish swimming around, including neon blue tangs and vibrant orange clownfish. Coral reefs in shades of pink, purple, and green add depth and texture to the scene. The water is clear, allowing visibility of the diverse marine life. The camera angle is slightly tilted, capturing the excitement and adventure of the journey.",720 +78,"A wide symmetrical shot of a painting in a museum, with the camera gradually zooming in for a closer look. The painting depicts a serene landscape featuring a tranquil lake surrounded by lush greenery and towering trees. The composition is balanced, with soft, pastel colors dominating the scene. In the foreground, a bridge spans the lake, leading to a small island adorned with blooming flowers. The background showcases rolling hills and a distant mountain range, creating a harmonious and peaceful atmosphere. The texture of the canvas is visible, adding to the authenticity of the artwork. A close-up shot with a slight tilt to the right.",1440 +79,"An ultra-fast disorienting hyperlapse photograph capturing a car racing through a tunnel, transitioning into a chaotic labyrinth of rapidly growing vines. The car's headlights illuminate the tunnel walls, which are adorned with peeling paint and graffiti. As the tunnel ends, the camera speeds into a dense forest of vines, their leaves and tendrils swaying wildly. The vines grow at an alarming rate, forming a maze-like structure that twists and turns. The car appears to be navigating this treacherous path, with the driver focused intently on the winding route. The background is filled with blurred, green foliage and twisted branches, creating a sense of urgency and chaos. The photo has a gritty, hyperrealistic texture, emphasizing the dynamic movement and intense visual effects. A wide-angle shot from a low angle, capturing the car's rapid descent into the vine-laden labyrinth.",720 +80,"A high-speed FPV (First Person View) shot inside the locomotive cab of a vintage European train, moving at hyper-speed through the bustling streets of an old European city. The cab is filled with intricate mechanical details, including dials, switches, and controls, with steam and smoke swirling around. The train's windows show blurred, colorful buildings and narrow cobblestone streets passing by quickly. The camera angle provides a dynamic, immersive view, capturing the intense motion and the rich architectural details of the cityscape. The overall style is detailed and realistic, emphasizing the speed and energy of the journey.",720 +81,"A hyper-realistic macro photograph capturing the intricate details of a dandelion, zooming in at an incredible speed to reveal a dream-like, abstract world. The petals are softly blurred, creating a mesmerizing effect that blends reality with fantasy. Each fiber and grain of pollen is vividly detailed, giving the image a surreal texture. The background fades into a gradient of soft pastel colors, enhancing the ethereal quality of the scene. The dandelion appears almost otherworldly, with its delicate structure and vibrant colors standing out against the blurred, abstract surroundings. A close-up shot with a dynamic zoom-in motion.",240 +82,"A hyper-realistic digital art piece capturing an internal window view inside a high-speed train moving through an old European city. The train interior is sleek and modern, with passengers seated in comfortable leather seats, some reading books or using laptops. The window frame is clear, showing the bustling streets and historic buildings of the city rushing past at incredible speed. The cityscape features ancient cobblestone streets, ornate facades, and spires of medieval churches, with people walking hurriedly and horse-drawn carriages passing by. The train's motion is vividly depicted, creating a sense of dynamic movement and adventure. The background is richly detailed, with the cityscape blurred and streaked, emphasizing the train's speed. The overall atmosphere is both futuristic and nostalgic, blending modern technology with historical charm. A wide-angle shot from inside the train, capturing the motion and the cityscape outside.",720 +83,"A handheld camera moving quickly captures the flickering light from a flashlight shining on a dilapidated white wall in an old alley at night. The wall is covered with a large, faded black graffiti that reads 'Runway'. The flashlight casts dynamic shadows, highlighting the rough texture of the wall and the worn-out letters. The background shows the dim, narrow alley with occasional glimpses of neighboring buildings and dark, shadowy figures in the distance. The photo has a gritty, documentary-style texture, emphasizing the movement and the eerie atmosphere of the scene. A low-angle, handheld shot capturing the dynamic interaction between the flashlight and the graffiti.",720 +84,"A dynamic super fast zoom-out shot starting from the peak of a majestic frozen mountain where a lone hiker is making their final push to reach the summit. The hiker, bundled in thick winter gear, trudges through the snow-covered terrain with determination etched on their face. Their breath forms visible clouds in the frigid air. As the camera pulls back, the vast, icy landscape unfolds, revealing rugged peaks and valleys, with distant snow-capped mountains stretching into the horizon. The sky is a stark, deep blue, filled with wisps of cloud. The overall scene captures the raw beauty and harshness of nature. A sweeping aerial view transitioning to a wide-angle shot.",720 +85,"A surreal first-person point-of-view shot rapidly flies through open doors, capturing the moment when the viewer suddenly finds themselves in the midst of a living room transformed into a dreamlike scene. At the center of this room stands a breathtaking waterfall, water cascading down from the ceiling and walls, creating a mesmerizing mist that fills the space. The living room is adorned with floating plants and ethereal lights, casting a soft, otherworldly glow. The camera angle shifts, providing a dynamic and immersive experience as it adjusts to the surreal environment.",1440 +86,"A dynamic first-person point-of-view shot rapidly zooms towards a house's front door at 10x speed, capturing the excitement and urgency of the scene. The camera angle is from the perspective of someone running towards the door, with the door and its surroundings quickly coming into focus. The front door is old and wooden, with a brass knocker and a small peephole. The background shows a garden with blooming flowers and green bushes, and a path leading up to the door. The scene has a gritty, realistic texture, emphasizing the speed and intensity of the movement. The camera angle is slightly tilted, giving a sense of depth and immediacy.",240 +87,"A pencil sketch in a classic architectural drafting style, depicting a detailed floor plan of a grand mansion. The drawing includes intricate lines and measurements, with a focus on the mansion's layout, including hallways, rooms, and windows. The building features ornate columns, arched doorways, and a large central staircase. The background is a blurred view of a sunny day, with hints of greenery and trees outside the mansion's windows. The pencil strokes are soft and precise, creating a realistic and detailed representation. A close-up shot from a slightly elevated angle.",720 +88,"An extreme close-up shot of an ant emerging from its nest, capturing the moment of its journey with vivid detail. The ant is small but resilient, with its body glistening slightly in the sunlight. As the camera pulls back, we see a picturesque neighborhood beyond the hill, with rows of houses and trees in the background. The hill itself is covered in lush green grass and wildflowers, adding to the natural setting. The scene has a warm, natural lighting effect, highlighting the tiny yet significant action of the ant. A gradual pull-back shot, emphasizing both the ant's movement and the broader landscape.",1440 +89,"A dramatic and dynamic scene in the style of a disaster movie, depicting a powerful tsunami rushing through a narrow alley in Bulgaria. The water is turbulent and chaotic, with waves crashing violently against the walls and buildings on either side. The alley is lined with old, weathered houses, their facades partially submerged and splintered. The camera angle is low, capturing the full force of the tsunami as it surges forward, creating a sense of urgency and danger. People can be seen running frantically, adding to the chaos. The background features a distant horizon, hinting at the larger scale of the tsunami. A dynamic, sweeping shot from a low-angle perspective, emphasizing the movement and intensity of the event.",720 +90,"An FPV drone shot capturing a majestic castle perched on a rocky cliff. The camera moves swiftly, revealing intricate stone walls, towering towers, and detailed gargoyles. The castle is partially shrouded in mist, adding a sense of mystery and grandeur. The cliff backdrop features jagged rocks and lush greenery, with patches of sunlight breaking through the clouds. The overall scene has a vivid and dynamic feel, with the camera angle emphasizing the height and imposing presence of the castle.",720 +91,"A cinematic wide-angle portrait of a man with his face illuminated by the warm glow of a TV screen. The man, with a rugged yet determined expression, leans forward slightly against a vintage wooden armchair. His dark hair is slightly disheveled, and he wears a worn leather jacket over a plain white shirt. The background features a cluttered living room with old books, newspapers, and a few framed photos scattered around. The TV shows static, with a faint image of a news broadcast flickering in the corner. The overall scene has a nostalgic and gritty feel, with a rich color palette and a soft, grainy texture. A wide-angle shot capturing the man's intense gaze and the warm ambiance of the room.",1440 +92,"A close-up portrait of a woman, her face illuminated by the side lighting, capturing her delicate features and expressive eyes. As the camera slowly pulls back, it reveals her sitting gracefully in a cozy armchair, her hair falling softly over her shoulders. She wears a elegant evening gown in a deep shade of blue, adorned with intricate lace and sparkling jewels. The background features a warm, candlelit room with soft shadows and a faint hint of a fireplace. The photo has a romantic and timeless quality, reminiscent of a classic Hollywood portrait. A medium shot transitioning to a wider view.",240 +93,"A zoom-in shot focusing on the face of a young woman sitting on a bench in the middle of an empty school gym. The woman has long wavy brown hair cascading down her shoulders and soft, warm hazel eyes. She wears a simple white t-shirt and blue jeans, her hands resting gently on her knees. Her expression is serene, with a slight smile playing on her lips. The gymnasium is mostly empty, with only a few scattered bleachers and a basketball hoop in the background. The lighting is soft and natural, creating gentle shadows under her eyes and nose. The overall atmosphere is peaceful and contemplative.",720 +94,"A close-up of an older man standing in a dimly lit warehouse, his weathered face etched with lines of experience. His eyes, though weary, hold a steady gaze, looking directly at the viewer. He wears a worn leather jacket over a faded t-shirt and blue jeans, his hands resting casually in his pockets. The background shows stacks of crates and old machinery, with light filtering in through dusty windows, casting long shadows. The camera gradually zooms out, revealing the vast, industrial space around him. The overall atmosphere is one of quiet resilience and endurance. A medium shot transitioning to a wider view.",1440 +95,"A classic black-and-white photograph style image of an older man playing the piano. The man, with a weathered face and kind eyes, sits at an antique piano with his fingers gracefully moving over the keys. The lighting comes from the side, casting dramatic shadows on his face and emphasizing the texture of his hands. His posture is upright and focused, conveying a sense of deep concentration and passion for music. The background is blurred, revealing only hints of a cozy room with wooden floors and old furniture. A close-up shot from a slightly elevated angle, capturing both the man and the piano in detail.",1440 +96,"A macro shot focusing on the face of a young woman with freckles, her expression intense as she looks intently for something. Her freckles are scattered across her cheeks and nose, adding a playful charm to her face. Her eyes are wide and slightly squinted, peering closely at the object of her search. Her hair is loose, framing her face gently, with strands falling over her forehead. The background is blurred, but you can make out the faint outline of a table or desk where she is searching. The texture of her skin is smooth and细腻,带有淡淡的红润。A close-up shot from a very close angle, capturing the natural and focused expression of the young woman.",720 +97,"An astronaut in a sleek, white spacesuit walks between two ancient stone buildings, their surfaces adorned with intricate carvings and moss. The astronaut's helmet reflects the dim, otherworldly light casting shadows across the worn stones. The buildings loom large, creating a narrow passage that seems to stretch into the distance. The background shows a barren landscape with distant, rocky hills and a pale, orange sky. The astronaut moves with a determined gait, one hand on the building's surface, the other holding a small device. The photo has a realistic, high-resolution texture, capturing the astronaut's focused expression and the textures of the ancient architecture. A medium shot from a slightly elevated angle, emphasizing the contrast between the modern astronaut and the ancient structures.",720 +98,"A dramatic moment captured in a realistic photographic style, depicting a middle-aged man transitioning from sadness to happiness. Initially, he appears solemn and bald, with a slightly downcast expression. Suddenly, a curly wig and sunglasses fall onto his head from above, transforming his appearance instantly. His face lights up with joy and surprise, his eyes widening and a broad smile forming. The background is a cluttered office space with scattered papers and a desk lamp casting shadows, creating a contrast between the man’s emotional shift and the mundane setting. The photo is taken from a low-angle perspective, emphasizing the dramatic change.",240 +99,"An ultra-wide shot of a colossal stone hand emerging from a chaotic pile of rocks at the base of a towering mountain. The hand is massive, with rough, weathered fingers and a palm as wide as a small room. It seems to be reaching out, as if grasping something unseen. The surrounding rocks are jagged and varied, creating a rugged landscape. In the distance, the mountain peaks rise sharply, shrouded in mist, adding a sense of mystery and grandeur. The texture of the stones is detailed, with subtle shadows highlighting their uneven surfaces. A dramatic and eerie atmosphere pervades the scene, with a mix of sunlight filtering through the clouds, casting long shadows.",240 +100,"An aerial view shot of a cloaked figure soaring through the sky amidst towering skyscrapers. The figure is partially concealed by the cloak, with only their outstretched arms and determined expression visible. The cityscape below is a blur of glass and steel, with lights twinkling in the distance. The background showcases a mix of bright city lights and a hint of a cloudy night sky. The figure seems to be mid-flight, with dynamic motion and a sense of freedom. A high-angle shot capturing the figure in motion.",720 +101,"An oil painting-style natural forest scene with a rich blend of autumn colors, featuring vibrant maple trees casting vivid hues across the landscape. The painting employs a cinematic parallax technique, creating a deep and immersive visual depth. In the foreground, the leaves of the maple trees are vividly colored, ranging from deep red to bright orange, while in the midground, the trees stand tall and majestic, their branches reaching towards the sky. The background reveals a misty distance with softer shades of green and brown, enhancing the sense of depth. The overall atmosphere is warm and inviting, with a soft golden light filtering through the canopy. The composition is a layered, panoramic view, capturing the essence of a serene autumn forest. A wide-angle shot with a slight tilt to the right.",1440 +102,"A nighttime scene from a vintage film-style photograph, depicting a giant, otherworldly creature slowly walking down a desolate, rundown city street. Only one dim streetlamp casts flickering shadows, illuminating the creature's massive, imposing form. Its skin is rough and covered in peculiar growths, with glowing eyes that reflect the dim light. The creature's steps echo in the empty alleyways, creating a sense of eerie quiet. The background features crumbling buildings, broken windows, and trash-strewn sidewalks. The photo has a grainy texture and a muted color palette, capturing the haunting atmosphere of the scene. A medium shot with a slight tilt to the camera, emphasizing the creature's movement and presence.",720 +103,"A full-body shot of a man crafted entirely from rocks, walking through a dense forest. His rocky form is rugged and textured, with various shades of gray and brown. He strides confidently, his steps creating small ripples in the forest floor. The forest behind him is vibrant with greenery, sunlight filtering through the canopy, casting dappled shadows. The background features tall trees with intricate bark patterns and wildflowers peeking through the underbrush. The scene has a mystical and ancient feel, reminiscent of a fantasy landscape.",1440 +104,"A slow cinematic push-in on an ostrich standing in a 1980s kitchen, the camera gradually zooming in to reveal the bird's curious expression. The kitchen is adorned with vintage appliances and Formica countertops, with a muted color palette of pastel greens and yellows. The ostrich, with its distinctive long neck and feathered plumage, stands confidently, one foot slightly raised. Its large brown eyes peer curiously at the viewer, as if pondering the strange surroundings. The background features blurred details of old newspapers scattered on the floor and a faded floral wallpaper. The lighting is warm and soft, casting gentle shadows. A close-up shot from a slightly lower angle.",1440 +105,"A vibrant and whimsical digital illustration in a cartoon style, depicting a giant humanoid figure composed of fluffy blue cotton candy. The humanoid is stomping its feet on the ground, causing a playful disturbance, while roaring towards the clear blue sky. The background features a bright, cloudless sky with soft, pastel tones, enhancing the dreamlike quality of the scene. The humanoid has expressive eyes and a mischievous smile, with arms and legs made of swirling cotton candy. A dynamic, full-body shot from a slightly elevated angle, capturing the energetic movement and playful nature of the creature.",1440 +106,"A dynamic night-time scene in a dark forest, captured in a high-speed aerial shot. Neon-lit flora glows brightly, casting an otherworldly glow through the dense canopy. The camera zooms through the forest, capturing the intricate details of glowing flowers and bioluminescent leaves. The forest floor is shrouded in shadows, with only patches of neon light illuminating the path ahead. The air is filled with the soft rustling of leaves and the distant hum of nocturnal insects. A vivid, surreal landscape with a focus on movement and vibrant colors.",720 +107,"A dynamic urban alleyway scene capturing the chaos of a cyclone of broken glass swirling through the narrow space. The glass pieces twirl and scatter in all directions, creating a mesmerizing and dangerous vortex. The alley is dimly lit, with flickering shadows dancing across the walls. The camera angle is low, emphasizing the height of the glass cyclone and the towering buildings that frame the scene. The background shows graffiti-covered brick walls and a few discarded trash cans, adding to the gritty urban atmosphere. The glass shatters and glints in the dim light, reflecting fragments of the surrounding environment. A close-up shot with fast-paced motion blur, capturing the frenzied movement of the glass storm.",1440 +108,"A dramatic photo in a gritty, realistic style of a middle-aged man standing in front of a partially collapsed, burning building. He gives a thumbs up sign, his face showing determination and resolve despite the danger. His weathered face and rugged, fire-resistant clothing suggest he is a firefighter or emergency responder. The background is a chaotic mix of flames, smoke, and debris, with emergency vehicles in the distance. The scene is captured from a low-angle perspective, emphasizing the man's bravery and the intensity of the situation.",240 +109,"A highly detailed close-up photograph in a scientific documentary style, focusing on a single bacterium under a microscope. The bacterium is spherical with a smooth, translucent outer membrane, revealing internal structures such as ribosomes and a nucleus. It is floating in a clear liquid medium, with some cellular components visible inside. The background is a blurred microscopic field with faint grids and scales. The photo has a crisp, high-resolution texture, emphasizing the intricate details of the microorganism. A macro shot from a slight angle, capturing the subject's natural movement and texture.",720 +110,"A Japanese animated film-style scene of a young woman standing on a ship, looking back at the camera with a gentle smile. She has long black hair tied in a loose ponytail and wears a traditional Japanese kimono with intricate patterns and vibrant colors. Her expression is serene and slightly contemplative. The ship is mid-ocean, with waves gently lapping against the sides, and the background shows a vast blue sea with distant clouds and a setting sun. The scene has a soft, dreamy quality, capturing the tranquility of the moment. A medium shot from a slightly elevated angle, emphasizing her graceful posture and the serene ocean backdrop.",1440 +111,"A close-up shot of a young woman driving a car, lost in thought as she gazes ahead. Raindrops blur the view of a green forest through the car window. She wears a sleek raincoat and sunglasses, her expression contemplative. Her hands gently grip the steering wheel, and her fingers tap rhythmically against it. The interior of the car is dimly lit, with water droplets clinging to the windshield. The blurred green forest and rain create a sense of mystery and introspection. The photo has a cinematic quality, capturing the moment just before a decision is made. A close-up shot from inside the car, focusing on the driver.",1440 +112,"An aerial shot of a fast-moving drone flying through a dense green jungle, capturing the vibrant foliage and lush canopy below. The drone glides smoothly, showcasing the intricate network of vines and towering trees. The background features a mix of bright green leaves and dappled sunlight filtering through the branches. The drone's path is dynamic, suggesting a sense of speed and movement. A high-angle aerial view with a clear focus on the drone's flight path.",240 +113,"A hyperlapse video shot through a long, narrow corridor with flashing lights, capturing the movement of a silver fabric billowing and flowing gracefully through the space. The fabric moves quickly, creating a dynamic and fluid effect against the backdrop of flickering lights. The camera follows the fabric, capturing its intricate folds and movements in vivid detail. The corridor is dimly lit, with the flashing lights creating a surreal and dramatic atmosphere. The fabric appears almost ethereal, reflecting the lights and casting shadows as it moves. A series of wide-angle shots with a slight tilt to the frame, emphasizing the continuous motion and the textures of the fabric.",240 +114,"An aerial shot of the ocean, capturing a mesmerizing maelstrom forming in the water, swirling violently before revealing the fiery depths below. The water churns with intense energy, creating a whirlpool effect that stretches from the surface to the murky depths. The swirling currents illuminate the underwater landscape, showcasing a vivid array of colors and textures, as if the ocean floor is alight with hidden fires. The camera angle provides a dramatic overhead view, emphasizing the dynamic motion and the vastness of the ocean.",240 +115,"A dynamic push shot through an ocean research outpost, capturing the bustling activity within. The camera moves through the entrance, revealing scientists in lab coats working at various stations, their faces focused and determined. The background shows rows of advanced scientific equipment, tanks filled with marine life, and large screens displaying complex data. The walls are adorned with charts and posters, adding to the academic atmosphere. The lighting shifts between the bright, fluorescent lights of the labs and the natural light streaming in from large windows overlooking the ocean. The outpost has a modern, utilitarian design, with sleek metal and glass structures. The camera angle provides a sense of movement and urgency, emphasizing the importance of the ongoing research.",1440 +116,"A vibrant concert stage scene in the style of a music video, featuring a woman in the spotlight, singing passionately. She stands confidently on the stage, microphone in hand, with a captivating expression on her face. The bright light behind her creates a dramatic silhouette, casting a warm glow over her. She wears a stylish, form-fitting black dress with intricate silver embroidery, emphasizing her graceful movements. The background features a blurred stage with colorful lights and banners advertising the event. A dynamic medium shot capturing the singer from a slightly elevated angle, highlighting her performance and the dramatic lighting effects.",1440 +117,"An over-the-shoulder shot of a determined woman in a white sports bra and black running shorts sprinting down a dusty trail, her gaze fixed on a rocket launching into the sky in the distance. Her hair flows behind her, and she pumps her arms for extra speed and momentum. The background shows a vast landscape with rolling hills and sparse trees, and the rocket trails a bright white plume against the clear blue sky. The camera angle captures her focused determination and the expansive scenery, emphasizing both her movement and the grandeur of the launch.",1440 +118,"A vibrant and dynamic illustration in the style of a nature documentary, featuring a dragon-toucan walking gracefully through the vast grasslands of the Serengeti. The dragon-toucan has iridescent green and blue feathers, with a long, curved beak and large, expressive eyes. It strides confidently across the savannah, its wings slightly spread for balance. The background showcases a rich tapestry of African wildlife, with zebras, gazelles, and elephants in the distance. The sun is setting, casting a warm golden glow over the landscape. The camera angle is from a low, ground-level perspective, capturing the dragon-toucan in motion as it moves through the grass.",1440 +119,"A dramatic and surreal photograph in a realistic style, capturing an abandoned warehouse where vibrant flowers are blooming from the cracked concrete walls. The flowers are diverse, ranging from wild daisies to delicate roses, their colors vivid and varied. The space is dimly lit, with shadows cast by the uneven concrete surfaces. The camera angle is low, emphasizing the growth and生命力, with a sense of nature reclaiming the urban environment. The background shows the remnants of old machinery and graffiti, adding to the desolate yet hopeful atmosphere. A close-up shot from a slightly downward angle, highlighting the contrast between the harsh industrial setting and the blooming flowers.",1440 +120,"A side profile shot of a woman with a dramatic backdrop of fireworks exploding in the distance. The woman has long flowing hair cascading down her back, and she gazes intently into the distance, her expression filled with a mix of wonder and excitement. She wears a elegant red dress with intricate lace detailing and a fitted bodice. The fireworks create a vibrant display of colors and light, casting a magical glow on her face. The background is blurred, capturing the burst of colors and smoke from the explosions. The photo has a dynamic and celebratory atmosphere. A medium shot with a slight tilt to the camera angle.",1440 +121,"A vibrant anime illustration in a dynamic motion style of a pink pig running rapidly towards the camera in a narrow alley in Tokyo. The pig has large, round eyes and a playful expression, with its ears perked up and body slightly hunched forward. It is wearing a small, pink bow tie, adding a cute touch to its appearance. The background showcases the bustling Tokyo alley, with colorful signs and neon lights reflecting off the wet pavement. The scene is captured from a low-angle perspective, emphasizing the pig's energetic movement.",720 +122,"A surreal digital art piece depicting a majestic bird gently landing on the surface of a tranquil lake, transforming into a sleek fish mid-mutation. The bird has vibrant plumage, with long wings spread wide as it touches the water. As it transforms, its body elongates and turns silver, fins forming from its wings and legs. The fish retains some bird-like features, such as large eyes and a curved beak. The background showcases a serene lakeside, with soft ripples on the water and gentle sunlight casting a warm glow. The scene has a dreamy, ethereal quality, with a slight blur effect on the surroundings. A medium shot from a slightly elevated angle, capturing the transformation in motion.",240 +123,"A dynamic tennis photograph in a realistic sports style, capturing a powerful serve from a determined woman. She stands tall and focused, her right arm extended forward with a tennis racket, about to hit the ball with fierce determination. Her left hand steadies the racket, and her legs are slightly bent, ready for the next move. She wears a white tennis outfit with a red trim, and her hair flows behind her as she pivots to make contact. The background shows a tennis court with blurred spectators in the stands, and the net is clearly visible. The sun casts a bright spotlight on her, highlighting her athletic form. A mid-shot from a slightly elevated angle, emphasizing her powerful motion.",240 +124,"A high-resolution photograph in a realistic style, capturing a green lizard in the act of catching a bug. The lizard has a vibrant green body with small black spots, and its sharp, reptilian eyes are focused intently on its prey. It is perched on a leaf, with its tail coiled around the stem for balance. The bug, likely a cricket or similar small insect, is just within reach, and the lizard's tongue is extended, poised to snatch it. The background is a lush, tropical forest with dense foliage and sunlight filtering through the leaves, creating dappled shadows. The photo has a crisp, clear texture, emphasizing the natural movement and detail. A medium shot from a slightly elevated angle, highlighting the lizard's dynamic action.",240 +125,"A dramatic and surreal scene in the style of a fantasy comic, a lightning bolt strikes a turtle in the middle of a tranquil lake, instantly transforming it into a fierce alligator. The alligator, now with the distinctive features of an alligator, including a longer snout and sharper teeth, stands in the water, its body contorted from the shock. The lake background shows ripples and splashes, with the water reflecting the stormy sky. The alligator's eyes are wide with surprise, and its skin is covered in tiny scales. The lighting is intense, with flashes of lightning illuminating the scene. A dynamic close-up from a slightly elevated angle, capturing the transformation and the alligator's immediate reaction.",240 +126,"A cyberpunk-style digital illustration of a metal skull growing muscle tendons and flesh, set in a dystopian urban environment. The skull's bones are partially covered by newly formed muscle tissue and skin, giving it a grotesque yet almost lifelike appearance. The background features a blurred cityscape with neon lights, rusted buildings, and graffiti-covered walls. The scene has a gritty, high-contrast texture. The perspective is from a low angle, capturing the skull in a close-up shot.",240 +127,"A dynamic action shot in the style of a high-energy sports illustration, depicting a fencer in mid-sprint, blade raised, and feet barely touching the ground. The fencer, a young man with taut muscles and focused expression, swings his sword with precision and speed. His hair flows behind him, and his eyes lock onto his opponent. The background is a blurred arena, with spectators in the distance, creating a sense of urgency and excitement. The fencer's clothing is a sleek black fencing outfit, and his face is partially obscured by his mask. A close-up shot from a low angle, emphasizing the intensity of the moment.",1440 +128,"A whimsical illustration in a soft watercolor style of a curious cat peeking out from a cozy, woven basket hidden behind a pile of fluffy cushions. The cat has large, expressive green eyes and a fluffy white fur coat with a black tipped tail. It is perched on one paw, ears pricked up, and its whiskers twitch as it gazes intently at something just beyond the viewer's line of sight. The background features a warm, inviting living room with hints of sunlight filtering through a window, casting a gentle glow on the scene. The basket is intricately detailed with patterns and textures. A close-up shot from a slightly lower angle, capturing the cat's entire body and the subtle play of light on its fur.",720 +129,"A vintage drag racing scene in a classic film noir style, featuring a group of six muscle cars lined up at the starting line of a straight asphalt strip. Each car, adorned with chrome accents and distinctive paint jobs, revs its engine loudly, smoke billowing from their exhausts. The cars are positioned side by side, ready to race, with the front wheels slightly lifted in anticipation. The background is a blurred, sunlit highway with faded road markings and distant buildings. A wide-angle shot captures the intense moment just before the race begins, emphasizing the dynamic movement and the roaring engines.",1440 +130,"A detailed realistic photograph captures a German Shepherd gently placing a butterfly that landed on its nose onto a colorful flower. The dog, with its alert and curious expression, appears tender and gentle. Its fur is short and sleek, with a brown and white coat, and it stands in a slightly crouched position, focusing intently on the flower. The background features a lush garden with green foliage and other flowers, creating a harmonious and natural setting. The photo has a clear and crisp focus, highlighting the interaction between the dog and the butterfly. A close-up shot from a low angle.",1440 +131,"A hyperrealistic portrait of a monstrous creature with its mouth closing, rendered in a detailed photorealistic style. The monster has a large, elongated snout with sharp fangs and a rough, textured skin that resembles old leather. Its eyes are wide and intense, with pupils narrowing as it closes its mouth. The creature's jaw muscles flex as it moves, adding to its dynamic expression. The background is a blurred forest scene with dense foliage and sunlight filtering through the leaves, creating a mysterious and eerie atmosphere. A medium shot with a slightly angled perspective.",1440 +132,"A high-resolution photograph capturing a pole vaulter in mid-flight, showcasing perfect form and precision. The athlete, a tall and muscular individual with a focused expression, leaps gracefully over the bar. The pole is bent sharply as it transfers energy, propelling the vaulter upwards. The background is blurred, revealing only a hint of the indoor track with a vaulting pit below. The scene has a dynamic, athletic feel, emphasizing the fluidity and power of the jump. The camera angle is from a slight angle, highlighting the vertical trajectory of the vaulter.",240 +133,"A vibrant and dynamic illustration in the style of a children's fantasy book, depicting a brown bear sitting in a vintage car, looking out the window with a curious expression. The bear has fluffy fur, big round eyes, and a small nose. It wears a red scarf and gloves, and its paws rest on the steering wheel. The car is an old-fashioned model with a wooden exterior and shiny chrome accents. The background features a forest landscape with tall trees, wildflowers, and a winding road leading to the horizon. The sky is clear with fluffy clouds. The scene captures the bear's playful and adventurous spirit, with a medium shot from a slightly behind-the-car angle, highlighting the bear's interaction with the vehicle.",1440 +134,"A whimsical digital art piece in a cartoon style depicting a cactus with googly eyes dancing gracefully in the breeze. The cactus is adorned with vibrant green spines and large, round, black googly eyes that seem to sparkle. It stands upright with its arms outstretched, swaying gently as if it were a lively dancer. The background features a soft, pastel landscape with patches of wildflowers and a gentle, flowing breeze. The scene is filled with natural movement, capturing the cactus in mid-dance. The camera angle is from a slight overhead view, emphasizing the dynamic pose and the playful spirit of the cactus.",720 +135,"A dramatic and dynamic moment captured in a realistic photographic style, featuring a golden retriever dog leaping into a pool to rescue a child. The dog is mid-jump, its legs stretched forward and its fur glistening in the sunlight. It appears determined and heroic. The child, partially submerged in the water, looks up at the dog with gratitude and relief. The pool is clear and blue, with ripples creating a splash effect. The background shows a sunny backyard with a wooden deck and some greenery. A high-angle shot captures the action from above, emphasizing the heroic effort of the dog.",720 +136,"A dramatic digital painting in the style of an epic fantasy, depicting humans walking into a dragon's open jaws as they descend into the underworld. The dragon has a massive, scaled body with a deep emerald green hue, and its teeth are sharp and menacing. The humans are small figures, one male and one female, dressed in ancient robes, their expressions filled with fear and determination. They hold torches, casting flickering shadows on the dragon's inner walls. The background features a dark, cavernous underworld with glowing red eyes of fireflies and jagged rocks. The scene is rendered in a high-detailed, cinematic style with a sense of depth and movement. The camera angle is from below, looking up at the dragon's open jaws, capturing the dramatic descent into the underworld.",720 +137,"A dramatic action scene in the style of a Hollywood crime thriller, a police helicopter hovers above a high-speed chase through a city street. The helicopter's rotors spin rapidly, creating a whirlwind effect. The suspect, a male in a dark hoodie and jeans, speeds away in a black sedan, tires screeching. Officers on the ground, armed and alert, follow closely behind, their faces tense and focused. The background features a bustling cityscape with tall buildings and neon signs, the streets filled with cars and pedestrians. The helicopter's camera angle provides a bird's-eye view, capturing the intense moment of pursuit. The scene is rendered in high-definition, with sharp contrasts and dynamic lighting. A medium shot from a low-angle overhead perspective.",240 +138,"An American-style promotional poster featuring a woman in a green jacket and brown boots practicing her archery skills at an outdoor range. She stands with a focused expression, holding a recurve bow and a quiver of arrows on her back. Her hair flows naturally behind her as she aims at the target. The background shows a blurred outdoor setting with a clear blue sky, patches of grass, and some trees in the distance. A slight wind blows, adding a dynamic element to the scene. The photo has a high-resolution, realistic texture. A medium shot from a slightly elevated angle capturing her determined pose.",1440 +139,"A dynamic action shot in a rugged mountainous landscape, a woman in a vibrant red parka leaps over a brown bear standing on its hind legs. The woman's long, wavy hair flows behind her as she mid-jump, her face filled with determination and excitement. The bear has a fierce expression, with its mouth open in a growl. The background features dense forest with tall trees and patches of sunlight filtering through the canopy. The photo has a dramatic, high contrast style, capturing the raw energy and tension of the moment. A high-angle shot emphasizing the woman's leap.",240 +140,"A dynamic action shot of a futsal squad displaying their skills on an indoor court. The team consists of five players, each wearing vibrant uniforms with their team logos prominently displayed. The players are in various positions: one player is mid-kick, another is about to receive the ball, a third is dribbling skillfully, and two others are preparing for a quick pass. The court is clearly marked with lines, and the ball bounces smoothly across the surface. The lighting highlights the intense focus and determination on their faces. The background shows a blurred indoor arena with spectators in the stands, creating a lively atmosphere. The photo captures the energy and teamwork of the squad, with a slightly elevated camera angle providing a clear view of the action.",720 +141,"A vibrant and dynamic illustration in the style of a children's storybook, depicting a kangaroo leaping through a bustling cityscape. The kangaroo is energetic and agile, with a playful expression and soft, furry brown fur. It is mid-jump, its hind legs stretched out and its front paws slightly off the ground, tail swishing behind it. The city is alive with tall skyscrapers, colorful advertisements, and busy streets filled with people and vehicles. The background shows a mix of bright neon lights and the occasional green tree, creating a lively and vibrant urban environment. The kangaroo's movements are fluid and natural, capturing the essence of its lively nature. A dynamic side-angle shot, emphasizing the kangaroo's motion.",720 +142,"A lively and dynamic digital illustration in a cartoon style of a squirrel leaping gracefully from one tree branch to another. The squirrel has fluffy brown fur, large round eyes, and a bushy tail that swishes as it moves. It appears alert and agile, mid-jump with its front paws extended towards the next branch. The background showcases a dense forest with tall trees, green leaves, and dappled sunlight filtering through. A bird is perched on a nearby branch, adding to the natural scene. The squirrel’s movements are fluid and natural, capturing the essence of its lively nature. A medium shot with a slight upward angle.",240 +143,"A dynamic illustration in a manga style depicting two cats and dogs engaged in a fierce sword fight. One cat, with sleek black fur and green eyes, holds a silver sword aloft, while the other, a fluffy white dog with brown eyes, lunges forward with a wooden sword. Both animals display intense focus and determination, their bodies tensed and ready for action. The background features a blurred garden setting with hints of green foliage and flowers. The scene is captured from a low-angle perspective, emphasizing the movement and energy of the battle.",720 +144,"A dynamic and lively scene in the style of a watercolor painting, where a fish leaps out of a glass fish tank and swims gracefully around a person's head mid-air. The fish has vibrant scales and gills flapping, creating ripples in the imaginary water droplets around it. The person appears surprised and amused, with an open-mouthed expression and slightly tilted head, looking up at the airborne fish. The background features a blurred aquarium with hints of colorful aquatic plants and a few other fish swimming calmly below. The lighting is soft and diffused, adding a dreamy quality to the scene. The camera angle is from a low, upward perspective, capturing the moment of the fish's leap.",720 +145,"A realistic photograph in a gritty urban setting, capturing a tow truck expertly pulling a stranded car onto its platform. The tow truck driver, wearing a rugged work uniform and a determined expression, operates the crane with precision. The car, with its hood slightly open, appears to have mechanical issues. The background shows a busy city street with other vehicles and pedestrians in the distance, giving the scene a dynamic and bustling atmosphere. The tow truck is positioned at a slight angle, highlighting the tension and effort required to lift the car. The photo has a high-resolution, documentary-style texture. A medium shot with the tow truck in the foreground and the cityscape in the background.",720 +146,"A vibrant and dynamic cooking scene in the style of a lively food documentary, featuring a skilled cook expertly flipping golden pancakes on a griddle. The cook, a middle-aged man with a warm smile and neat chef's hat, moves confidently with each flip, the pancakes sizzling and releasing a delightful aroma. His apron is slightly stained with flour, and he holds a spatula poised for another flip. The background shows a bustling kitchen with countertops filled with ingredients and appliances, and a blurred view of other chefs working behind him. The lighting highlights the cook's movements and the golden-brown pancakes, creating a warm and inviting atmosphere. A dynamic medium shot capturing the cook from a slightly elevated angle, emphasizing his fluid and energetic movements.",240 +147,"A realistic photograph capturing a dynamic scene where a sleek black cat with piercing green eyes is energetically chasing a tiny brown mouse across a lush green field. The mouse scampers towards an underground burrow, its tail flicking behind it as it frantically tries to escape. The cat's expression shifts from focused determination to disappointment as it realizes the mouse has disappeared into the hole. The field is dotted with wildflowers and tall grasses swaying gently in the breeze. The background is blurred, highlighting the tension and movement of the moment. A medium shot from a slightly elevated angle, emphasizing the cat's hopeful pursuit and the mouse's desperate dash.",240 +148,"A heartwarming family moment captured in a gentle, soft focus photograph. A parent, likely a mother, stands behind a young child, both laughing and enjoying the simple joy of swinging. The mother wears a warm, casual outfit suitable for a sunny day at the park, her expression full of love and joy. The child, with bright, curious eyes, leans back in the swing, arms outstretched. The background features a clear blue sky with fluffy clouds, and a few trees providing a natural frame. The swing set is old but sturdy, adding to the nostalgic feel. The camera angle is slightly elevated, capturing the interaction between the two in a medium shot, emphasizing their shared happiness and bond.",240 +149,"A dramatic action scene in the style of a classic adventure film, featuring a man standing confidently on a small fishing boat, battling a massive fish that thrashes wildly in the water. The man, with rugged facial features and determined expression, grips a fishing rod tightly, his muscles strained. The fish, with a shimmering silver body and fierce eyes, leaps out of the water, creating a splash. The boat rocks violently, adding tension to the scene. The background shows turbulent waters and a cloudy sky, with distant waves breaking against the shore. The photo has a gritty, realistic texture, capturing the raw power and struggle between man and nature. A dynamic medium shot from a slightly elevated angle, emphasizing the intensity of the moment.",720 +150,"A detailed and vibrant illustration in the style of a nature documentary, depicting a dragonfly gracefully flying over a delicate pink flower, with its wings glistening in the sunlight. Beside it, a hummingbird perches on another nearby flower, its feathers shimmering in various hues of green and purple. The dragonfly has large, transparent wings and a slender body, while the hummingbird is small and agile, with a long, thin beak. The background features a lush garden with soft green leaves and colorful wildflowers, creating a serene and harmonious environment. The camera angle captures the dragonfly from below, while the hummingbird is shown from a side view, emphasizing their natural movements and interactions.",240 +151,"A vibrant and dynamic street art illustration depicting a chimpanzee performing a backflip on a skateboard on a bustling city sidewalk. The chimp is agile and energetic, mid-air with its legs extended and arms outstretched, showcasing its acrobatic skills. It has a playful expression, with mischievous eyes and a slight grin. The skateboard is colorful and adorned with stickers, adding to the lively scene. The background features a busy cityscape with tall buildings, people walking, and cars passing by, creating a lively urban environment. The chimp is wearing a small, round cap and a backpack. A close-up shot from a slightly elevated angle, capturing the excitement and movement.",1440 +152,"A dynamic seal training scene in a vibrant water park style, capturing a large, playful seal eagerly catching a fish tossed by its trainer. The seal has a sleek, black coat and bright, curious eyes, leaping gracefully out of the water to catch the fish mid-air. The trainer, wearing a colorful aquatic outfit, stands beside the pool, tossing the fish with enthusiasm. The background features a clear, shimmering pool with rippling water and some aquatic plants. A close-up shot from a slightly elevated angle, emphasizing the seal's agile movements and joyful expression.",1440 +153,"A whimsical and surreal illustration in the style of a modern comic, depicting a fish walking confidently into a cozy coffee shop. The fish is depicted with large, expressive eyes and a friendly smile, wearing a small, stylish hat. It holds a piece of paper with a handwritten note that reads, ""Can I please have a cup of coffee?"" The background features a warm, inviting coffee shop with wooden tables, comfortable chairs, and a barista preparing drinks behind the counter. The shop is filled with the aroma of freshly brewed coffee and the soft hum of conversation. The fish's tail moves naturally as it walks, creating ripples in the water droplets clinging to its scales. A close-up shot from a slightly elevated angle, capturing the fish's interaction with the shop's patrons.",240 +154,"A vibrant underwater scene in the style of a marine biology illustration, featuring a trio of seahorses gracefully holding onto seagrass with their tails. Each seahorse has a distinctive pattern on its body, ranging from deep blues and greens to lighter aquas and whites. Their tails wrap tightly around the swaying seagrass, which moves gently in the current. The seahorses have expressive eyes and small, delicate fins that flutter softly. The background showcases a rich variety of marine life, including colorful coral and various fish swimming around. The water is clear and filled with tiny bubbles rising to the surface. A close-up shot from a slightly elevated angle, capturing the intricate details of the seahorses and their environment.",720 +155,"A high-end culinary photography style shot of a skilled chef meticulously drizzling a glossy red sauce onto a pristine white plate. The chef, a middle-aged man with a neatly trimmed beard and a focused expression, holds a fine bottle in one hand and a sharp knife in the other. His movements are precise and deliberate, each drop of sauce landing perfectly on the plate. The background is a clean, modern kitchen with stainless steel appliances and sleek countertops, providing a stark contrast to the vibrant sauce. The lighting is soft yet dramatic, highlighting the texture and shine of the sauce. A close-up shot from a slightly elevated angle, capturing both the chef's hands and the final result.",240 +156,"A whimsical cartoon illustration in a vibrant and colorful style, depicting a small green frog leaping into a magical kiss, transforming mid-air into a creamy chocolate milkshake. The frog's legs and arms stretch out as if frozen in time, while its eyes widen in surprise. The milkshake is richly colored, with swirls of chocolate and foam on top, and a sprinkle of chocolate chips. The background is a fantastical, dreamlike landscape with floating clouds and twinkling stars. A dynamic aerial view, capturing the moment of transformation.",720 +157,"A synchronized diving photo in a realistic sports style, capturing two young divers performing a synchronized dive into a clear blue pool. Both divers are in mid-air, their bodies perfectly aligned and streamlined, arms and legs extended. Their expressions are focused and determined. One diver is wearing a black cap and a blue swimsuit, while the other is in a white cap and a red swimsuit. The water around them is blurred, creating a sense of speed and fluidity. The background shows the edge of the pool with spectators in the stands, creating a vibrant and energetic atmosphere. A high-angle shot emphasizing the synchronization and grace of the dive.",720 +158,"A dramatic and fiery scene from a sci-fi concept art piece, where a guitar is being swallowed by a volcanic eruption, engulfed in intense magma. The guitar, made of dark wood and adorned with intricate carvings, struggles against the molten lava that flows around it. The volcano's crater is wide open, with steam and ash rising into the air, casting an ominous shadow over the molten landscape. The camera angle is from a low, ground-level perspective, capturing the raw power and chaos of the eruption. The background features rugged, rocky terrain and glowing hot lava flows, creating a surreal and awe-inspiring environment. The texture of the magma is vivid and realistic, highlighting the intense heat and movement of the molten rock. A close-up shot emphasizing the struggle of the guitar within the erupting volcano.",240 +159,"A dynamic and lively hamster illustration in a bright cartoon style, capturing the hamster energetically running on a spinning wheel. The hamster has a playful expression, with round cheeks and alert eyes focused on the wheel. It is wearing a small, colorful harness that matches its cheerful demeanor. The background features a cozy, wooden cage with a checkered floor and some toys scattered around, adding to the hamster’s homey environment. The spinning wheel is intricately detailed, with spokes and a small door that opens and closes as it turns. The scene is captured from a slightly elevated angle, emphasizing the hamster’s movement and the intricate details of its surroundings.",240 +160,"A dynamic photograph in a realistic documentary style captures a yellow school bus chugging up a steep hill. The bus's engine roars loudly as it conquers the incline, smoke billowing from the exhaust. The bus is filled with children and teachers, their expressions a mix of excitement and concentration. The hillside is rugged with patches of green grass and wildflowers, and the trees on either side stretch towards the sky. The sunlight casts a golden glow on the scene, highlighting the bus and its passengers. The camera angle is slightly elevated, providing a clear view of the bus's determined climb.",240 +161,"A mystical Chinese ink painting depicting a crescent blue moon slowly rising over a serene mountain landscape. The moon appears ethereal and glowing, casting a soft, bluish light on the tranquil scene. Mountains in the distance are outlined in ink, with a few pine trees standing tall against the night sky. The foreground features a small stream with ripples reflecting the moonlight. A few bamboo shoots are scattered around, adding to the serene atmosphere. The sky transitions from deep indigo to lighter shades of blue as dawn approaches. A bird can be seen flying towards the moon, adding a sense of movement and life to the composition. A medium shot with a slightly upward angle.",1440 +162,"A dynamic and action-packed illustration in a cartoony yet realistic style, depicting a group of bears figuring out how to launch a rocket. The bears are diverse in appearance—some are brown, others are black, and one is even a polar bear. They stand around a small, partially assembled rocket, with tools and parts scattered around them. The bears look excited and determined, with various expressions ranging from concentration to anticipation. One bear is using a wrench, another is adjusting a circuit board, and a third is pointing towards the rocket, gesturing enthusiastically. The background shows a forest setting with tall trees, undergrowth, and a clear sky with fluffy clouds. The scene captures a moment of intense focus and teamwork. The camera angle is slightly elevated, providing a bird's-eye view of the bears and their work.",240 +163,"A whimsical, cartoon-style illustration depicting dogs as poker players at The World Series of Poker. The dogs are drinking large bowls of water in a very sloppy manner, causing water to splash onto the cards and the green felt of the poker table. One dog, with a tilted head in confusion, looks up at the camera. The background features a blurred casino setting with slot machines and poker chips scattered about. The dogs have playful expressions and are dressed in small, oversized suits. A close-up shot from a slightly elevated angle, capturing the chaotic and humorous scene.",1440 +164,"A dynamic scene captured in the style of a vibrant food photography shoot, showcasing a chef expertly tossing a salad in a large ceramic bowl. The chef, with a lively expression and focused intensity, moves with grace and precision, the salad spinning gracefully in the air before landing back in the bowl with a satisfying clatter. The chef is dressed in a crisp white chef's coat and black pants, with a white hat perched on his head. The background is a clean, modern kitchen with stainless steel appliances and a backdrop of warm, soft lighting that highlights the freshness of the ingredients. A mid-shot from a slightly elevated angle, capturing both the chef's action and the vibrant salad.",1440 +165,"A high-energy motorcycle stunt scene, capturing a daring backflip mid-air over a ramp. The stunt rider, wearing a black helmet and racing服, soars through the air with intense concentration and a fierce expression. The motorcycle spins gracefully, its wheels barely touching the ramp as it executes the backflip. The background features a blurred outdoor setting with a bright blue sky and distant mountains, emphasizing the dynamic movement and the thrill of the stunt. A dynamic shot from a low-angle perspective, highlighting the rider's momentum and the dramatic arc of the flip.",720 +166,"A serene night scene in traditional Chinese countryside style, depicting a rural road under a starry sky with the full moon hanging high. The road winds through lush fields, with the leaves and grass on both sides swaying gently, intermittently, and slowly in the breeze. The stars twinkle brightly overhead, casting a soft glow over the landscape. The path is quiet and peaceful, with a gentle rustling of leaves and grass creating a soothing ambiance. A wide-angle shot capturing the vastness of the night sky and the tranquil road.",720 +167,"A charming photograph in a soft, warm lighting style, capturing a toddler sitting on a cozy carpet, happily sharing a chocolate chip cookie with a cute teddy bear. The toddler has rosy cheeks, big bright eyes, and a gentle smile, reaching out to offer the cookie to the bear, which also has a friendly expression, leaning in to accept it. The teddy bear is dressed in a small red shirt and blue pants, adding to the whimsical scene. The background features a simple, wooden coffee table with a few colorful toys scattered around, and a large window letting in soft sunlight. A medium shot with a slight angle emphasizing the interaction between the child and the bear.",1440 +168,"A dynamic beach scene captured in a vibrant watercolor style, depicting a man standing at the shoreline, tossing a brown stick into the waves. The man, with tousled sandy blonde hair and a casual summer shirt, has a joyful expression as he throws the stick. His cat, a sleek gray tabby with green eyes, leaps excitedly towards the stick, mid-jump, tail flicking energetically. The background features clear blue skies, rolling waves, and a few seagulls flying overhead. Sand dunes stretch out behind them, with a few other beachgoers in the distance. A mid-shot from a slightly elevated angle, capturing both the man and the cat in action.",240 +169,"A dynamic photograph capturing a marathon runner in the final moments of a grueling race, crossing the finish line. The runner, a young man with a determined expression, is sprinting with arms pumping and legs striding forcefully. His face is flushed, and he is breathing heavily, sweat glistening on his forehead and body. He is wearing a white sports jersey with ""Marathon"" printed on the back, and black running shorts with sponsor logos. The background is blurred, revealing a crowd cheering and a banner reading ""Finish Line."" The finish line itself is marked by a colorful tape, and the runner's shadow stretches out behind him, emphasizing his momentum. The photo has a vibrant and energetic feel, capturing the intense moment of victory. A medium shot from a slightly elevated angle, focusing on the runner's determined expression and the blur of the crowd.",1440 +170,"A dramatic and surreal scene in a post-apocalyptic style, depicting a crumbling building slowly sinking into a pool of molten lava. The building is a dilapidated structure with cracked walls and broken windows, covered in soot and ash. The lava is a deep, glowing red with small bubbles rising to the surface, casting flickering shadows on the building. The air is thick with smoke and steam, creating a hazy, otherworldly atmosphere. The camera angle is from a low, ground-level perspective, emphasizing the vastness of the lava and the impending doom of the building.",720 +171,"A dramatic and dynamic moment captured in the style of a wildlife documentary, featuring a penguin flying into the open mouth of a blue whale as it breaks the surface of the ocean. The penguin is in mid-flight, wings spread wide, with a determined look on its face. The blue whale’s massive mouth is wide open, revealing its cavernous interior and rows of baleen plates. The background is a vast, deep blue sea with ripples caused by the whale’s breach, and a few seagulls flying overhead. The scene is bathed in natural sunlight, casting a warm glow on the water. The camera angle is from below, looking up at the action.",1440 +172,"A dramatic space scene in the style of a sci-fi movie poster, featuring a sleek silver spaceship being forcefully pulled into a swirling black hole. The spaceship is engulfed in a bright glow, with its hull reflecting the intense gravitational pull. The black hole is surrounded by a halo of shimmering particles and distorted starlight, creating a surreal and terrifying atmosphere. The background shows a vast cosmic void with distant galaxies and nebulae faintly visible. The spaceship is in a low-angle shot, emphasizing its struggle against the powerful gravitational force.",1440 +173,"A dynamic and chaotic scene in a dense forest during a heavy rainstorm, capturing a real girl frantically running through the foliage. Her wild hair flows behind her as she sprints, her arms flailing and her face contorted in fear and desperation. Behind her, various animals—rabbits, deer, and birds—are also running, creating a frenzied atmosphere. The girl's clothes are soaked, clinging to her body, and she is screaming and shouting as she tries to escape. The background is a blur of greenery and rain-drenched trees, with occasional glimpses of the darkening sky. A wide-angle shot from a low angle, emphasizing the urgency and chaos of the moment.",720 +174,"A detailed golfing scene in the style of a professional tournament photo, capturing a golfer sinking a long putt on the green. The golfer, a well-built Caucasian man with a focused expression, stands confidently with his left foot slightly forward, his right knee bent, and his club poised just behind the ball. His eyes are fixed intently on the ball, which sits on the edge of the cup. The green is lush and well-manicured, with a subtle slope leading to the cup. The background shows other greens, fairways, and trees in the distance, with a clear blue sky overhead. The golfer's stance is dynamic, with his arms extended and muscles tense, ready to make the perfect stroke. A medium shot from a slightly elevated angle, emphasizing the golfer's determined pose and the challenge of the putt.",1440 +175,"A traditional Chinese painting-style portrait of a middle-aged woman sipping a steaming cup of tea. She has warm, golden-brown skin and gentle, kind eyes that reflect the warmth of the moment. Her long black hair is tied back in a loose bun, and she wears a simple yet elegant qipao with intricate floral embroidery. She sits gracefully on a bamboo stool, her fingers gently cradling the porcelain cup. The background features a serene teahouse interior with wooden floors, paper lanterns hanging from the ceiling, and a small bonsai tree in a corner. A low-angle shot capturing her thoughtful expression as she enjoys her tea.",240 +176,"A dynamic photograph in a naturalistic style captures an orange cat leaping onto a kitchen counter. The cat's fur glistens in the warm light, and its eyes gleam with excitement as it spots the butter. It arches its back and extends its front paws to grasp the edge of the counter, mid-jump. The background shows a partially blurred kitchen scene with countertops, utensils, and appliances, hinting at a busy home environment. A close-up shot from a slightly lower angle, emphasizing the cat's playful and determined expression.",720 +177,"A dynamic softball game photograph capturing a player sliding safely into second base. The player, a young woman with short blonde hair and determined expression, moves with swift momentum, her legs bent and arms outstretched. Her uniform, a bright red jersey with white sleeves and black shorts, is taut against her athletic frame. She wears protective knee pads and cleats, her hands gripping the ball securely. The background shows a blurred baseball field with spectators in the stands, cheering and waving flags. The camera angle is slightly from behind, capturing the intense moment of her feet touching the base. The photo has a crisp, high-definition quality, emphasizing the action and emotion. A mid-shot with a slight upward angle.",240 +178,"A dynamic skate park scene in the style of a high-energy action sports video, capturing a group of skilled skateboarders performing impressive tricks on ramps and rails. The lead skateboarder, a young man with short brown hair and a determined expression, is mid-air, doing a flip over a metal rail, his board arcing gracefully through the air. Another skateboarder, a teenage girl with long blonde hair flowing behind her, is grinding smoothly along a wooden ramp, her body slightly crouched and her arms outstretched for balance. A third skateboarder, a boy with a skateboard helmet and a mischievous grin, is sliding down a steep concrete ramp, his board gliding effortlessly. The background features a bustling skate park with other skaters in the distance, a few onlookers cheering, and a graffiti-covered wall in the backdrop. The camera angle captures the action from a low, slightly elevated position, emphasizing the height and speed of the tricks.",240 +179,"A dynamic and lively scene in the style of a children's picture book, featuring a playful ferret tossing a red rubber ball with its mouth. The ferret has a sleek, brown coat and curious, mischievous eyes, standing on all fours with a joyful expression. Behind the ferret, a cute and energetic golden retriever puppy is chasing the ball with wagging tail and pricked ears. The puppy runs with bounding steps, its white fur contrasting against the green grass. The background shows a lush, sunny garden with blooming flowers and a few birds perched on branches. The photo has a warm and cheerful feel, capturing the moment of pure joy and companionship. A medium shot from a slightly elevated angle, focusing on the interaction between the two animals.",720 +180,"A vibrant and lively illustration in a whimsical cartoon style depicts a small golden retriever dog dancing joyfully in a sparkling pink tutu. The dog lifts one paw while wagging its tail, with a mischievous grin on its face. It strides confidently down a bustling city street, surrounded by tall buildings and busy pedestrians. The background features a colorful mix of street signs, parked cars, and passing bicycles. A dynamic mid-shot from a slightly elevated angle captures the dog's energetic movement and playful expression.",1440 +181,"A bustling ancient Chinese marketplace filled with lively activity. Merchants sell colorful spices and intricately patterned fabrics from large woven baskets and bolts. The air is rich with the scent of exotic spices like cinnamon and cardamom. Stalls are lined up side by side, each offering a variety of goods. Customers haggle with sellers, their voices blending into a harmonious cacophony. The background features a vibrant mix of red lanterns hanging overhead, wooden stalls with intricate carvings, and a bustling crowd in traditional attire. The scene is captured in a dynamic, high-angle shot, capturing the energy and movement of the marketplace.",120 +182,"A stunning Santorini landscape photo captured during the blue hour, featuring a red panda and a toucan strolling hand-in-hand through the picturesque village. The red panda, with its distinctive reddish-brown fur and large round eyes, carries a small backpack, while the toucan, with its vibrant orange and black feathers and a large curved beak, holds a colorful flower. They walk along a winding cobblestone path, passing by whitewashed buildings with blue doors and windows. The setting sun casts a soft golden glow, creating a warm and serene atmosphere. The sky is painted with shades of blue and purple, with a few twinkling stars beginning to appear. A wide-angle shot from a slightly elevated angle, capturing the intimate moment between these two unlikely friends.",120 +183,"A surreal scene in the style of a magical realism painting, featuring a person drinking tea from a cup made of ice that never melts. The person, a young woman with fair skin and wavy brown hair tied in a loose bun, has a serene and contemplative expression. She wears a simple white blouse and black pants, sitting on a wooden stool under a large, ancient tree with shimmering leaves. The background is filled with floating snowflakes and misty clouds, creating a dreamlike atmosphere. The cup, made of an ethereal, glowing ice, catches the light and reflects it back in mesmerizing patterns. A close-up shot from a slightly elevated angle, capturing the intricate details of the ice cup and the woman's tranquil face.",120 +184,"A photograph in a warm, candid style captures a middle-aged man's joyful face illuminated with genuine happiness as he receives a heartfelt compliment. The man, with a friendly smile and twinkling eyes, appears to be standing in a cozy living room, perhaps at a social gathering. He wears a casual shirt and jeans, his hair neatly combed but with a few loose strands falling over his forehead. The background is blurred, revealing soft lighting and a few other guests in the background, adding to the intimate and welcoming atmosphere. A close-up shot from a slightly lower angle, emphasizing his delighted expression.",120 +185,"A dramatic scene in the style of an action movie, where gold coins spill out as the elevator doors open. The elevator interior is sleek and modern, with metallic panels and a few flickering lights. A man in a business suit steps out, looking surprised and pleased. The coins fall in a cascade, creating a glittering shower. The background features a blurred view of the hallway, with a faint outline of office doors and a distant fluorescent light. The camera angle is from below, capturing the man's reaction and the falling coins. A close-up shot with dynamic motion.",120 +186,"A vibrant and lively street scene in Boston, captured in a whimsical comic book style, features a giant duck strutting confidently through the city. The duck has a golden yellow body with black feathers and a wide orange bill. It waddles with a playful gait, its feet leaving small splashes in the puddles. The duck wears a tiny bow tie and sunglasses, adding a touch of humor. The background shows blurred images of iconic Boston landmarks like the Boston Common and the Massachusetts State House, with the skyline visible in the distance. Pedestrians and cars are seen in the background, creating a bustling city atmosphere. The duck looks directly at the viewer, its expression full of curiosity and mischief. A medium shot from a slightly elevated angle.",120 +187,"An old man in blue jeans and a white t-shirt taking a pleasant stroll in Johannesburg, South Africa, during a vibrant and colorful festival. He walks with a gentle sway, his weathered face reflecting a sense of contentment. The festival is bustling with activity, featuring multicolored decorations, lively music, and people in festive attire. The background showcases a mix of traditional African and modern elements, with colorful banners and street vendors. The old man's hands rest casually in his pockets, and he looks around, enjoying the lively atmosphere. The scene is captured in a warm and inviting style, with a slight focus on the old man from a medium shot angle.",120 +188,"A dynamic urban scene in a realistic photography style, capturing a large truck navigating through a bustling city street during rush hour. The truck is moving smoothly with its wheels spinning slightly, following the flow of traffic and pedestrians. The driver looks focused, with the steering wheel turned slightly to the right. The background features a mix of tall buildings, crowded sidewalks, and cars honking in the dense traffic. Pedestrians hurry past, some carrying shopping bags or briefcases. The air is filled with the sounds of horns and chatter, creating a lively atmosphere. The photo has a sharp focus and a natural color palette, emphasizing the movement and energy of the city. A medium shot from a slightly elevated angle, capturing both the truck and the surrounding environment.",120 +189,"A bustling train station in the heart of a vibrant city, captured in the style of a vibrant urban street scene. The station is packed with people in various outfits, rushing to catch their trains or waiting anxiously. A young man in a casual shirt and jeans stands near a large digital clock, checking his phone. His expression is a mix of impatience and curiosity. The background features a mix of modern architectural elements, including sleek glass buildings and colorful advertisements. The lighting is warm and inviting, with natural sunlight streaming through large windows. A dynamic medium shot with a slightly elevated angle, capturing the energy and movement of the crowd.",120 +190,"A vibrant and lively scene in Johannesburg, South Africa, captured in a colorful festival atmosphere. A woman wearing purple overalls and cowboy boots takes a pleasant stroll, her steps rhythmic and joyful. Her face is filled with delight, and she carries a small bag slung over one shoulder. The festival is bustling with activity, featuring colorful decorations, vibrant costumes, and lively music. People of various ethnicities mingle, their laughter and chatter adding to the festive mood. The background is a blend of traditional African patterns and modern cityscapes, with bright lights and stalls selling local crafts and foods. The camera angle captures her from behind, showing her full stride and the joyous expressions of those around her. The overall scene is captured in a warm and dynamic style, emphasizing the energy and spirit of the festival. A mid-shot from a slightly elevated angle.",120 +191,"A high-fantasy painting style depiction of a young artist wearing a hooded cloak and holding a spray paint can, standing on the side of a flying spaceship. The artist has messy brown hair and intense, determined eyes, focused intently on their work. The spaceship has intricate designs and glowing lights, with wings spread wide and a trail of sparks behind it. The background features swirling cosmic clouds and distant galaxies, creating a surreal and ethereal atmosphere. The artist is mid-spray, with paint splatters flying in the air, capturing a dynamic moment of action. A close-up shot from a slightly elevated angle.",120 +192,"A close-up shot of sparkling water being poured into a glass, capturing the detailed flow and bubbles as they rise and burst on the surface. The glass is clear and tall, with a slender stem. The water flows smoothly, creating ripples and tiny bubbles that dance and scatter across the liquid's surface. The background is blurred, showcasing a soft, warm ambient light that highlights the vibrant play of light and shadow on the water. The scene has a crisp, high-definition texture, emphasizing the dynamic movement of the water.",120 +193,"A macro realistic style photograph of an elderly man wearing an antique diving helmet with dark glass and a jetpack. He stands on the intricate veins of a large, lush leaf, his steps deliberate and steady. The man has a weathered face with deep wrinkles and a determined expression. His arms are slightly bent, supporting the jetpack, which adds a sense of balance and purpose. The leaf's veins are detailed and vibrant, with hints of green and brown, creating a striking contrast with the man's attire. The background is blurred, showing a hint of sunlight filtering through, casting dappled shadows. A close-up macro shot from a slightly elevated angle.",120 +194,"A vibrant and dynamic scene capturing a young man's eyes widening in amazement as he steps into a surprise party. The man, with lively brown eyes and a youthful, open expression, stands in the center of a room filled with friends and family, all dressed in colorful party attire. He wears a casual white t-shirt and jeans, with a slight smile spreading across his face. The background features a mix of decorations, including balloons, streamers, and a banner that reads ""Surprise!"" in bold letters. The room is brightly lit, with warm, ambient lighting creating a festive atmosphere. The camera angle is from below, capturing the man's reaction with a sense of excitement and joy.",120 +195,"A clay model being slowly deformed as it is pressed and molded into a new shape by hand. The clay is a rich brown color, and the model, originally a simple figure, is gradually taking on a more complex form. The sculptor, a middle-aged man with weathered hands and focused expression, gently presses and molds the clay with precision. His movements are deliberate and steady, and the clay yields to his touch, revealing intricate details like folds and textures. The background is a dimly lit studio with shelves filled with various tools and other clay models. The camera angle is from the side, capturing both the sculptor's hands and the transformation of the clay. A close-up shot with a slight tilt to emphasize the process.",120 +196,"A dynamic hip-hop dance scene in a vibrant urban style, featuring an Asian girl in a bright yellow T-shirt and white pants. She is mid-dance move, arms stretched out and feet rhythmically stepping, exuding energy and confidence. Her hair is tied up in a ponytail, and she has a mischievous smile on her face. The background shows a bustling city street with blurred reflections of tall buildings and passing cars. The scene captures the lively and energetic atmosphere of a hip-hop performance, with a slightly grainy texture. A medium shot from a low-angle perspective.",120 +197,"A dynamic action shot in the style of a high-energy sports photo, capturing a base jumper accelerating after leaping off a cliff. The jumper is mid-air, arms extended and legs bent, body tilted forward in free-fall. The sky is vast and blue, with clouds in the distance, creating a dramatic contrast against the rugged cliff edge below. The background features blurred rocky terrain and dense forest, adding depth to the scene. The jumper's expression is intense and focused, conveying the thrill and adrenaline of the moment. A high-angle shot emphasizing the vastness of the sky and the sheer drop below.",120 +198,"A cinematic landscape in the style of a romantic drama, capturing a couple walking hand in hand along a sandy beach as the sun sets over the vast ocean. The man, with tousled brown hair and a gentle smile, wears a casual white shirt and jeans, while the woman, with flowing blonde hair and a serene expression, is dressed in a light blue sundress. They walk towards the horizon, their shadows elongating as the sky turns a gradient of pinks, oranges, and purples. The beach is lined with seagulls and scattered shells, and the water reflects the golden hues of the setting sun. The camera slowly zooms out, providing a sweeping view of the entire scene, emphasizing the tranquility and romance of the moment. A wide-angle shot from a slightly elevated perspective.",120 +199,"A serene and tranquil photo-style image of a pedestal rising from the surface of a pond, breaking the surface tension to reveal the lily pads and their reflections. The pedestal is slightly weathered, with moss growing along its edges. The lily pads float gracefully on the water, their green surfaces glistening under the sunlight. The reflections in the water create a mirror-like effect, doubling the beauty of the scene. The background features a lush green environment with tall reeds and aquatic plants, and a few ducks swimming nearby. The water ripples gently, adding a sense of movement and life to the composition. A medium shot from a slightly elevated angle, capturing both the pedestal and the surrounding water and reflections.",120 +200,"An adorable kangaroo, wearing blue jeans and a white t-shirt, takes a pleasant stroll through the streets of Mumbai, India, during a winter storm. The kangaroo moves gracefully, its pouch empty but ready. The cityscape is blurred in the background, with tall buildings and narrow lanes visible through the swirling snow. The kangaroo's fur is slightly damp from the rain, and it occasionally stops to sniff the air. The storm adds a dramatic flair, with lightning illuminating the scene and strong winds creating a sense of movement. The photo has a vibrant, almost surreal quality, capturing both the unexpected and the whimsical. A dynamic shot from a slightly elevated angle, emphasizing the kangaroo's natural and joyful movement.",120 +201,"A dynamic and bustling first-person experience of walking through a vibrant market, with colorful stalls lining both sides of the narrow alleyway. The scene is filled with the lively chatter and enthusiastic calls of vendors selling fruits, vegetables, spices, and textiles. The air is thick with the sweet scent of ripe mangoes and the pungent aroma of freshly ground spices. People move past you, their faces animated with the excitement of haggling and bargaining. The camera follows your path, capturing the vibrant array of goods displayed on each stall—brightly colored fabrics, exotic fruits piled high, and aromatic herbs arranged in neat rows. The background is a chaotic yet harmonious blend of bustling activity, with the sun casting warm, golden hues through the gaps in the canopy overhead. A series of medium shots from various angles, emphasizing the energy and movement of the crowd.",120 +202,"A vibrant and lively celebration scene in the style of a music festival photo. A group of diverse people, including East Asians, Africans, and Caucasians, are enthusiastically clapping and cheering. They have joyful expressions, with some smiling widely and others raising their hands in excitement. The crowd is standing in a semi-circle around a stage, with a DJ booth and a large speaker system visible. The background features colorful balloons, banners with ""Happy Anniversary"" written in bold letters, and a backdrop of fireworks in the distance. The camera angle is from slightly above, capturing the dynamic energy of the crowd.",120 +203,"A winter storm scene in Johannesburg, South Africa, where a woman walks leisurely with a gentle breeze blowing. She wears a vibrant green dress and a sun hat, adding a pop of color against the gloomy sky. Her steps are steady and graceful, and she carries an umbrella, shielding herself from the rain. The background features tall buildings and bustling streets, with blurred silhouettes of people and vehicles in the distance. The sky is overcast, with dark clouds and occasional flashes of lightning, creating a dramatic yet serene atmosphere. A medium shot capturing her walking down the street from a slightly elevated angle.",120 +204,"A dynamic and chaotic scene captured in the style of a realistic action photo, depicting a shopping cart careening down a steep hill, its wheels spinning rapidly. The cart collides with a parked car, causing groceries to scatter across the ground. The shopping cart is filled with various items, including fruits, vegetables, and canned goods, spilling out in a messy pile. The car is slightly dented from the impact, with its doors partially open. The background shows a residential street with blurred houses and trees in the distance, suggesting a busy neighborhood. The photo captures the moment of collision from a low-angle perspective, emphasizing the movement and chaos.",120 +205,"A macro shot in realistic style of a man wearing an antique diving helmet with dark glass and a jetpack, standing on a molten lava surface. He strides confidently, his body slightly bent forward, with a determined expression. Behind him, a majestic dragon soars through the sky, its wings spreading wide and scales glistening in the flickering light. The background is a dramatic landscape with smoldering volcanic peaks and swirling clouds, creating a sense of otherworldly danger and adventure. The man’s muscles are flexed, and his arms are outstretched as he walks, adding a dynamic quality to the scene. A medium shot with a slight tilt upwards, emphasizing both the man and the flying dragon.",120 +206,"A vintage-style illustration of a Rocket Man in a spacesuit, complete with a black glass face shield, sitting inside a sleek, retro-futuristic spaceship. The spaceship is flying through a large, intricate blood vessel, with the interior of the vessel filled with large, pulsating red blood cells. The Rocket Man appears determined, with a focused expression, and his hands are placed firmly on the control panel. The background shows the walls of the blood vessel with detailed, swirling patterns, giving the scene a dynamic and vivid feel. The spaceship has a smooth, metallic surface with subtle pinstripes and a few dents, adding to its vintage charm. The camera angle is slightly from below, capturing the Rocket Man and the spaceship mid-flight through the blood vessel.",120 +207,"A dynamic and lively moment captured in a vibrant pop art style, showing a young woman jumping up and down with joy, her movements full of energy and excitement. She dances energetically, her arms flailing and legs kicking in the air. Her face is filled with happiness and a wide smile. She wears a colorful floral dress that flows with her movements. The background features a blurred cityscape with hints of tall buildings and bright lights, giving the scene a bustling urban feel. A mid-shot from a slightly low angle, capturing the full range of her joyful dance.",120 +208,"A serene autumn landscape photo, capturing the gentle filtering of sunlight through a dense canopy of colorful leaves. The leaves, a mix of golden, orange, and crimson hues, create a warm, dappled pattern on the forest floor below. The scene is bathed in soft, natural light, enhancing the rich, vibrant colors. A medium shot from a slightly elevated angle, emphasizing the intricate play of light and shadow.",120 +209,"A dark neon-inspired rainforest scene, glowing with fantastical fauna and animals. The forest is lush and dense, with towering trees covered in bioluminescent moss and vines. Neon hues of green, blue, and purple illuminate the area, casting a surreal glow on the creatures within. Various exotic and fantastical animals, including glowing butterflies, neon frogs, and luminescent birds, flit about the forest, adding to its otherworldly charm. The camera captures a medium shot, focusing on a group of these magical creatures as they interact in the vibrant, glowing environment.",120 +210,"A realistic photograph capturing a middle-aged woman coughing into her hand, her eyes squinting due to the force of the cough. She has a concerned and slightly pained expression, her face slightly flushed. Her hands are covered in a light layer of dust from the cough, and she appears to be standing in a dimly lit room with peeling wallpaper and a few old, broken pieces of furniture. The background is blurry, revealing only faint shadows of a cluttered space. A close-up shot from a slightly lower angle, emphasizing her distressed facial expression.",120 +211,"A dynamic camera arc shot capturing a golden retriever barking fiercely at a scurrying gray squirrel in the garden. The dog stands alert, its tail wagging nervously, while its expressive brown eyes focus intently on the tiny rodent. The squirrel pauses mid-jump, turning to face the dog with quick, curious movements. The background features a lush green lawn dotted with wildflowers and a few scattered trees. The air is filled with the scent of freshly cut grass and the sound of distant birds chirping. The photo has a vibrant, naturalistic style, emphasizing the lively interaction between the two animals.",120 +212,"A vibrant and dynamic digital art piece in the style of a modern dance performance, depicting a person dancing energetically under the moonlight. The dancer, with flowing, flowing black hair and glowing skin, is performing a graceful yet powerful routine. Their shadow, which has come to life, dances alongside them, distorted and elongated, creating a surreal and captivating scene. The background features a blurred night sky with stars and a crescent moon, adding to the ethereal atmosphere. The camera angle is from a slightly elevated position, capturing both the dancer and their animated shadow in a medium shot.",120 +213,"A high-energy action shot of a skier racing down a steep slope during a downhill competition. The skier, a fit and determined individual with a helmet and goggles, is in mid-ski with both poles planted firmly in the snow. They are wearing a bright red ski suit with white stripes, exuding confidence and speed. The background is a blurred mix of snowy trees and distant mountains, with the sky starting to lighten, indicating early morning conditions. The camera angle is from below, capturing the dynamic motion and the thrill of the race.",120 +214,"An old man in vibrant purple overalls and sturdy cowboy boots takes a leisurely stroll through Antarctica during a lively and colorful festival. His weathered face and twinkling eyes reflect a sense of joy and wonder. The festival is filled with vibrant decorations and people in festive attire, creating a unique blend of warmth and cold. The background shows the stark yet beautiful Antarctic landscape, with icebergs and snow-covered mountains in the distance. The sky is painted with hues of orange, pink, and purple, adding to the festive atmosphere. The old man moves with a gentle sway, his hands clasped behind his back, enjoying the moment. The scene is captured from a slightly elevated angle, emphasizing the contrast between the man and the vast, icy landscape.",120 +215,"A realistic style paper origami dragon riding a boat through waves, with intricate folds and textures. The dragon has a fierce expression, its eyes glowing with intensity, and its scales shimmering in the sunlight. It is perched on the edge of the boat, wings partially spread, ready to take flight. The boat bobs up and down with the waves, creating a dynamic motion. The water is choppy, with ripples and splashes around the boat, adding to the sense of movement. The background features a clear blue sky with fluffy clouds, and a few seagulls flying overhead. A mid-shot capturing the dragon's powerful stance and the boat's motion.",120 +216,"A vibrant anime illustration in a dynamic, thick-line painting style of a young girl blowing a kiss to the camera. She has long flowing hair that cascades down her back, framed by soft bangs that partially cover her eyes. The girl wears a colorful floral dress with ruffled sleeves and a delicate belt. She has bright, sparkling eyes and a sweet, joyful smile. Her lips are parted, and she blows a kiss towards the camera with a playful and innocent expression. The background is a blurred outdoor setting with a gentle sunset, highlighting warm hues of orange and pink. A close-up shot from a slightly tilted angle, capturing the moment of her kiss.",120 +217,"A close-up shot of a baby with wide-open eyes sucking on a pacifier. The baby has soft, rosy cheeks and a small nose with a hint of down. The baby's eyes are full of wonder and curiosity, looking directly at the viewer. The pacifier is securely held between the baby's lips, and the baby's tiny hands rest gently on the cheeks. The background is softly blurred, revealing a warm and cozy nursery with pastel-colored walls and a few toys scattered on the floor. The overall atmosphere is gentle and serene, capturing the innocence and joy of early childhood.",120 +218,"A cinematic trailer in the style of a heartwarming coming-of-age film, showcasing a group of playful Samoyed puppies learning to become chefs. The puppies, with their fluffy white coats and bright eyes, gather around a colorful kitchen filled with pots, pans, and ingredients. They wag their tails excitedly as they attempt to mix batter and fold dough under the watchful eye of a wise, elderly dog. The puppies’ expressions range from determined to mischievous, with one puppy accidentally knocking over a stack of plates. The background transitions between warm, inviting kitchen scenes and glimpses of the puppies’ playful antics outside. The camera angles vary from wide shots of the puppies working together to close-ups capturing their joyful faces. A soft, uplifting score plays in the background, enhancing the sense of adventure and growth.",120 +219,"A serene watercolor painting depicting a mother otter floating gracefully on her back in a tranquil river. The otter cradles her playful pup on her stomach, gently keeping it warm and safe in the gentle current. The pup's small paws dangle in the water, while the mother's fur glistens in the soft sunlight. The background features a lush forest with tall trees reflected in the river, and a few wildflowers dotting the banks. The water has a soft, ethereal quality, emphasizing the peacefulness of the scene. A medium shot capturing the tender interaction between the mother and her pup from a slightly overhead angle.",120 +220,"A realistic photograph of a princess riding a horse across a river. The princess, with fair skin and delicate features, wears a flowing white gown with intricate lace detailing and a long veil. She sits gracefully on a sturdy, brown horse, her hands firmly gripping the reins. The horse's mane flows freely in the breeze, and its hooves kick up small splashes of water as it gallops across the river. The riverbank is lined with tall grasses and wildflowers, with a few trees providing shade. The background shows a misty landscape, with distant hills and a hint of blue sky peeking through the clouds. The photo captures a moment of natural movement, with the princess and horse seeming almost weightless as they cross the river. A medium shot from a slightly elevated angle, emphasizing the princess's determined expression and the horse's powerful stride.",120 +221,"A dynamic action shot in the style of a high-speed photography sequence, capturing a rubber band being stretched to its maximum length and then suddenly released. The rubber band snaps back to its original shape with a burst of energy, creating a vivid visual effect. The background is blurred, focusing attention on the rapid movement and tension release. The camera angle is from the side, emphasizing the elasticity and power of the rubber band.",120 +222,"A slow-motion video capturing the intricate process of pouring a drink into a classic martini glass, showcasing the detailed flow and splashes of the liquid as it cascades down the rim. The camera angle is slightly elevated, allowing viewers to see the fine droplets clinging to the glass and the ripples spreading across the surface. The background is a dimly lit bar, with soft lighting casting shadows and highlighting the elegance of the glass. The video has a cinematic quality, emphasizing the fluidity and artistry of the pour. A medium shot with dynamic camera movement following the flowing liquid.",120 +223,"A cinematic pull-out from a close-up of a beautifully handwritten letter, gradually revealing a person sitting at a wooden desk, lost in deep thought. The letter, penned in elegant cursive, is placed on the desk, partially folded. The person, with slightly furrowed brows and a faraway gaze, appears engrossed in the contents of the letter. The background shows a cluttered but organized workspace, with books, papers, and a half-filled cup of coffee nearby. The lighting is soft and warm, casting gentle shadows. A medium shot with a slightly elevated camera angle, capturing both the letter and the person’s contemplative expression.",120 +224,"A close-up shot of a pair of chopsticks delicately picking up a piece of sushi and dipping it into a small dish of soy sauce. The chopsticks are held by a person with skilled fingers, their hands steady and precise. The sushi is fresh and colorful, with a slice of fish and rice perfectly balanced. The soy sauce dish is ceramic, with a glossy finish and a slight reflection of the chopsticks. The background is a traditional Japanese dining room, with a low table and ornate decorations. The lighting is soft and warm, highlighting the textures and colors. A medium close-up with a slight tilt, capturing the moment of the chopsticks touching the soy sauce.",120 +225,"A winter storm rages in Antarctica, with fierce winds and heavy snow creating a dramatic backdrop. A woman in a green dress and a sun hat takes a pleasant stroll, her steps steady and confident. Her dress flows slightly with the wind, and she holds her sun hat securely in place with one hand. The snow-covered landscape is blurred and ethereal, with distant mountains and icebergs peeking through the storm. The woman's face is slightly tilted向上,眼中闪烁着坚定与从容。A medium shot capturing her walking through the storm, with the camera angle slightly elevated to emphasize her resilience.",120 +226,"A whimsical illustration in a cartoon style, depicting a fluffy white rabbit with large floppy ears holding a glowing crescent moon on its back. The rabbit has big, round eyes and a small nose, with a playful smile on its face. It is mid-flight, wings slightly spread, moving gracefully through the night sky. The background features a starry night with a full moon and twinkling stars, creating a serene and magical atmosphere. A dynamic aerial view capturing the rabbit in mid-flight.",120 +227,"A soft and intimate moment captured in a warm and cozy living room setting. A woman with long flowing brown hair sings gently to a baby swaddled in a soft blanket. Her lips move softly, forming tender words as she holds the baby close. The woman wears a simple yet elegant dress, with a gentle smile on her face. The baby, with wide-eyed curiosity, listens intently. The background features a few scattered toys and a fireplace with a warm glow. The lighting is soft and diffused, creating a warm and inviting atmosphere. A close-up shot from a slightly lower angle, capturing both the woman and the baby.",120 +228,"A dramatic skydiving scene in a realistic photographic style, capturing a skydiver accelerating during free fall. The skydiver, a young man with a determined expression, is mid-air with arms outstretched and legs extended. His body is in dynamic motion, creating a sense of speed and tension. The background features a vast blue sky with fluffy clouds, contrasting sharply with the intense focus on the skydiver. The camera angle is from below, looking up at the skydiver as he descends rapidly, emphasizing his powerful leap. The photo has a high-resolution, sharp texture, highlighting every detail of his athletic form and the rush of air around him. A medium shot with a slight downward angle.",120 +229,"A dynamic action shot in the style of a professional martial arts film, showcasing a young Asian martial artist delivering a powerful punch to break a wooden board. The martial artist is dressed in traditional black gi with white stripes down the sides, emphasizing his strength and agility. His expression is intense and focused, with a slight grimace as he connects with the board. His muscles are taut, and his stance is firm and balanced. The board splits cleanly in half, creating a satisfying crack. The background features a blurred indoor dojo with a wooden floor and hanging martial arts flags, adding to the authenticity of the scene. The camera angle is from the side, capturing the full power of the punch.",120 +230,"A dramatic tilt-down shot from a magnificent chandelier in a grand hall, showcasing the ornate decor and people mingling below. The chandelier itself is intricately designed with crystal prisms and gold filigree, casting a sparkling light on the room. The hall is lavishly decorated with gilded columns, intricate murals, and plush carpets. Guests in elegant attire are seen conversing and sipping cocktails, their faces illuminated by the soft, warm lighting. The background features a large, arched window with a view of the night sky, adding depth to the scene. The overall style is opulent and classical, reminiscent of a high society gala.",120 +231,"An adorable kangaroo wearing purple overalls and cowboy boots takes a pleasant stroll through the bustling streets of Mumbai, India, during a winter storm. The kangaroo's fur is soft and fluffy, with large, expressive eyes and a playful smile. It hops along confidently, its overalls and boots adding a touch of whimsy to the scene. The background features a mix of colorful Indian street vendors, rickshaws, and tall buildings, with the storm clouds casting dramatic shadows. The storm is fierce yet beautiful, with heavy rain and strong winds, creating a dynamic and enchanting atmosphere. The kangaroo pauses occasionally to inspect its surroundings, adding a sense of curiosity and wonder. A mid-shot with a slightly elevated camera angle, capturing both the kangaroo and the vibrant cityscape.",120 +232,"A close-up shot of a Chinese child eagerly eating dumplings. The child has dark, curly hair tied into a ponytail and large, curious eyes. They wear a traditional red and gold jacket with intricate embroidery, and their face is framed by a delicate, round face. The dumplings are steaming hot, with visible fillings peeking out, and the child's fingers are stained with sauce. The background shows a cluttered dining table with other dishes and toys, creating a warm and cozy home environment. The photo has a soft, natural lighting and a warm color palette. A close-up shot capturing the child's joyful expression and the food.",120 +233,"A vibrant and dynamic illustration in the style of a fairy tale, depicting a person conducting an orchestra of flowers. Each flower is blooming and playing a different musical note, their petals moving gracefully in time with the music. The person, dressed in a flowing, pastel-colored gown, has a serene and focused expression, arms elegantly extended to guide the flowers. The background is a lush, enchanted garden with intricate patterns and magical elements, such as glowing mushrooms and sparkling dewdrops. The scene is bathed in soft, warm lighting, creating a dreamlike atmosphere. A medium shot with a slightly elevated angle, capturing both the conductor and the orchestra of flowers.",120 +234,"A fairy tale-style illustration depicting a person walking on a path of glowing floating lily pads. The person wears a flowing white gown with intricate floral patterns and holds a lantern that casts a warm, golden glow. Each lily pad lights up with a soft, ethereal light as they step on it, creating a magical effect. The background features a tranquil pond with lotus flowers and serene water lilies, reflecting a peaceful twilight sky. The scene is rendered in a detailed, fantasy art style with smooth brushstrokes and a dreamy atmosphere. The camera angle is slightly elevated, capturing the person's graceful walk and the glowing lily pads beneath their feet.",120 +235,"A surreal and whimsical scene in the style of a fantasy illustration, depicting a person standing on a rooftop, their feet barely touching the ground as they plant flowers upside down into the ceiling. The person wears a colorful floral dress with intricate patterns and a mischievous smile, their hands deftly placing seeds and soil into small pots attached to the ceiling. The flowers grow upwards, their petals facing downwards, creating a vibrant and inverted garden. The background shows a city skyline with distant buildings and a clear blue sky, adding to the fantastical atmosphere. The lighting is soft and ethereal, highlighting the unusual setting. A close-up shot from a slightly elevated angle, capturing the person's joyful expression and the upside-down flowers.",120 +236,"A vibrant and lively photograph capturing a young woman with rosy cheeks and a delighted expression as she savoring a sumptuous meal. She has long flowing brown hair tied in a loose bun, with strands framing her face. Her eyes sparkle with joy, and her lips are curved into a warm smile. She is seated at a rustic wooden table, with a plate of steaming food in front of her. The background features a cozy dining room with soft lighting, warm wooden walls, and a few scattered books on a nearby shelf. The scene is filled with the aroma of delicious food, creating a warm and inviting atmosphere. A close-up shot from a slightly angled perspective, emphasizing her joyful expression and the mouth-watering meal.",120 +237,"A winter landscape photograph capturing the subtle beauty of a person exhaling in the chilly air. The foggy breath forms tiny clouds that condense and disperse with each exhale, creating a mesmerizing effect against the backdrop of a snowy forest. The person stands still, their breath creating intricate patterns in the air, casting a soft mist over the surrounding trees and bushes. The air is crisp and cold, with a hint of frost on the ground. The photo has a soft, ethereal quality, emphasizing the transient nature of the moment. A close-up shot from a slightly elevated angle, focusing on the interaction between the person and the environment.",120 +238,"A dramatic moment captured in a dynamic aerial photography style, showcasing a drone mid-air collision with a grand stone statue. The drone's propellers and body are shattered, pieces scattering in various directions. The statue, made of weathered stone, remains mostly intact but shows cracks along its surface. The background features a bustling cityscape with skyscrapers and busy streets, creating a stark contrast between the modern and ancient elements. The camera angle is from below, looking up at the collision from a low altitude, emphasizing the scale and impact of the event.",120 +239,"An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man.",120 +240,"A melancholic scene from a vintage film-style photograph captures a woman's lips trembling with sadness as she reads a farewell letter. Her eyes are filled with tears, and her expression conveys deep sorrow. She is seated at a wooden table, surrounded by old books and papers, creating a somber ambiance. The background is blurred, revealing only hints of a dimly lit room with a fireplace in the distance. The letter, held tightly in her hand, is partially visible, adding to the emotional intensity. A medium shot with a soft focus on her face.",120 diff --git a/Helios/eval/playground/results/all_models_merged.json b/Helios/eval/playground/results/all_models_merged.json new file mode 100644 index 0000000000000000000000000000000000000000..60e84bbeadd7f060b20babd6b2b7389087cec565 --- /dev/null +++ b/Helios/eval/playground/results/all_models_merged.json @@ -0,0 +1,31 @@ +{ + "num_models": 1, + "score_type": "rating", + "metrics": [ + "aesthetic", + "drifting_aesthetic", + "drifting_motion_smoothness", + "drifting_naturalness", + "drifting_semantic", + "motion_amplitude", + "motion_smoothness", + "naturalness", + "semantic", + "total_weighted_rating" + ], + "models": { + "toy-video": { + "aesthetic": 9, + "motion_amplitude": 3, + "motion_smoothness": 10, + "naturalness": 7, + "semantic": 8, + "drifting_aesthetic": 8, + "drifting_motion_smoothness": 10, + "drifting_naturalness": 10, + "drifting_semantic": 10, + "total_weighted_rating": 8.247 + } + }, + "rating_scale": 10 +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/aesthetic_results.json b/Helios/eval/playground/results/toy-video/aesthetic_results.json new file mode 100644 index 0000000000000000000000000000000000000000..9a3679d8ff2cd3b0921d60e4a8667b80f43d9b58 --- /dev/null +++ b/Helios/eval/playground/results/toy-video/aesthetic_results.json @@ -0,0 +1,17 @@ +{ + "metric": "aesthetic", + "average_score": 0.6564263701438904, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "aesthetic_score": 0.6802743077278137 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "aesthetic_score": 0.632578432559967 + } + ] +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/drifting_aesthetic_results.json b/Helios/eval/playground/results/toy-video/drifting_aesthetic_results.json new file mode 100644 index 0000000000000000000000000000000000000000..226fe467060e42542696d5b7217e56cc27e2bd7d --- /dev/null +++ b/Helios/eval/playground/results/toy-video/drifting_aesthetic_results.json @@ -0,0 +1,22 @@ +{ + "metric": "drifting_aesthetic", + "description": "Start-end contrast of aesthetic (first/last 15% frames)", + "average_drift_score": 0.027865678071975708, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "drift_aesthetic_score": 0.002410709857940674, + "start_aesthetic_score": 0.6802361011505127, + "end_aesthetic_score": 0.677825391292572 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "drift_aesthetic_score": 0.05332064628601074, + "start_aesthetic_score": 0.6535003185272217, + "end_aesthetic_score": 0.6001796722412109 + } + ] +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/drifting_motion_smoothness_results.json b/Helios/eval/playground/results/toy-video/drifting_motion_smoothness_results.json new file mode 100644 index 0000000000000000000000000000000000000000..92b33c049519425420f3fd6500ca8f08577f81e9 --- /dev/null +++ b/Helios/eval/playground/results/toy-video/drifting_motion_smoothness_results.json @@ -0,0 +1,22 @@ +{ + "metric": "drifting_motion_smoothness", + "description": "Start-end contrast of motion smoothness (first/last 15% frames)", + "average_drift_score": 0.0009624073235373065, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "drift_motion_smoothness_score": 0.0016874511579993978, + "start_motion_smoothness_score": 0.9880413336530265, + "end_motion_smoothness_score": 0.9897287848110259 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "drift_motion_smoothness_score": 0.0002373634890752152, + "start_motion_smoothness_score": 0.9948747067013198, + "end_motion_smoothness_score": 0.995112070190395 + } + ] +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/drifting_naturalness_results.json b/Helios/eval/playground/results/toy-video/drifting_naturalness_results.json new file mode 100644 index 0000000000000000000000000000000000000000..d36a8a7eccdae8ab584b1cf9b762016fd4882812 --- /dev/null +++ b/Helios/eval/playground/results/toy-video/drifting_naturalness_results.json @@ -0,0 +1,27 @@ +{ + "metric": "drifting_naturalness", + "description": "Start-end contrast of naturalness (first/last 15% frames)", + "average_drift_score": 0.0, + "num_videos": 2, + "model_name": "gpt-5.2-2025-12-11", + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "drift_naturalness_score": 0.0, + "start_naturalness_score": 0.0, + "end_naturalness_score": 0.0, + "start_raw_score": "1", + "end_raw_score": "1" + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "drift_naturalness_score": 0.0, + "start_naturalness_score": 0.75, + "end_naturalness_score": 0.75, + "start_raw_score": "4", + "end_raw_score": "4" + } + ] +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/drifting_semantic_results.json b/Helios/eval/playground/results/toy-video/drifting_semantic_results.json new file mode 100644 index 0000000000000000000000000000000000000000..84cb138ed4cfafa00bbcadb2e4f0cf238f798448 --- /dev/null +++ b/Helios/eval/playground/results/toy-video/drifting_semantic_results.json @@ -0,0 +1,24 @@ +{ + "metric": "drifting_semantic", + "description": "Start-end contrast of semantic consistency (first/last 15% frames)", + "average_drift_score": 0.006637156009674072, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "prompt": "A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity.", + "drift_semantic_score": 0.0044051408767700195, + "start_semantic_score": 0.2939550578594208, + "end_semantic_score": 0.2983601987361908 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "prompt": "An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man.", + "drift_semantic_score": 0.008869171142578125, + "start_semantic_score": 0.2703956365585327, + "end_semantic_score": 0.2615264654159546 + } + ] +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/merged_results.json b/Helios/eval/playground/results/toy-video/merged_results.json new file mode 100644 index 0000000000000000000000000000000000000000..1c62e1a2796f06ccb95f6417c53ad2f83fa12f81 --- /dev/null +++ b/Helios/eval/playground/results/toy-video/merged_results.json @@ -0,0 +1,74 @@ +{ + "rating_scale": 10, + "summary": { + "non_drifting": { + "aesthetic": { + "name": "Aesthetic", + "raw_score": 0.6564263701438904, + "normalized_score": 0.6564263701438904, + "rating": 9, + "num_videos": 2 + }, + "motion_amplitude": { + "name": "Motion Amplitude", + "raw_score": 0.12899818271398544, + "normalized_score": 0.12899818271398544, + "rating": 3, + "num_videos": 2 + }, + "motion_smoothness": { + "name": "Motion Smoothness", + "raw_score": 0.9922347277689807, + "normalized_score": 0.9922347277689807, + "rating": 10, + "num_videos": 2 + }, + "naturalness": { + "name": "Naturalness", + "raw_score": 0.5, + "normalized_score": 0.5, + "rating": 7, + "num_videos": 2 + }, + "semantic": { + "name": "Semantic", + "raw_score": 0.2817579507827759, + "normalized_score": 0.2817579507827759, + "rating": 8, + "num_videos": 2 + } + }, + "drifting": { + "drifting_aesthetic": { + "name": "Drifting Aesthetic", + "raw_score": 0.027865678071975708, + "normalized_score": 0.027865678071975708, + "rating": 8, + "num_videos": 2 + }, + "drifting_motion_smoothness": { + "name": "Drifting Motion Smoothness", + "raw_score": 0.0009624073235373065, + "normalized_score": 0.0009624073235373065, + "rating": 10, + "num_videos": 2 + }, + "drifting_naturalness": { + "name": "Drifting Naturalness", + "raw_score": 0.0, + "normalized_score": 0.0, + "rating": 10, + "num_videos": 2 + }, + "drifting_semantic": { + "name": "Drifting Semantic", + "raw_score": 0.006637156009674072, + "normalized_score": 0.006637156009674072, + "rating": 10, + "num_videos": 2 + } + }, + "total_weighted_rating": 8.247 + }, + "per_video": {} +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/motion_amplitude_results.json b/Helios/eval/playground/results/toy-video/motion_amplitude_results.json new file mode 100644 index 0000000000000000000000000000000000000000..8b701beb32e0ab3a5e68e81e74c03399a73d0adf --- /dev/null +++ b/Helios/eval/playground/results/toy-video/motion_amplitude_results.json @@ -0,0 +1,17 @@ +{ + "metric": "motion_fb", + "average_score": 0.12899818271398544, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "motion_fb": 0.19912056624889374 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "motion_fb": 0.05887579917907715 + } + ] +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/motion_smoothness_results.json b/Helios/eval/playground/results/toy-video/motion_smoothness_results.json new file mode 100644 index 0000000000000000000000000000000000000000..b93bbfe7df38a3ee9b1f2303dcb3088b9d98c8bd --- /dev/null +++ b/Helios/eval/playground/results/toy-video/motion_smoothness_results.json @@ -0,0 +1,17 @@ +{ + "metric": "motion_smoothness", + "average_score": 0.9922347277689807, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "motion_smoothness_score": 0.9896801291593404 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "motion_smoothness_score": 0.9947893263786209 + } + ] +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/naturalness_results.json b/Helios/eval/playground/results/toy-video/naturalness_results.json new file mode 100644 index 0000000000000000000000000000000000000000..8fdfc668e72eda738a55d926c366e156e5eaa627 --- /dev/null +++ b/Helios/eval/playground/results/toy-video/naturalness_results.json @@ -0,0 +1,21 @@ +{ + "metric": "naturalness", + "average_score": 0.5, + "num_videos": 2, + "model_name": "gpt-5.2-2025-12-11", + "num_frames_per_video": 16, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "naturalness_score": 0.25, + "raw_score": "2" + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "naturalness_score": 0.75, + "raw_score": "4" + } + ] +} \ No newline at end of file diff --git a/Helios/eval/playground/results/toy-video/semantic_results.json b/Helios/eval/playground/results/toy-video/semantic_results.json new file mode 100644 index 0000000000000000000000000000000000000000..39dc928ed3dea09c0b1b8e6830094237f5e9f089 --- /dev/null +++ b/Helios/eval/playground/results/toy-video/semantic_results.json @@ -0,0 +1,19 @@ +{ + "metric": "semantic", + "average_score": 0.2817579507827759, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "prompt": "A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity.", + "semantic_score": 0.29471662640571594 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "prompt": "An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man.", + "semantic_score": 0.2687992751598358 + } + ] +} \ No newline at end of file diff --git a/Helios/eval/utils/convert_json_to_excel.py b/Helios/eval/utils/convert_json_to_excel.py new file mode 100644 index 0000000000000000000000000000000000000000..ccde57bcead51bd544c8d429ead41c0725af6d62 --- /dev/null +++ b/Helios/eval/utils/convert_json_to_excel.py @@ -0,0 +1,136 @@ +import argparse +import json + +import pandas as pd + + +CUSTOM_ORDER = [ + "total_weighted_rating", + "aesthetic", + "motion_amplitude", + "motion_smoothness", + "semantic", + "naturalness", + "drifting_aesthetic", + "drifting_motion_smoothness", + "drifting_semantic", + "drifting_naturalness", +] + +SELECTED_METRICS = [ + "total_weighted_rating", + "aesthetic", + "motion_amplitude", + "motion_smoothness", + "semantic", + "naturalness", +] + + +def json_to_excel(json_path, excel_path=None, use_selected_metrics=False, show_raw_values=False, score_type=""): + with open(json_path, "r") as f: + data = json.load(f) + + models_data = data["models"] + df = pd.DataFrame.from_dict(models_data, orient="index") + + df.reset_index(inplace=True) + df.rename(columns={"index": "model_name"}, inplace=True) + + if use_selected_metrics: + available_cols = ["model_name"] + [col for col in SELECTED_METRICS if col in df.columns] + df = df[available_cols] + print(f"Selected {len(available_cols) - 1} metrics from available metrics") + + valid_order = ["model_name"] + [col for col in CUSTOM_ORDER if col in df.columns] + df = df[valid_order] + print(f"Kept {len(valid_order) - 1} metrics as specified in CUSTOM_ORDER") + + if excel_path is None: + excel_path = json_path.rsplit(".", 1)[0] + f"_{score_type}" + ".xlsx" + + with pd.ExcelWriter(excel_path, engine="openpyxl") as writer: + df.to_excel(writer, sheet_name="Models", index=False) + + metadata = pd.DataFrame( + { + "Property": ["timestamp", "num_models", "num_metrics", "filtered", "format"], + "Value": [ + data.get("timestamp", "N/A"), + data.get("num_models", len(models_data)), + len(df.columns) - 1, + "Yes" if use_selected_metrics else "No", + "Raw Values" if show_raw_values else "Percentage", + ], + } + ) + metadata.to_excel(writer, sheet_name="Metadata", index=False) + + worksheet = writer.sheets["Models"] + for idx, col in enumerate(df.columns): + max_length = max(df[col].astype(str).apply(len).max(), len(col)) + if idx < 26: + col_letter = chr(65 + idx) + else: + col_letter = chr(65 + idx // 26 - 1) + chr(65 + idx % 26) + worksheet.column_dimensions[col_letter].width = min(max_length + 2, 50) + + if col != "model_name" and pd.api.types.is_numeric_dtype(df[col]): + for row in range(2, len(df) + 2): # Start from row 2 (after header) + cell = worksheet[f"{col_letter}{row}"] + if cell.value is not None: + if col == "total_weighted_rating": + cell.number_format = "0.00" + elif show_raw_values: + cell.number_format = "0" + else: + cell.value = cell.value * 100 + cell.number_format = '0.00"%"' + + print(f"Conversion successful! Output file: {excel_path}") + print(f"Processed {len(df)} models with {len(df.columns) - 1} metrics") + print(f"Format: {'Raw values' if show_raw_values else 'Percentage'}") + + return excel_path + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + parser.add_argument("--json_file", type=str, required=True, help="Input JSON file path") + parser.add_argument( + "--excel_file", + type=str, + required=True, + help="Output Excel file path (optional, defaults to input filename.xlsx)", + ) + parser.add_argument("--filter", action="store_true", help="Use only metrics defined in SELECTED_METRICS list") + parser.add_argument( + "--score_type", + type=str, + choices=["raw", "normalized", "rating"], + default="rating", + help="Type of scores to use: 'raw', 'normalized', or 'rating'", + ) + + args = parser.parse_args() + + if args.score_type == "rating": + raw_value = True + else: + raw_value = False + + try: + json_to_excel( + args.json_file, + args.excel_file, + use_selected_metrics=args.filter, + show_raw_values=raw_value, + score_type=args.score_type, + ) + except FileNotFoundError: + print(f"Error: File not found {args.json_file}") + except json.JSONDecodeError: + print(f"Error: {args.json_file} is not a valid JSON file") + except Exception as e: + print(f"Error: {e}") diff --git a/Helios/eval/utils/extract_short_from_long.py b/Helios/eval/utils/extract_short_from_long.py new file mode 100644 index 0000000000000000000000000000000000000000..74ee4eb755721ed98e0c6c27a769e58bb8ac1ec3 --- /dev/null +++ b/Helios/eval/utils/extract_short_from_long.py @@ -0,0 +1,97 @@ +import argparse +import os +import subprocess +from pathlib import Path + + +def extract_first_n_frames(input_root, output_root, num_frames=81): + input_path = Path(input_root) + output_path = Path(output_root) + + for subfolder in input_path.iterdir(): + if not subfolder.is_dir(): + continue + + print(f"Processing folder: {subfolder.name}") + + output_subfolder = output_path / subfolder.name + output_subfolder.mkdir(parents=True, exist_ok=True) + + video_files = list(subfolder.glob("*.mp4")) + + for i, video_file in enumerate(video_files, 1): + original_name = video_file.stem + if "_ori" in original_name: + new_name = original_name.rsplit("_ori", 1)[0] + f"_ori{num_frames}.mp4" + else: + new_name = video_file.name + + output_file = output_subfolder / new_name + if os.path.exists(output_file): + print(f"Skipping existing file: {output_file}") + continue + + cmd = [ + "ffmpeg", + "-i", + str(video_file), + "-vframes", + str(num_frames), # Extract only first N frames + "-map", + "0", # Copy all streams (video + audio) + "-c", + "copy", # Try direct copy (fastest, preserves all parameters) + "-y", + str(output_file), + ] + + try: + result = subprocess.run(cmd, capture_output=True) + + if result.returncode != 0: + print(f" Direct copy failed for {video_file.name}, re-encoding...") + cmd = [ + "ffmpeg", + "-i", + str(video_file), + "-vframes", + str(num_frames), + "-c:v", + "libx264", # Re-encode video + "-qp", + "0", # Lossless quality + "-c:a", + "copy", # Copy audio directly + "-map", + "0", # Copy all streams + "-y", + str(output_file), + ] + subprocess.run(cmd, check=True, capture_output=True) + + print(f" [{i}/{len(video_files)}] {video_file.name} -> {new_name}") + except subprocess.CalledProcessError as e: + print(f" Error processing {video_file.name}: {e}") + continue + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Extract first N frames from videos") + parser.add_argument( + "--input", + type=str, + default="long", + help="Input root directory (default: current directory)", + ) + parser.add_argument( + "--output", + type=str, + default="short/0_from_long", + help="Output root directory (default: ./output_frames)", + ) + parser.add_argument("--frames", type=int, default=81, help="Number of frames to extract (default: 81)") + + args = parser.parse_args() + + extract_first_n_frames(args.input, args.output, args.frames) + print("\nDone!") diff --git a/Helios/eval/utils/third_party/ViCLIP/__init__.py b/Helios/eval/utils/third_party/ViCLIP/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/ViCLIP/simple_tokenizer.py b/Helios/eval/utils/third_party/ViCLIP/simple_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..b705017efb1bdb4818db44604b4bb4197c76cd60 --- /dev/null +++ b/Helios/eval/utils/third_party/ViCLIP/simple_tokenizer.py @@ -0,0 +1,147 @@ +import gzip +import html +import os +import subprocess +from functools import lru_cache + +import ftfy +import regex as re + + +def default_bpe(): + tokenizer_file = os.path.join("checkpoints", "ViCLIP/bpe_simple_vocab_16e6.txt.gz") + if not os.path.exists(tokenizer_file): + print(f"Downloading ViCLIP tokenizer to {tokenizer_file}") + wget_command = [ + "wget", + "https://raw.githubusercontent.com/openai/CLIP/main/clip/bpe_simple_vocab_16e6.txt.gz", + "-P", + os.path.dirname(tokenizer_file), + ] + subprocess.run(wget_command) + return tokenizer_file + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = ( + list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) + ) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8 + n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r"\s+", " ", text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe()): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split("\n") + merges = merges[1 : 49152 - 256 - 2 + 1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v + "" for v in vocab] + for merge in merges: + vocab.append("".join(merge)) + vocab.extend(["<|startoftext|>", "<|endoftext|>"]) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {"<|startoftext|>": "<|startoftext|>", "<|endoftext|>": "<|endoftext|>"} + self.pat = re.compile( + r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", + re.IGNORECASE, + ) + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + (token[-1] + "",) + pairs = get_pairs(word) + + if not pairs: + return token + "" + + while True: + bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except Exception: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word) - 1 and word[i + 1] == second: + new_word.append(first + second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = " ".join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = "".join(self.byte_encoder[b] for b in token.encode("utf-8")) + bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")) + return bpe_tokens + + def decode(self, tokens): + text = "".join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors="replace").replace("", " ") + return text diff --git a/Helios/eval/utils/third_party/ViCLIP/viclip.py b/Helios/eval/utils/third_party/ViCLIP/viclip.py new file mode 100644 index 0000000000000000000000000000000000000000..835fdbf59c2172442a99b98e20a8cb89d5911342 --- /dev/null +++ b/Helios/eval/utils/third_party/ViCLIP/viclip.py @@ -0,0 +1,216 @@ +import logging +import os + +import torch +from torch import nn + +from .simple_tokenizer import SimpleTokenizer as _Tokenizer +from .viclip_text import clip_text_l14 +from .viclip_vision import clip_joint_l14 + + +logger = logging.getLogger(__name__) + + +class ViCLIP(nn.Module): + """docstring for ViCLIP""" + + def __init__( + self, + tokenizer=None, + pretrain=os.path.join(os.path.dirname(os.path.abspath(__file__)), "ViClip-InternVid-10M-FLT.pth"), + freeze_text=True, + ): + super(ViCLIP, self).__init__() + if tokenizer: + self.tokenizer = tokenizer + else: + self.tokenizer = _Tokenizer() + self.max_txt_l = 32 + + self.vision_encoder_name = "vit_l14" + + self.vision_encoder_pretrained = False + self.inputs_image_res = 224 + self.vision_encoder_kernel_size = 1 + self.vision_encoder_center = True + self.video_input_num_frames = 8 + self.vision_encoder_drop_path_rate = 0.1 + self.vision_encoder_checkpoint_num = 24 + self.is_pretrain = pretrain + self.vision_width = 1024 + self.text_width = 768 + self.embed_dim = 768 + self.masking_prob = 0.9 + + self.text_encoder_name = "vit_l14" + self.text_encoder_pretrained = False #'bert-base-uncased' + self.text_encoder_d_model = 768 + + self.text_encoder_vocab_size = 49408 + + # create modules. + self.vision_encoder = self.build_vision_encoder() + self.text_encoder = self.build_text_encoder() + + self.temp = nn.parameter.Parameter(torch.ones([]) * 1 / 100.0) + self.temp_min = 1 / 100.0 + + if pretrain: + logger.info(f"Load pretrained weights from {pretrain}") + state_dict = torch.load(pretrain, map_location="cpu", weights_only=False)["model"] + self.load_state_dict(state_dict) + + # Freeze weights + if freeze_text: + self.freeze_text() + + def freeze_text(self): + """freeze text encoder""" + for p in self.text_encoder.parameters(): + p.requires_grad = False + + def no_weight_decay(self): + ret = {"temp"} + ret.update({"vision_encoder." + k for k in self.vision_encoder.no_weight_decay()}) + ret.update({"text_encoder." + k for k in self.text_encoder.no_weight_decay()}) + + return ret + + def forward(self, image, text, raw_text, idx, log_generation=None, return_sims=False): + """forward and calculate loss. + + Args: + image (torch.Tensor): The input images. Shape: [B,T,C,H,W]. + text (dict): TODO + idx (torch.Tensor): TODO + + Returns: TODO + + """ + self.clip_contrastive_temperature() + + vision_embeds = self.encode_vision(image) + text_embeds = self.encode_text(raw_text) + if return_sims: + sims = torch.nn.functional.normalize(vision_embeds, dim=-1) @ torch.nn.functional.normalize( + text_embeds, dim=-1 + ).transpose(0, 1) + return sims + + # calculate loss + + ## VTC loss + loss_vtc = self.clip_loss.vtc_loss(vision_embeds, text_embeds, idx, self.temp, all_gather=True) + + return { + "loss_vtc": loss_vtc, + } + + def encode_vision(self, image, test=False): + """encode image / videos as features. + + Args: + image (torch.Tensor): The input images. + test (bool): Whether testing. + + Returns: tuple. + - vision_embeds (torch.Tensor): The features of all patches. Shape: [B,T,L,C]. + - pooled_vision_embeds (torch.Tensor): The pooled features. Shape: [B,T,C]. + + """ + if image.ndim == 5: + image = image.permute(0, 2, 1, 3, 4).contiguous() + else: + image = image.unsqueeze(2) + + if not test and self.masking_prob > 0.0: + return self.vision_encoder(image, masking_prob=self.masking_prob) + + return self.vision_encoder(image) + + def encode_text(self, text): + """encode text. + Args: + text (dict): The output of huggingface's `PreTrainedTokenizer`. contains keys: + - input_ids (torch.Tensor): Token ids to be fed to a model. Shape: [B,L]. + - attention_mask (torch.Tensor): The mask indicate padded tokens. Shape: [B,L]. 0 is padded token. + - other keys refer to "https://huggingface.co/docs/transformers/v4.21.2/en/main_classes/tokenizer#transformers.PreTrainedTokenizer.__call__". + Returns: tuple. + - text_embeds (torch.Tensor): The features of all tokens. Shape: [B,L,C]. + - pooled_text_embeds (torch.Tensor): The pooled features. Shape: [B,C]. + + """ + device = next(self.text_encoder.parameters()).device + text = self.text_encoder.tokenize(text, context_length=self.max_txt_l).to(device) + text_embeds = self.text_encoder(text) + return text_embeds + + @torch.no_grad() + def clip_contrastive_temperature(self, min_val=0.001, max_val=0.5): + """Seems only used during pre-training""" + self.temp.clamp_(min=self.temp_min) + + def build_vision_encoder(self): + """build vision encoder + Returns: (vision_encoder, vision_layernorm). Each is a `nn.Module`. + + """ + encoder_name = self.vision_encoder_name + if encoder_name != "vit_l14": + raise ValueError(f"Not implemented: {encoder_name}") + vision_encoder = clip_joint_l14( + pretrained=self.vision_encoder_pretrained, + input_resolution=self.inputs_image_res, + kernel_size=self.vision_encoder_kernel_size, + center=self.vision_encoder_center, + num_frames=self.video_input_num_frames, + drop_path=self.vision_encoder_drop_path_rate, + checkpoint_num=self.vision_encoder_checkpoint_num, + ) + return vision_encoder + + def build_text_encoder(self): + """build text_encoder and possiblly video-to-text multimodal fusion encoder. + Returns: nn.Module. The text encoder + + """ + encoder_name = self.text_encoder_name + if encoder_name != "vit_l14": + raise ValueError(f"Not implemented: {encoder_name}") + text_encoder = clip_text_l14( + pretrained=self.text_encoder_pretrained, + embed_dim=self.text_encoder_d_model, + context_length=self.max_txt_l, + vocab_size=self.text_encoder_vocab_size, + checkpoint_num=0, + ) + + return text_encoder + + def get_text_encoder(self): + """get text encoder, used for text and cross-modal encoding""" + encoder = self.text_encoder + return encoder.bert if hasattr(encoder, "bert") else encoder + + def get_text_features(self, input_text, tokenizer, text_feature_dict={}): + if input_text in text_feature_dict: + return text_feature_dict[input_text] + text_template = f"{input_text}" + with torch.no_grad(): + # text_token = tokenizer.encode(text_template).cuda() + text_features = self.encode_text(text_template).float() + text_features /= text_features.norm(dim=-1, keepdim=True) + text_feature_dict[input_text] = text_features + return text_features + + def get_vid_features(self, input_frames): + with torch.no_grad(): + clip_feat = self.encode_vision(input_frames, test=True).float() + clip_feat /= clip_feat.norm(dim=-1, keepdim=True) + return clip_feat + + def get_predict_label(self, clip_feature, text_feats_tensor, top=5): + label_probs = (100.0 * clip_feature @ text_feats_tensor.T).softmax(dim=-1) + top_probs, top_labels = label_probs.cpu().topk(top, dim=-1) + return top_probs, top_labels diff --git a/Helios/eval/utils/third_party/ViCLIP/viclip_text.py b/Helios/eval/utils/third_party/ViCLIP/viclip_text.py new file mode 100644 index 0000000000000000000000000000000000000000..9aed79c9f2d5ecb8022cb1608ca988a88ad3a28d --- /dev/null +++ b/Helios/eval/utils/third_party/ViCLIP/viclip_text.py @@ -0,0 +1,260 @@ +import functools +import logging +import os +from collections import OrderedDict + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +from pkg_resources import packaging +from torch import nn + +from .simple_tokenizer import SimpleTokenizer as _Tokenizer + + +logger = logging.getLogger(__name__) + + +MODEL_PATH = "https://huggingface.co/laion/CLIP-ViT-L-14-DataComp.XL-s13B-b90K" +_MODELS = { + "ViT-L/14": os.path.join(MODEL_PATH, "vit_l14_text.pth"), +} + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16.""" + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + ret = super().forward(x.type(torch.float32)) + return ret.type(orig_type) + + +class QuickGELU(nn.Module): + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class ResidualAttentionBlock(nn.Module): + def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): + super().__init__() + + self.attn = nn.MultiheadAttention(d_model, n_head) + self.ln_1 = LayerNorm(d_model) + self.mlp = nn.Sequential( + OrderedDict( + [ + ("c_fc", nn.Linear(d_model, d_model * 4)), + ("gelu", QuickGELU()), + ("c_proj", nn.Linear(d_model * 4, d_model)), + ] + ) + ) + self.ln_2 = LayerNorm(d_model) + self.attn_mask = attn_mask + + def attention(self, x: torch.Tensor): + self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None + return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] + + def forward(self, x: torch.Tensor): + x = x + self.attention(self.ln_1(x)) + x = x + self.mlp(self.ln_2(x)) + return x + + +class Transformer(nn.Module): + def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None, checkpoint_num: int = 0): + super().__init__() + self.width = width + self.layers = layers + self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) + + self.checkpoint_num = checkpoint_num + + def forward(self, x: torch.Tensor): + if self.checkpoint_num > 0: + segments = min(self.checkpoint_num, len(self.resblocks)) + return checkpoint.checkpoint_sequential(self.resblocks, segments, x) + else: + return self.resblocks(x) + + +class CLIP_TEXT(nn.Module): + def __init__( + self, + embed_dim: int, + context_length: int, + vocab_size: int, + transformer_width: int, + transformer_heads: int, + transformer_layers: int, + checkpoint_num: int, + ): + super().__init__() + + self.context_length = context_length + self._tokenizer = _Tokenizer() + + self.transformer = Transformer( + width=transformer_width, + layers=transformer_layers, + heads=transformer_heads, + attn_mask=self.build_attention_mask(), + checkpoint_num=checkpoint_num, + ) + + self.vocab_size = vocab_size + self.token_embedding = nn.Embedding(vocab_size, transformer_width) + self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) + self.ln_final = LayerNorm(transformer_width) + + self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) + + def no_weight_decay(self): + return {"token_embedding", "positional_embedding"} + + @functools.lru_cache(maxsize=None) + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.context_length, self.context_length) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def tokenize(self, texts, context_length=77, truncate=True): + """ + Returns the tokenized representation of given input string(s) + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + truncate: bool + Whether to truncate the text in case its encoding is longer than the context length + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]. + We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long. + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = self._tokenizer.encoder["<|startoftext|>"] + eot_token = self._tokenizer.encoder["<|endoftext|>"] + all_tokens = [[sot_token] + self._tokenizer.encode(text) + [eot_token] for text in texts] + if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"): + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + else: + result = torch.zeros(len(all_tokens), context_length, dtype=torch.int) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + if truncate: + tokens = tokens[:context_length] + tokens[-1] = eot_token + else: + raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") + result[i, : len(tokens)] = torch.tensor(tokens) + + return result + + def forward(self, text): + x = self.token_embedding(text) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + + return x + + +def clip_text_b16( + embed_dim=512, + context_length=77, + vocab_size=49408, + transformer_width=512, + transformer_heads=8, + transformer_layers=12, +): + raise NotImplementedError + model = CLIP_TEXT(embed_dim, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers) + pretrained = _MODELS["ViT-B/16"] + logger.info(f"Load pretrained weights from {pretrained}") + state_dict = torch.load(pretrained, map_location="cpu") + model.load_state_dict(state_dict, strict=False) + return model.eval() + + +def clip_text_l14( + embed_dim=768, + context_length=77, + vocab_size=49408, + transformer_width=768, + transformer_heads=12, + transformer_layers=12, + checkpoint_num=0, + pretrained=True, +): + model = CLIP_TEXT( + embed_dim, + context_length, + vocab_size, + transformer_width, + transformer_heads, + transformer_layers, + checkpoint_num, + ) + if pretrained: + if isinstance(pretrained, str) and pretrained != "bert-base-uncased": + pretrained = _MODELS[pretrained] + else: + pretrained = _MODELS["ViT-L/14"] + logger.info(f"Load pretrained weights from {pretrained}") + state_dict = torch.load(pretrained, map_location="cpu") + if context_length != state_dict["positional_embedding"].size(0): + # assert context_length < state_dict["positional_embedding"].size(0), "Cannot increase context length." + print(f"Resize positional embedding from {state_dict['positional_embedding'].size(0)} to {context_length}") + if context_length < state_dict["positional_embedding"].size(0): + state_dict["positional_embedding"] = state_dict["positional_embedding"][:context_length] + else: + state_dict["positional_embedding"] = F.pad( + state_dict["positional_embedding"], + (0, 0, 0, context_length - state_dict["positional_embedding"].size(0)), + value=0, + ) + + message = model.load_state_dict(state_dict, strict=False) + print(f"Load pretrained weights from {pretrained}: {message}") + return model.eval() + + +def clip_text_l14_336( + embed_dim=768, + context_length=77, + vocab_size=49408, + transformer_width=768, + transformer_heads=12, + transformer_layers=12, +): + raise NotImplementedError + model = CLIP_TEXT(embed_dim, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers) + pretrained = _MODELS["ViT-L/14_336"] + logger.info(f"Load pretrained weights from {pretrained}") + state_dict = torch.load(pretrained, map_location="cpu") + model.load_state_dict(state_dict, strict=False) + return model.eval() + + +def build_clip(config): + model_cls = config.text_encoder.clip_teacher + model = eval(model_cls)() + return model diff --git a/Helios/eval/utils/third_party/ViCLIP/viclip_vision.py b/Helios/eval/utils/third_party/ViCLIP/viclip_vision.py new file mode 100644 index 0000000000000000000000000000000000000000..20eabbf3038947c2fd80690c0ea650349743ee3e --- /dev/null +++ b/Helios/eval/utils/third_party/ViCLIP/viclip_vision.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python +import logging +import os +from collections import OrderedDict + +import torch +import torch.utils.checkpoint as checkpoint +from einops import rearrange +from timm.layers import DropPath +from timm.models import register_model +from torch import nn + + +logger = logging.getLogger(__name__) + + +def load_temp_embed_with_mismatch(temp_embed_old, temp_embed_new, add_zero=True): + """ + Add/Remove extra temporal_embeddings as needed. + https://arxiv.org/abs/2104.00650 shows adding zero paddings works. + + temp_embed_old: (1, num_frames_old, 1, d) + temp_embed_new: (1, num_frames_new, 1, d) + add_zero: bool, if True, add zero, else, interpolate trained embeddings. + """ + # TODO zero pad + num_frms_new = temp_embed_new.shape[1] + num_frms_old = temp_embed_old.shape[1] + logger.info(f"Load temporal_embeddings, lengths: {num_frms_old}-->{num_frms_new}") + if num_frms_new > num_frms_old: + if add_zero: + temp_embed_new[:, :num_frms_old] = temp_embed_old # untrained embeddings are zeros. + else: + pass + # temp_embed_new = interpolate_temporal_pos_embed(temp_embed_old, num_frms_new) + elif num_frms_new < num_frms_old: + temp_embed_new = temp_embed_old[:, :num_frms_new] + else: # = + temp_embed_new = temp_embed_old + return temp_embed_new + + +MODEL_PATH = "https://pjlab-gvm-data.oss-cn-shanghai.aliyuncs.com/internvideo/viclip/" +_MODELS = { + "ViT-L/14": os.path.join(MODEL_PATH, "ViClip-InternVid-10M-FLT.pth"), +} + + +class QuickGELU(nn.Module): + def forward(self, x): + return x * torch.sigmoid(1.702 * x) + + +class ResidualAttentionBlock(nn.Module): + def __init__(self, d_model, n_head, drop_path=0.0, attn_mask=None, dropout=0.0): + super().__init__() + + self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.attn = nn.MultiheadAttention(d_model, n_head, dropout=dropout) + self.ln_1 = nn.LayerNorm(d_model) + self.mlp = nn.Sequential( + OrderedDict( + [ + ("c_fc", nn.Linear(d_model, d_model * 4)), + ("gelu", QuickGELU()), + ("drop1", nn.Dropout(dropout)), + ("c_proj", nn.Linear(d_model * 4, d_model)), + ("drop2", nn.Dropout(dropout)), + ] + ) + ) + self.ln_2 = nn.LayerNorm(d_model) + self.attn_mask = attn_mask + + def attention(self, x): + self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None + return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] + + def forward(self, x): + x = x + self.drop_path1(self.attention(self.ln_1(x))) + x = x + self.drop_path2(self.mlp(self.ln_2(x))) + return x + + +class Transformer(nn.Module): + def __init__(self, width, layers, heads, drop_path=0.0, checkpoint_num=0, dropout=0.0): + super().__init__() + dpr = [x.item() for x in torch.linspace(0, drop_path, layers)] + self.resblocks = nn.ModuleList() + for idx in range(layers): + self.resblocks.append(ResidualAttentionBlock(width, heads, drop_path=dpr[idx], dropout=dropout)) + self.checkpoint_num = checkpoint_num + + def forward(self, x): + for idx, blk in enumerate(self.resblocks): + if idx < self.checkpoint_num: + x = checkpoint.checkpoint(blk, x, use_reentrant=False) + else: + x = blk(x) + return x + + +class VisionTransformer(nn.Module): + def __init__( + self, + input_resolution, + patch_size, + width, + layers, + heads, + output_dim=None, + kernel_size=1, + num_frames=8, + drop_path=0, + checkpoint_num=0, + dropout=0.0, + temp_embed=True, + ): + super().__init__() + self.output_dim = output_dim + self.conv1 = nn.Conv3d( + 3, + width, + (kernel_size, patch_size, patch_size), + (kernel_size, patch_size, patch_size), + (0, 0, 0), + bias=False, + ) + + scale = width**-0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) + self.ln_pre = nn.LayerNorm(width) + if temp_embed: + self.temporal_positional_embedding = nn.Parameter(torch.zeros(1, num_frames, width)) + + self.transformer = Transformer( + width, layers, heads, drop_path=drop_path, checkpoint_num=checkpoint_num, dropout=dropout + ) + + self.ln_post = nn.LayerNorm(width) + if output_dim is not None: + self.proj = nn.Parameter(torch.empty(width, output_dim)) + else: + self.proj = None + + self.dropout = nn.Dropout(dropout) + + def get_num_layers(self): + return len(self.transformer.resblocks) + + @torch.jit.ignore + def no_weight_decay(self): + return {"positional_embedding", "class_embedding", "temporal_positional_embedding"} + + def mask_tokens(self, inputs, masking_prob=0.0): + B, L, _ = inputs.shape + + # This is different from text as we are masking a fix number of tokens + Lm = int(masking_prob * L) + masked_indices = torch.zeros(B, L) + indices = torch.argsort(torch.rand_like(masked_indices), dim=-1)[:, :Lm] + batch_indices = torch.arange(masked_indices.shape[0]).unsqueeze(-1).expand_as(indices) + masked_indices[batch_indices, indices] = 1 + + masked_indices = masked_indices.bool() + + return inputs[~masked_indices].reshape(B, -1, inputs.shape[-1]) + + def forward(self, x, masking_prob=0.0): + x = self.conv1(x) # shape = [*, width, grid, grid] + B, C, T, H, W = x.shape + x = x.permute(0, 2, 3, 4, 1).reshape(B * T, H * W, C) + + x = torch.cat( + [ + self.class_embedding.to(x.dtype) + + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), + x, + ], + dim=1, + ) # shape = [*, grid ** 2 + 1, width] + x = x + self.positional_embedding.to(x.dtype) + + # temporal pos + cls_tokens = x[:B, :1, :] + x = x[:, 1:] + x = rearrange(x, "(b t) n m -> (b n) t m", b=B, t=T) + if hasattr(self, "temporal_positional_embedding"): + if x.size(1) == 1: + # This is a workaround for unused parameter issue + x = x + self.temporal_positional_embedding.mean(1) + else: + x = x + self.temporal_positional_embedding + x = rearrange(x, "(b n) t m -> b (n t) m", b=B, t=T) + + if masking_prob > 0.0: + x = self.mask_tokens(x, masking_prob) + + x = torch.cat((cls_tokens, x), dim=1) + + x = self.ln_pre(x) + + x = x.permute(1, 0, 2) # BND -> NBD + x = self.transformer(x) + + x = self.ln_post(x) + + if self.proj is not None: + x = self.dropout(x[0]) @ self.proj + else: + x = x.permute(1, 0, 2) # NBD -> BND + + return x + + +def inflate_weight(weight_2d, time_dim, center=True): + logger.info(f"Init center: {center}") + if center: + weight_3d = torch.zeros(*weight_2d.shape) + weight_3d = weight_3d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1) + middle_idx = time_dim // 2 + weight_3d[:, :, middle_idx, :, :] = weight_2d + else: + weight_3d = weight_2d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1) + weight_3d = weight_3d / time_dim + return weight_3d + + +def load_state_dict(model, state_dict, input_resolution=224, patch_size=16, center=True): + state_dict_3d = model.state_dict() + for k in state_dict.keys(): + if k in state_dict_3d.keys() and state_dict[k].shape != state_dict_3d[k].shape: + if len(state_dict_3d[k].shape) <= 2: + logger.info(f"Ignore: {k}") + continue + logger.info(f"Inflate: {k}, {state_dict[k].shape} => {state_dict_3d[k].shape}") + time_dim = state_dict_3d[k].shape[2] + state_dict[k] = inflate_weight(state_dict[k], time_dim, center=center) + + pos_embed_checkpoint = state_dict["positional_embedding"] + embedding_size = pos_embed_checkpoint.shape[-1] + num_patches = (input_resolution // patch_size) ** 2 + orig_size = int((pos_embed_checkpoint.shape[-2] - 1) ** 0.5) + new_size = int(num_patches**0.5) + if orig_size != new_size: + logger.info(f"Pos_emb from {orig_size} to {new_size}") + extra_tokens = pos_embed_checkpoint[:1] + pos_tokens = pos_embed_checkpoint[1:] + pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) + pos_tokens = torch.nn.functional.interpolate( + pos_tokens, size=(new_size, new_size), mode="bicubic", align_corners=False + ) + pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(0, 2) + new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=0) + state_dict["positional_embedding"] = new_pos_embed + + message = model.load_state_dict(state_dict, strict=False) + logger.info(f"Load pretrained weights: {message}") + + +@register_model +def clip_joint_b16(pretrained=True, input_resolution=224, kernel_size=1, center=True, num_frames=8, drop_path=0.0): + model = VisionTransformer( + input_resolution=input_resolution, + patch_size=16, + width=768, + layers=12, + heads=12, + output_dim=512, + kernel_size=kernel_size, + num_frames=num_frames, + drop_path=drop_path, + ) + raise NotImplementedError + if pretrained: + logger.info("load pretrained weights") + state_dict = torch.load(_MODELS["ViT-B/16"], map_location="cpu") + load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=16, center=center) + return model.eval() + + +@register_model +def clip_joint_l14( + pretrained=False, + input_resolution=224, + kernel_size=1, + center=True, + num_frames=8, + drop_path=0.0, + checkpoint_num=0, + dropout=0.0, +): + model = VisionTransformer( + input_resolution=input_resolution, + patch_size=14, + width=1024, + layers=24, + heads=16, + output_dim=768, + kernel_size=kernel_size, + num_frames=num_frames, + drop_path=drop_path, + checkpoint_num=checkpoint_num, + dropout=dropout, + ) + if pretrained: + if isinstance(pretrained, str): + model_name = pretrained + else: + model_name = "ViT-L/14" + logger.info("load pretrained weights") + state_dict = torch.load(_MODELS[model_name], map_location="cpu") + load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=14, center=center) + return model.eval() + + +@register_model +def clip_joint_l14_336(pretrained=True, input_resolution=336, kernel_size=1, center=True, num_frames=8, drop_path=0.0): + raise NotImplementedError + model = VisionTransformer( + input_resolution=input_resolution, + patch_size=14, + width=1024, + layers=24, + heads=16, + output_dim=768, + kernel_size=kernel_size, + num_frames=num_frames, + drop_path=drop_path, + ) + if pretrained: + logger.info("load pretrained weights") + state_dict = torch.load(_MODELS["ViT-L/14_336"], map_location="cpu") + load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=14, center=center) + return model.eval() + + +def interpolate_pos_embed_vit(state_dict, new_model): + key = "vision_encoder.temporal_positional_embedding" + if key in state_dict: + vision_temp_embed_new = new_model.state_dict()[key] + vision_temp_embed_new = vision_temp_embed_new.unsqueeze(2) # [1, n, d] -> [1, n, 1, d] + vision_temp_embed_old = state_dict[key] + vision_temp_embed_old = vision_temp_embed_old.unsqueeze(2) + + state_dict[key] = load_temp_embed_with_mismatch( + vision_temp_embed_old, vision_temp_embed_new, add_zero=False + ).squeeze(2) + + key = "text_encoder.positional_embedding" + if key in state_dict: + text_temp_embed_new = new_model.state_dict()[key] + text_temp_embed_new = text_temp_embed_new.unsqueeze(0).unsqueeze(2) # [n, d] -> [1, n, 1, d] + text_temp_embed_old = state_dict[key] + text_temp_embed_old = text_temp_embed_old.unsqueeze(0).unsqueeze(2) + + state_dict[key] = ( + load_temp_embed_with_mismatch(text_temp_embed_old, text_temp_embed_new, add_zero=False) + .squeeze(2) + .squeeze(0) + ) + return state_dict diff --git a/Helios/eval/utils/third_party/amt/LICENSE b/Helios/eval/utils/third_party/amt/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c9cecbde136da03a4ceb1a6e90230900cd33828d --- /dev/null +++ b/Helios/eval/utils/third_party/amt/LICENSE @@ -0,0 +1,176 @@ +## creative commons + +# Attribution-NonCommercial 4.0 International + +Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +### Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). + +* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). + +## Creative Commons Attribution-NonCommercial 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +### Section 1 – Definitions. + +a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + +b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + +c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + +e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + +f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + +g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + +h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. + +i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. + +j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + +k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + +l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +### Section 2 – Scope. + +a. ___License grant.___ + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and + + B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. + + 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. __Term.__ The term of this Public License is specified in Section 6(a). + + 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. __Downstream recipients.__ + + A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + +b. ___Other rights.___ + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. + +### Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + +a. ___Attribution.___ + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. + +### Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; + +b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and + +c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +### Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ + +b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ + +c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +### Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + +c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + +d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +### Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +### Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + +b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + +c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. +> +> Creative Commons may be contacted at creativecommons.org + + +### Commercial licensing opportunities +For commercial uses of the Model & Software, please send email to cmm[AT]nankai.edu.cn + +Citation: + +@inproceedings{licvpr23amt, + title = {AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation}, + author = {Li, Zhen and Zhu, Zuo-Liang and Han, Ling-Hao and Hou, Qibin and Guo, Chun-Le and Cheng, Ming-Ming}, + booktitle = {IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, + year = {2023} +} + +Copyright (c) 2023 MCG-NKU \ No newline at end of file diff --git a/Helios/eval/utils/third_party/amt/README.md b/Helios/eval/utils/third_party/amt/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2f3224318fa319dc39b86e6bf9ec74ce3dee2e3e --- /dev/null +++ b/Helios/eval/utils/third_party/amt/README.md @@ -0,0 +1,167 @@ +# AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation + + +This repository contains the official implementation of the following paper: +> **AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation**
+> [Zhen Li](https://paper99.github.io/)\*, [Zuo-Liang Zhu](https://nk-cs-zzl.github.io/)\*, [Ling-Hao Han](https://scholar.google.com/citations?user=0ooNdgUAAAAJ&hl=en), [Qibin Hou](https://scholar.google.com/citations?hl=en&user=fF8OFV8AAAAJ&view_op=list_works), [Chun-Le Guo](https://scholar.google.com/citations?hl=en&user=RZLYwR0AAAAJ), [Ming-Ming Cheng](https://mmcheng.net/cmm)
+> (\* denotes equal contribution)
+> Nankai University
+> In CVPR 2023
+ +[[Paper](https://arxiv.org/abs/2304.09790)] +[[Project Page](https://nk-cs-zzl.github.io/projects/amt/index.html)] +[[Web demos](#web-demos)] +[Video] + +AMT is a **lightweight, fast, and accurate** algorithm for Frame Interpolation. +It aims to provide practical solutions for **video generation** from **a few given frames (at least two frames)**. + +![Demo gif](assets/amt_demo.gif) +* More examples can be found in our [project page](https://nk-cs-zzl.github.io/projects/amt/index.html). + +## Web demos +Integrated into [Hugging Face Spaces 🤗](https://huggingface.co/spaces) using [Gradio](https://github.com/gradio-app/gradio). Try out the Web Demo: [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/NKU-AMT/AMT) + +Try AMT to interpolate between two or more images at [![PyTTI-Tools:FILM](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1IeVO5BmLouhRh6fL2z_y18kgubotoaBq?usp=sharing) + + +## Change Log +- **Apr 20, 2023**: Our code is publicly available. + + +## Method Overview +![pipeline](https://user-images.githubusercontent.com/21050959/229420451-65951bd0-732c-4f09-9121-f291a3862d6e.png) + +For technical details, please refer to the [method.md](docs/method.md) file, or read the full report on [arXiv](https://arxiv.org/abs/2304.09790). + +## Dependencies and Installation +1. Clone Repo + + ```bash + git clone https://github.com/MCG-NKU/AMT.git + ``` + +2. Create Conda Environment and Install Dependencies + + ```bash + conda env create -f environment.yaml + conda activate amt + ``` +3. Download pretrained models for demos from [Pretrained Models](#pretrained-models) and place them to the `pretrained` folder + +## Quick Demo + +**Note that the selected pretrained model (`[CKPT_PATH]`) needs to match the config file (`[CFG]`).** + + > Creating a video demo, increasing $n$ will slow down the motion in the video. (With $m$ input frames, `[N_ITER]` $=n$ corresponds to $2^n\times (m-1)+1$ output frames.) + + + ```bash + python demos/demo_2x.py -c [CFG] -p [CKPT] -n [N_ITER] -i [INPUT] -o [OUT_PATH] -r [FRAME_RATE] + # e.g. [INPUT] + # -i could be a video / a regular expression / a folder contains multiple images + # -i demo.mp4 (video)/img_*.png (regular expression)/img0.png img1.png (images)/demo_input (folder) + + # e.g. a simple usage + python demos/demo_2x.py -c cfgs/AMT-S.yaml -p pretrained/amt-s.pth -n 6 -i assets/quick_demo/img0.png assets/quick_demo/img1.png + + ``` + + + Note: Please enable `--save_images` for saving the output images (Save speed will be slowed down if there are too many output images) + + Input type supported: `a video` / `a regular expression` / `multiple images` / `a folder containing input frames`. + + Results are in the `[OUT_PATH]` (default is `results/2x`) folder. + +## Pretrained Models + +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dataset :link: Download Links Config file Trained on Arbitrary/Fixed
AMT-S [Google Driver][Baidu Cloud][Hugging Face] [cfgs/AMT-S] Vimeo90kFixed
AMT-L[Google Driver][Baidu Cloud][Hugging Face] [cfgs/AMT-L] Vimeo90kFixed
AMT-G[Google Driver][Baidu Cloud][Hugging Face] [cfgs/AMT-G] Vimeo90kFixed
AMT-S[Google Driver][Baidu Cloud][Hugging Face] [cfgs/AMT-S_gopro] GoProArbitrary
+ +## Training and Evaluation + +Please refer to [develop.md](docs/develop.md) to learn how to benchmark the AMT and how to train a new AMT model from scratch. + + +## Citation + If you find our repo useful for your research, please consider citing our paper: + + ```bibtex + @inproceedings{licvpr23amt, + title={AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation}, + author={Li, Zhen and Zhu, Zuo-Liang and Han, Ling-Hao and Hou, Qibin and Guo, Chun-Le and Cheng, Ming-Ming}, + booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, + year={2023} + } + ``` + + +## License +This code is licensed under the [Creative Commons Attribution-NonCommercial 4.0 International](https://creativecommons.org/licenses/by-nc/4.0/) for non-commercial use only. +Please note that any commercial use of this code requires formal permission prior to use. + +## Contact + +For technical questions, please contact `zhenli1031[AT]gmail.com` and `nkuzhuzl[AT]gmail.com`. + +For commercial licensing, please contact `cmm[AT]nankai.edu.cn` + +## Acknowledgement + +We thank Jia-Wen Xiao, Zheng-Peng Duan, Rui-Qi Wu, and Xin Jin for proof reading. +We thank [Zhewei Huang](https://github.com/hzwer) for his suggestions. + +Here are some great resources we benefit from: + +- [IFRNet](https://github.com/ltkong218/IFRNet) and [RIFE](https://github.com/megvii-research/ECCV2022-RIFE) for data processing, benchmarking, and loss designs. +- [RAFT](https://github.com/princeton-vl/RAFT), [M2M-VFI](https://github.com/feinanshan/M2M_VFI), and [GMFlow](https://github.com/haofeixu/gmflow) for inspirations. +- [FILM](https://github.com/google-research/frame-interpolation) for Web demo reference. + + +**If you develop/use AMT in your projects, welcome to let us know. We will list your projects in this repository.** + +We also thank all of our contributors. + + + + + diff --git a/Helios/eval/utils/third_party/amt/__init__.py b/Helios/eval/utils/third_party/amt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/benchmarks/__init__.py b/Helios/eval/utils/third_party/amt/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/benchmarks/adobe240.py b/Helios/eval/utils/third_party/amt/benchmarks/adobe240.py new file mode 100644 index 0000000000000000000000000000000000000000..20598d711fb25a9fdbcf6991369f9afe77bb24b9 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/benchmarks/adobe240.py @@ -0,0 +1,65 @@ +import argparse +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from datasets.adobe_datasets import Adobe240_Dataset +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Adobe240 evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S_gopro.yaml") +parser.add_argument( + "-p", + "--ckpt", + default="pretrained/gopro_amt-s.pth", +) +parser.add_argument( + "-r", + "--root", + default="data/Adobe240/test_frames", +) +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +dataset = Adobe240_Dataset(dataset_dir=root, augment=False) + +psnr_list = [] +ssim_list = [] +pbar = tqdm.tqdm(dataset, total=len(dataset)) +for data in pbar: + input_dict = {} + for k, v in data.items(): + input_dict[k] = v.to(device).unsqueeze(0) + with torch.no_grad(): + imgt_pred = model(**input_dict)["imgt_pred"] + psnr = calculate_psnr(imgt_pred, input_dict["imgt"]) + ssim = calculate_ssim(imgt_pred, input_dict["imgt"]) + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/Adobe240] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval/utils/third_party/amt/benchmarks/gopro.py b/Helios/eval/utils/third_party/amt/benchmarks/gopro.py new file mode 100644 index 0000000000000000000000000000000000000000..27897013ca50baea29992f7b070434da6799b464 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/benchmarks/gopro.py @@ -0,0 +1,65 @@ +import argparse +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from datasets.gopro_datasets import GoPro_Test_Dataset +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg + + +parser = argparse.ArgumentParser( + prog="AMT", + description="GOPRO evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S_gopro.yaml") +parser.add_argument( + "-p", + "--ckpt", + default="pretrained/gopro_amt-s.pth", +) +parser.add_argument( + "-r", + "--root", + default="data/GOPRO", +) +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +dataset = GoPro_Test_Dataset(dataset_dir=root) + +psnr_list = [] +ssim_list = [] +pbar = tqdm.tqdm(dataset, total=len(dataset)) +for data in pbar: + input_dict = {} + for k, v in data.items(): + input_dict[k] = v.to(device).unsqueeze(0) + with torch.no_grad(): + imgt_pred = model(**input_dict)["imgt_pred"] + psnr = calculate_psnr(imgt_pred, input_dict["imgt"]) + ssim = calculate_ssim(imgt_pred, input_dict["imgt"]) + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/GOPRO] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval/utils/third_party/amt/benchmarks/snu_film.py b/Helios/eval/utils/third_party/amt/benchmarks/snu_film.py new file mode 100644 index 0000000000000000000000000000000000000000..ec0417ee4ba7fe0d52da939d5977f55315f125d0 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/benchmarks/snu_film.py @@ -0,0 +1,76 @@ +import argparse +import os +import os.path as osp +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import InputPadder, img2tensor, read + + +def parse_path(path): + path_list = path.split("/") + new_path = osp.join(*path_list[-3:]) + return new_path + + +parser = argparse.ArgumentParser( + prog="AMT", + description="SNU-FILM evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument("-p", "--ckpt", default="pretrained/amt-s.pth") +parser.add_argument("-r", "--root", default="data/SNU_FILM") +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +divisor = 20 +scale_factor = 0.8 +splits = ["easy", "medium", "hard", "extreme"] +for split in splits: + with open(os.path.join(root, f"test-{split}.txt"), "r") as fr: + file_list = [l.strip().split(" ") for l in fr.readlines()] + pbar = tqdm.tqdm(file_list, total=len(file_list)) + + psnr_list = [] + ssim_list = [] + for name in pbar: + img0 = img2tensor(read(osp.join(root, parse_path(name[0])))).to(device) + imgt = img2tensor(read(osp.join(root, parse_path(name[1])))).to(device) + img1 = img2tensor(read(osp.join(root, parse_path(name[2])))).to(device) + padder = InputPadder(img0.shape, divisor) + img0, img1 = padder.pad(img0, img1) + + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + imgt_pred = model(img0, img1, embt, scale_factor=scale_factor, eval=True)["imgt_pred"] + imgt_pred = padder.unpad(imgt_pred) + + psnr = calculate_psnr(imgt_pred, imgt).detach().cpu().numpy() + ssim = calculate_ssim(imgt_pred, imgt).detach().cpu().numpy() + + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/SNU-FILM] [{split}] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval/utils/third_party/amt/benchmarks/speed_parameters.py b/Helios/eval/utils/third_party/amt/benchmarks/speed_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..be6d4569f0f55e36f244d61ee537dcf4bbd05a62 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/benchmarks/speed_parameters.py @@ -0,0 +1,41 @@ +import argparse +import sys +import time + +import torch +from omegaconf import OmegaConf + + +sys.path.append(".") +from utils.build_utils import build_from_cfg + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Speed¶meter benchmark", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +args = parser.parse_args() + +cfg_path = args.config +network_cfg = OmegaConf.load(cfg_path).network +model = build_from_cfg(network_cfg) +model = model.cuda() +model.eval() + +img0 = torch.randn(1, 3, 256, 448).cuda() +img1 = torch.randn(1, 3, 256, 448).cuda() +embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).cuda() + +with torch.no_grad(): + for i in range(100): + out = model(img0, img1, embt, eval=True) + torch.cuda.synchronize() + time_stamp = time.time() + for i in range(1000): + out = model(img0, img1, embt, eval=True) + torch.cuda.synchronize() + print("Time: {:.5f}s".format((time.time() - time_stamp) / 1)) + +total = sum([param.nelement() for param in model.parameters()]) +print("Parameters: {:.2f}M".format(total / 1e6)) diff --git a/Helios/eval/utils/third_party/amt/benchmarks/ucf101.py b/Helios/eval/utils/third_party/amt/benchmarks/ucf101.py new file mode 100644 index 0000000000000000000000000000000000000000..7741c19d4c6ba2f8e46d7d1725119a7ef07b61c6 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/benchmarks/ucf101.py @@ -0,0 +1,63 @@ +import argparse +import os +import os.path as osp +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import img2tensor, read + + +parser = argparse.ArgumentParser( + prog="AMT", + description="UCF101 evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument("-p", "--ckpt", default="pretrained/amt-s.pth") +parser.add_argument("-r", "--root", default="data/ucf101_interp_ours") +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +dirs = sorted(os.listdir(root)) +psnr_list = [] +ssim_list = [] +pbar = tqdm.tqdm(dirs, total=len(dirs)) +for d in pbar: + dir_path = osp.join(root, d) + I0 = img2tensor(read(osp.join(dir_path, "frame_00.png"))).to(device) + I1 = img2tensor(read(osp.join(dir_path, "frame_01_gt.png"))).to(device) + I2 = img2tensor(read(osp.join(dir_path, "frame_02.png"))).to(device) + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + + I1_pred = model(I0, I2, embt, eval=True)["imgt_pred"] + + psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy() + ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy() + + psnr_list.append(psnr) + ssim_list.append(ssim) + + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/UCF101] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval/utils/third_party/amt/benchmarks/vimeo90k.py b/Helios/eval/utils/third_party/amt/benchmarks/vimeo90k.py new file mode 100644 index 0000000000000000000000000000000000000000..d70e1e32b21d459d6ccb633d29796819bfa730ac --- /dev/null +++ b/Helios/eval/utils/third_party/amt/benchmarks/vimeo90k.py @@ -0,0 +1,75 @@ +import argparse +import os.path as osp +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import img2tensor, read + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Vimeo90K evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument( + "-p", + "--ckpt", + default="pretrained/amt-s.pth", +) +parser.add_argument( + "-r", + "--root", + default="data/vimeo_triplet", +) +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +with open(osp.join(root, "tri_testlist.txt"), "r") as fr: + file_list = fr.readlines() + +psnr_list = [] +ssim_list = [] + +pbar = tqdm.tqdm(file_list, total=len(file_list)) +for name in pbar: + name = str(name).strip() + if len(name) <= 1: + continue + dir_path = osp.join(root, "sequences", name) + I0 = img2tensor(read(osp.join(dir_path, "im1.png"))).to(device) + I1 = img2tensor(read(osp.join(dir_path, "im2.png"))).to(device) + I2 = img2tensor(read(osp.join(dir_path, "im3.png"))).to(device) + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + + I1_pred = model(I0, I2, embt, scale_factor=1.0, eval=True)["imgt_pred"] + + psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy() + ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy() + + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/Vimeo90K] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval/utils/third_party/amt/benchmarks/vimeo90k_tta.py b/Helios/eval/utils/third_party/amt/benchmarks/vimeo90k_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..af6c91f079a9942b0b66f89ecff173821e938864 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/benchmarks/vimeo90k_tta.py @@ -0,0 +1,76 @@ +import argparse +import os.path as osp +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import img2tensor, read + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Vimeo90K evaluation (with Test-Time Augmentation)", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument( + "p", + "--ckpt", + default="pretrained/amt-s.pth", +) +parser.add_argument( + "-r", + "--root", + default="data/vimeo_triplet", +) +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +with open(osp.join(root, "tri_testlist.txt"), "r") as fr: + file_list = fr.readlines() + +psnr_list = [] +ssim_list = [] + +pbar = tqdm.tqdm(file_list, total=len(file_list)) +for name in pbar: + name = str(name).strip() + if len(name) <= 1: + continue + dir_path = osp.join(root, "sequences", name) + I0 = img2tensor(read(osp.join(dir_path, "im1.png"))).to(device) + I1 = img2tensor(read(osp.join(dir_path, "im2.png"))).to(device) + I2 = img2tensor(read(osp.join(dir_path, "im3.png"))).to(device) + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + + I1_pred1 = model(I0, I2, embt, scale_factor=1.0, eval=True)["imgt_pred"] + I1_pred2 = model(torch.flip(I0, [2]), torch.flip(I2, [2]), embt, scale_factor=1.0, eval=True)["imgt_pred"] + I1_pred = I1_pred1 / 2 + torch.flip(I1_pred2, [2]) / 2 + psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy() + ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy() + + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/Vimeo90K] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval/utils/third_party/amt/benchmarks/xiph.py b/Helios/eval/utils/third_party/amt/benchmarks/xiph.py new file mode 100644 index 0000000000000000000000000000000000000000..7f134a0ec17ffdab73eff431bb10216242e282d5 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/benchmarks/xiph.py @@ -0,0 +1,117 @@ +import argparse +import glob +import os +import os.path as osp +import sys + +import cv2 +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import InputPadder, img2tensor, read + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Xiph evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument("-p", "--ckpt", default="pretrained/amt-s.pth") +parser.add_argument("-r", "--root", default="data/xiph") +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"], False) +model = model.to(device) +model.eval() + +############################################# Prepare Dataset ############################################# +download_links = [ + "https://media.xiph.org/video/derf/ElFuente/Netflix_BoxingPractice_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_Crosswalk_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/Chimera/Netflix_DrivingPOV_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket2_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_RitualDance_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_SquareAndTimelapse_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_Tango_4096x2160_60fps_10bit_420.y4m", +] +file_list = [ + "BoxingPractice", + "Crosswalk", + "DrivingPOV", + "FoodMarket", + "FoodMarket2", + "RitualDance", + "SquareAndTimelapse", + "Tango", +] + +for file_name, link in zip(file_list, download_links): + data_dir = osp.join(root, file_name) + if osp.exists(data_dir) is False: + os.makedirs(data_dir) + if len(glob.glob(f"{data_dir}/*.png")) < 100: + os.system(f"ffmpeg -i {link} -pix_fmt rgb24 -vframes 100 {data_dir}/%03d.png") +############################################### Prepare End ############################################### + + +divisor = 32 +scale_factor = 0.5 +for category in ["resized-2k", "cropped-4k"]: + psnr_list = [] + ssim_list = [] + pbar = tqdm.tqdm(file_list, total=len(file_list)) + for flie_name in pbar: + dir_name = osp.join(root, flie_name) + for intFrame in range(2, 99, 2): + img0 = read(f"{dir_name}/{intFrame - 1:03d}.png") + img1 = read(f"{dir_name}/{intFrame + 1:03d}.png") + imgt = read(f"{dir_name}/{intFrame:03d}.png") + + if category == "resized-2k": + img0 = cv2.resize(src=img0, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA) + img1 = cv2.resize(src=img1, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA) + imgt = cv2.resize(src=imgt, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA) + + elif category == "cropped-4k": + img0 = img0[540:-540, 1024:-1024, :] + img1 = img1[540:-540, 1024:-1024, :] + imgt = imgt[540:-540, 1024:-1024, :] + img0 = img2tensor(img0).to(device) + imgt = img2tensor(imgt).to(device) + img1 = img2tensor(img1).to(device) + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + + padder = InputPadder(img0.shape, divisor) + img0, img1 = padder.pad(img0, img1) + + with torch.no_grad(): + imgt_pred = model(img0, img1, embt, scale_factor=scale_factor, eval=True)["imgt_pred"] + imgt_pred = padder.unpad(imgt_pred) + + psnr = calculate_psnr(imgt_pred, imgt) + ssim = calculate_ssim(imgt_pred, imgt) + + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + psnr_list.append(psnr) + ssim_list.append(ssim) + desc_str = f"[{network_name}/Xiph] [{category}/{flie_name}] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + + pbar.set_description_str(desc_str) diff --git a/Helios/eval/utils/third_party/amt/cfgs/AMT-G.yaml b/Helios/eval/utils/third_party/amt/cfgs/AMT-G.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b3bb39bda6b41dc5cdc3300ffccb7b4e7d537ce --- /dev/null +++ b/Helios/eval/utils/third_party/amt/cfgs/AMT-G.yaml @@ -0,0 +1,62 @@ +exp_name: floloss1e-2_300epoch_bs24_lr1p5e-4 +seed: 2023 +epochs: 300 +distributed: true +lr: 1.5e-4 +lr_min: 2e-5 +weight_decay: 0.0 +resume_state: null +save_dir: work_dir +eval_interval: 1 + +network: + name: networks.AMT-G.Model + params: + corr_radius: 3 + corr_lvls: 4 + num_flows: 5 +data: + train: + name: datasets.vimeo_datasets.Vimeo90K_Train_Dataset + params: + dataset_dir: data/vimeo_triplet + val: + name: datasets.vimeo_datasets.Vimeo90K_Test_Dataset + params: + dataset_dir: data/vimeo_triplet + train_loader: + batch_size: 24 + num_workers: 12 + val_loader: + batch_size: 24 + num_workers: 3 + +logger: + use_wandb: true + resume_id: null + +losses: + - { + name: losses.loss.CharbonnierLoss, + nickname: l_rec, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.TernaryLoss, + nickname: l_ter, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.MultipleFlowLoss, + nickname: l_flo, + params: { + loss_weight: 0.005, + keys: [flow0_pred, flow1_pred, flow] + } + } diff --git a/Helios/eval/utils/third_party/amt/cfgs/AMT-L.yaml b/Helios/eval/utils/third_party/amt/cfgs/AMT-L.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0cd60ce868ad98a9dea74dd77227f556738715e8 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/cfgs/AMT-L.yaml @@ -0,0 +1,62 @@ +exp_name: floloss1e-2_300epoch_bs24_lr2e-4 +seed: 2023 +epochs: 300 +distributed: true +lr: 2e-4 +lr_min: 2e-5 +weight_decay: 0.0 +resume_state: null +save_dir: work_dir +eval_interval: 1 + +network: + name: networks.AMT-L.Model + params: + corr_radius: 3 + corr_lvls: 4 + num_flows: 5 +data: + train: + name: datasets.vimeo_datasets.Vimeo90K_Train_Dataset + params: + dataset_dir: data/vimeo_triplet + val: + name: datasets.vimeo_datasets.Vimeo90K_Test_Dataset + params: + dataset_dir: data/vimeo_triplet + train_loader: + batch_size: 24 + num_workers: 12 + val_loader: + batch_size: 24 + num_workers: 3 + +logger: + use_wandb: true + resume_id: null + +losses: + - { + name: losses.loss.CharbonnierLoss, + nickname: l_rec, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.TernaryLoss, + nickname: l_ter, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.MultipleFlowLoss, + nickname: l_flo, + params: { + loss_weight: 0.002, + keys: [flow0_pred, flow1_pred, flow] + } + } diff --git a/Helios/eval/utils/third_party/amt/cfgs/AMT-S_gopro.yaml b/Helios/eval/utils/third_party/amt/cfgs/AMT-S_gopro.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb50cfb04ed509e7766bbd279e0308d03db98d62 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/cfgs/AMT-S_gopro.yaml @@ -0,0 +1,56 @@ +exp_name: wofloloss_400epoch_bs24_lr2e-4 +seed: 2023 +epochs: 400 +distributed: true +lr: 2e-4 +lr_min: 2e-5 +weight_decay: 0.0 +resume_state: null +save_dir: work_dir +eval_interval: 1 + +network: + name: networks.AMT-S.Model + params: + corr_radius: 3 + corr_lvls: 4 + num_flows: 3 + +data: + train: + name: datasets.gopro_datasets.GoPro_Train_Dataset + params: + dataset_dir: data/GOPRO + val: + name: datasets.gopro_datasets.GoPro_Test_Dataset + params: + dataset_dir: data/GOPRO + train_loader: + batch_size: 24 + num_workers: 12 + val_loader: + batch_size: 24 + num_workers: 3 + +logger: + use_wandb: false + resume_id: null + +losses: + - { + name: losses.loss.CharbonnierLoss, + nickname: l_rec, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.TernaryLoss, + nickname: l_ter, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + diff --git a/Helios/eval/utils/third_party/amt/cfgs/IFRNet.yaml b/Helios/eval/utils/third_party/amt/cfgs/IFRNet.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ce67ca48901e501956ea0d07b2373b5d7af74df --- /dev/null +++ b/Helios/eval/utils/third_party/amt/cfgs/IFRNet.yaml @@ -0,0 +1,67 @@ +exp_name: floloss1e-2_geoloss1e-2_300epoch_bs24_lr1e-4 +seed: 2023 +epochs: 300 +distributed: true +lr: 1e-4 +lr_min: 1e-5 +weight_decay: 1e-6 +resume_state: null +save_dir: work_dir +eval_interval: 1 + +network: + name: networks.IFRNet.Model + +data: + train: + name: datasets.datasets.Vimeo90K_Train_Dataset + params: + dataset_dir: data/vimeo_triplet + val: + name: datasets.datasets.Vimeo90K_Test_Dataset + params: + dataset_dir: data/vimeo_triplet + train_loader: + batch_size: 24 + num_workers: 12 + val_loader: + batch_size: 24 + num_workers: 3 + +logger: + use_wandb: true + resume_id: null + +losses: + - { + name: losses.loss.CharbonnierLoss, + nickname: l_rec, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.TernaryLoss, + nickname: l_ter, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.IFRFlowLoss, + nickname: l_flo, + params: { + loss_weight: 0.01, + keys: [flow0_pred, flow1_pred, flow] + } + } + - { + name: losses.loss.GeometryLoss, + nickname: l_geo, + params: { + loss_weight: 0.01, + keys: [ft_pred, ft_gt] + } + } diff --git a/Helios/eval/utils/third_party/amt/datasets/__init__.py b/Helios/eval/utils/third_party/amt/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/datasets/adobe_datasets.py b/Helios/eval/utils/third_party/amt/datasets/adobe_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..cf543ab88cf72c6ee6118d8cc192aba8b7d7cea0 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/datasets/adobe_datasets.py @@ -0,0 +1,77 @@ +import os +import sys + +import numpy as np +import torch +from torch.utils.data import Dataset + + +sys.path.append(".") +from datasets.gopro_datasets import ( + center_crop_woflow, + random_crop_woflow, + random_horizontal_flip_woflow, + random_resize_woflow, + random_reverse_channel_woflow, + random_reverse_time_woflow, + random_rotate_woflow, + random_vertical_flip_woflow, +) + +from utils.utils import img2tensor, read + + +class Adobe240_Dataset(Dataset): + def __init__(self, dataset_dir="data/adobe240/test_frames", interFrames=7, augment=True): + super().__init__() + self.augment = augment + self.interFrames = interFrames + self.setLength = interFrames + 2 + self.dataset_dir = os.path.join(dataset_dir) + video_list = os.listdir(self.dataset_dir)[9::10] + self.frames_list = [] + self.file_list = [] + for video in video_list: + frames = sorted(os.listdir(os.path.join(self.dataset_dir, video))) + n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1 + videoInputs = [ + frames[(interFrames + 1) * i : (interFrames + 1) * i + self.setLength] for i in range(n_sets) + ] + videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs] + self.file_list.extend(videoInputs) + + def __getitem__(self, idx): + clip_idx = idx // self.interFrames + embt_idx = idx % self.interFrames + imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]] + pick_idxs = list(range(0, self.setLength, self.interFrames + 1)) + imgt_beg = self.setLength // 2 - self.interFrames // 2 + imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2 + imgt_idx = list(range(imgt_beg, imgt_end)) + input_paths = [imgpaths[idx] for idx in pick_idxs] + imgt_paths = [imgpaths[idx] for idx in imgt_idx] + + img0 = np.array(read(input_paths[0])) + imgt = np.array(read(imgt_paths[embt_idx])) + img1 = np.array(read(input_paths[1])) + embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)).reshape(1, 1, 1).astype(np.float32)) + + if self.augment: + img0, imgt, img1 = random_resize_woflow(img0, imgt, img1, p=0.1) + img0, imgt, img1 = random_crop_woflow(img0, imgt, img1, crop_size=(224, 224)) + img0, imgt, img1 = random_reverse_channel_woflow(img0, imgt, img1, p=0.5) + img0, imgt, img1 = random_vertical_flip_woflow(img0, imgt, img1, p=0.3) + img0, imgt, img1 = random_horizontal_flip_woflow(img0, imgt, img1, p=0.5) + img0, imgt, img1 = random_rotate_woflow(img0, imgt, img1, p=0.05) + img0, imgt, img1, embt = random_reverse_time_woflow(img0, imgt, img1, embt=embt, p=0.5) + else: + img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)) + + img0 = img2tensor(img0).squeeze(0) + imgt = img2tensor(imgt).squeeze(0) + img1 = img2tensor(img1).squeeze(0) + + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "embt": embt} + + def __len__(self): + return len(self.file_list) * self.interFrames diff --git a/Helios/eval/utils/third_party/amt/datasets/gopro_datasets.py b/Helios/eval/utils/third_party/amt/datasets/gopro_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..9c5acb441a449af2d2ae1a7d6b0bd3bd9e093d30 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/datasets/gopro_datasets.py @@ -0,0 +1,213 @@ +import os +import random + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from utils.utils import img2tensor, read + + +def random_resize_woflow(img0, imgt, img1, p=0.1): + if random.uniform(0, 1) < p: + img0 = cv2.resize(img0, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + imgt = cv2.resize(imgt, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + img1 = cv2.resize(img1, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + return img0, imgt, img1 + + +def random_crop_woflow(img0, imgt, img1, crop_size=(224, 224)): + h, w = crop_size[0], crop_size[1] + ih, iw, _ = img0.shape + x = np.random.randint(0, ih - h + 1) + y = np.random.randint(0, iw - w + 1) + img0 = img0[x : x + h, y : y + w, :] + imgt = imgt[x : x + h, y : y + w, :] + img1 = img1[x : x + h, y : y + w, :] + return img0, imgt, img1 + + +def center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)): + h, w = crop_size[0], crop_size[1] + ih, iw, _ = img0.shape + img0 = img0[ih // 2 - h // 2 : ih // 2 + h // 2, iw // 2 - w // 2 : iw // 2 + w // 2, :] + imgt = imgt[ih // 2 - h // 2 : ih // 2 + h // 2, iw // 2 - w // 2 : iw // 2 + w // 2, :] + img1 = img1[ih // 2 - h // 2 : ih // 2 + h // 2, iw // 2 - w // 2 : iw // 2 + w // 2, :] + return img0, imgt, img1 + + +def random_reverse_channel_woflow(img0, imgt, img1, p=0.5): + if random.uniform(0, 1) < p: + img0 = img0[:, :, ::-1] + imgt = imgt[:, :, ::-1] + img1 = img1[:, :, ::-1] + return img0, imgt, img1 + + +def random_vertical_flip_woflow(img0, imgt, img1, p=0.3): + if random.uniform(0, 1) < p: + img0 = img0[::-1] + imgt = imgt[::-1] + img1 = img1[::-1] + return img0, imgt, img1 + + +def random_horizontal_flip_woflow(img0, imgt, img1, p=0.5): + if random.uniform(0, 1) < p: + img0 = img0[:, ::-1] + imgt = imgt[:, ::-1] + img1 = img1[:, ::-1] + return img0, imgt, img1 + + +def random_rotate_woflow(img0, imgt, img1, p=0.05): + if random.uniform(0, 1) < p: + img0 = img0.transpose((1, 0, 2)) + imgt = imgt.transpose((1, 0, 2)) + img1 = img1.transpose((1, 0, 2)) + return img0, imgt, img1 + + +def random_reverse_time_woflow(img0, imgt, img1, embt, p=0.5): + if random.uniform(0, 1) < p: + tmp = img1 + img1 = img0 + img0 = tmp + embt = 1 - embt + return img0, imgt, img1, embt + + +class GoPro_Train_Dataset(Dataset): + def __init__(self, dataset_dir="data/GOPRO", interFrames=7, augment=True): + self.dataset_dir = dataset_dir + "/train" + self.interFrames = interFrames + self.augment = augment + self.setLength = interFrames + 2 + video_list = [ + "GOPR0372_07_00", + "GOPR0374_11_01", + "GOPR0378_13_00", + "GOPR0384_11_01", + "GOPR0384_11_04", + "GOPR0477_11_00", + "GOPR0868_11_02", + "GOPR0884_11_00", + "GOPR0372_07_01", + "GOPR0374_11_02", + "GOPR0379_11_00", + "GOPR0384_11_02", + "GOPR0385_11_00", + "GOPR0857_11_00", + "GOPR0871_11_01", + "GOPR0374_11_00", + "GOPR0374_11_03", + "GOPR0380_11_00", + "GOPR0384_11_03", + "GOPR0386_11_00", + "GOPR0868_11_01", + "GOPR0881_11_00", + ] + self.frames_list = [] + self.file_list = [] + for video in video_list: + frames = sorted(os.listdir(os.path.join(self.dataset_dir, video))) + n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1 + videoInputs = [ + frames[(interFrames + 1) * i : (interFrames + 1) * i + self.setLength] for i in range(n_sets) + ] + videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs] + self.file_list.extend(videoInputs) + + def __len__(self): + return len(self.file_list) * self.interFrames + + def __getitem__(self, idx): + clip_idx = idx // self.interFrames + embt_idx = idx % self.interFrames + imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]] + pick_idxs = list(range(0, self.setLength, self.interFrames + 1)) + imgt_beg = self.setLength // 2 - self.interFrames // 2 + imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2 + imgt_idx = list(range(imgt_beg, imgt_end)) + input_paths = [imgpaths[idx] for idx in pick_idxs] + imgt_paths = [imgpaths[idx] for idx in imgt_idx] + + embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)).reshape(1, 1, 1).astype(np.float32)) + img0 = np.array(read(input_paths[0])) + imgt = np.array(read(imgt_paths[embt_idx])) + img1 = np.array(read(input_paths[1])) + + if self.augment: + img0, imgt, img1 = random_resize_woflow(img0, imgt, img1, p=0.1) + img0, imgt, img1 = random_crop_woflow(img0, imgt, img1, crop_size=(224, 224)) + img0, imgt, img1 = random_reverse_channel_woflow(img0, imgt, img1, p=0.5) + img0, imgt, img1 = random_vertical_flip_woflow(img0, imgt, img1, p=0.3) + img0, imgt, img1 = random_horizontal_flip_woflow(img0, imgt, img1, p=0.5) + img0, imgt, img1 = random_rotate_woflow(img0, imgt, img1, p=0.05) + img0, imgt, img1, embt = random_reverse_time_woflow(img0, imgt, img1, embt=embt, p=0.5) + else: + img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)) + + img0 = img2tensor(img0.copy()).squeeze(0) + imgt = img2tensor(imgt.copy()).squeeze(0) + img1 = img2tensor(img1.copy()).squeeze(0) + + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "embt": embt} + + +class GoPro_Test_Dataset(Dataset): + def __init__(self, dataset_dir="data/GOPRO", interFrames=7): + self.dataset_dir = dataset_dir + "/test" + self.interFrames = interFrames + self.setLength = interFrames + 2 + video_list = [ + "GOPR0384_11_00", + "GOPR0385_11_01", + "GOPR0410_11_00", + "GOPR0862_11_00", + "GOPR0869_11_00", + "GOPR0881_11_01", + "GOPR0384_11_05", + "GOPR0396_11_00", + "GOPR0854_11_00", + "GOPR0868_11_00", + "GOPR0871_11_00", + ] + self.frames_list = [] + self.file_list = [] + for video in video_list: + frames = sorted(os.listdir(os.path.join(self.dataset_dir, video))) + n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1 + videoInputs = [ + frames[(interFrames + 1) * i : (interFrames + 1) * i + self.setLength] for i in range(n_sets) + ] + videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs] + self.file_list.extend(videoInputs) + + def __len__(self): + return len(self.file_list) * self.interFrames + + def __getitem__(self, idx): + clip_idx = idx // self.interFrames + embt_idx = idx % self.interFrames + imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]] + pick_idxs = list(range(0, self.setLength, self.interFrames + 1)) + imgt_beg = self.setLength // 2 - self.interFrames // 2 + imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2 + imgt_idx = list(range(imgt_beg, imgt_end)) + input_paths = [imgpaths[idx] for idx in pick_idxs] + imgt_paths = [imgpaths[idx] for idx in imgt_idx] + + img0 = np.array(read(input_paths[0])) + imgt = np.array(read(imgt_paths[embt_idx])) + img1 = np.array(read(input_paths[1])) + + img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)) + + img0 = img2tensor(img0).squeeze(0) + imgt = img2tensor(imgt).squeeze(0) + img1 = img2tensor(img1).squeeze(0) + + embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)).reshape(1, 1, 1).astype(np.float32)) + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "embt": embt} diff --git a/Helios/eval/utils/third_party/amt/datasets/vimeo_datasets.py b/Helios/eval/utils/third_party/amt/datasets/vimeo_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..c792a210ff57e960eab33200a9c0d27c692a76b1 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/datasets/vimeo_datasets.py @@ -0,0 +1,168 @@ +import os +import random + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from utils.utils import read + + +def random_resize(img0, imgt, img1, flow, p=0.1): + if random.uniform(0, 1) < p: + img0 = cv2.resize(img0, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + imgt = cv2.resize(imgt, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + img1 = cv2.resize(img1, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + flow = cv2.resize(flow, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) * 2.0 + return img0, imgt, img1, flow + + +def random_crop(img0, imgt, img1, flow, crop_size=(224, 224)): + h, w = crop_size[0], crop_size[1] + ih, iw, _ = img0.shape + x = np.random.randint(0, ih - h + 1) + y = np.random.randint(0, iw - w + 1) + img0 = img0[x : x + h, y : y + w, :] + imgt = imgt[x : x + h, y : y + w, :] + img1 = img1[x : x + h, y : y + w, :] + flow = flow[x : x + h, y : y + w, :] + return img0, imgt, img1, flow + + +def random_reverse_channel(img0, imgt, img1, flow, p=0.5): + if random.uniform(0, 1) < p: + img0 = img0[:, :, ::-1] + imgt = imgt[:, :, ::-1] + img1 = img1[:, :, ::-1] + return img0, imgt, img1, flow + + +def random_vertical_flip(img0, imgt, img1, flow, p=0.3): + if random.uniform(0, 1) < p: + img0 = img0[::-1] + imgt = imgt[::-1] + img1 = img1[::-1] + flow = flow[::-1] + flow = np.concatenate((flow[:, :, 0:1], -flow[:, :, 1:2], flow[:, :, 2:3], -flow[:, :, 3:4]), 2) + return img0, imgt, img1, flow + + +def random_horizontal_flip(img0, imgt, img1, flow, p=0.5): + if random.uniform(0, 1) < p: + img0 = img0[:, ::-1] + imgt = imgt[:, ::-1] + img1 = img1[:, ::-1] + flow = flow[:, ::-1] + flow = np.concatenate((-flow[:, :, 0:1], flow[:, :, 1:2], -flow[:, :, 2:3], flow[:, :, 3:4]), 2) + return img0, imgt, img1, flow + + +def random_rotate(img0, imgt, img1, flow, p=0.05): + if random.uniform(0, 1) < p: + img0 = img0.transpose((1, 0, 2)) + imgt = imgt.transpose((1, 0, 2)) + img1 = img1.transpose((1, 0, 2)) + flow = flow.transpose((1, 0, 2)) + flow = np.concatenate((flow[:, :, 1:2], flow[:, :, 0:1], flow[:, :, 3:4], flow[:, :, 2:3]), 2) + return img0, imgt, img1, flow + + +def random_reverse_time(img0, imgt, img1, flow, p=0.5): + if random.uniform(0, 1) < p: + tmp = img1 + img1 = img0 + img0 = tmp + flow = np.concatenate((flow[:, :, 2:4], flow[:, :, 0:2]), 2) + return img0, imgt, img1, flow + + +class Vimeo90K_Train_Dataset(Dataset): + def __init__(self, dataset_dir="data/vimeo_triplet", flow_dir=None, augment=True, crop_size=(224, 224)): + self.dataset_dir = dataset_dir + self.augment = augment + self.crop_size = crop_size + self.img0_list = [] + self.imgt_list = [] + self.img1_list = [] + self.flow_t0_list = [] + self.flow_t1_list = [] + if flow_dir is None: + flow_dir = "flow" + with open(os.path.join(dataset_dir, "tri_trainlist.txt"), "r") as f: + for i in f: + name = str(i).strip() + if len(name) <= 1: + continue + self.img0_list.append(os.path.join(dataset_dir, "sequences", name, "im1.png")) + self.imgt_list.append(os.path.join(dataset_dir, "sequences", name, "im2.png")) + self.img1_list.append(os.path.join(dataset_dir, "sequences", name, "im3.png")) + self.flow_t0_list.append(os.path.join(dataset_dir, flow_dir, name, "flow_t0.flo")) + self.flow_t1_list.append(os.path.join(dataset_dir, flow_dir, name, "flow_t1.flo")) + + def __len__(self): + return len(self.imgt_list) + + def __getitem__(self, idx): + img0 = read(self.img0_list[idx]) + imgt = read(self.imgt_list[idx]) + img1 = read(self.img1_list[idx]) + flow_t0 = read(self.flow_t0_list[idx]) + flow_t1 = read(self.flow_t1_list[idx]) + flow = np.concatenate((flow_t0, flow_t1), 2).astype(np.float64) + + if self.augment: + img0, imgt, img1, flow = random_resize(img0, imgt, img1, flow, p=0.1) + img0, imgt, img1, flow = random_crop(img0, imgt, img1, flow, crop_size=self.crop_size) + img0, imgt, img1, flow = random_reverse_channel(img0, imgt, img1, flow, p=0.5) + img0, imgt, img1, flow = random_vertical_flip(img0, imgt, img1, flow, p=0.3) + img0, imgt, img1, flow = random_horizontal_flip(img0, imgt, img1, flow, p=0.5) + img0, imgt, img1, flow = random_rotate(img0, imgt, img1, flow, p=0.05) + img0, imgt, img1, flow = random_reverse_time(img0, imgt, img1, flow, p=0.5) + + img0 = torch.from_numpy(img0.transpose((2, 0, 1)).astype(np.float32) / 255.0) + imgt = torch.from_numpy(imgt.transpose((2, 0, 1)).astype(np.float32) / 255.0) + img1 = torch.from_numpy(img1.transpose((2, 0, 1)).astype(np.float32) / 255.0) + flow = torch.from_numpy(flow.transpose((2, 0, 1)).astype(np.float32)) + embt = torch.from_numpy(np.array(1 / 2).reshape(1, 1, 1).astype(np.float32)) + + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "flow": flow.float(), "embt": embt} + + +class Vimeo90K_Test_Dataset(Dataset): + def __init__(self, dataset_dir="data/vimeo_triplet"): + self.dataset_dir = dataset_dir + self.img0_list = [] + self.imgt_list = [] + self.img1_list = [] + self.flow_t0_list = [] + self.flow_t1_list = [] + with open(os.path.join(dataset_dir, "tri_testlist.txt"), "r") as f: + for i in f: + name = str(i).strip() + if len(name) <= 1: + continue + self.img0_list.append(os.path.join(dataset_dir, "sequences", name, "im1.png")) + self.imgt_list.append(os.path.join(dataset_dir, "sequences", name, "im2.png")) + self.img1_list.append(os.path.join(dataset_dir, "sequences", name, "im3.png")) + self.flow_t0_list.append(os.path.join(dataset_dir, "flow", name, "flow_t0.flo")) + self.flow_t1_list.append(os.path.join(dataset_dir, "flow", name, "flow_t1.flo")) + + def __len__(self): + return len(self.imgt_list) + + def __getitem__(self, idx): + img0 = read(self.img0_list[idx]) + imgt = read(self.imgt_list[idx]) + img1 = read(self.img1_list[idx]) + flow_t0 = read(self.flow_t0_list[idx]) + flow_t1 = read(self.flow_t1_list[idx]) + flow = np.concatenate((flow_t0, flow_t1), 2) + + img0 = torch.from_numpy(img0.transpose((2, 0, 1)).astype(np.float32) / 255.0) + imgt = torch.from_numpy(imgt.transpose((2, 0, 1)).astype(np.float32) / 255.0) + img1 = torch.from_numpy(img1.transpose((2, 0, 1)).astype(np.float32) / 255.0) + flow = torch.from_numpy(flow.transpose((2, 0, 1)).astype(np.float32)) + embt = torch.from_numpy(np.array(1 / 2).reshape(1, 1, 1).astype(np.float32)) + + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "flow": flow.float(), "embt": embt} diff --git a/Helios/eval/utils/third_party/amt/docs/develop.md b/Helios/eval/utils/third_party/amt/docs/develop.md new file mode 100644 index 0000000000000000000000000000000000000000..e927e97632041b7da0adca95e944d9570cfe440c --- /dev/null +++ b/Helios/eval/utils/third_party/amt/docs/develop.md @@ -0,0 +1,239 @@ +# Development for evaluation and training + +- [Datasets](#Datasets) +- [Pretrained Models](#pretrained-models) +- [Evaluation](#evaluation) +- [Training](#training) + +## Datasets

+First, please prepare standard datasets for evaluation and training. + +We present most of prevailing datasets in video frame interpolation, though some are not used in our project. Hope this collection could help your research. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dataset :link: Source Train/Eval Arbitrary/Fixed
Vimeo90kToFlow (IJCV 2019)BothFixed
ATD-12KAnimeInterp (CVPR 2021)BothFixed
SNU-FILMCAIN (AAAI 2021)EvalFixed
UCF101Google DriverEvalFixed
HDMEMC-Net (TPAMI 2018)/Google DriverEvalFixed
Xiph-2k/-4kSoftSplat (CVPR 2020)EvalFixed
MiddleBuryMiddleBuryEvalFixed
GoProGoProBothArbitrary
Adobe240fpsDBN (CVPR 2017)BothArbitrary
X4K1000FPSXVFI (ICCV 2021)BothArbitrary
+ + +## Pretrained Models + +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dataset :link: Download Links Config file Trained on Arbitrary/Fixed
AMT-S [Google Driver][Baidu Cloud] [cfgs/AMT-S] Vimeo90kFixed
AMT-L[Google Driver][Baidu Cloud] [cfgs/AMT-L] Vimeo90kFixed
AMT-G[Google Driver][Baidu Cloud] [cfgs/AMT-G] Vimeo90kFixed
AMT-S[Google Driver][Baidu Cloud] [cfgs/AMT-S_gopro] GoProArbitrary
+ +## Evaluation +Before evaluation, you should: + +1. Check the dataroot is organized as follows: + +```shell +./data +├── Adobe240 +│ ├── original_high_fps_videos +│ └── test_frames # using ffmpeg to extract 240 fps frames from `original_high_fps_videos` +├── GOPRO +│ ├── test +│ └── train +├── SNU_FILM +│ ├── GOPRO_test +│ ├── test-easy.txt +│ ├── test-extreme.txt +│ ├── test-hard.txt +│ ├── test-medium.txt +│ └── YouTube_test +├── ucf101_interp_ours +│ ├── 1 +│ ├── 1001 +│ └── ... +└── vimeo_triplet + ├── readme.txt + ├── sequences + ├── tri_testlist.txt + └── tri_trainlist.txt +``` + +2. Download the provided [pretrained models](#pretrained-models). + +Then, you can perform evaluation as follows: + ++ Run all benchmarks for fixed-time models. + + ```shell + sh ./scripts/benchmark_fixed.sh [CFG] [CKPT_PATH] + ## e.g. + sh ./scripts/benchmark_fixed.sh cfgs/AMT-S.yaml pretrained/amt-s.pth + ``` + ++ Run all benchmarks for arbitrary-time models. + + ```shell + sh ./scripts/benchmark_arbitrary.sh [CFG] [CKPT_PATH] + ## e.g. + sh ./scripts/benchmark_arbitrary.sh cfgs/AMT-S.yaml pretrained/gopro_amt-s.pth + ``` + ++ Run a single benchmark for fixed-time models. *You can custom data paths in this case*. + + ```shell + python [BENCHMARK] -c [CFG] -p [CKPT_PATH] -r [DATAROOT] + ## e.g. + python benchmarks/vimeo90k.py -c cfgs/AMT-S.yaml -p pretrained/amt-s.pth -r data/vimeo_triplet + ``` + ++ Run the inference speed & model size comparisons using: + + ```shell + python speed_parameters.py -c [CFG] + ## e.g. + python speed_parameters.py -c cfgs/AMT-S.yaml + ``` + + +## Training + +Before training, please first prepare the optical flows (which are used for supervision). + +We need to install `cupy` first before flow generation: + +```shell +conda activate amt # satisfying `requirement.txt` +conda install -c conda-forge cupy +``` + + +After installing `cupy`, we can generate optical flows by the following command: + +```shell +python flow_generation/gen_flow.py -r [DATA_ROOT] +## e.g. +python flow_generation/gen_flow.py -r data/vimeo_triplet +``` + +After obtaining the optical flow of the training data, +run the following commands for training (DDP mode): + +```shell + sh ./scripts/train.sh [NUM_GPU] [CFG] [MASTER_PORT] + ## e.g. + sh ./scripts/train.sh 2 cfgs/AMT-S.yaml 14514 +``` + +Our training configuration files are provided in [`cfgs`](../cfgs). Please carefully check the `dataset_dir` is suitable for you. + + +Note: + +- If you intend to turn off DDP training, you can switch the key `distributed` from `true` +to `false` in the config file. + +- If you do not use wandb, you can switch the key `logger.use_wandb` from `true` +to `false` in the config file. \ No newline at end of file diff --git a/Helios/eval/utils/third_party/amt/docs/method.md b/Helios/eval/utils/third_party/amt/docs/method.md new file mode 100644 index 0000000000000000000000000000000000000000..1343649b503f807a0e6c46f0895d78c3fc6f4e79 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/docs/method.md @@ -0,0 +1,126 @@ +# Illustration of AMT + +

+ +

+ +### :rocket: Highlights: + ++ [**Good tradeoff**](#good-tradeoff) between performance and efficiency. + ++ [**All-pairs correlation**](#all-pairs-correlation) for modeling large motions during interpolation. + ++ A [**plug-and-play operator**](#multi-field-refinement) to improve the diversity of predicted task-oriented flows, further **boosting the interpolation performance**. + + +## Good Tradeoff + +

+ +

+ +We examine the proposed AMT on several public benchmarks with different model scales, showing strong performance and high efficiency in contrast to the SOTA methods (see Figure). Our small model outperforms [IFRNet-B](https://arxiv.org/abs/2205.14620), a SOTA lightweight model, by **\+0.17dB PSNR** on Vimeo90K with **only 60% of its FLOPs and parameters**. For large-scale setting, our AMT exceeds the previous SOTA (i.e., [IFRNet-L](https://arxiv.org/abs/2205.14620)) by **+0.15 dB PSNR** on Vimeo90K with **75% of its FLOPs and 65% of its parameters**. Besides, we provide a huge model for comparison +with the SOTA transformer-based method [VFIFormer](https://arxiv.org/abs/2205.07230). Our convolution-based AMT shows a **comparable performance** but only needs **nearly 23× less computational cost** compared to VFIFormer. + +Considering its effectiveness, we hope our AMT could bring a new perspective for the architecture design in efficient frame interpolation. + +## All-pairs correlation + +We build all-pairs correlation to effectively model large motions during interpolation. + +Here is an example about the update operation at a single scale in AMT: + +```python + # Construct bidirectional correlation volumes + fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [B, C, H//8, W//8] + corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels) + + # Correlation scaled lookup (bilateral -> bidirectional) + t1_scale = 1. / embt + t0_scale = 1. / (1. - embt) + coord = coords_grid(b, h // 8, w // 8, img0.device) + corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale) + corr = torch.cat([corr0, corr1], dim=1) + flow = torch.cat([flow0, flow1], dim=1) + + # Update both intermediate feature and bilateral flows + delta_feat, delta_flow = self.update(feat, flow, corr) + delta_flow0, delta_flow1 = torch.chunk(delta_flow, 2, 1) + flow0 = flow0 + delta_flow0 + flow1= flow1 + delta_flow1 + feat = feat + delta_feat + +``` + +Note: we extend above operations to each pyramid scale (except for the last one), which guarantees the consistency of flows on the coarse scale. + +### ⏫ performance gain +| | Vimeo 90k | Hard | Extreme | +|-------------------------|-----------|-------|---------| +| Baseline | 35.60 | 30.39 | 25.06 | +| + All-pairs correlation | 35.97 (**+0.37**) | 30.60 (**+0.21**) | 25.30 (**+0.24**) | + +More ablations can be found in the [paper](https://arxiv.org/abs/2304.09790). + +## Multi-field Refinement + +For most frame interpolation methods which are based on backward warping, the common formulation for +interpolating the final intermediate frame $I_{t}$ is: + +$I_{t} = M \odot \mathcal{W}(I_{0}, F_{t\rightarrow 0}) + (1 - M) \odot \mathcal{W}(I_{1}, F_{t\rightarrow 1}) + R$ + +Above formualtion only utilizes **one set of** bilateral optical flows $F_{t\rightarrow 0}$ and $F_{t\rightarrow 1}$, occulusion masks $M$, and residuals $R$. + +Multi-field refinement aims to improve the common formulation of backward warping. +Specifically, we first predict **multiple** bilateral optical flows (accompanied by the corresponding masks and residuals) through simply enlarging the output channels of the last decoder. +Then, we use aforementioned equation to genearate each interpolated candidate frame. Finally, we obtain the final interpolated frame through combining candidate frames using stacked convolutional layers. + +Please refer to [this code snippet](../networks/blocks/multi_flow.py#L46) for the details of the first step. +Please refer to [this code snippet](../networks/blocks/multi_flow.py#L10) for the details of the last two steps. + +### 🌟 easy to use +The proposed multi-field refinement can be **easily migrated to any frame interpolation model** to improve the performance. + +Code examples are shown below: + +```python + +# (At the __init__ stage) Initialize a decoder that predicts multiple flow fields (accompanied by the corresponding masks and residuals) +self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows) +... + +# (At the forward stage) Predict multiple flow fields (accompanied by the corresponding masks and residuals) +up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) +# Merge multiple predictions +imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, # self.comb_block stacks two convolutional layers + mask, img_res, mean_) + +``` + +### ⏫ performance gain + +| # Number of flow pairs | Vimeo 90k | Hard | Extreme | +|------------------------|---------------|---------------|---------------| +| Baseline (1 pair) | 35.84 | 30.52 | 25.25 | +| 3 pairs | 35.97 (**+0.13**) | 30.60 (**+0.08**) | 25.30 (**+0.05**) | +| 5 pairs | 36.00 (**+0.16**) | 30.63 (**+0.11**) | 25.33 (**+0.08**) | + +## Comparison with SOTA methods +

+ +

+ + +## Discussions + +We encountered the challenges about the novelty issue during the rebuttal process. + +We are ready to clarify again here: + +1. We consider the estimation of task-oriented flows from **the perspective of architecture formulation rather than loss function designs** in previous works. The detailed analysis can be found in Sec. 1 of the main paper. We introduce all-pairs correlation to strengthen the ability +in motion modeling, which guarantees **the consistency of flows on the coarse scale**. We employ multi-field refinement to **ensure diversity for the flow regions that need to be task-specific at the finest scale**. The two designs also enable our AMT to capture large motions and successfully handle occlusion regions with high efficiency. As a consequence, they both bring noticeable performance improvements, as shown in the ablations. +2. The frame interpolation task is closely related to the **motion modeling**. We strongly believe that a [RAFT-style](https://arxiv.org/abs/2003.12039) approach to motion modeling would be beneficial for the frame interpolation task. However, such style **has not been well studied** in the recent frame interpolation literature. Experimental results show that **all-pairs correlation is very important for the performance gain**. We also involve many novel and task-specific designs +beyond the original RAFT. For other task-related design choices, our volume design, scaled lookup strategy, content update, and cross-scale update way have good performance gains on challenging cases (i.e., Hard and Extreme). Besides, if we discard all design choices (but remaining multi-field refinement) and follow the original RAFT to retrain a new model, **the PSNR values will dramatically decrease** (-0.20dB on Vimeo, -0.33dB on Hard, and -0.39dB on Extreme). +3. [M2M-VFI](https://arxiv.org/abs/2204.03513) is the most relevant to our multi-field refinement. It also generates multiple flows through the decoder and prepares warped candidates in the image domain. However, there are **five key differences** between our multi-field refinement and M2M-VFI. **First**, our method generates the candidate frames by backward warping rather than forward warping in M2M-VFI. The proposed multi-field refinement aims to improve the common formulation of backward warping (see Eqn.~(4) in the main paper). **Second**, while M2M-VFI predicts multiple flows to overcome the hole issue and artifacts in overlapped regions caused by forward warping, we aim to alleviate the ambiguity issue in the occluded areas and motion boundaries by enhancing the diversity of flows. **Third**, M2M-VFI needs to estimate bidirectional flows first through an off-the-shelf optical flow estimator and then predict multiple bilateral flows through a motion refinement network. On the contrary, we directly estimate multiple bilateral flows in a one-stage network. In this network, we first estimate one pair of bilateral flows at the coarse scale and then derive multiple groups of fine-grained bilateral flows from the coarse flow pairs. **Fourth**, M2M-VFI jointly estimates two reliability maps together with all pairs of bilateral flows, which can be further used to fuse the overlapping pixels caused by forward warping. As shown in Eqn. (5) of the main paper, we estimate not only an occlusion mask but a residual content for cooperating with each pair of bilateral flows. The residual content is used to compensate for the unreliable details after warping. This design has been investigated in Tab. 2e of the main paper. **Fifth**, we stack two convolutional layers to adaptively merge candidate frames, while M2M-VFI normalizes the sum of all candidate frames through a pre-computed weighting map + +More discussions and details can be found in the [appendix](https://arxiv.org/abs/2304.09790) of our paper. diff --git a/Helios/eval/utils/third_party/amt/environment.yaml b/Helios/eval/utils/third_party/amt/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd402d0bcdc80996e6ef504a7ef607b3d3e840f3 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/environment.yaml @@ -0,0 +1,19 @@ +name: amt +channels: + - pytorch + - conda-forge + - defaults +dependencies: + - python=3.8.5 + - pip=20.3 + - cudatoolkit=11.3 + - pytorch=1.11.0 + - torchvision=0.12.0 + - numpy=1.21.5 + - pip: + - opencv-python==4.1.2.30 + - imageio==2.19.3 + - omegaconf==2.3.0 + - Pillow==9.4.0 + - tqdm==4.64.1 + - wandb==0.12.21 \ No newline at end of file diff --git a/Helios/eval/utils/third_party/amt/flow_generation/__init__.py b/Helios/eval/utils/third_party/amt/flow_generation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/flow_generation/gen_flow.py b/Helios/eval/utils/third_party/amt/flow_generation/gen_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..75e2d7e7940fb95b47e22faec3629293745064a2 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/flow_generation/gen_flow.py @@ -0,0 +1,76 @@ +import argparse +import os +import os.path as osp +import sys + +import torch + + +sys.path.append(".") +from flow_generation.liteflownet.run import estimate + +from utils.utils import read, write + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Flow generation", +) +parser.add_argument("-r", "--root", default="data/vimeo_triplet") +args = parser.parse_args() + +vimeo90k_dir = args.root +vimeo90k_sequences_dir = osp.join(vimeo90k_dir, "sequences") +vimeo90k_flow_dir = osp.join(vimeo90k_dir, "flow") + + +def pred_flow(img1, img2): + img1 = torch.from_numpy(img1).float().permute(2, 0, 1) / 255.0 + img2 = torch.from_numpy(img2).float().permute(2, 0, 1) / 255.0 + + flow = estimate(img1, img2) + + flow = flow.permute(1, 2, 0).cpu().numpy() + return flow + + +print("Built Flow Path") +if not osp.exists(vimeo90k_flow_dir): + os.makedirs(vimeo90k_flow_dir) + +for sequences_path in sorted(os.listdir(vimeo90k_sequences_dir)): + vimeo90k_sequences_path_dir = osp.join(vimeo90k_sequences_dir, sequences_path) + vimeo90k_flow_path_dir = osp.join(vimeo90k_flow_dir, sequences_path) + if not osp.exists(vimeo90k_flow_path_dir): + os.mkdir(vimeo90k_flow_path_dir) + + for sequences_id in sorted(os.listdir(vimeo90k_sequences_path_dir)): + vimeo90k_flow_id_dir = osp.join(vimeo90k_flow_path_dir, sequences_id) + if not osp.exists(vimeo90k_flow_id_dir): + os.mkdir(vimeo90k_flow_id_dir) + +for sequences_path in sorted(os.listdir(vimeo90k_sequences_dir)): + vimeo90k_sequences_path_dir = os.path.join(vimeo90k_sequences_dir, sequences_path) + vimeo90k_flow_path_dir = os.path.join(vimeo90k_flow_dir, sequences_path) + + for sequences_id in sorted(os.listdir(vimeo90k_sequences_path_dir)): + vimeo90k_sequences_id_dir = os.path.join(vimeo90k_sequences_path_dir, sequences_id) + vimeo90k_flow_id_dir = os.path.join(vimeo90k_flow_path_dir, sequences_id) + + img0_path = vimeo90k_sequences_id_dir + "/im1.png" + imgt_path = vimeo90k_sequences_id_dir + "/im2.png" + img1_path = vimeo90k_sequences_id_dir + "/im3.png" + flow_t0_path = vimeo90k_flow_id_dir + "/flow_t0.flo" + flow_t1_path = vimeo90k_flow_id_dir + "/flow_t1.flo" + + img0 = read(img0_path) + imgt = read(imgt_path) + img1 = read(img1_path) + + flow_t0 = pred_flow(imgt, img0) + flow_t1 = pred_flow(imgt, img1) + + write(flow_t0_path, flow_t0) + write(flow_t1_path, flow_t1) + + print("Written Sequences {}".format(sequences_path)) diff --git a/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/README.md b/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9511ad984f0209048ad912250b611f8e0459668b --- /dev/null +++ b/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/README.md @@ -0,0 +1,45 @@ +# pytorch-liteflownet +This is a personal reimplementation of LiteFlowNet [1] using PyTorch. Should you be making use of this work, please cite the paper accordingly. Also, make sure to adhere to the licensing terms of the authors. Should you be making use of this particular implementation, please acknowledge it appropriately [2]. + +Paper + +For the original Caffe version of this work, please see: https://github.com/twhui/LiteFlowNet +
+Other optical flow implementations from me: [pytorch-pwc](https://github.com/sniklaus/pytorch-pwc), [pytorch-unflow](https://github.com/sniklaus/pytorch-unflow), [pytorch-spynet](https://github.com/sniklaus/pytorch-spynet) + +## setup +The correlation layer is implemented in CUDA using CuPy, which is why CuPy is a required dependency. It can be installed using `pip install cupy` or alternatively using one of the provided [binary packages](https://docs.cupy.dev/en/stable/install.html#installing-cupy) as outlined in the CuPy repository. If you would like to use Docker, you can take a look at [this](https://github.com/sniklaus/pytorch-liteflownet/pull/43) pull request to get started. + +## usage +To run it on your own pair of images, use the following command. You can choose between three models, please make sure to see their paper / the code for more details. + +``` +python run.py --model default --one ./images/one.png --two ./images/two.png --out ./out.flo +``` + +I am afraid that I cannot guarantee that this reimplementation is correct. However, it produced results pretty much identical to the implementation of the original authors in the examples that I tried. There are some numerical deviations that stem from differences in the `DownsampleLayer` of Caffe and the `torch.nn.functional.interpolate` function of PyTorch. Please feel free to contribute to this repository by submitting issues and pull requests. + +## comparison +

Comparison

+ +## license +As stated in the licensing terms of the authors of the paper, their material is provided for research purposes only. Please make sure to further consult their licensing terms. + +## references +``` +[1] @inproceedings{Hui_CVPR_2018, + author = {Tak-Wai Hui and Xiaoou Tang and Chen Change Loy}, + title = {{LiteFlowNet}: A Lightweight Convolutional Neural Network for Optical Flow Estimation}, + booktitle = {IEEE Conference on Computer Vision and Pattern Recognition}, + year = {2018} + } +``` + +``` +[2] @misc{pytorch-liteflownet, + author = {Simon Niklaus}, + title = {A Reimplementation of {LiteFlowNet} Using {PyTorch}}, + year = {2019}, + howpublished = {\url{https://github.com/sniklaus/pytorch-liteflownet}} + } +``` \ No newline at end of file diff --git a/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/__init__.py b/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/README.md b/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e80f923bfa484ff505366c30f66fa88da0bfd566 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/README.md @@ -0,0 +1 @@ +This is an adaptation of the FlowNet2 implementation in order to compute cost volumes. Should you be making use of this work, please make sure to adhere to the licensing terms of the original authors. Should you be making use or modify this particular implementation, please acknowledge it appropriately. \ No newline at end of file diff --git a/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/correlation.py b/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..c1efcfcf120f0d10784f67427a7f40788d25f54e --- /dev/null +++ b/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/correlation.py @@ -0,0 +1,446 @@ +#!/usr/bin/env python + +import math +import re + +import cupy +import torch + + +kernel_Correlation_rearrange = """ + extern "C" __global__ void kernel_Correlation_rearrange( + const int n, + const float* input, + float* output + ) { + int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; + if (intIndex >= n) { + return; + } + int intSample = blockIdx.z; + int intChannel = blockIdx.y; + float fltValue = input[(((intSample * SIZE_1(input)) + intChannel) * SIZE_2(input) * SIZE_3(input)) + intIndex]; + __syncthreads(); + int intPaddedY = (intIndex / SIZE_3(input)) + 3*{{intStride}}; + int intPaddedX = (intIndex % SIZE_3(input)) + 3*{{intStride}}; + int intRearrange = ((SIZE_3(input) + 6*{{intStride}}) * intPaddedY) + intPaddedX; + output[(((intSample * SIZE_1(output) * SIZE_2(output)) + intRearrange) * SIZE_1(input)) + intChannel] = fltValue; + } +""" + +kernel_Correlation_updateOutput = """ + extern "C" __global__ void kernel_Correlation_updateOutput( + const int n, + const float* rbot0, + const float* rbot1, + float* top + ) { + extern __shared__ char patch_data_char[]; + float *patch_data = (float *)patch_data_char; + // First (upper left) position of kernel upper-left corner in current center position of neighborhood in image 1 + int x1 = (blockIdx.x + 3) * {{intStride}}; + int y1 = (blockIdx.y + 3) * {{intStride}}; + int item = blockIdx.z; + int ch_off = threadIdx.x; + // Load 3D patch into shared shared memory + for (int j = 0; j < 1; j++) { // HEIGHT + for (int i = 0; i < 1; i++) { // WIDTH + int ji_off = (j + i) * SIZE_3(rbot0); + for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS + int idx1 = ((item * SIZE_1(rbot0) + y1+j) * SIZE_2(rbot0) + x1+i) * SIZE_3(rbot0) + ch; + int idxPatchData = ji_off + ch; + patch_data[idxPatchData] = rbot0[idx1]; + } + } + } + __syncthreads(); + __shared__ float sum[32]; + // Compute correlation + for (int top_channel = 0; top_channel < SIZE_1(top); top_channel++) { + sum[ch_off] = 0; + int s2o = (top_channel % 7 - 3) * {{intStride}}; + int s2p = (top_channel / 7 - 3) * {{intStride}}; + for (int j = 0; j < 1; j++) { // HEIGHT + for (int i = 0; i < 1; i++) { // WIDTH + int ji_off = (j + i) * SIZE_3(rbot0); + for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS + int x2 = x1 + s2o; + int y2 = y1 + s2p; + int idxPatchData = ji_off + ch; + int idx2 = ((item * SIZE_1(rbot0) + y2+j) * SIZE_2(rbot0) + x2+i) * SIZE_3(rbot0) + ch; + sum[ch_off] += patch_data[idxPatchData] * rbot1[idx2]; + } + } + } + __syncthreads(); + if (ch_off == 0) { + float total_sum = 0; + for (int idx = 0; idx < 32; idx++) { + total_sum += sum[idx]; + } + const int sumelems = SIZE_3(rbot0); + const int index = ((top_channel*SIZE_2(top) + blockIdx.y)*SIZE_3(top))+blockIdx.x; + top[index + item*SIZE_1(top)*SIZE_2(top)*SIZE_3(top)] = total_sum / (float)sumelems; + } + } + } +""" + +kernel_Correlation_updateGradOne = """ + #define ROUND_OFF 50000 + extern "C" __global__ void kernel_Correlation_updateGradOne( + const int n, + const int intSample, + const float* rbot0, + const float* rbot1, + const float* gradOutput, + float* gradOne, + float* gradTwo + ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) { + int n = intIndex % SIZE_1(gradOne); // channels + int l = (intIndex / SIZE_1(gradOne)) % SIZE_3(gradOne) + 3*{{intStride}}; // w-pos + int m = (intIndex / SIZE_1(gradOne) / SIZE_3(gradOne)) % SIZE_2(gradOne) + 3*{{intStride}}; // h-pos + // round_off is a trick to enable integer division with ceil, even for negative numbers + // We use a large offset, for the inner part not to become negative. + const int round_off = ROUND_OFF; + const int round_off_s1 = {{intStride}} * round_off; + // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior: + int xmin = (l - 3*{{intStride}} + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}}) / {{intStride}} + int ymin = (m - 3*{{intStride}} + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}}) / {{intStride}} + // Same here: + int xmax = (l - 3*{{intStride}} + round_off_s1) / {{intStride}} - round_off; // floor (l - 3*{{intStride}}) / {{intStride}} + int ymax = (m - 3*{{intStride}} + round_off_s1) / {{intStride}} - round_off; // floor (m - 3*{{intStride}}) / {{intStride}} + float sum = 0; + if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) { + xmin = max(0,xmin); + xmax = min(SIZE_3(gradOutput)-1,xmax); + ymin = max(0,ymin); + ymax = min(SIZE_2(gradOutput)-1,ymax); + for (int p = -3; p <= 3; p++) { + for (int o = -3; o <= 3; o++) { + // Get rbot1 data: + int s2o = {{intStride}} * o; + int s2p = {{intStride}} * p; + int idxbot1 = ((intSample * SIZE_1(rbot0) + (m+s2p)) * SIZE_2(rbot0) + (l+s2o)) * SIZE_3(rbot0) + n; + float bot1tmp = rbot1[idxbot1]; // rbot1[l+s2o,m+s2p,n] + // Index offset for gradOutput in following loops: + int op = (p+3) * 7 + (o+3); // index[o,p] + int idxopoffset = (intSample * SIZE_1(gradOutput) + op); + for (int y = ymin; y <= ymax; y++) { + for (int x = xmin; x <= xmax; x++) { + int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p] + sum += gradOutput[idxgradOutput] * bot1tmp; + } + } + } + } + } + const int sumelems = SIZE_1(gradOne); + const int bot0index = ((n * SIZE_2(gradOne)) + (m-3*{{intStride}})) * SIZE_3(gradOne) + (l-3*{{intStride}}); + gradOne[bot0index + intSample*SIZE_1(gradOne)*SIZE_2(gradOne)*SIZE_3(gradOne)] = sum / (float)sumelems; + } } +""" + +kernel_Correlation_updateGradTwo = """ + #define ROUND_OFF 50000 + extern "C" __global__ void kernel_Correlation_updateGradTwo( + const int n, + const int intSample, + const float* rbot0, + const float* rbot1, + const float* gradOutput, + float* gradOne, + float* gradTwo + ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) { + int n = intIndex % SIZE_1(gradTwo); // channels + int l = (intIndex / SIZE_1(gradTwo)) % SIZE_3(gradTwo) + 3*{{intStride}}; // w-pos + int m = (intIndex / SIZE_1(gradTwo) / SIZE_3(gradTwo)) % SIZE_2(gradTwo) + 3*{{intStride}}; // h-pos + // round_off is a trick to enable integer division with ceil, even for negative numbers + // We use a large offset, for the inner part not to become negative. + const int round_off = ROUND_OFF; + const int round_off_s1 = {{intStride}} * round_off; + float sum = 0; + for (int p = -3; p <= 3; p++) { + for (int o = -3; o <= 3; o++) { + int s2o = {{intStride}} * o; + int s2p = {{intStride}} * p; + //Get X,Y ranges and clamp + // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior: + int xmin = (l - 3*{{intStride}} - s2o + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}} - s2o) / {{intStride}} + int ymin = (m - 3*{{intStride}} - s2p + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}} - s2o) / {{intStride}} + // Same here: + int xmax = (l - 3*{{intStride}} - s2o + round_off_s1) / {{intStride}} - round_off; // floor (l - 3*{{intStride}} - s2o) / {{intStride}} + int ymax = (m - 3*{{intStride}} - s2p + round_off_s1) / {{intStride}} - round_off; // floor (m - 3*{{intStride}} - s2p) / {{intStride}} + if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) { + xmin = max(0,xmin); + xmax = min(SIZE_3(gradOutput)-1,xmax); + ymin = max(0,ymin); + ymax = min(SIZE_2(gradOutput)-1,ymax); + // Get rbot0 data: + int idxbot0 = ((intSample * SIZE_1(rbot0) + (m-s2p)) * SIZE_2(rbot0) + (l-s2o)) * SIZE_3(rbot0) + n; + float bot0tmp = rbot0[idxbot0]; // rbot1[l+s2o,m+s2p,n] + // Index offset for gradOutput in following loops: + int op = (p+3) * 7 + (o+3); // index[o,p] + int idxopoffset = (intSample * SIZE_1(gradOutput) + op); + for (int y = ymin; y <= ymax; y++) { + for (int x = xmin; x <= xmax; x++) { + int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p] + sum += gradOutput[idxgradOutput] * bot0tmp; + } + } + } + } + } + const int sumelems = SIZE_1(gradTwo); + const int bot1index = ((n * SIZE_2(gradTwo)) + (m-3*{{intStride}})) * SIZE_3(gradTwo) + (l-3*{{intStride}}); + gradTwo[bot1index + intSample*SIZE_1(gradTwo)*SIZE_2(gradTwo)*SIZE_3(gradTwo)] = sum / (float)sumelems; + } } +""" + + +def cupy_kernel(strFunction, objVariables): + strKernel = globals()[strFunction].replace("{{intStride}}", str(objVariables["intStride"])) + + while True: + objMatch = re.search(r"(SIZE_)([0-4])(\()([^\)]*)(\))", strKernel) + + if objMatch is None: + break + # end + + intArg = int(objMatch.group(2)) + + strTensor = objMatch.group(4) + intSizes = objVariables[strTensor].size() + + strKernel = strKernel.replace( + objMatch.group(), + str(intSizes[intArg] if not torch.is_tensor(intSizes[intArg]) else intSizes[intArg].item()), + ) + # end + + while True: + objMatch = re.search(r"(VALUE_)([0-4])(\()([^\)]+)(\))", strKernel) + + if objMatch is None: + break + # end + + intArgs = int(objMatch.group(2)) + strArgs = objMatch.group(4).split(",") + + strTensor = strArgs[0] + intStrides = objVariables[strTensor].stride() + strIndex = [ + "((" + + strArgs[intArg + 1].replace("{", "(").replace("}", ")").strip() + + ")*" + + str(intStrides[intArg] if not torch.is_tensor(intStrides[intArg]) else intStrides[intArg].item()) + + ")" + for intArg in range(intArgs) + ] + + strKernel = strKernel.replace(objMatch.group(0), strTensor + "[" + str.join("+", strIndex) + "]") + # end + + return strKernel + + +# end + + +@cupy.memoize(for_each_device=True) +def cupy_launch(strFunction, strKernel): + return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction) + + +# end + + +class _FunctionCorrelation(torch.autograd.Function): + @staticmethod + def forward(self, one, two, intStride): + rbot0 = one.new_zeros( + [one.shape[0], one.shape[2] + (6 * intStride), one.shape[3] + (6 * intStride), one.shape[1]] + ) + rbot1 = one.new_zeros( + [one.shape[0], one.shape[2] + (6 * intStride), one.shape[3] + (6 * intStride), one.shape[1]] + ) + + self.intStride = intStride + + one = one.contiguous() + assert one.is_cuda + two = two.contiguous() + assert two.is_cuda + + output = one.new_zeros( + [one.shape[0], 49, int(math.ceil(one.shape[2] / intStride)), int(math.ceil(one.shape[3] / intStride))] + ) + + if one.is_cuda: + n = one.shape[2] * one.shape[3] + cupy_launch( + "kernel_Correlation_rearrange", + cupy_kernel( + "kernel_Correlation_rearrange", {"intStride": self.intStride, "input": one, "output": rbot0} + ), + )( + grid=(int((n + 16 - 1) / 16), one.shape[1], one.shape[0]), + block=(16, 1, 1), + args=[cupy.int32(n), one.data_ptr(), rbot0.data_ptr()], + ) + + n = two.shape[2] * two.shape[3] + cupy_launch( + "kernel_Correlation_rearrange", + cupy_kernel( + "kernel_Correlation_rearrange", {"intStride": self.intStride, "input": two, "output": rbot1} + ), + )( + grid=(int((n + 16 - 1) / 16), two.shape[1], two.shape[0]), + block=(16, 1, 1), + args=[cupy.int32(n), two.data_ptr(), rbot1.data_ptr()], + ) + + n = output.shape[1] * output.shape[2] * output.shape[3] + cupy_launch( + "kernel_Correlation_updateOutput", + cupy_kernel( + "kernel_Correlation_updateOutput", + {"intStride": self.intStride, "rbot0": rbot0, "rbot1": rbot1, "top": output}, + ), + )( + grid=(output.shape[3], output.shape[2], output.shape[0]), + block=(32, 1, 1), + shared_mem=one.shape[1] * 4, + args=[cupy.int32(n), rbot0.data_ptr(), rbot1.data_ptr(), output.data_ptr()], + ) + + elif not one.is_cuda: + raise NotImplementedError() + + # end + + self.save_for_backward(one, two, rbot0, rbot1) + + return output + + # end + + @staticmethod + def backward(self, gradOutput): + one, two, rbot0, rbot1 = self.saved_tensors + + gradOutput = gradOutput.contiguous() + assert gradOutput.is_cuda + + gradOne = ( + one.new_zeros([one.shape[0], one.shape[1], one.shape[2], one.shape[3]]) + if self.needs_input_grad[0] + else None + ) + gradTwo = ( + one.new_zeros([one.shape[0], one.shape[1], one.shape[2], one.shape[3]]) + if self.needs_input_grad[1] + else None + ) + + if one.is_cuda: + if gradOne is not None: + for intSample in range(one.shape[0]): + n = one.shape[1] * one.shape[2] * one.shape[3] + cupy_launch( + "kernel_Correlation_updateGradOne", + cupy_kernel( + "kernel_Correlation_updateGradOne", + { + "intStride": self.intStride, + "rbot0": rbot0, + "rbot1": rbot1, + "gradOutput": gradOutput, + "gradOne": gradOne, + "gradTwo": None, + }, + ), + )( + grid=(int((n + 512 - 1) / 512), 1, 1), + block=(512, 1, 1), + args=[ + cupy.int32(n), + intSample, + rbot0.data_ptr(), + rbot1.data_ptr(), + gradOutput.data_ptr(), + gradOne.data_ptr(), + None, + ], + ) + # end + # end + + if gradTwo is not None: + for intSample in range(one.shape[0]): + n = one.shape[1] * one.shape[2] * one.shape[3] + cupy_launch( + "kernel_Correlation_updateGradTwo", + cupy_kernel( + "kernel_Correlation_updateGradTwo", + { + "intStride": self.intStride, + "rbot0": rbot0, + "rbot1": rbot1, + "gradOutput": gradOutput, + "gradOne": None, + "gradTwo": gradTwo, + }, + ), + )( + grid=(int((n + 512 - 1) / 512), 1, 1), + block=(512, 1, 1), + args=[ + cupy.int32(n), + intSample, + rbot0.data_ptr(), + rbot1.data_ptr(), + gradOutput.data_ptr(), + None, + gradTwo.data_ptr(), + ], + ) + # end + # end + + elif not one.is_cuda: + raise NotImplementedError() + + # end + + return gradOne, gradTwo, None + + # end + + +# end + + +def FunctionCorrelation(tenOne, tenTwo, intStride): + return _FunctionCorrelation.apply(tenOne, tenTwo, intStride) + + +# end + + +class ModuleCorrelation(torch.nn.Module): + def __init__(self): + super().__init__() + + # end + + def forward(self, tenOne, tenTwo, intStride): + return _FunctionCorrelation.apply(tenOne, tenTwo, intStride) + + # end + + +# end diff --git a/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/run.py b/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/run.py new file mode 100644 index 0000000000000000000000000000000000000000..4444ede7163d773125e904724622561c4b06e7b5 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/flow_generation/liteflownet/run.py @@ -0,0 +1,602 @@ +#!/usr/bin/env python + +import getopt +import math +import sys + +import numpy +import PIL +import PIL.Image +import torch + + +try: + from .correlation import correlation # the custom cost volume layer +except Exception: + sys.path.insert(0, "./correlation") + import correlation # you should consider upgrading python +# end + +########################################################## + +assert int(str("").join(torch.__version__.split(".")[0:2])) >= 13 # requires at least pytorch version 1.3.0 + +torch.set_grad_enabled(False) # make sure to not compute gradients for computational performance + +torch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance + +########################################################## + +arguments_strModel = "default" # 'default', or 'kitti', or 'sintel' +arguments_strOne = "./images/one.png" +arguments_strTwo = "./images/two.png" +arguments_strOut = "./out.flo" + +for strOption, strArgument in getopt.getopt( + sys.argv[1:], "", [strParameter[2:] + "=" for strParameter in sys.argv[1::2]] +)[0]: + if strOption == "--model" and strArgument != "": + arguments_strModel = strArgument # which model to use + if strOption == "--one" and strArgument != "": + arguments_strOne = strArgument # path to the first frame + if strOption == "--two" and strArgument != "": + arguments_strTwo = strArgument # path to the second frame + if strOption == "--out" and strArgument != "": + arguments_strOut = strArgument # path to where the output should be stored +# end + +########################################################## + +backwarp_tenGrid = {} + + +def backwarp(tenInput, tenFlow): + if str(tenFlow.shape) not in backwarp_tenGrid: + tenHor = ( + torch.linspace(-1.0 + (1.0 / tenFlow.shape[3]), 1.0 - (1.0 / tenFlow.shape[3]), tenFlow.shape[3]) + .view(1, 1, 1, -1) + .repeat(1, 1, tenFlow.shape[2], 1) + ) + tenVer = ( + torch.linspace(-1.0 + (1.0 / tenFlow.shape[2]), 1.0 - (1.0 / tenFlow.shape[2]), tenFlow.shape[2]) + .view(1, 1, -1, 1) + .repeat(1, 1, 1, tenFlow.shape[3]) + ) + + backwarp_tenGrid[str(tenFlow.shape)] = torch.cat([tenHor, tenVer], 1).cuda() + # end + + tenFlow = torch.cat( + [ + tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), + tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0), + ], + 1, + ) + + return torch.nn.functional.grid_sample( + input=tenInput, + grid=(backwarp_tenGrid[str(tenFlow.shape)] + tenFlow).permute(0, 2, 3, 1), + mode="bilinear", + padding_mode="zeros", + align_corners=False, + ) + + +# end + +########################################################## + + +class Network(torch.nn.Module): + def __init__(self): + super().__init__() + + class Features(torch.nn.Module): + def __init__(self): + super().__init__() + + self.netOne = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=3, out_channels=32, kernel_size=7, stride=1, padding=3), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netTwo = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netThr = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netFou = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netFiv = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netSix = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=128, out_channels=192, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + # end + + def forward(self, tenInput): + tenOne = self.netOne(tenInput) + tenTwo = self.netTwo(tenOne) + tenThr = self.netThr(tenTwo) + tenFou = self.netFou(tenThr) + tenFiv = self.netFiv(tenFou) + tenSix = self.netSix(tenFiv) + + return [tenOne, tenTwo, tenThr, tenFou, tenFiv, tenSix] + + # end + + # end + + class Matching(torch.nn.Module): + def __init__(self, intLevel): + super().__init__() + + self.fltBackwarp = [0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625][intLevel] + + if intLevel != 2: + self.netFeat = torch.nn.Sequential() + + elif intLevel == 2: + self.netFeat = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=1, stride=1, padding=0), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + # end + + if intLevel == 6: + self.netUpflow = None + + elif intLevel != 6: + self.netUpflow = torch.nn.ConvTranspose2d( + in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1, bias=False, groups=2 + ) + + # end + + if intLevel >= 4: + self.netUpcorr = None + + elif intLevel < 4: + self.netUpcorr = torch.nn.ConvTranspose2d( + in_channels=49, out_channels=49, kernel_size=4, stride=2, padding=1, bias=False, groups=49 + ) + + # end + + self.netMain = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=49, out_channels=128, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d( + in_channels=32, + out_channels=2, + kernel_size=[0, 0, 7, 5, 5, 3, 3][intLevel], + stride=1, + padding=[0, 0, 3, 2, 2, 1, 1][intLevel], + ), + ) + + # end + + def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow): + tenFeaturesOne = self.netFeat(tenFeaturesOne) + tenFeaturesTwo = self.netFeat(tenFeaturesTwo) + + if tenFlow is not None: + tenFlow = self.netUpflow(tenFlow) + # end + + if tenFlow is not None: + tenFeaturesTwo = backwarp(tenInput=tenFeaturesTwo, tenFlow=tenFlow * self.fltBackwarp) + # end + + if self.netUpcorr is None: + tenCorrelation = torch.nn.functional.leaky_relu( + input=correlation.FunctionCorrelation( + tenOne=tenFeaturesOne, tenTwo=tenFeaturesTwo, intStride=1 + ), + negative_slope=0.1, + inplace=False, + ) + + elif self.netUpcorr is not None: + tenCorrelation = self.netUpcorr( + torch.nn.functional.leaky_relu( + input=correlation.FunctionCorrelation( + tenOne=tenFeaturesOne, tenTwo=tenFeaturesTwo, intStride=2 + ), + negative_slope=0.1, + inplace=False, + ) + ) + + # end + + return (tenFlow if tenFlow is not None else 0.0) + self.netMain(tenCorrelation) + + # end + + # end + + class Subpixel(torch.nn.Module): + def __init__(self, intLevel): + super().__init__() + + self.fltBackward = [0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625][intLevel] + + if intLevel != 2: + self.netFeat = torch.nn.Sequential() + + elif intLevel == 2: + self.netFeat = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=1, stride=1, padding=0), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + # end + + self.netMain = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=[0, 0, 130, 130, 194, 258, 386][intLevel], + out_channels=128, + kernel_size=3, + stride=1, + padding=1, + ), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d( + in_channels=32, + out_channels=2, + kernel_size=[0, 0, 7, 5, 5, 3, 3][intLevel], + stride=1, + padding=[0, 0, 3, 2, 2, 1, 1][intLevel], + ), + ) + + # end + + def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow): + tenFeaturesOne = self.netFeat(tenFeaturesOne) + tenFeaturesTwo = self.netFeat(tenFeaturesTwo) + + if tenFlow is not None: + tenFeaturesTwo = backwarp(tenInput=tenFeaturesTwo, tenFlow=tenFlow * self.fltBackward) + # end + + return (tenFlow if tenFlow is not None else 0.0) + self.netMain( + torch.cat([tenFeaturesOne, tenFeaturesTwo, tenFlow], 1) + ) + + # end + + # end + + class Regularization(torch.nn.Module): + def __init__(self, intLevel): + super().__init__() + + self.fltBackward = [0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625][intLevel] + + self.intUnfold = [0, 0, 7, 5, 5, 3, 3][intLevel] + + if intLevel >= 5: + self.netFeat = torch.nn.Sequential() + + elif intLevel < 5: + self.netFeat = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=[0, 0, 32, 64, 96, 128, 192][intLevel], + out_channels=128, + kernel_size=1, + stride=1, + padding=0, + ), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + # end + + self.netMain = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=[0, 0, 131, 131, 131, 131, 195][intLevel], + out_channels=128, + kernel_size=3, + stride=1, + padding=1, + ), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + if intLevel >= 5: + self.netDist = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=32, + out_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], + kernel_size=[0, 0, 7, 5, 5, 3, 3][intLevel], + stride=1, + padding=[0, 0, 3, 2, 2, 1, 1][intLevel], + ) + ) + + elif intLevel < 5: + self.netDist = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=32, + out_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], + kernel_size=([0, 0, 7, 5, 5, 3, 3][intLevel], 1), + stride=1, + padding=([0, 0, 3, 2, 2, 1, 1][intLevel], 0), + ), + torch.nn.Conv2d( + in_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], + out_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], + kernel_size=(1, [0, 0, 7, 5, 5, 3, 3][intLevel]), + stride=1, + padding=(0, [0, 0, 3, 2, 2, 1, 1][intLevel]), + ), + ) + + # end + + self.netScaleX = torch.nn.Conv2d( + in_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], out_channels=1, kernel_size=1, stride=1, padding=0 + ) + self.netScaleY = torch.nn.Conv2d( + in_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], out_channels=1, kernel_size=1, stride=1, padding=0 + ) + + # eny + + def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow): + tenDifference = ( + ((tenOne - backwarp(tenInput=tenTwo, tenFlow=tenFlow * self.fltBackward)) ** 2) + .sum(1, True) + .sqrt() + .detach() + ) + + tenDist = self.netDist( + self.netMain( + torch.cat( + [ + tenDifference, + tenFlow + - tenFlow.view(tenFlow.shape[0], 2, -1).mean(2, True).view(tenFlow.shape[0], 2, 1, 1), + self.netFeat(tenFeaturesOne), + ], + 1, + ) + ) + ) + tenDist = (tenDist**2).neg() + tenDist = (tenDist - tenDist.max(1, True)[0]).exp() + + tenDivisor = tenDist.sum(1, True).reciprocal() + + tenScaleX = ( + self.netScaleX( + tenDist + * torch.nn.functional.unfold( + input=tenFlow[:, 0:1, :, :], + kernel_size=self.intUnfold, + stride=1, + padding=int((self.intUnfold - 1) / 2), + ).view_as(tenDist) + ) + * tenDivisor + ) + tenScaleY = ( + self.netScaleY( + tenDist + * torch.nn.functional.unfold( + input=tenFlow[:, 1:2, :, :], + kernel_size=self.intUnfold, + stride=1, + padding=int((self.intUnfold - 1) / 2), + ).view_as(tenDist) + ) + * tenDivisor + ) + + return torch.cat([tenScaleX, tenScaleY], 1) + + # end + + # end + + self.netFeatures = Features() + self.netMatching = torch.nn.ModuleList([Matching(intLevel) for intLevel in [2, 3, 4, 5, 6]]) + self.netSubpixel = torch.nn.ModuleList([Subpixel(intLevel) for intLevel in [2, 3, 4, 5, 6]]) + self.netRegularization = torch.nn.ModuleList([Regularization(intLevel) for intLevel in [2, 3, 4, 5, 6]]) + + self.load_state_dict( + { + strKey.replace("module", "net"): tenWeight + for strKey, tenWeight in torch.hub.load_state_dict_from_url( + url="http://content.sniklaus.com/github/pytorch-liteflownet/network-" + + arguments_strModel + + ".pytorch" + ).items() + } + ) + # self.load_state_dict(torch.load('./liteflownet/network-default.pth')) + + # end + + def forward(self, tenOne, tenTwo): + tenOne[:, 0, :, :] = tenOne[:, 0, :, :] - 0.411618 + tenOne[:, 1, :, :] = tenOne[:, 1, :, :] - 0.434631 + tenOne[:, 2, :, :] = tenOne[:, 2, :, :] - 0.454253 + + tenTwo[:, 0, :, :] = tenTwo[:, 0, :, :] - 0.410782 + tenTwo[:, 1, :, :] = tenTwo[:, 1, :, :] - 0.433645 + tenTwo[:, 2, :, :] = tenTwo[:, 2, :, :] - 0.452793 + + tenFeaturesOne = self.netFeatures(tenOne) + tenFeaturesTwo = self.netFeatures(tenTwo) + + tenOne = [tenOne] + tenTwo = [tenTwo] + + for intLevel in [1, 2, 3, 4, 5]: + tenOne.append( + torch.nn.functional.interpolate( + input=tenOne[-1], + size=(tenFeaturesOne[intLevel].shape[2], tenFeaturesOne[intLevel].shape[3]), + mode="bilinear", + align_corners=False, + ) + ) + tenTwo.append( + torch.nn.functional.interpolate( + input=tenTwo[-1], + size=(tenFeaturesTwo[intLevel].shape[2], tenFeaturesTwo[intLevel].shape[3]), + mode="bilinear", + align_corners=False, + ) + ) + # end + + tenFlow = None + + for intLevel in [-1, -2, -3, -4, -5]: + tenFlow = self.netMatching[intLevel]( + tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow + ) + tenFlow = self.netSubpixel[intLevel]( + tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow + ) + tenFlow = self.netRegularization[intLevel]( + tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow + ) + # end + + return tenFlow * 20.0 + + # end + + +# end + +netNetwork = None + +########################################################## + + +def estimate(tenOne, tenTwo): + global netNetwork + + if netNetwork is None: + netNetwork = Network().cuda().eval() + # end + + assert tenOne.shape[1] == tenTwo.shape[1] + assert tenOne.shape[2] == tenTwo.shape[2] + + intWidth = tenOne.shape[2] + intHeight = tenOne.shape[1] + + # assert(intWidth == 1024) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue + # assert(intHeight == 436) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue + + tenPreprocessedOne = tenOne.cuda().view(1, 3, intHeight, intWidth) + tenPreprocessedTwo = tenTwo.cuda().view(1, 3, intHeight, intWidth) + + intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 32.0) * 32.0)) + intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 32.0) * 32.0)) + + tenPreprocessedOne = torch.nn.functional.interpolate( + input=tenPreprocessedOne, + size=(intPreprocessedHeight, intPreprocessedWidth), + mode="bilinear", + align_corners=False, + ) + tenPreprocessedTwo = torch.nn.functional.interpolate( + input=tenPreprocessedTwo, + size=(intPreprocessedHeight, intPreprocessedWidth), + mode="bilinear", + align_corners=False, + ) + + tenFlow = torch.nn.functional.interpolate( + input=netNetwork(tenPreprocessedOne, tenPreprocessedTwo), + size=(intHeight, intWidth), + mode="bilinear", + align_corners=False, + ) + + tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth) + tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight) + + return tenFlow[0, :, :, :].cpu() + + +# end + +########################################################## + +if __name__ == "__main__": + tenOne = torch.FloatTensor( + numpy.ascontiguousarray( + numpy.array(PIL.Image.open(arguments_strOne))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) + * (1.0 / 255.0) + ) + ) + tenTwo = torch.FloatTensor( + numpy.ascontiguousarray( + numpy.array(PIL.Image.open(arguments_strTwo))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) + * (1.0 / 255.0) + ) + ) + + tenOutput = estimate(tenOne, tenTwo) + + objOutput = open(arguments_strOut, "wb") + + numpy.array([80, 73, 69, 72], numpy.uint8).tofile(objOutput) + numpy.array([tenOutput.shape[2], tenOutput.shape[1]], numpy.int32).tofile(objOutput) + numpy.array(tenOutput.numpy().transpose(1, 2, 0), numpy.float32).tofile(objOutput) + + objOutput.close() +# end diff --git a/Helios/eval/utils/third_party/amt/losses/__init__.py b/Helios/eval/utils/third_party/amt/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/losses/loss.py b/Helios/eval/utils/third_party/amt/losses/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..36d9f3ab20da3dd919418e4fed07f4511161d8e7 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/losses/loss.py @@ -0,0 +1,201 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class Loss(nn.Module): + def __init__(self, loss_weight, keys, mapping=None) -> None: + """ + mapping: map the kwargs keys into desired ones. + """ + super().__init__() + self.loss_weight = loss_weight + self.keys = keys + self.mapping = mapping + if isinstance(mapping, dict): + self.mapping = {k: v for k, v in mapping if v in keys} + + def forward(self, **kwargs): + params = {k: v for k, v in kwargs.items() if k in self.keys} + if self.mapping is not None: + for k, v in kwargs.items(): + if self.mapping.get(k) is not None: + params[self.mapping[k]] = v + + return self._forward(**params) * self.loss_weight + + def _forward(self, **kwargs): + pass + + +class CharbonnierLoss(Loss): + def __init__(self, loss_weight, keys) -> None: + super().__init__(loss_weight, keys) + + def _forward(self, imgt_pred, imgt): + diff = imgt_pred - imgt + loss = ((diff**2 + 1e-6) ** 0.5).mean() + return loss + + +class AdaCharbonnierLoss(Loss): + def __init__(self, loss_weight, keys) -> None: + super().__init__(loss_weight, keys) + + def _forward(self, imgt_pred, imgt, weight): + alpha = weight / 2 + epsilon = 10 ** (-(10 * weight - 1) / 3) + + diff = imgt_pred - imgt + loss = ((diff**2 + epsilon**2) ** alpha).mean() + return loss + + +class TernaryLoss(Loss): + def __init__(self, loss_weight, keys, patch_size=7): + super().__init__(loss_weight, keys) + self.patch_size = patch_size + out_channels = patch_size * patch_size + self.w = np.eye(out_channels).reshape((patch_size, patch_size, 1, out_channels)) + self.w = np.transpose(self.w, (3, 2, 0, 1)) + self.w = torch.tensor(self.w, dtype=torch.float32) + + def transform(self, tensor): + self.w = self.w.to(tensor.device) + tensor_ = tensor.mean(dim=1, keepdim=True) + patches = F.conv2d(tensor_, self.w, padding=self.patch_size // 2, bias=None) + loc_diff = patches - tensor_ + loc_diff_norm = loc_diff / torch.sqrt(0.81 + loc_diff**2) + return loc_diff_norm + + def valid_mask(self, tensor): + padding = self.patch_size // 2 + b, c, h, w = tensor.size() + inner = torch.ones(b, 1, h - 2 * padding, w - 2 * padding).type_as(tensor) + mask = F.pad(inner, [padding] * 4) + return mask + + def _forward(self, imgt_pred, imgt): + loc_diff_x = self.transform(imgt_pred) + loc_diff_y = self.transform(imgt) + diff = loc_diff_x - loc_diff_y.detach() + dist = (diff**2 / (0.1 + diff**2)).mean(dim=1, keepdim=True) + mask = self.valid_mask(imgt_pred) + loss = (dist * mask).mean() + return loss + + +class GeometryLoss(Loss): + def __init__(self, loss_weight, keys, patch_size=3): + super().__init__(loss_weight, keys) + self.patch_size = patch_size + out_channels = patch_size * patch_size + self.w = np.eye(out_channels).reshape((patch_size, patch_size, 1, out_channels)) + self.w = np.transpose(self.w, (3, 2, 0, 1)) + self.w = torch.tensor(self.w).float() + + def transform(self, tensor): + b, c, h, w = tensor.size() + self.w = self.w.to(tensor.device) + tensor_ = tensor.reshape(b * c, 1, h, w) + patches = F.conv2d(tensor_, self.w, padding=self.patch_size // 2, bias=None) + loc_diff = patches - tensor_ + loc_diff_ = loc_diff.reshape(b, c * (self.patch_size**2), h, w) + loc_diff_norm = loc_diff_ / torch.sqrt(0.81 + loc_diff_**2) + return loc_diff_norm + + def valid_mask(self, tensor): + padding = self.patch_size // 2 + b, c, h, w = tensor.size() + inner = torch.ones(b, 1, h - 2 * padding, w - 2 * padding).type_as(tensor) + mask = F.pad(inner, [padding] * 4) + return mask + + def _forward(self, ft_pred, ft_gt): + loss = 0.0 + for pred, gt in zip(ft_pred, ft_gt): + loc_diff_x = self.transform(pred) + loc_diff_y = self.transform(gt) + diff = loc_diff_x - loc_diff_y + dist = (diff**2 / (0.1 + diff**2)).mean(dim=1, keepdim=True) + mask = self.valid_mask(pred) + loss = loss + (dist * mask).mean() + return loss + + +class IFRFlowLoss(Loss): + def __init__(self, loss_weight, keys, beta=0.3) -> None: + super().__init__(loss_weight, keys) + self.beta = beta + self.ada_cb_loss = AdaCharbonnierLoss(1.0, ["imgt_pred", "imgt", "weight"]) + + def _forward(self, flow0_pred, flow1_pred, flow): + robust_weight0 = self.get_robust_weight(flow0_pred[0], flow[:, 0:2]) + robust_weight1 = self.get_robust_weight(flow1_pred[0], flow[:, 2:4]) + loss = 0 + for lvl in range(1, len(flow0_pred)): + scale_factor = 2**lvl + loss = loss + self.ada_cb_loss( + **{ + "imgt_pred": self.resize(flow0_pred[lvl], scale_factor), + "imgt": flow[:, 0:2], + "weight": robust_weight0, + } + ) + loss = loss + self.ada_cb_loss( + **{ + "imgt_pred": self.resize(flow1_pred[lvl], scale_factor), + "imgt": flow[:, 2:4], + "weight": robust_weight1, + } + ) + return loss + + def resize(self, x, scale_factor): + return scale_factor * F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False) + + def get_robust_weight(self, flow_pred, flow_gt): + epe = ((flow_pred.detach() - flow_gt) ** 2).sum(dim=1, keepdim=True) ** 0.5 + robust_weight = torch.exp(-self.beta * epe) + return robust_weight + + +class MultipleFlowLoss(Loss): + def __init__(self, loss_weight, keys, beta=0.3) -> None: + super().__init__(loss_weight, keys) + self.beta = beta + self.ada_cb_loss = AdaCharbonnierLoss(1.0, ["imgt_pred", "imgt", "weight"]) + + def _forward(self, flow0_pred, flow1_pred, flow): + robust_weight0 = self.get_mutli_flow_robust_weight(flow0_pred[0], flow[:, 0:2]) + robust_weight1 = self.get_mutli_flow_robust_weight(flow1_pred[0], flow[:, 2:4]) + loss = 0 + for lvl in range(1, len(flow0_pred)): + scale_factor = 2**lvl + loss = loss + self.ada_cb_loss( + **{ + "imgt_pred": self.resize(flow0_pred[lvl], scale_factor), + "imgt": flow[:, 0:2], + "weight": robust_weight0, + } + ) + loss = loss + self.ada_cb_loss( + **{ + "imgt_pred": self.resize(flow1_pred[lvl], scale_factor), + "imgt": flow[:, 2:4], + "weight": robust_weight1, + } + ) + return loss + + def resize(self, x, scale_factor): + return scale_factor * F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False) + + def get_mutli_flow_robust_weight(self, flow_pred, flow_gt): + b, num_flows, c, h, w = flow_pred.shape + flow_pred = flow_pred.view(b, num_flows, c, h, w) + flow_gt = flow_gt.repeat(1, num_flows, 1, 1).view(b, num_flows, c, h, w) + epe = ((flow_pred.detach() - flow_gt) ** 2).sum(dim=2, keepdim=True).max(1)[0] ** 0.5 + robust_weight = torch.exp(-self.beta * epe) + return robust_weight diff --git a/Helios/eval/utils/third_party/amt/metrics/__init__.py b/Helios/eval/utils/third_party/amt/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/metrics/psnr_ssim.py b/Helios/eval/utils/third_party/amt/metrics/psnr_ssim.py new file mode 100644 index 0000000000000000000000000000000000000000..157dbf75541ab4fc8361ecdfd41645aa32f14ad9 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/metrics/psnr_ssim.py @@ -0,0 +1,142 @@ +from math import exp + +import torch +import torch.nn.functional as F + + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + +def gaussian(window_size, sigma): + gauss = torch.Tensor([exp(-((x - window_size // 2) ** 2) / float(2 * sigma**2)) for x in range(window_size)]) + return gauss / gauss.sum() + + +def create_window(window_size, channel=1): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0).to(device) + window = _2D_window.expand(channel, 1, window_size, window_size).contiguous() + return window + + +def create_window_3d(window_size, channel=1): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()) + _3D_window = _2D_window.unsqueeze(2) @ (_1D_window.t()) + window = _3D_window.expand(1, channel, window_size, window_size, window_size).contiguous().to(device) + return window + + +def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None): + if val_range is None: + if torch.max(img1) > 128: + max_val = 255 + else: + max_val = 1 + + if torch.min(img1) < -0.5: + min_val = -1 + else: + min_val = 0 + L = max_val - min_val + else: + L = val_range + + padd = 0 + (_, channel, height, width) = img1.size() + if window is None: + real_size = min(window_size, height, width) + window = create_window(real_size, channel=channel).to(img1.device) + + mu1 = F.conv2d(F.pad(img1, (5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=channel) + mu2 = F.conv2d(F.pad(img2, (5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv2d(F.pad(img1 * img1, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu1_sq + sigma2_sq = F.conv2d(F.pad(img2 * img2, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu2_sq + sigma12 = F.conv2d(F.pad(img1 * img2, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu1_mu2 + + C1 = (0.01 * L) ** 2 + C2 = (0.03 * L) ** 2 + + v1 = 2.0 * sigma12 + C2 + v2 = sigma1_sq + sigma2_sq + C2 + cs = torch.mean(v1 / v2) + + ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2) + + if size_average: + ret = ssim_map.mean() + else: + ret = ssim_map.mean(1).mean(1).mean(1) + + if full: + return ret, cs + return ret + + +def calculate_ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None): + if val_range is None: + if torch.max(img1) > 128: + max_val = 255 + else: + max_val = 1 + + if torch.min(img1) < -0.5: + min_val = -1 + else: + min_val = 0 + L = max_val - min_val + else: + L = val_range + + padd = 0 + (_, _, height, width) = img1.size() + if window is None: + real_size = min(window_size, height, width) + window = create_window_3d(real_size, channel=1).to(img1.device) + + img1 = img1.unsqueeze(1) + img2 = img2.unsqueeze(1) + + mu1 = F.conv3d(F.pad(img1, (5, 5, 5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=1) + mu2 = F.conv3d(F.pad(img2, (5, 5, 5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=1) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv3d(F.pad(img1 * img1, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu1_sq + sigma2_sq = F.conv3d(F.pad(img2 * img2, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu2_sq + sigma12 = F.conv3d(F.pad(img1 * img2, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu1_mu2 + + C1 = (0.01 * L) ** 2 + C2 = (0.03 * L) ** 2 + + v1 = 2.0 * sigma12 + C2 + v2 = sigma1_sq + sigma2_sq + C2 + cs = torch.mean(v1 / v2) + + ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2) + + if size_average: + ret = ssim_map.mean() + else: + ret = ssim_map.mean(1).mean(1).mean(1) + + if full: + return ret, cs + return ret.detach().cpu().numpy() + + +def calculate_psnr(img1, img2): + psnr = -10 * torch.log10(((img1 - img2) * (img1 - img2)).mean()) + return psnr.detach().cpu().numpy() + + +def calculate_ie(img1, img2): + ie = torch.abs(torch.round(img1 * 255.0) - torch.round(img2 * 255.0)).mean() + return ie.detach().cpu().numpy() diff --git a/Helios/eval/utils/third_party/amt/networks/AMT-G.py b/Helios/eval/utils/third_party/amt/networks/AMT-G.py new file mode 100644 index 0000000000000000000000000000000000000000..16bc9e645f829c3bb9d83543a9ade114c2f4923f --- /dev/null +++ b/Helios/eval/utils/third_party/amt/networks/AMT-G.py @@ -0,0 +1,156 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.feat_enc import LargeEncoder +from utils.third_party.amt.networks.blocks.ifrnet import Encoder, InitDecoder, IntermediateDecoder, resize +from utils.third_party.amt.networks.blocks.multi_flow import MultiFlowDecoder, multi_flow_combine +from utils.third_party.amt.networks.blocks.raft import BasicUpdateBlock, BidirCorrBlock, coords_grid + + +class Model(nn.Module): + def __init__(self, corr_radius=3, corr_lvls=4, num_flows=5, channels=[84, 96, 112, 128], skip_channels=84): + super(Model, self).__init__() + self.radius = corr_radius + self.corr_levels = corr_lvls + self.num_flows = num_flows + + self.feat_encoder = LargeEncoder(output_dim=128, norm_fn="instance", dropout=0.0) + self.encoder = Encoder(channels, large=True) + self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels) + self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels) + self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels) + self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows) + + self.update4 = self._get_updateblock(112, None) + self.update3_low = self._get_updateblock(96, 2.0) + self.update2_low = self._get_updateblock(84, 4.0) + + self.update3_high = self._get_updateblock(96, None) + self.update2_high = self._get_updateblock(84, None) + + self.comb_block = nn.Sequential( + nn.Conv2d(3 * self.num_flows, 6 * self.num_flows, 7, 1, 3), + nn.PReLU(6 * self.num_flows), + nn.Conv2d(6 * self.num_flows, 3, 7, 1, 3), + ) + + def _get_updateblock(self, cdim, scale_factor=None): + return BasicUpdateBlock( + cdim=cdim, + hidden_dim=192, + flow_dim=64, + corr_dim=256, + corr_dim2=192, + fc_dim=188, + scale_factor=scale_factor, + corr_levels=self.corr_levels, + radius=self.radius, + ) + + def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1): + # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0 + # based on linear assumption + t1_scale = 1.0 / embt + t0_scale = 1.0 / (1.0 - embt) + if downsample != 1: + inv = 1 / downsample + flow0 = inv * resize(flow0, scale_factor=inv) + flow1 = inv * resize(flow1, scale_factor=inv) + + corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale) + corr = torch.cat([corr0, corr1], dim=1) + flow = torch.cat([flow0, flow1], dim=1) + return corr, flow + + def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs): + mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True) + img0 = img0 - mean_ + img1 = img1 - mean_ + img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0 + img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1 + b, _, h, w = img0_.shape + coord = coords_grid(b, h // 8, w // 8, img0.device) + + fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8] + corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels) + + # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4] + # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16] + f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_) + f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_) + + ######################################### the 4th decoder ######################################### + up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt) + corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord, up_flow0_4, up_flow1_4, embt, downsample=1) + + # residue update with lookup corr + delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4) + delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1) + up_flow0_4 = up_flow0_4 + delta_flow0_4 + up_flow1_4 = up_flow1_4 + delta_flow1_4 + ft_3_ = ft_3_ + delta_ft_3_ + + ######################################### the 3rd decoder ######################################### + up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4) + corr_3, flow_3 = self._corr_scale_lookup(corr_fn, coord, up_flow0_3, up_flow1_3, embt, downsample=2) + + # residue update with lookup corr + delta_ft_2_, delta_flow_3 = self.update3_low(ft_2_, flow_3, corr_3) + delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1) + up_flow0_3 = up_flow0_3 + delta_flow0_3 + up_flow1_3 = up_flow1_3 + delta_flow1_3 + ft_2_ = ft_2_ + delta_ft_2_ + + # residue update with lookup corr (hr) + corr_3 = resize(corr_3, scale_factor=2.0) + up_flow_3 = torch.cat([up_flow0_3, up_flow1_3], dim=1) + delta_ft_2_, delta_up_flow_3 = self.update3_high(ft_2_, up_flow_3, corr_3) + ft_2_ += delta_ft_2_ + up_flow0_3 += delta_up_flow_3[:, 0:2] + up_flow1_3 += delta_up_flow_3[:, 2:4] + + ######################################### the 2nd decoder ######################################### + up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3) + corr_2, flow_2 = self._corr_scale_lookup(corr_fn, coord, up_flow0_2, up_flow1_2, embt, downsample=4) + + # residue update with lookup corr + delta_ft_1_, delta_flow_2 = self.update2_low(ft_1_, flow_2, corr_2) + delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1) + up_flow0_2 = up_flow0_2 + delta_flow0_2 + up_flow1_2 = up_flow1_2 + delta_flow1_2 + ft_1_ = ft_1_ + delta_ft_1_ + + # residue update with lookup corr (hr) + corr_2 = resize(corr_2, scale_factor=4.0) + up_flow_2 = torch.cat([up_flow0_2, up_flow1_2], dim=1) + delta_ft_1_, delta_up_flow_2 = self.update2_high(ft_1_, up_flow_2, corr_2) + ft_1_ += delta_ft_1_ + up_flow0_2 += delta_up_flow_2[:, 0:2] + up_flow1_2 += delta_up_flow_2[:, 2:4] + + ######################################### the 1st decoder ######################################### + up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) + + if scale_factor != 1.0: + up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + mask = resize(mask, scale_factor=(1.0 / scale_factor)) + img_res = resize(img_res, scale_factor=(1.0 / scale_factor)) + + # Merge multiple predictions + imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, mask, img_res, mean_) + imgt_pred = torch.clamp(imgt_pred, 0, 1) + + if eval: + return { + "imgt_pred": imgt_pred, + } + else: + up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w) + up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w) + return { + "imgt_pred": imgt_pred, + "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4], + "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4], + "ft_pred": [ft_1_, ft_2_, ft_3_], + } diff --git a/Helios/eval/utils/third_party/amt/networks/AMT-L.py b/Helios/eval/utils/third_party/amt/networks/AMT-L.py new file mode 100644 index 0000000000000000000000000000000000000000..fee9366ab71553d78289bb63c1cd0f85496130ea --- /dev/null +++ b/Helios/eval/utils/third_party/amt/networks/AMT-L.py @@ -0,0 +1,140 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.feat_enc import ( + BasicEncoder, +) +from utils.third_party.amt.networks.blocks.ifrnet import Encoder, InitDecoder, IntermediateDecoder, resize +from utils.third_party.amt.networks.blocks.multi_flow import MultiFlowDecoder, multi_flow_combine +from utils.third_party.amt.networks.blocks.raft import BasicUpdateBlock, BidirCorrBlock, coords_grid + + +class Model(nn.Module): + def __init__(self, corr_radius=3, corr_lvls=4, num_flows=5, channels=[48, 64, 72, 128], skip_channels=48): + super(Model, self).__init__() + self.radius = corr_radius + self.corr_levels = corr_lvls + self.num_flows = num_flows + + self.feat_encoder = BasicEncoder(output_dim=128, norm_fn="instance", dropout=0.0) + self.encoder = Encoder([48, 64, 72, 128], large=True) + + self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels) + self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels) + self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels) + self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows) + + self.update4 = self._get_updateblock(72, None) + self.update3 = self._get_updateblock(64, 2.0) + self.update2 = self._get_updateblock(48, 4.0) + + self.comb_block = nn.Sequential( + nn.Conv2d(3 * self.num_flows, 6 * self.num_flows, 7, 1, 3), + nn.PReLU(6 * self.num_flows), + nn.Conv2d(6 * self.num_flows, 3, 7, 1, 3), + ) + + def _get_updateblock(self, cdim, scale_factor=None): + return BasicUpdateBlock( + cdim=cdim, + hidden_dim=128, + flow_dim=48, + corr_dim=256, + corr_dim2=160, + fc_dim=124, + scale_factor=scale_factor, + corr_levels=self.corr_levels, + radius=self.radius, + ) + + def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1): + # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0 + # based on linear assumption + t1_scale = 1.0 / embt + t0_scale = 1.0 / (1.0 - embt) + if downsample != 1: + inv = 1 / downsample + flow0 = inv * resize(flow0, scale_factor=inv) + flow1 = inv * resize(flow1, scale_factor=inv) + + corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale) + corr = torch.cat([corr0, corr1], dim=1) + flow = torch.cat([flow0, flow1], dim=1) + return corr, flow + + def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs): + mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True) + img0 = img0 - mean_ + img1 = img1 - mean_ + img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0 + img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1 + b, _, h, w = img0_.shape + coord = coords_grid(b, h // 8, w // 8, img0.device) + + fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8] + corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels) + + # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4] + # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16] + f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_) + f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_) + + ######################################### the 4th decoder ######################################### + up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt) + corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord, up_flow0_4, up_flow1_4, embt, downsample=1) + + # residue update with lookup corr + delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4) + delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1) + up_flow0_4 = up_flow0_4 + delta_flow0_4 + up_flow1_4 = up_flow1_4 + delta_flow1_4 + ft_3_ = ft_3_ + delta_ft_3_ + + ######################################### the 3rd decoder ######################################### + up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4) + corr_3, flow_3 = self._corr_scale_lookup(corr_fn, coord, up_flow0_3, up_flow1_3, embt, downsample=2) + + # residue update with lookup corr + delta_ft_2_, delta_flow_3 = self.update3(ft_2_, flow_3, corr_3) + delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1) + up_flow0_3 = up_flow0_3 + delta_flow0_3 + up_flow1_3 = up_flow1_3 + delta_flow1_3 + ft_2_ = ft_2_ + delta_ft_2_ + + ######################################### the 2nd decoder ######################################### + up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3) + corr_2, flow_2 = self._corr_scale_lookup(corr_fn, coord, up_flow0_2, up_flow1_2, embt, downsample=4) + + # residue update with lookup corr + delta_ft_1_, delta_flow_2 = self.update2(ft_1_, flow_2, corr_2) + delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1) + up_flow0_2 = up_flow0_2 + delta_flow0_2 + up_flow1_2 = up_flow1_2 + delta_flow1_2 + ft_1_ = ft_1_ + delta_ft_1_ + + ######################################### the 1st decoder ######################################### + up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) + + if scale_factor != 1.0: + up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + mask = resize(mask, scale_factor=(1.0 / scale_factor)) + img_res = resize(img_res, scale_factor=(1.0 / scale_factor)) + + # Merge multiple predictions + imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, mask, img_res, mean_) + imgt_pred = torch.clamp(imgt_pred, 0, 1) + + if eval: + return { + "imgt_pred": imgt_pred, + } + else: + up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w) + up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w) + return { + "imgt_pred": imgt_pred, + "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4], + "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4], + "ft_pred": [ft_1_, ft_2_, ft_3_], + } diff --git a/Helios/eval/utils/third_party/amt/networks/AMT-S.py b/Helios/eval/utils/third_party/amt/networks/AMT-S.py new file mode 100644 index 0000000000000000000000000000000000000000..64a6e32340a36d6e7ba6ee4353ec3ade1c12b293 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/networks/AMT-S.py @@ -0,0 +1,139 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.feat_enc import SmallEncoder +from utils.third_party.amt.networks.blocks.ifrnet import Encoder, InitDecoder, IntermediateDecoder, resize +from utils.third_party.amt.networks.blocks.multi_flow import MultiFlowDecoder, multi_flow_combine +from utils.third_party.amt.networks.blocks.raft import BidirCorrBlock, SmallUpdateBlock, coords_grid + + +class Model(nn.Module): + def __init__(self, corr_radius=3, corr_lvls=4, num_flows=3, channels=[20, 32, 44, 56], skip_channels=20): + super(Model, self).__init__() + self.radius = corr_radius + self.corr_levels = corr_lvls + self.num_flows = num_flows + self.channels = channels + self.skip_channels = skip_channels + + self.feat_encoder = SmallEncoder(output_dim=84, norm_fn="instance", dropout=0.0) + self.encoder = Encoder(channels) + + self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels) + self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels) + self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels) + self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows) + + self.update4 = self._get_updateblock(44) + self.update3 = self._get_updateblock(32, 2) + self.update2 = self._get_updateblock(20, 4) + + self.comb_block = nn.Sequential( + nn.Conv2d(3 * num_flows, 6 * num_flows, 3, 1, 1), + nn.PReLU(6 * num_flows), + nn.Conv2d(6 * num_flows, 3, 3, 1, 1), + ) + + def _get_updateblock(self, cdim, scale_factor=None): + return SmallUpdateBlock( + cdim=cdim, + hidden_dim=76, + flow_dim=20, + corr_dim=64, + fc_dim=68, + scale_factor=scale_factor, + corr_levels=self.corr_levels, + radius=self.radius, + ) + + def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1): + # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0 + # based on linear assumption + t1_scale = 1.0 / embt + t0_scale = 1.0 / (1.0 - embt) + if downsample != 1: + inv = 1 / downsample + flow0 = inv * resize(flow0, scale_factor=inv) + flow1 = inv * resize(flow1, scale_factor=inv) + + corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale) + corr = torch.cat([corr0, corr1], dim=1) + flow = torch.cat([flow0, flow1], dim=1) + return corr, flow + + def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs): + mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True) + img0 = img0 - mean_ + img1 = img1 - mean_ + img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0 + img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1 + b, _, h, w = img0_.shape + coord = coords_grid(b, h // 8, w // 8, img0.device) + + fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8] + corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels) + + # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4] + # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16] + f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_) + f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_) + + ######################################### the 4th decoder ######################################### + up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt) + corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord, up_flow0_4, up_flow1_4, embt, downsample=1) + + # residue update with lookup corr + delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4) + delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1) + up_flow0_4 = up_flow0_4 + delta_flow0_4 + up_flow1_4 = up_flow1_4 + delta_flow1_4 + ft_3_ = ft_3_ + delta_ft_3_ + + ######################################### the 3rd decoder ######################################### + up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4) + corr_3, flow_3 = self._corr_scale_lookup(corr_fn, coord, up_flow0_3, up_flow1_3, embt, downsample=2) + + # residue update with lookup corr + delta_ft_2_, delta_flow_3 = self.update3(ft_2_, flow_3, corr_3) + delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1) + up_flow0_3 = up_flow0_3 + delta_flow0_3 + up_flow1_3 = up_flow1_3 + delta_flow1_3 + ft_2_ = ft_2_ + delta_ft_2_ + + ######################################### the 2nd decoder ######################################### + up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3) + corr_2, flow_2 = self._corr_scale_lookup(corr_fn, coord, up_flow0_2, up_flow1_2, embt, downsample=4) + + # residue update with lookup corr + delta_ft_1_, delta_flow_2 = self.update2(ft_1_, flow_2, corr_2) + delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1) + up_flow0_2 = up_flow0_2 + delta_flow0_2 + up_flow1_2 = up_flow1_2 + delta_flow1_2 + ft_1_ = ft_1_ + delta_ft_1_ + + ######################################### the 1st decoder ######################################### + up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) + + if scale_factor != 1.0: + up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + mask = resize(mask, scale_factor=(1.0 / scale_factor)) + img_res = resize(img_res, scale_factor=(1.0 / scale_factor)) + + # Merge multiple predictions + imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, mask, img_res, mean_) + imgt_pred = torch.clamp(imgt_pred, 0, 1) + + if eval: + return { + "imgt_pred": imgt_pred, + } + else: + up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w) + up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w) + return { + "imgt_pred": imgt_pred, + "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4], + "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4], + "ft_pred": [ft_1_, ft_2_, ft_3_], + } diff --git a/Helios/eval/utils/third_party/amt/networks/IFRNet.py b/Helios/eval/utils/third_party/amt/networks/IFRNet.py new file mode 100644 index 0000000000000000000000000000000000000000..e1edd419d53fe8780aa5ced1900d38664071d703 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/networks/IFRNet.py @@ -0,0 +1,153 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.ifrnet import ( + ResBlock, + convrelu, + resize, +) +from utils.third_party.amt.utils.flow_utils import warp + + +class Encoder(nn.Module): + def __init__(self): + super(Encoder, self).__init__() + self.pyramid1 = nn.Sequential(convrelu(3, 32, 3, 2, 1), convrelu(32, 32, 3, 1, 1)) + self.pyramid2 = nn.Sequential(convrelu(32, 48, 3, 2, 1), convrelu(48, 48, 3, 1, 1)) + self.pyramid3 = nn.Sequential(convrelu(48, 72, 3, 2, 1), convrelu(72, 72, 3, 1, 1)) + self.pyramid4 = nn.Sequential(convrelu(72, 96, 3, 2, 1), convrelu(96, 96, 3, 1, 1)) + + def forward(self, img): + f1 = self.pyramid1(img) + f2 = self.pyramid2(f1) + f3 = self.pyramid3(f2) + f4 = self.pyramid4(f3) + return f1, f2, f3, f4 + + +class Decoder4(nn.Module): + def __init__(self): + super(Decoder4, self).__init__() + self.convblock = nn.Sequential( + convrelu(192 + 1, 192), ResBlock(192, 32), nn.ConvTranspose2d(192, 76, 4, 2, 1, bias=True) + ) + + def forward(self, f0, f1, embt): + b, c, h, w = f0.shape + embt = embt.repeat(1, 1, h, w) + f_in = torch.cat([f0, f1, embt], 1) + f_out = self.convblock(f_in) + return f_out + + +class Decoder3(nn.Module): + def __init__(self): + super(Decoder3, self).__init__() + self.convblock = nn.Sequential( + convrelu(220, 216), ResBlock(216, 32), nn.ConvTranspose2d(216, 52, 4, 2, 1, bias=True) + ) + + def forward(self, ft_, f0, f1, up_flow0, up_flow1): + f0_warp = warp(f0, up_flow0) + f1_warp = warp(f1, up_flow1) + f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1) + f_out = self.convblock(f_in) + return f_out + + +class Decoder2(nn.Module): + def __init__(self): + super(Decoder2, self).__init__() + self.convblock = nn.Sequential( + convrelu(148, 144), ResBlock(144, 32), nn.ConvTranspose2d(144, 36, 4, 2, 1, bias=True) + ) + + def forward(self, ft_, f0, f1, up_flow0, up_flow1): + f0_warp = warp(f0, up_flow0) + f1_warp = warp(f1, up_flow1) + f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1) + f_out = self.convblock(f_in) + return f_out + + +class Decoder1(nn.Module): + def __init__(self): + super(Decoder1, self).__init__() + self.convblock = nn.Sequential( + convrelu(100, 96), ResBlock(96, 32), nn.ConvTranspose2d(96, 8, 4, 2, 1, bias=True) + ) + + def forward(self, ft_, f0, f1, up_flow0, up_flow1): + f0_warp = warp(f0, up_flow0) + f1_warp = warp(f1, up_flow1) + f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1) + f_out = self.convblock(f_in) + return f_out + + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + self.encoder = Encoder() + self.decoder4 = Decoder4() + self.decoder3 = Decoder3() + self.decoder2 = Decoder2() + self.decoder1 = Decoder1() + + def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs): + mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True) + img0 = img0 - mean_ + img1 = img1 - mean_ + + img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0 + img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1 + + f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_) + f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_) + + out4 = self.decoder4(f0_4, f1_4, embt) + up_flow0_4 = out4[:, 0:2] + up_flow1_4 = out4[:, 2:4] + ft_3_ = out4[:, 4:] + + out3 = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4) + up_flow0_3 = out3[:, 0:2] + 2.0 * resize(up_flow0_4, scale_factor=2.0) + up_flow1_3 = out3[:, 2:4] + 2.0 * resize(up_flow1_4, scale_factor=2.0) + ft_2_ = out3[:, 4:] + + out2 = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3) + up_flow0_2 = out2[:, 0:2] + 2.0 * resize(up_flow0_3, scale_factor=2.0) + up_flow1_2 = out2[:, 2:4] + 2.0 * resize(up_flow1_3, scale_factor=2.0) + ft_1_ = out2[:, 4:] + + out1 = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) + up_flow0_1 = out1[:, 0:2] + 2.0 * resize(up_flow0_2, scale_factor=2.0) + up_flow1_1 = out1[:, 2:4] + 2.0 * resize(up_flow1_2, scale_factor=2.0) + up_mask_1 = torch.sigmoid(out1[:, 4:5]) + up_res_1 = out1[:, 5:] + + if scale_factor != 1.0: + up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_mask_1 = resize(up_mask_1, scale_factor=(1.0 / scale_factor)) + up_res_1 = resize(up_res_1, scale_factor=(1.0 / scale_factor)) + + img0_warp = warp(img0, up_flow0_1) + img1_warp = warp(img1, up_flow1_1) + imgt_merge = up_mask_1 * img0_warp + (1 - up_mask_1) * img1_warp + mean_ + imgt_pred = imgt_merge + up_res_1 + imgt_pred = torch.clamp(imgt_pred, 0, 1) + + if eval: + return { + "imgt_pred": imgt_pred, + } + else: + return { + "imgt_pred": imgt_pred, + "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4], + "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4], + "ft_pred": [ft_1_, ft_2_, ft_3_], + "img0_warp": img0_warp, + "img1_warp": img1_warp, + } diff --git a/Helios/eval/utils/third_party/amt/networks/__init__.py b/Helios/eval/utils/third_party/amt/networks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/networks/blocks/__init__.py b/Helios/eval/utils/third_party/amt/networks/blocks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/networks/blocks/feat_enc.py b/Helios/eval/utils/third_party/amt/networks/blocks/feat_enc.py new file mode 100644 index 0000000000000000000000000000000000000000..479833824b8b2da7e9e3ba05c84b0359b8c79c37 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/networks/blocks/feat_enc.py @@ -0,0 +1,335 @@ +import torch +import torch.nn as nn + + +class BottleneckBlock(nn.Module): + def __init__(self, in_planes, planes, norm_fn="group", stride=1): + super(BottleneckBlock, self).__init__() + + self.conv1 = nn.Conv2d(in_planes, planes // 4, kernel_size=1, padding=0) + self.conv2 = nn.Conv2d(planes // 4, planes // 4, kernel_size=3, padding=1, stride=stride) + self.conv3 = nn.Conv2d(planes // 4, planes, kernel_size=1, padding=0) + self.relu = nn.ReLU(inplace=True) + + num_groups = planes // 8 + + if norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes // 4) + self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes // 4) + self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + if not stride == 1: + self.norm4 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + + elif norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(planes // 4) + self.norm2 = nn.BatchNorm2d(planes // 4) + self.norm3 = nn.BatchNorm2d(planes) + if not stride == 1: + self.norm4 = nn.BatchNorm2d(planes) + + elif norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(planes // 4) + self.norm2 = nn.InstanceNorm2d(planes // 4) + self.norm3 = nn.InstanceNorm2d(planes) + if not stride == 1: + self.norm4 = nn.InstanceNorm2d(planes) + + elif norm_fn == "none": + self.norm1 = nn.Sequential() + self.norm2 = nn.Sequential() + self.norm3 = nn.Sequential() + if not stride == 1: + self.norm4 = nn.Sequential() + + if stride == 1: + self.downsample = None + + else: + self.downsample = nn.Sequential(nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm4) + + def forward(self, x): + y = x + y = self.relu(self.norm1(self.conv1(y))) + y = self.relu(self.norm2(self.conv2(y))) + y = self.relu(self.norm3(self.conv3(y))) + + if self.downsample is not None: + x = self.downsample(x) + + return self.relu(x + y) + + +class ResidualBlock(nn.Module): + def __init__(self, in_planes, planes, norm_fn="group", stride=1): + super(ResidualBlock, self).__init__() + + self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) + self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1) + self.relu = nn.ReLU(inplace=True) + + num_groups = planes // 8 + + if norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + if not stride == 1: + self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + + elif norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(planes) + self.norm2 = nn.BatchNorm2d(planes) + if not stride == 1: + self.norm3 = nn.BatchNorm2d(planes) + + elif norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(planes) + self.norm2 = nn.InstanceNorm2d(planes) + if not stride == 1: + self.norm3 = nn.InstanceNorm2d(planes) + + elif norm_fn == "none": + self.norm1 = nn.Sequential() + self.norm2 = nn.Sequential() + if not stride == 1: + self.norm3 = nn.Sequential() + + if stride == 1: + self.downsample = None + + else: + self.downsample = nn.Sequential(nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3) + + def forward(self, x): + y = x + y = self.relu(self.norm1(self.conv1(y))) + y = self.relu(self.norm2(self.conv2(y))) + + if self.downsample is not None: + x = self.downsample(x) + + return self.relu(x + y) + + +class SmallEncoder(nn.Module): + def __init__(self, output_dim=128, norm_fn="batch", dropout=0.0): + super(SmallEncoder, self).__init__() + self.norm_fn = norm_fn + + if self.norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=8, num_channels=32) + + elif self.norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(32) + + elif self.norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(32) + + elif self.norm_fn == "none": + self.norm1 = nn.Sequential() + + self.conv1 = nn.Conv2d(3, 32, kernel_size=7, stride=2, padding=3) + self.relu1 = nn.ReLU(inplace=True) + + self.in_planes = 32 + self.layer1 = self._make_layer(32, stride=1) + self.layer2 = self._make_layer(64, stride=2) + self.layer3 = self._make_layer(96, stride=2) + + self.dropout = None + if dropout > 0: + self.dropout = nn.Dropout2d(p=dropout) + + self.conv2 = nn.Conv2d(96, output_dim, kernel_size=1) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): + if m.weight is not None: + nn.init.constant_(m.weight, 1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def _make_layer(self, dim, stride=1): + layer1 = BottleneckBlock(self.in_planes, dim, self.norm_fn, stride=stride) + layer2 = BottleneckBlock(dim, dim, self.norm_fn, stride=1) + layers = (layer1, layer2) + + self.in_planes = dim + return nn.Sequential(*layers) + + def forward(self, x): + # if input is list, combine batch dimension + is_list = isinstance(x, tuple) or isinstance(x, list) + if is_list: + batch_dim = x[0].shape[0] + x = torch.cat(x, dim=0) + + x = self.conv1(x) + x = self.norm1(x) + x = self.relu1(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.conv2(x) + + if self.training and self.dropout is not None: + x = self.dropout(x) + + if is_list: + x = torch.split(x, [batch_dim, batch_dim], dim=0) + + return x + + +class BasicEncoder(nn.Module): + def __init__(self, output_dim=128, norm_fn="batch", dropout=0.0): + super(BasicEncoder, self).__init__() + self.norm_fn = norm_fn + + if self.norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) + + elif self.norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(64) + + elif self.norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(64) + + elif self.norm_fn == "none": + self.norm1 = nn.Sequential() + + self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3) + self.relu1 = nn.ReLU(inplace=True) + + self.in_planes = 64 + self.layer1 = self._make_layer(64, stride=1) + self.layer2 = self._make_layer(72, stride=2) + self.layer3 = self._make_layer(128, stride=2) + + # output convolution + self.conv2 = nn.Conv2d(128, output_dim, kernel_size=1) + + self.dropout = None + if dropout > 0: + self.dropout = nn.Dropout2d(p=dropout) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): + if m.weight is not None: + nn.init.constant_(m.weight, 1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def _make_layer(self, dim, stride=1): + layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) + layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) + layers = (layer1, layer2) + + self.in_planes = dim + return nn.Sequential(*layers) + + def forward(self, x): + # if input is list, combine batch dimension + is_list = isinstance(x, tuple) or isinstance(x, list) + if is_list: + batch_dim = x[0].shape[0] + x = torch.cat(x, dim=0) + + x = self.conv1(x) + x = self.norm1(x) + x = self.relu1(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + + x = self.conv2(x) + + if self.training and self.dropout is not None: + x = self.dropout(x) + + if is_list: + x = torch.split(x, [batch_dim, batch_dim], dim=0) + + return x + + +class LargeEncoder(nn.Module): + def __init__(self, output_dim=128, norm_fn="batch", dropout=0.0): + super(LargeEncoder, self).__init__() + self.norm_fn = norm_fn + + if self.norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) + + elif self.norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(64) + + elif self.norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(64) + + elif self.norm_fn == "none": + self.norm1 = nn.Sequential() + + self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3) + self.relu1 = nn.ReLU(inplace=True) + + self.in_planes = 64 + self.layer1 = self._make_layer(64, stride=1) + self.layer2 = self._make_layer(112, stride=2) + self.layer3 = self._make_layer(160, stride=2) + self.layer3_2 = self._make_layer(160, stride=1) + + # output convolution + self.conv2 = nn.Conv2d(self.in_planes, output_dim, kernel_size=1) + + self.dropout = None + if dropout > 0: + self.dropout = nn.Dropout2d(p=dropout) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): + if m.weight is not None: + nn.init.constant_(m.weight, 1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def _make_layer(self, dim, stride=1): + layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) + layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) + layers = (layer1, layer2) + + self.in_planes = dim + return nn.Sequential(*layers) + + def forward(self, x): + # if input is list, combine batch dimension + is_list = isinstance(x, tuple) or isinstance(x, list) + if is_list: + batch_dim = x[0].shape[0] + x = torch.cat(x, dim=0) + + x = self.conv1(x) + x = self.norm1(x) + x = self.relu1(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer3_2(x) + + x = self.conv2(x) + + if self.training and self.dropout is not None: + x = self.dropout(x) + + if is_list: + x = torch.split(x, [batch_dim, batch_dim], dim=0) + + return x diff --git a/Helios/eval/utils/third_party/amt/networks/blocks/ifrnet.py b/Helios/eval/utils/third_party/amt/networks/blocks/ifrnet.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfe241523f689fad7b3f6c104a57daff30ef85e --- /dev/null +++ b/Helios/eval/utils/third_party/amt/networks/blocks/ifrnet.py @@ -0,0 +1,115 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +from utils.third_party.amt.utils.flow_utils import warp + + +def resize(x, scale_factor): + return F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False) + + +def convrelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True): + return nn.Sequential( + nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias=bias), + nn.PReLU(out_channels), + ) + + +class ResBlock(nn.Module): + def __init__(self, in_channels, side_channels, bias=True): + super(ResBlock, self).__init__() + self.side_channels = side_channels + self.conv1 = nn.Sequential( + nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias), nn.PReLU(in_channels) + ) + self.conv2 = nn.Sequential( + nn.Conv2d(side_channels, side_channels, kernel_size=3, stride=1, padding=1, bias=bias), + nn.PReLU(side_channels), + ) + self.conv3 = nn.Sequential( + nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias), nn.PReLU(in_channels) + ) + self.conv4 = nn.Sequential( + nn.Conv2d(side_channels, side_channels, kernel_size=3, stride=1, padding=1, bias=bias), + nn.PReLU(side_channels), + ) + self.conv5 = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias) + self.prelu = nn.PReLU(in_channels) + + def forward(self, x): + out = self.conv1(x) + + res_feat = out[:, : -self.side_channels, ...] + side_feat = out[:, -self.side_channels :, :, :] + side_feat = self.conv2(side_feat) + out = self.conv3(torch.cat([res_feat, side_feat], 1)) + + res_feat = out[:, : -self.side_channels, ...] + side_feat = out[:, -self.side_channels :, :, :] + side_feat = self.conv4(side_feat) + out = self.conv5(torch.cat([res_feat, side_feat], 1)) + + out = self.prelu(x + out) + return out + + +class Encoder(nn.Module): + def __init__(self, channels, large=False): + super(Encoder, self).__init__() + self.channels = channels + prev_ch = 3 + for idx, ch in enumerate(channels, 1): + k = 7 if large and idx == 1 else 3 + p = 3 if k == 7 else 1 + self.register_module( + f"pyramid{idx}", nn.Sequential(convrelu(prev_ch, ch, k, 2, p), convrelu(ch, ch, 3, 1, 1)) + ) + prev_ch = ch + + def forward(self, in_x): + fs = [] + for idx in range(len(self.channels)): + out_x = getattr(self, f"pyramid{idx + 1}")(in_x) + fs.append(out_x) + in_x = out_x + return fs + + +class InitDecoder(nn.Module): + def __init__(self, in_ch, out_ch, skip_ch) -> None: + super().__init__() + self.convblock = nn.Sequential( + convrelu(in_ch * 2 + 1, in_ch * 2), + ResBlock(in_ch * 2, skip_ch), + nn.ConvTranspose2d(in_ch * 2, out_ch + 4, 4, 2, 1, bias=True), + ) + + def forward(self, f0, f1, embt): + h, w = f0.shape[2:] + embt = embt.repeat(1, 1, h, w) + out = self.convblock(torch.cat([f0, f1, embt], 1)) + flow0, flow1 = torch.chunk(out[:, :4, ...], 2, 1) + ft_ = out[:, 4:, ...] + return flow0, flow1, ft_ + + +class IntermediateDecoder(nn.Module): + def __init__(self, in_ch, out_ch, skip_ch) -> None: + super().__init__() + self.convblock = nn.Sequential( + convrelu(in_ch * 3 + 4, in_ch * 3), + ResBlock(in_ch * 3, skip_ch), + nn.ConvTranspose2d(in_ch * 3, out_ch + 4, 4, 2, 1, bias=True), + ) + + def forward(self, ft_, f0, f1, flow0_in, flow1_in): + f0_warp = warp(f0, flow0_in) + f1_warp = warp(f1, flow1_in) + f_in = torch.cat([ft_, f0_warp, f1_warp, flow0_in, flow1_in], 1) + out = self.convblock(f_in) + flow0, flow1 = torch.chunk(out[:, :4, ...], 2, 1) + ft_ = out[:, 4:, ...] + flow0 = flow0 + 2.0 * resize(flow0_in, scale_factor=2.0) + flow1 = flow1 + 2.0 * resize(flow1_in, scale_factor=2.0) + return flow0, flow1, ft_ diff --git a/Helios/eval/utils/third_party/amt/networks/blocks/multi_flow.py b/Helios/eval/utils/third_party/amt/networks/blocks/multi_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..e054bccd0e4141cb99a0c14c819d995eb8a90e99 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/networks/blocks/multi_flow.py @@ -0,0 +1,65 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.ifrnet import ( + ResBlock, + convrelu, + resize, +) +from utils.third_party.amt.utils.flow_utils import warp + + +def multi_flow_combine(comb_block, img0, img1, flow0, flow1, mask=None, img_res=None, mean=None): + """ + A parallel implementation of multiple flow field warping + comb_block: An nn.Seqential object. + img shape: [b, c, h, w] + flow shape: [b, 2*num_flows, h, w] + mask (opt): + If 'mask' is None, the function conduct a simple average. + img_res (opt): + If 'img_res' is None, the function adds zero instead. + mean (opt): + If 'mean' is None, the function adds zero instead. + """ + b, c, h, w = flow0.shape + num_flows = c // 2 + flow0 = flow0.reshape(b, num_flows, 2, h, w).reshape(-1, 2, h, w) + flow1 = flow1.reshape(b, num_flows, 2, h, w).reshape(-1, 2, h, w) + + mask = mask.reshape(b, num_flows, 1, h, w).reshape(-1, 1, h, w) if mask is not None else None + img_res = img_res.reshape(b, num_flows, 3, h, w).reshape(-1, 3, h, w) if img_res is not None else 0 + img0 = torch.stack([img0] * num_flows, 1).reshape(-1, 3, h, w) + img1 = torch.stack([img1] * num_flows, 1).reshape(-1, 3, h, w) + mean = torch.stack([mean] * num_flows, 1).reshape(-1, 1, 1, 1) if mean is not None else 0 + + img0_warp = warp(img0, flow0) + img1_warp = warp(img1, flow1) + img_warps = mask * img0_warp + (1 - mask) * img1_warp + mean + img_res + img_warps = img_warps.reshape(b, num_flows, 3, h, w) + imgt_pred = img_warps.mean(1) + comb_block(img_warps.view(b, -1, h, w)) + return imgt_pred + + +class MultiFlowDecoder(nn.Module): + def __init__(self, in_ch, skip_ch, num_flows=3): + super(MultiFlowDecoder, self).__init__() + self.num_flows = num_flows + self.convblock = nn.Sequential( + convrelu(in_ch * 3 + 4, in_ch * 3), + ResBlock(in_ch * 3, skip_ch), + nn.ConvTranspose2d(in_ch * 3, 8 * num_flows, 4, 2, 1, bias=True), + ) + + def forward(self, ft_, f0, f1, flow0, flow1): + n = self.num_flows + f0_warp = warp(f0, flow0) + f1_warp = warp(f1, flow1) + out = self.convblock(torch.cat([ft_, f0_warp, f1_warp, flow0, flow1], 1)) + delta_flow0, delta_flow1, mask, img_res = torch.split(out, [2 * n, 2 * n, n, 3 * n], 1) + mask = torch.sigmoid(mask) + + flow0 = delta_flow0 + 2.0 * resize(flow0, scale_factor=2.0).repeat(1, self.num_flows, 1, 1) + flow1 = delta_flow1 + 2.0 * resize(flow1, scale_factor=2.0).repeat(1, self.num_flows, 1, 1) + + return flow0, flow1, mask, img_res diff --git a/Helios/eval/utils/third_party/amt/networks/blocks/raft.py b/Helios/eval/utils/third_party/amt/networks/blocks/raft.py new file mode 100644 index 0000000000000000000000000000000000000000..1576889201c49614224450c9a223b871e8031f2d --- /dev/null +++ b/Helios/eval/utils/third_party/amt/networks/blocks/raft.py @@ -0,0 +1,213 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def resize(x, scale_factor): + return F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False) + + +def bilinear_sampler(img, coords, mask=False): + """Wrapper for grid_sample, uses pixel coordinates""" + H, W = img.shape[-2:] + xgrid, ygrid = coords.split([1, 1], dim=-1) + xgrid = 2 * xgrid / (W - 1) - 1 + ygrid = 2 * ygrid / (H - 1) - 1 + + grid = torch.cat([xgrid, ygrid], dim=-1) + img = F.grid_sample(img, grid, align_corners=True) + + if mask: + mask = (xgrid > -1) & (ygrid > -1) & (xgrid < 1) & (ygrid < 1) + return img, mask.float() + + return img + + +def coords_grid(batch, ht, wd, device): + coords = torch.meshgrid(torch.arange(ht, device=device), torch.arange(wd, device=device), indexing="ij") + coords = torch.stack(coords[::-1], dim=0).float() + return coords[None].repeat(batch, 1, 1, 1) + + +class SmallUpdateBlock(nn.Module): + def __init__(self, cdim, hidden_dim, flow_dim, corr_dim, fc_dim, corr_levels=4, radius=3, scale_factor=None): + super(SmallUpdateBlock, self).__init__() + cor_planes = corr_levels * (2 * radius + 1) ** 2 + self.scale_factor = scale_factor + + self.convc1 = nn.Conv2d(2 * cor_planes, corr_dim, 1, padding=0) + self.convf1 = nn.Conv2d(4, flow_dim * 2, 7, padding=3) + self.convf2 = nn.Conv2d(flow_dim * 2, flow_dim, 3, padding=1) + self.conv = nn.Conv2d(corr_dim + flow_dim, fc_dim, 3, padding=1) + + self.gru = nn.Sequential( + nn.Conv2d(fc_dim + 4 + cdim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + ) + + self.feat_head = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, cdim, 3, padding=1), + ) + + self.flow_head = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, 4, 3, padding=1), + ) + + self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True) + + def forward(self, net, flow, corr): + net = resize(net, 1 / self.scale_factor) if self.scale_factor is not None else net + cor = self.lrelu(self.convc1(corr)) + flo = self.lrelu(self.convf1(flow)) + flo = self.lrelu(self.convf2(flo)) + cor_flo = torch.cat([cor, flo], dim=1) + inp = self.lrelu(self.conv(cor_flo)) + inp = torch.cat([inp, flow, net], dim=1) + + out = self.gru(inp) + delta_net = self.feat_head(out) + delta_flow = self.flow_head(out) + + if self.scale_factor is not None: + delta_net = resize(delta_net, scale_factor=self.scale_factor) + delta_flow = self.scale_factor * resize(delta_flow, scale_factor=self.scale_factor) + + return delta_net, delta_flow + + +class BasicUpdateBlock(nn.Module): + def __init__( + self, + cdim, + hidden_dim, + flow_dim, + corr_dim, + corr_dim2, + fc_dim, + corr_levels=4, + radius=3, + scale_factor=None, + out_num=1, + ): + super(BasicUpdateBlock, self).__init__() + cor_planes = corr_levels * (2 * radius + 1) ** 2 + + self.scale_factor = scale_factor + self.convc1 = nn.Conv2d(2 * cor_planes, corr_dim, 1, padding=0) + self.convc2 = nn.Conv2d(corr_dim, corr_dim2, 3, padding=1) + self.convf1 = nn.Conv2d(4, flow_dim * 2, 7, padding=3) + self.convf2 = nn.Conv2d(flow_dim * 2, flow_dim, 3, padding=1) + self.conv = nn.Conv2d(flow_dim + corr_dim2, fc_dim, 3, padding=1) + + self.gru = nn.Sequential( + nn.Conv2d(fc_dim + 4 + cdim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + ) + + self.feat_head = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, cdim, 3, padding=1), + ) + + self.flow_head = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, 4 * out_num, 3, padding=1), + ) + + self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True) + + def forward(self, net, flow, corr): + net = resize(net, 1 / self.scale_factor) if self.scale_factor is not None else net + cor = self.lrelu(self.convc1(corr)) + cor = self.lrelu(self.convc2(cor)) + flo = self.lrelu(self.convf1(flow)) + flo = self.lrelu(self.convf2(flo)) + cor_flo = torch.cat([cor, flo], dim=1) + inp = self.lrelu(self.conv(cor_flo)) + inp = torch.cat([inp, flow, net], dim=1) + + out = self.gru(inp) + delta_net = self.feat_head(out) + delta_flow = self.flow_head(out) + + if self.scale_factor is not None: + delta_net = resize(delta_net, scale_factor=self.scale_factor) + delta_flow = self.scale_factor * resize(delta_flow, scale_factor=self.scale_factor) + return delta_net, delta_flow + + +class BidirCorrBlock: + def __init__(self, fmap1, fmap2, num_levels=4, radius=4): + self.num_levels = num_levels + self.radius = radius + self.corr_pyramid = [] + self.corr_pyramid_T = [] + + corr = BidirCorrBlock.corr(fmap1, fmap2) + batch, h1, w1, dim, h2, w2 = corr.shape + corr_T = corr.clone().permute(0, 4, 5, 3, 1, 2) + + corr = corr.reshape(batch * h1 * w1, dim, h2, w2) + corr_T = corr_T.reshape(batch * h2 * w2, dim, h1, w1) + + self.corr_pyramid.append(corr) + self.corr_pyramid_T.append(corr_T) + + for _ in range(self.num_levels - 1): + corr = F.avg_pool2d(corr, 2, stride=2) + corr_T = F.avg_pool2d(corr_T, 2, stride=2) + self.corr_pyramid.append(corr) + self.corr_pyramid_T.append(corr_T) + + def __call__(self, coords0, coords1): + r = self.radius + coords0 = coords0.permute(0, 2, 3, 1) + coords1 = coords1.permute(0, 2, 3, 1) + assert coords0.shape == coords1.shape, f"coords0 shape: [{coords0.shape}] is not equal to [{coords1.shape}]" + batch, h1, w1, _ = coords0.shape + + out_pyramid = [] + out_pyramid_T = [] + for i in range(self.num_levels): + corr = self.corr_pyramid[i] + corr_T = self.corr_pyramid_T[i] + + dx = torch.linspace(-r, r, 2 * r + 1, device=coords0.device) + dy = torch.linspace(-r, r, 2 * r + 1, device=coords0.device) + delta = torch.stack(torch.meshgrid(dy, dx, indexing="ij"), axis=-1) + delta_lvl = delta.view(1, 2 * r + 1, 2 * r + 1, 2) + + centroid_lvl_0 = coords0.reshape(batch * h1 * w1, 1, 1, 2) / 2**i + centroid_lvl_1 = coords1.reshape(batch * h1 * w1, 1, 1, 2) / 2**i + coords_lvl_0 = centroid_lvl_0 + delta_lvl + coords_lvl_1 = centroid_lvl_1 + delta_lvl + + corr = bilinear_sampler(corr, coords_lvl_0) + corr_T = bilinear_sampler(corr_T, coords_lvl_1) + corr = corr.view(batch, h1, w1, -1) + corr_T = corr_T.view(batch, h1, w1, -1) + out_pyramid.append(corr) + out_pyramid_T.append(corr_T) + + out = torch.cat(out_pyramid, dim=-1) + out_T = torch.cat(out_pyramid_T, dim=-1) + return out.permute(0, 3, 1, 2).contiguous().float(), out_T.permute(0, 3, 1, 2).contiguous().float() + + @staticmethod + def corr(fmap1, fmap2): + batch, dim, ht, wd = fmap1.shape + fmap1 = fmap1.view(batch, dim, ht * wd) + fmap2 = fmap2.view(batch, dim, ht * wd) + + corr = torch.matmul(fmap1.transpose(1, 2), fmap2) + corr = corr.view(batch, ht, wd, 1, ht, wd) + return corr / torch.sqrt(torch.tensor(dim).float()) diff --git a/Helios/eval/utils/third_party/amt/scripts/benchmark_arbitrary.sh b/Helios/eval/utils/third_party/amt/scripts/benchmark_arbitrary.sh new file mode 100644 index 0000000000000000000000000000000000000000..108daea15e6548e276a386e34698d10d0f58981c --- /dev/null +++ b/Helios/eval/utils/third_party/amt/scripts/benchmark_arbitrary.sh @@ -0,0 +1,5 @@ +CFG=$1 +CKPT=$2 + +python benchmarks/gopro.py -c $CFG -p $CKPT +python benchmarks/adobe240.py -c $CFG -p $CKPT \ No newline at end of file diff --git a/Helios/eval/utils/third_party/amt/scripts/benchmark_fixed.sh b/Helios/eval/utils/third_party/amt/scripts/benchmark_fixed.sh new file mode 100644 index 0000000000000000000000000000000000000000..55d06b04a28a8e8456e3721c7f8731ae2e432579 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/scripts/benchmark_fixed.sh @@ -0,0 +1,7 @@ +CFG=$1 +CKPT=$2 + +python benchmarks/vimeo90k.py -c $CFG -p $CKPT +python benchmarks/ucf101.py -c $CFG -p $CKPT +python benchmarks/snu_film.py -c $CFG -p $CKPT +python benchmarks/xiph.py -c $CFG -p $CKPT \ No newline at end of file diff --git a/Helios/eval/utils/third_party/amt/scripts/train.sh b/Helios/eval/utils/third_party/amt/scripts/train.sh new file mode 100644 index 0000000000000000000000000000000000000000..92afb6465c444bdbd49fc6073337f96e80ae05d1 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/scripts/train.sh @@ -0,0 +1,6 @@ +NUM_GPU=$1 +CFG=$2 +PORT=$3 +python -m torch.distributed.launch \ +--nproc_per_node $NUM_GPU \ +--master_port $PORT train.py -c $CFG \ No newline at end of file diff --git a/Helios/eval/utils/third_party/amt/train.py b/Helios/eval/utils/third_party/amt/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2839c05b54e4285f97bb733a634a95845d82f688 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/train.py @@ -0,0 +1,69 @@ +import argparse +import datetime +import importlib +import os +from shutil import copyfile + +import torch +import torch.distributed as dist +from omegaconf import OmegaConf + +from utils.dist_utils import ( + get_world_size, +) +from utils.utils import seed_all + + +parser = argparse.ArgumentParser(description="VFI") +parser.add_argument("-c", "--config", type=str) +parser.add_argument("-p", "--port", default="23455", type=str) +parser.add_argument("--local_rank", default="0") + +args = parser.parse_args() + + +def main_worker(rank, config): + if "local_rank" not in config: + config["local_rank"] = config["global_rank"] = rank + if torch.cuda.is_available(): + print(f"Rank {rank} is available") + config["device"] = f"cuda:{rank}" + if config["distributed"]: + dist.init_process_group(backend="nccl", timeout=datetime.timedelta(seconds=5400)) + else: + config["device"] = "cpu" + + cfg_name = os.path.basename(args.config).split(".")[0] + config["exp_name"] = cfg_name + "_" + config["exp_name"] + config["save_dir"] = os.path.join(config["save_dir"], config["exp_name"]) + + if (not config["distributed"]) or rank == 0: + os.makedirs(config["save_dir"], exist_ok=True) + os.makedirs(f"{config['save_dir']}/ckpts", exist_ok=True) + config_path = os.path.join(config["save_dir"], args.config.split("/")[-1]) + if not os.path.isfile(config_path): + copyfile(args.config, config_path) + print("[**] create folder {}".format(config["save_dir"])) + + trainer_name = config.get("trainer_type", "base_trainer") + print(f"using GPU {rank} for training") + if rank == 0: + print(trainer_name) + trainer_pack = importlib.import_module("trainers." + trainer_name) + trainer = trainer_pack.Trainer(config) + + trainer.train() + + +if __name__ == "__main__": + torch.backends.cudnn.benchmark = True + cfg = OmegaConf.load(args.config) + seed_all(cfg.seed) + rank = int(args.local_rank) + torch.cuda.set_device(torch.device(f"cuda:{rank}")) + # setting distributed cfgurations + cfg["world_size"] = get_world_size() + cfg["local_rank"] = rank + if rank == 0: + print("world_size: ", cfg["world_size"]) + main_worker(rank, cfg) diff --git a/Helios/eval/utils/third_party/amt/trainers/__init__.py b/Helios/eval/utils/third_party/amt/trainers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/trainers/base_trainer.py b/Helios/eval/utils/third_party/amt/trainers/base_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..722791be5ca8d9d5ccc81ddf460ef366c5ea0f41 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/trainers/base_trainer.py @@ -0,0 +1,248 @@ +import logging +import os.path as osp +import time +from collections import OrderedDict + +import numpy as np +import torch +import wandb +from metrics.psnr_ssim import calculate_psnr +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.optim import AdamW +from torch.utils.data import DataLoader +from torch.utils.data.distributed import DistributedSampler + +from utils.build_utils import build_from_cfg +from utils.utils import AverageMeterGroups + +from .logger import CustomLogger + + +class Trainer: + def __init__(self, config): + super().__init__() + self.config = config + self.rank = self.config["local_rank"] + init_log = self._init_logger() + self._init_dataset() + self._init_loss() + self.model_name = config["exp_name"] + self.model = build_from_cfg(config.network).to(self.config.device) + + if config["distributed"]: + self.model = DDP( + self.model, + device_ids=[self.rank], + output_device=self.rank, + broadcast_buffers=True, + find_unused_parameters=False, + ) + + init_log += str(self.model) + self.optimizer = AdamW(self.model.parameters(), lr=config.lr, weight_decay=config.weight_decay) + if self.rank == 0: + print(init_log) + self.logger(init_log) + self.resume_training() + + def resume_training(self): + ckpt_path = self.config.get("resume_state") + if ckpt_path is not None: + ckpt = torch.load(self.config["resume_state"]) + if self.config["distributed"]: + self.model.module.load_state_dict(ckpt["state_dict"]) + else: + self.model.load_state_dict(ckpt["state_dict"]) + self.optimizer.load_state_dict(ckpt["optim"]) + self.resume_epoch = ckpt.get("epoch") + self.logger(f"load model from {ckpt_path} and training resumes from epoch {self.resume_epoch}") + else: + self.resume_epoch = 0 + + def _init_logger(self): + init_log = "" + console_cfg = { + "level": logging.INFO, + "format": "%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s %(message)s", + "datefmt": "%a, %d %b %Y %H:%M:%S", + "filename": f"{self.config['save_dir']}/log", + "filemode": "w", + } + tb_cfg = {"log_dir": osp.join(self.config["save_dir"], "tb_logger")} + wandb_cfg = None + use_wandb = self.config["logger"].get("use_wandb", False) + if use_wandb: + resume_id = self.config["logger"].get("resume_id", None) + if resume_id: + wandb_id = resume_id + resume = "allow" + init_log += f"Resume wandb logger with id={wandb_id}." + else: + wandb_id = wandb.util.generate_id() + resume = "never" + + wandb_cfg = { + "id": wandb_id, + "resume": resume, + "name": osp.basename(self.config["save_dir"]), + "config": self.config, + "project": "YOUR PROJECT", + "entity": "YOUR ENTITY", + "sync_tensorboard": True, + } + init_log += f"Use wandb logger with id={wandb_id}; project=[YOUR PROJECT]." + self.logger = CustomLogger(console_cfg, tb_cfg, wandb_cfg, self.rank) + return init_log + + def _init_dataset(self): + dataset_train = build_from_cfg(self.config.data.train) + dataset_val = build_from_cfg(self.config.data.val) + + self.sampler = DistributedSampler( + dataset_train, num_replicas=self.config["world_size"], rank=self.config["local_rank"] + ) + self.config.data.train_loader.batch_size //= self.config["world_size"] + self.loader_train = DataLoader( + dataset_train, **self.config.data.train_loader, pin_memory=True, drop_last=True, sampler=self.sampler + ) + + self.loader_val = DataLoader( + dataset_val, **self.config.data.val_loader, pin_memory=True, shuffle=False, drop_last=False + ) + + def _init_loss(self): + self.loss_dict = {} + for loss_cfg in self.config.losses: + loss = build_from_cfg(loss_cfg) + self.loss_dict[loss_cfg["nickname"]] = loss + + def set_lr(self, optimizer, lr): + for param_group in optimizer.param_groups: + param_group["lr"] = lr + + def get_lr(self, iters): + ratio = 0.5 * (1.0 + np.cos(iters / (self.config["epochs"] * self.loader_train.__len__()) * np.pi)) + lr = (self.config["lr"] - self.config["lr_min"]) * ratio + self.config["lr_min"] + return lr + + def train(self): + local_rank = self.config["local_rank"] + best_psnr = 0.0 + loss_group = AverageMeterGroups() + time_group = AverageMeterGroups() + iters_per_epoch = self.loader_train.__len__() + iters = self.resume_epoch * iters_per_epoch + total_iters = self.config["epochs"] * iters_per_epoch + + start_t = time.time() + total_t = 0 + for epoch in range(self.resume_epoch, self.config["epochs"]): + self.sampler.set_epoch(epoch) + for data in self.loader_train: + for k, v in data.items(): + data[k] = v.to(self.config["device"]) + data_t = time.time() - start_t + + lr = self.get_lr(iters) + self.set_lr(self.optimizer, lr) + + self.optimizer.zero_grad() + results = self.model(**data) + total_loss = torch.tensor(0.0, device=self.config["device"]) + for name, loss in self.loss_dict.items(): + l = loss(**results, **data) + loss_group.update({name: l.cpu().data}) + total_loss += l + total_loss.backward() + self.optimizer.step() + + iters += 1 + + iter_t = time.time() - start_t + total_t += iter_t + time_group.update({"data_t": data_t, "iter_t": iter_t}) + + if (iters + 1) % 100 == 0 and local_rank == 0: + tpi = total_t / (iters - self.resume_epoch * iters_per_epoch) + eta = total_iters * tpi + remainder = (total_iters - iters) * tpi + eta = self.eta_format(eta) + + remainder = self.eta_format(remainder) + log_str = f"[{self.model_name}]epoch:{epoch + 1}/{self.config['epochs']} " + log_str += f"iter:{iters + 1}/{self.config['epochs'] * iters_per_epoch} " + log_str += f"time:{time_group.avg('iter_t'):.3f}({time_group.avg('data_t'):.3f}) " + log_str += f"lr:{lr:.3e} eta:{remainder}({eta})\n" + for name in self.loss_dict.keys(): + avg_l = loss_group.avg(name) + log_str += f"{name}:{avg_l:.3e} " + self.logger(tb_msg=[f"loss/{name}", avg_l, iters]) + log_str += f"best:{best_psnr:.2f}dB\n\n" + self.logger(log_str) + loss_group.reset() + time_group.reset() + start_t = time.time() + + if (epoch + 1) % self.config["eval_interval"] == 0 and local_rank == 0: + psnr, eval_t = self.evaluate(epoch) + total_t += eval_t + self.logger(tb_msg=["eval/psnr", psnr, epoch]) + if psnr > best_psnr: + best_psnr = psnr + self.save("psnr_best.pth", epoch) + if self.logger.enable_wandb: + wandb.run.summary["best_psnr"] = best_psnr + if (epoch + 1) % 50 == 0: + self.save(f"epoch_{epoch + 1}.pth", epoch) + self.save("latest.pth", epoch) + + self.logger.close() + + def evaluate(self, epoch): + psnr_list = [] + time_stamp = time.time() + for i, data in enumerate(self.loader_val): + for k, v in data.items(): + data[k] = v.to(self.config["device"]) + + with torch.no_grad(): + results = self.model(**data, eval=True) + imgt_pred = results["imgt_pred"] + for j in range(data["img0"].shape[0]): + psnr = calculate_psnr(imgt_pred[j].detach().unsqueeze(0), data["imgt"][j].unsqueeze(0)).cpu().data + psnr_list.append(psnr) + + eval_time = time.time() - time_stamp + + self.logger( + "eval epoch:{}/{} time:{:.2f} psnr:{:.3f}".format( + epoch + 1, self.config["epochs"], eval_time, np.array(psnr_list).mean() + ) + ) + return np.array(psnr_list).mean(), eval_time + + def save(self, name, epoch): + save_path = "{}/{}/{}".format(self.config["save_dir"], "ckpts", name) + ckpt = OrderedDict(epoch=epoch) + if self.config["distributed"]: + ckpt["state_dict"] = self.model.module.state_dict() + else: + ckpt["state_dict"] = self.model.state_dict() + ckpt["optim"] = self.optimizer.state_dict() + torch.save(ckpt, save_path) + + def eta_format(self, eta): + time_str = "" + if eta >= 3600: + hours = int(eta // 3600) + eta -= hours * 3600 + time_str = f"{hours}" + + if eta >= 60: + mins = int(eta // 60) + eta -= mins * 60 + time_str = f"{time_str}:{mins:02}" + + eta = int(eta) + time_str = f"{time_str}:{eta:02}" + return time_str diff --git a/Helios/eval/utils/third_party/amt/trainers/logger.py b/Helios/eval/utils/third_party/amt/trainers/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..069e95275e48c100c3ced627bacc0b3fcf8fc8fa --- /dev/null +++ b/Helios/eval/utils/third_party/amt/trainers/logger.py @@ -0,0 +1,62 @@ +import logging +import os.path as osp +import shutil +import time + +import wandb +from torch.utils.tensorboard import SummaryWriter + + +def mv_archived_logger(name): + timestamp = time.strftime("%Y-%m-%d_%H:%M:%S_", time.localtime()) + basename = "archived_" + timestamp + osp.basename(name) + archived_name = osp.join(osp.dirname(name), basename) + shutil.move(name, archived_name) + + +class CustomLogger: + def __init__(self, common_cfg, tb_cfg=None, wandb_cfg=None, rank=0): + global global_logger + self.rank = rank + + if self.rank == 0: + self.logger = logging.getLogger("VFI") + self.logger.setLevel(logging.INFO) + format_str = logging.Formatter(common_cfg["format"]) + + console_handler = logging.StreamHandler() + console_handler.setFormatter(format_str) + + if osp.exists(common_cfg["filename"]): + mv_archived_logger(common_cfg["filename"]) + + file_handler = logging.FileHandler(common_cfg["filename"], common_cfg["filemode"]) + file_handler.setFormatter(format_str) + + self.logger.addHandler(console_handler) + self.logger.addHandler(file_handler) + self.tb_logger = None + + self.enable_wandb = False + + if wandb_cfg is not None: + self.enable_wandb = True + wandb.init(**wandb_cfg) + + if tb_cfg is not None: + self.tb_logger = SummaryWriter(**tb_cfg) + + global_logger = self + + def __call__(self, msg=None, level=logging.INFO, tb_msg=None): + if self.rank != 0: + return + if msg is not None: + self.logger.log(level, msg) + + if self.tb_logger is not None and tb_msg is not None: + self.tb_logger.add_scalar(*tb_msg) + + def close(self): + if self.rank == 0 and self.enable_wandb: + wandb.finish() diff --git a/Helios/eval/utils/third_party/amt/utils/__init__.py b/Helios/eval/utils/third_party/amt/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval/utils/third_party/amt/utils/build_utils.py b/Helios/eval/utils/third_party/amt/utils/build_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d4fc052d24bb57c460e173435b1ad0d575f46004 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/utils/build_utils.py @@ -0,0 +1,17 @@ +import importlib +import os +import sys + + +CUR_DIR = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(os.path.join(CUR_DIR, "../")) + + +def base_build_fn(module, cls, params): + return getattr(importlib.import_module(module, package=None), cls)(**params) + + +def build_from_cfg(config): + module, cls = config["name"].rsplit(".", 1) + params = config.get("params", {}) + return base_build_fn(module, cls, params) diff --git a/Helios/eval/utils/third_party/amt/utils/dist_utils.py b/Helios/eval/utils/third_party/amt/utils/dist_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d754d4fc7a6ed1a9bae246b2f895456218d815ea --- /dev/null +++ b/Helios/eval/utils/third_party/amt/utils/dist_utils.py @@ -0,0 +1,48 @@ +import os + +import torch + + +def get_world_size(): + """Find OMPI world size without calling mpi functions + :rtype: int + """ + if os.environ.get("PMI_SIZE") is not None: + return int(os.environ.get("PMI_SIZE") or 1) + elif os.environ.get("OMPI_COMM_WORLD_SIZE") is not None: + return int(os.environ.get("OMPI_COMM_WORLD_SIZE") or 1) + else: + return torch.cuda.device_count() + + +def get_global_rank(): + """Find OMPI world rank without calling mpi functions + :rtype: int + """ + if os.environ.get("PMI_RANK") is not None: + return int(os.environ.get("PMI_RANK") or 0) + elif os.environ.get("OMPI_COMM_WORLD_RANK") is not None: + return int(os.environ.get("OMPI_COMM_WORLD_RANK") or 0) + else: + return 0 + + +def get_local_rank(): + """Find OMPI local rank without calling mpi functions + :rtype: int + """ + if os.environ.get("MPI_LOCALRANKID") is not None: + return int(os.environ.get("MPI_LOCALRANKID") or 0) + elif os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK") is not None: + return int(os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK") or 0) + else: + return 0 + + +def get_master_ip(): + if os.environ.get("AZ_BATCH_MASTER_NODE") is not None: + return os.environ.get("AZ_BATCH_MASTER_NODE").split(":")[0] + elif os.environ.get("AZ_BATCHAI_MPI_MASTER_NODE") is not None: + return os.environ.get("AZ_BATCHAI_MPI_MASTER_NODE") + else: + return "127.0.0.1" diff --git a/Helios/eval/utils/third_party/amt/utils/flow_utils.py b/Helios/eval/utils/third_party/amt/utils/flow_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..059401503b5148f604488d21966c7825ef40563c --- /dev/null +++ b/Helios/eval/utils/third_party/amt/utils/flow_utils.py @@ -0,0 +1,126 @@ +import numpy as np +import torch +import torch.nn.functional as F +from PIL import ImageFile + + +ImageFile.LOAD_TRUNCATED_IMAGES = True + + +def warp(img, flow): + B, _, H, W = flow.shape + xx = torch.linspace(-1.0, 1.0, W).view(1, 1, 1, W).expand(B, -1, H, -1) + yy = torch.linspace(-1.0, 1.0, H).view(1, 1, H, 1).expand(B, -1, -1, W) + grid = torch.cat([xx, yy], 1).to(img) + flow_ = torch.cat([flow[:, 0:1, :, :] / ((W - 1.0) / 2.0), flow[:, 1:2, :, :] / ((H - 1.0) / 2.0)], 1) + grid_ = (grid + flow_).permute(0, 2, 3, 1) + output = F.grid_sample(input=img, grid=grid_, mode="bilinear", padding_mode="border", align_corners=True) + return output + + +def make_colorwheel(): + """ + Generates a color wheel for optical flow visualization as presented in: + Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007) + URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf + Code follows the original C++ source code of Daniel Scharstein. + Code follows the the Matlab source code of Deqing Sun. + Returns: + np.ndarray: Color wheel + """ + + RY = 15 + YG = 6 + GC = 4 + CB = 11 + BM = 13 + MR = 6 + + ncols = RY + YG + GC + CB + BM + MR + colorwheel = np.zeros((ncols, 3)) + col = 0 + + # RY + colorwheel[0:RY, 0] = 255 + colorwheel[0:RY, 1] = np.floor(255 * np.arange(0, RY) / RY) + col = col + RY + # YG + colorwheel[col : col + YG, 0] = 255 - np.floor(255 * np.arange(0, YG) / YG) + colorwheel[col : col + YG, 1] = 255 + col = col + YG + # GC + colorwheel[col : col + GC, 1] = 255 + colorwheel[col : col + GC, 2] = np.floor(255 * np.arange(0, GC) / GC) + col = col + GC + # CB + colorwheel[col : col + CB, 1] = 255 - np.floor(255 * np.arange(CB) / CB) + colorwheel[col : col + CB, 2] = 255 + col = col + CB + # BM + colorwheel[col : col + BM, 2] = 255 + colorwheel[col : col + BM, 0] = np.floor(255 * np.arange(0, BM) / BM) + col = col + BM + # MR + colorwheel[col : col + MR, 2] = 255 - np.floor(255 * np.arange(MR) / MR) + colorwheel[col : col + MR, 0] = 255 + return colorwheel + + +def flow_uv_to_colors(u, v, convert_to_bgr=False): + """ + Applies the flow color wheel to (possibly clipped) flow components u and v. + According to the C++ source code of Daniel Scharstein + According to the Matlab source code of Deqing Sun + Args: + u (np.ndarray): Input horizontal flow of shape [H,W] + v (np.ndarray): Input vertical flow of shape [H,W] + convert_to_bgr (bool, optional): Convert output image to BGR. Defaults to False. + Returns: + np.ndarray: Flow visualization image of shape [H,W,3] + """ + flow_image = np.zeros((u.shape[0], u.shape[1], 3), np.uint8) + colorwheel = make_colorwheel() # shape [55x3] + ncols = colorwheel.shape[0] + rad = np.sqrt(np.square(u) + np.square(v)) + a = np.arctan2(-v, -u) / np.pi + fk = (a + 1) / 2 * (ncols - 1) + k0 = np.floor(fk).astype(np.int32) + k1 = k0 + 1 + k1[k1 == ncols] = 0 + f = fk - k0 + for i in range(colorwheel.shape[1]): + tmp = colorwheel[:, i] + col0 = tmp[k0] / 255.0 + col1 = tmp[k1] / 255.0 + col = (1 - f) * col0 + f * col1 + idx = rad <= 1 + col[idx] = 1 - rad[idx] * (1 - col[idx]) + col[~idx] = col[~idx] * 0.75 # out of range + # Note the 2-i => BGR instead of RGB + ch_idx = 2 - i if convert_to_bgr else i + flow_image[:, :, ch_idx] = np.floor(255 * col) + return flow_image + + +def flow_to_image(flow_uv, clip_flow=None, convert_to_bgr=False): + """ + Expects a two dimensional flow image of shape. + Args: + flow_uv (np.ndarray): Flow UV image of shape [H,W,2] + clip_flow (float, optional): Clip maximum of flow values. Defaults to None. + convert_to_bgr (bool, optional): Convert output image to BGR. Defaults to False. + Returns: + np.ndarray: Flow visualization image of shape [H,W,3] + """ + assert flow_uv.ndim == 3, "input flow must have three dimensions" + assert flow_uv.shape[2] == 2, "input flow must have shape [H,W,2]" + if clip_flow is not None: + flow_uv = np.clip(flow_uv, 0, clip_flow) + u = flow_uv[:, :, 0] + v = flow_uv[:, :, 1] + rad = np.sqrt(np.square(u) + np.square(v)) + rad_max = np.max(rad) + epsilon = 1e-5 + u = u / (rad_max + epsilon) + v = v / (rad_max + epsilon) + return flow_uv_to_colors(u, v, convert_to_bgr) diff --git a/Helios/eval/utils/third_party/amt/utils/utils.py b/Helios/eval/utils/third_party/amt/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c784fbb8b029e2c26794e9a71c580c6a49c0a2d8 --- /dev/null +++ b/Helios/eval/utils/third_party/amt/utils/utils.py @@ -0,0 +1,315 @@ +import random +import re +import sys + +import numpy as np +import torch +import torch.nn.functional as F +from imageio import imread, imwrite +from PIL import ImageFile + + +ImageFile.LOAD_TRUNCATED_IMAGES = True + + +class AverageMeter: + def __init__(self): + self.reset() + + def reset(self): + self.val = 0.0 + self.avg = 0.0 + self.sum = 0.0 + self.count = 0 + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + + +class AverageMeterGroups: + def __init__(self) -> None: + self.meter_dict = {} + + def update(self, dict, n=1): + for name, val in dict.items(): + if self.meter_dict.get(name) is None: + self.meter_dict[name] = AverageMeter() + self.meter_dict[name].update(val, n) + + def reset(self, name=None): + if name is None: + for v in self.meter_dict.values(): + v.reset() + else: + meter = self.meter_dict.get(name) + if meter is not None: + meter.reset() + + def avg(self, name): + meter = self.meter_dict.get(name) + if meter is not None: + return meter.avg + + +class InputPadder: + """Pads images such that dimensions are divisible by divisor""" + + def __init__(self, dims, divisor=16): + self.ht, self.wd = dims[-2:] + pad_ht = (((self.ht // divisor) + 1) * divisor - self.ht) % divisor + pad_wd = (((self.wd // divisor) + 1) * divisor - self.wd) % divisor + self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, pad_ht // 2, pad_ht - pad_ht // 2] + + def pad(self, *inputs): + if len(inputs) == 1: + return F.pad(inputs[0], self._pad, mode="replicate") + else: + return [F.pad(x, self._pad, mode="replicate") for x in inputs] + + def unpad(self, *inputs): + if len(inputs) == 1: + return self._unpad(inputs[0]) + else: + return [self._unpad(x) for x in inputs] + + def _unpad(self, x): + ht, wd = x.shape[-2:] + c = [self._pad[2], ht - self._pad[3], self._pad[0], wd - self._pad[1]] + return x[..., c[0] : c[1], c[2] : c[3]] + + +def img2tensor(img): + if img.shape[-1] > 3: + img = img[:, :, :3] + return torch.tensor(img).permute(2, 0, 1).unsqueeze(0) / 255.0 + + +def tensor2img(img_t): + return (img_t * 255.0).detach().squeeze(0).permute(1, 2, 0).cpu().numpy().clip(0, 255).astype(np.uint8) + + +def seed_all(seed): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +def read(file): + if file.endswith(".float3"): + return readFloat(file) + elif file.endswith(".flo"): + return readFlow(file) + elif file.endswith(".ppm"): + return readImage(file) + elif file.endswith(".pgm"): + return readImage(file) + elif file.endswith(".png"): + return readImage(file) + elif file.endswith(".jpg"): + return readImage(file) + elif file.endswith(".pfm"): + return readPFM(file)[0] + else: + raise Exception("don't know how to read %s" % file) + + +def write(file, data): + if file.endswith(".float3"): + return writeFloat(file, data) + elif file.endswith(".flo"): + return writeFlow(file, data) + elif file.endswith(".ppm"): + return writeImage(file, data) + elif file.endswith(".pgm"): + return writeImage(file, data) + elif file.endswith(".png"): + return writeImage(file, data) + elif file.endswith(".jpg"): + return writeImage(file, data) + elif file.endswith(".pfm"): + return writePFM(file, data) + else: + raise Exception("don't know how to write %s" % file) + + +def readPFM(file): + file = open(file, "rb") + + color = None + width = None + height = None + scale = None + endian = None + + header = file.readline().rstrip() + if header.decode("ascii") == "PF": + color = True + elif header.decode("ascii") == "Pf": + color = False + else: + raise Exception("Not a PFM file.") + + dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii")) + if dim_match: + width, height = list(map(int, dim_match.groups())) + else: + raise Exception("Malformed PFM header.") + + scale = float(file.readline().decode("ascii").rstrip()) + if scale < 0: + endian = "<" + scale = -scale + else: + endian = ">" + + data = np.fromfile(file, endian + "f") + shape = (height, width, 3) if color else (height, width) + + data = np.reshape(data, shape) + data = np.flipud(data) + return data, scale + + +def writePFM(file, image, scale=1): + file = open(file, "wb") + + color = None + + if image.dtype.name != "float32": + raise Exception("Image dtype must be float32.") + + image = np.flipud(image) + + if len(image.shape) == 3 and image.shape[2] == 3: + color = True + elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: + color = False + else: + raise Exception("Image must have H x W x 3, H x W x 1 or H x W dimensions.") + + file.write("PF\n" if color else "Pf\n".encode()) + file.write("%d %d\n".encode() % (image.shape[1], image.shape[0])) + + endian = image.dtype.byteorder + + if endian == "<" or endian == "=" and sys.byteorder == "little": + scale = -scale + + file.write("%f\n".encode() % scale) + + image.tofile(file) + + +def readFlow(name): + if name.endswith(".pfm") or name.endswith(".PFM"): + return readPFM(name)[0][:, :, 0:2] + + f = open(name, "rb") + + header = f.read(4) + if header.decode("utf-8") != "PIEH": + raise Exception("Flow file header does not contain PIEH") + + width = np.fromfile(f, np.int32, 1).squeeze() + height = np.fromfile(f, np.int32, 1).squeeze() + + flow = np.fromfile(f, np.float32, width * height * 2).reshape((height, width, 2)) + + return flow.astype(np.float32) + + +def readImage(name): + if name.endswith(".pfm") or name.endswith(".PFM"): + data = readPFM(name)[0] + if len(data.shape) == 3: + return data[:, :, 0:3] + else: + return data + return imread(name) + + +def writeImage(name, data): + if name.endswith(".pfm") or name.endswith(".PFM"): + return writePFM(name, data, 1) + return imwrite(name, data) + + +def writeFlow(name, flow): + f = open(name, "wb") + f.write("PIEH".encode("utf-8")) + np.array([flow.shape[1], flow.shape[0]], dtype=np.int32).tofile(f) + flow = flow.astype(np.float32) + flow.tofile(f) + + +def readFloat(name): + f = open(name, "rb") + + if (f.readline().decode("utf-8")) != "float\n": + raise Exception("float file %s did not contain keyword" % name) + + dim = int(f.readline()) + + dims = [] + count = 1 + for i in range(0, dim): + d = int(f.readline()) + dims.append(d) + count *= d + + dims = list(reversed(dims)) + + data = np.fromfile(f, np.float32, count).reshape(dims) + if dim > 2: + data = np.transpose(data, (2, 1, 0)) + data = np.transpose(data, (1, 0, 2)) + + return data + + +def writeFloat(name, data): + f = open(name, "wb") + + dim = len(data.shape) + if dim > 3: + raise Exception("bad float file dimension: %d" % dim) + + f.write(("float\n").encode("ascii")) + f.write(("%d\n" % dim).encode("ascii")) + + if dim == 1: + f.write(("%d\n" % data.shape[0]).encode("ascii")) + else: + f.write(("%d\n" % data.shape[1]).encode("ascii")) + f.write(("%d\n" % data.shape[0]).encode("ascii")) + for i in range(2, dim): + f.write(("%d\n" % data.shape[i]).encode("ascii")) + + data = data.astype(np.float32) + if dim == 2: + data.tofile(f) + + else: + np.transpose(data, (2, 0, 1)).tofile(f) + + +def check_dim_and_resize(tensor_list): + shape_list = [] + for t in tensor_list: + shape_list.append(t.shape[2:]) + + if len(set(shape_list)) > 1: + desired_shape = shape_list[0] + print(f"Inconsistent size of input video frames. All frames will be resized to {desired_shape}") + + resize_tensor_list = [] + for t in tensor_list: + resize_tensor_list.append(torch.nn.functional.interpolate(t, size=tuple(desired_shape), mode="bilinear")) + + tensor_list = resize_tensor_list + + return tensor_list diff --git a/Helios/eval/utils/utils.py b/Helios/eval/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e2e990e54a33bf1c063752c62a3213c73b076083 --- /dev/null +++ b/Helios/eval/utils/utils.py @@ -0,0 +1,297 @@ +import random + +import numpy as np +import torch +from PIL import Image, ImageSequence +from torchvision import transforms +from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor +from video_reader import PyVideoReader + + +try: + from torchvision.transforms import InterpolationMode + + BICUBIC = InterpolationMode.BICUBIC + BILINEAR = InterpolationMode.BILINEAR +except ImportError: + BICUBIC = Image.BICUBIC + BILINEAR = Image.BILINEAR + + +def clip_transform(n_px): + return Compose( + [ + Resize(n_px, interpolation=BICUBIC, antialias=False), + CenterCrop(n_px), + transforms.Lambda(lambda x: x.float().div(255.0)), + Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), + ] + ) + + +def clip_transform_Image(n_px): + return Compose( + [ + Resize(n_px, interpolation=BICUBIC, antialias=False), + CenterCrop(n_px), + ToTensor(), + Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), + ] + ) + + +def get_frame_indices(num_frames, vlen, sample="rand", fix_start=None, input_fps=1, max_num_frames=-1): + if sample in ["rand", "middle"]: # uniform sampling + acc_samples = min(num_frames, vlen) + # split the video into `acc_samples` intervals, and sample from each interval. + intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int) + ranges = [] + for idx, interv in enumerate(intervals[:-1]): + ranges.append((interv, intervals[idx + 1] - 1)) + if sample == "rand": + try: + frame_indices = [random.choice(range(x[0], x[1])) for x in ranges] + except Exception: + frame_indices = np.random.permutation(vlen)[:acc_samples] + frame_indices.sort() + frame_indices = list(frame_indices) + elif fix_start is not None: + frame_indices = [x[0] + fix_start for x in ranges] + elif sample == "middle": + frame_indices = [(x[0] + x[1]) // 2 for x in ranges] + else: + raise NotImplementedError + + if len(frame_indices) < num_frames: # padded with last frame + padded_frame_indices = [frame_indices[-1]] * num_frames + padded_frame_indices[: len(frame_indices)] = frame_indices + frame_indices = padded_frame_indices + elif "fps" in sample: # fps0.5, sequentially sample frames at 0.5 fps + output_fps = float(sample[3:]) + duration = float(vlen) / input_fps + delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents + frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta) + frame_indices = np.around(frame_seconds * input_fps).astype(int) + frame_indices = [e for e in frame_indices if e < vlen] + if max_num_frames > 0 and len(frame_indices) > max_num_frames: + frame_indices = frame_indices[:max_num_frames] + # frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames) + else: + raise ValueError + return frame_indices + + +def align_dimension(value, alignment=2): + return int(round(value / alignment) * alignment) + + +def load_video(video_path, data_transform=None, num_frames=None, return_tensor=True, width=None, height=None): + if video_path.endswith(".gif"): + frame_ls = [] + img = Image.open(video_path) + for frame in ImageSequence.Iterator(img): + frame = frame.convert("RGB") + frame = np.array(frame).astype(np.uint8) + frame_ls.append(frame) + buffer = np.array(frame_ls).astype(np.uint8) + elif video_path.endswith(".png"): + frame = Image.open(video_path) + frame = frame.convert("RGB") + frame = np.array(frame).astype(np.uint8) + frame_ls = [frame] + buffer = np.array(frame_ls) + elif video_path.endswith(".mp4"): + vr = PyVideoReader(video_path, threads=0) + if width is not None and height is not None: + (_, original_height, original_width) = vr.get_shape() + original_aspect_ratio = original_width / original_height + if width > height: + target_width = width + target_height = int(width / original_aspect_ratio) + else: + target_height = height + target_width = int(height * original_aspect_ratio) + target_height = align_dimension(target_height, 2) + target_width = align_dimension(target_width, 2) + vr = PyVideoReader(video_path, target_height=target_height, target_width=target_width, threads=0) + buffer = vr.decode() + vr = None + del vr + else: + raise NotImplementedError + + frames = buffer + if num_frames and not video_path.endswith(".mp4"): + frame_indices = get_frame_indices(num_frames, len(frames), sample="middle") + frames = frames[frame_indices] + + if data_transform: + frames = data_transform(frames) + elif return_tensor: + frames = torch.Tensor(frames) + frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8 + + return frames + + +def read_frames_decord_by_fps( + video_path, + sample_fps=2, + sample="rand", + fix_start=None, + max_num_frames=-1, + trimmed30=False, + num_frames=8, + width=None, + height=None, +): + vr_info = PyVideoReader(video_path, threads=0) + (vlen, original_height, original_width) = vr_info.get_shape() + fps = vr_info.get_fps() + duration = vlen / float(fps) + vr_info = None + del vr_info + + if trimmed30 and duration > 30: + duration = 30 + vlen = int(30 * float(fps)) + + target_width = None + target_height = None + if width is not None and height is not None: + original_aspect_ratio = original_width / original_height + if width > height: + target_width = width + target_height = int(width / original_aspect_ratio) + else: + target_height = height + target_width = int(height * original_aspect_ratio) + target_height = align_dimension(target_height, 2) + target_width = align_dimension(target_width, 2) + + frame_indices = get_frame_indices( + num_frames, vlen, sample=sample, fix_start=fix_start, input_fps=fps, max_num_frames=max_num_frames + ) + + vr = PyVideoReader(video_path, target_height=target_height, target_width=target_width, threads=0) + buffer = vr.decode() + vr = None + del vr + + frames = buffer[frame_indices] + if not isinstance(frames, torch.Tensor): + frames = torch.from_numpy(frames) + + frames = frames.permute(0, 3, 1, 2) # (T, H, W, C) -> (T, C, H, W) + + return frames + + +def load_video_frames(video_path, start_ratio=0.0, end_ratio=1.0, num_frames=8, height=384, width=640): + # First pass: get video shape + vr = PyVideoReader(video_path, threads=0) + (total_frames, original_height, original_width) = vr.get_shape() + + # Calculate target dimensions maintaining aspect ratio + original_aspect_ratio = original_width / original_height + if width > height: + target_width = width + target_height = int(width / original_aspect_ratio) + else: + target_height = height + target_width = int(height * original_aspect_ratio) + + target_height = align_dimension(target_height, 2) + target_width = align_dimension(target_width, 2) + + # Calculate frame range + start_frame = int(total_frames * start_ratio) + end_frame = int(total_frames * end_ratio) + portion_length = end_frame - start_frame + + if portion_length < num_frames: + # Expand the range to accommodate num_frames + needed_frames = num_frames - portion_length + expansion = needed_frames / 2 + + # Try to expand symmetrically + new_start = max(0, start_frame - int(np.ceil(expansion))) + new_end = min(total_frames, end_frame + int(np.floor(expansion))) + + # If still not enough, expand further in available direction + if new_end - new_start < num_frames: + if new_start == 0: + new_end = min(total_frames, new_start + num_frames) + elif new_end == total_frames: + new_start = max(0, new_end - num_frames) + + start_frame = new_start + end_frame = new_end + portion_length = end_frame - start_frame + + # Now sample frames + frame_indices = np.linspace(start_frame, end_frame - 1, num_frames, dtype=int) + else: + # Sample uniformly from the portion + step = portion_length / num_frames + frame_indices = [int(start_frame + i * step) for i in range(num_frames)] + + # Ensure indices are within bounds + frame_indices = [min(idx, total_frames - 1) for idx in frame_indices] + + # Second pass: decode only needed frames with target dimensions + vr = PyVideoReader(video_path, target_height=target_height, target_width=target_width, threads=0) + frames = vr.get_batch(frame_indices) # Only decode needed frames (num_frames, H, W, C) + + # Convert to tensor if needed and permute to (T, C, H, W) + if not isinstance(frames, torch.Tensor): + frames = torch.from_numpy(frames) + frames = frames.permute(0, 3, 1, 2) # (T, C, H, W) + + # Clean up + vr = None + del vr + + return frames + + +def extract_video_segment(input_path, output_path, start_ratio, end_ratio): + """ + 尽可能保持原视频编码参数 + """ + import ffmpeg + + # 获取原视频信息 + probe = ffmpeg.probe(input_path) + video_stream = next(s for s in probe["streams"] if s["codec_type"] == "video") + + duration = float(probe["format"]["duration"]) + start_time = duration * start_ratio + segment_duration = duration * (end_ratio - start_ratio) + + # 检测原视频编码参数 + orig_codec = video_stream.get("codec_name", "h264") + orig_pix_fmt = video_stream.get("pix_fmt", "yuv420p") + + # 如果原视频是 h264/h265,使用相同编码器 + if orig_codec in ["h264", "hevc"]: + codec_name = "libx264" if orig_codec == "h264" else "libx265" + else: + codec_name = "libx264" # fallback + + ( + ffmpeg.input(input_path, ss=start_time) + .output( + output_path, + t=segment_duration, + vcodec=codec_name, + crf=0, + preset="medium", + pix_fmt=orig_pix_fmt, + acodec="copy", + vsync="cfr", + map_metadata=0, + ) + .overwrite_output() + .run(quiet=True) + ) diff --git a/Helios/eval_moviebench/checkpoints/.gitattributes b/Helios/eval_moviebench/checkpoints/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..183c06101ff0f1dd9a1f3c7d133a486291e54fbd --- /dev/null +++ b/Helios/eval_moviebench/checkpoints/.gitattributes @@ -0,0 +1,37 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text +Videoreward/checkpoint-11352/tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -text +demo_data/Vidprom_filtered_extended.txt filter=lfs diff=lfs merge=lfs -text diff --git a/Helios/eval_moviebench/checkpoints/README.md b/Helios/eval_moviebench/checkpoints/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b78634f01d4323579280df3eda7104a6e6576a32 --- /dev/null +++ b/Helios/eval_moviebench/checkpoints/README.md @@ -0,0 +1,512 @@ +--- +license: apache-2.0 +language: +- en +base_model: +- Wan-AI/Wan2.1-T2V-14B-Diffusers +pipeline_tag: text-to-video +base_model_relation: finetune +library_name: diffusers +--- + +
+ +
+ +

Helios: Real Real-Time Long Video Generation Model

+ +
⭐ 14B Real-Time Long Video Generation Model can be Cheaper, Faster but Keep Stronger than 1.3B ones ⭐
+ +
+ +[![arXiv](https://img.shields.io/badge/arXiv-2603.04379-b31b1b.svg?logo=arxiv)](https://arxiv.org/abs/2603.04379) +[![hf_paper](https://img.shields.io/badge/🤗-Paper%20In%20HF-red.svg)](https://huggingface.co/papers/2603.04379) +[![Project Page](https://img.shields.io/badge/Project-Website-2ea44f)](https://pku-yuangroup.github.io/Helios-Page) +[![hf_space](https://img.shields.io/badge/🤗-Gradio-00b4d8.svg)](https://huggingface.co/spaces/multimodalart/Helios-Distilled/) +[![HuggingFace](https://img.shields.io/badge/🤗-HuggingFace-blue)](https://huggingface.co/collections/BestWishYsh/helios) +[![ModelScope](https://img.shields.io/badge/🤖-ModelScope-purple)](https://modelscope.cn/collections/BestWishYSH/Helios) +[![GitHub](https://img.shields.io/badge/GitHub-black?logo=github)](https://github.com/PKU-YuanGroup/Helios) +[![GitCode](https://img.shields.io/badge/GitCodes-blue?logo=gitcode)](https://gitcode.com/weixin_47617277/Helios) + +[![Ascend](https://img.shields.io/badge/Inference-Ascend--NPU-red)](https://www.hiascend.com/) +[![Diffusers](https://img.shields.io/badge/Inference-Diffusers-blueviolet)](https://github.com/huggingface/diffusers/pull/13208) +[![SGLang Diffusion](https://img.shields.io/badge/Backend-SGLang--Diffusion-yellow)](https://github.com/sgl-project/sglang/pull/19782) +[![vLLM-Omni](https://img.shields.io/badge/Backend-vLLM--Omni-orange)](https://github.com/vllm-project/vllm-omni/pull/1604) + + + +
+ +
+This repository is the official implementation of Helios, which is a breakthrough video generation model that achieves minute-scale, high-quality video synthesis at 19.5 FPS on a single H100 GPU (about 10 FPS on a single Ascend NPU) —without relying on conventional long video anti-drifting strategies or standard video acceleration techniques. +
+ +
+ +## ✨ Highlights + + +1. **Without commonly used anti-drifting strategies** (e.g., self-forcing, error-banks, keyframe sampling, or inverted sampling), Helios generates minute-scale videos with high quality and strong coherence. + +2. **Without standard acceleration techniques** (e.g., KV-cache, causal masking, sparse/linear attention, TinyVAE, progressive noise schedules, hidden-state caching, or quantization), Helios achieves 19.5 FPS in end-to-end inference on a single H100 GPU. + +3. **We introduce optimizations that improve both training and inference throughput while reducing memory consumption,** enabling image-diffusion-scale batch sizes during training while fitting up to four 14B models within 80 GB of GPU memory. + + + +## 🎬 Video Demos + + + +[![Demo Video of Helios](https://github.com/user-attachments/assets/1d10da4a-aba9-4ac1-ab02-cd0dfce8d35b)](https://www.youtube.com/watch?v=vd_AgHtOUFQ) +or you can click here to get the video. Some best prompts are [here](./example/prompt.txt). + + +## 📣 Latest News!! + +* `[2026.03.08]` 👋 Helios now fully supports [Group Offloading](#-group-offloading-to-save-vram) and [Context Parallelism](#-context-parallelism-on-multiple-gpus)! These features significantly optimize VRAM (**only ~6GB**) usage and enable inference across multiple GPUs with *Ulysses Attention*, *Ring Attention*, *Unified Attention*, and *Ulysses Anything Attention*. +* `[2026.03.06]` 🚀 [Cache-DiT](https://github.com/vipshop/cache-dit/pull/834) now supports Helios, it offers Fully Cache Acceleration and Parallelism support for Helios! Special thanks to the Cache-DiT Team for their amazing work. +* `[2026.03.06]` 🚀 We fix the Parallel Inference logits for Helios, and provide an example [here](#-parallel-inference-on-multiple-gpus). Thanks [Cache-DiT Team](https://github.com/vipshop/cache-dit/pull/836). +* `[2026.03.06]` 👋 We official release the [Gradio Demo](https://huggingface.co/spaces/BestWishYsh/Helios-14B-RealTime), welcome to try it. +* `[2026.03.05]` 👋 We are excited to announce the release of the Helios [technical report](https://arxiv.org/abs/2603.04379) on arXiv. We welcome discussions and feedback! +* `[2026.03.04]` 🚀 Day-0 support for [Ascend-NPU](https://www.hiascend.com),with sincere gratitude to the Ascend Team for their support. +* `[2026.03.04]` 🚀 Day-0 support for [Diffusers](https://github.com/huggingface/diffusers/pull/13208),with special thanks to the HuggingFace Team for their support. +* `[2026.03.04]` 🚀 Day-0 support for [SGLang-Diffusion](https://github.com/sgl-project/sglang/pull/19782),with huge thanks to the SGLang Team for their support. +* `[2026.03.04]` 🚀 Day-0 support for [vLLM-Omni](https://github.com/vllm-project/vllm-omni/pull/1604),with heartfelt gratitude to the vLLM Team for their support. +* `[2026.03.04]` 🔥 We've released the training/inference code and weights of **Helios-Base**, **Helios-Mid** and **Helios-Distilled**. + + +## 🔥 Friendly Links + +If your work has improved **Helios** and you would like more people to see it, please inform us. + +* [Ascend-NPU](https://www.hiascend.com/): Developed by Huawei, this hardware is designed for efficient AI model training and inference, boosting performance in tasks like computer vision, natural language processing, and autonomous driving. +* [Diffusers](https://github.com/huggingface/diffusers/pull/13208): A popular library designed for working with diffusion models and other generative models in deep learning. It supports easy integration and manipulation of a wide range of generative models. +* [SGLang-Diffusion](https://github.com/sgl-project/sglang/pull/19782): An inference framework for accelerated image and video generation using diffusion models. It provides an end-to-end unified pipeline with optimized kernels and an efficient scheduler loop. +* [vLLM-Omni](https://github.com/vllm-project/vllm-omni/pull/1604): A fully disaggregated serving system for any-to-any models. vLLM-Omni breaks complex architectures into a stage-based graph, using a decoupled backend to maximize resource efficiency and throughput. +* [Cache-DiT](https://github.com/vipshop/cache-dit/pull/834): A PyTorch-native and Flexible Inference Engine with Hybrid Cache Acceleration and Parallelism for DiTs. It built on top of the Diffusers library and now supports nearly ALL DiTs from Diffusers. + + + +### Model Download + +| Models | Download Link | Supports | Notes | +|------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------|---------------------------------------------------------------------------------------------| +| Helios-Base | 🤗 [Huggingface](https://huggingface.co/BestWishYsh/Helios-Base) 🤖 [ModelScope](https://modelscope.cn/models/BestWishYSH/Helios-Base) | T2V ✅ I2V ✅ V2V ✅ Interactive ✅ | Best Quality, with v-prediction, standard CFG and custom HeliosScheduler. | +| Helios-Mid | 🤗 [Huggingface](https://huggingface.co/BestWishYsh/Helios-Mid) 🤖 [ModelScope](https://modelscope.cn/models/BestWishYSH/Helios-Mid) | T2V ✅ I2V ✅ V2V ✅ Interactive ✅ | Intermediate Ckpt, with v-prediction, CFG-Zero* and custom HeliosScheduler. | +| Helios-Distilled | 🤗 [Huggingface](https://huggingface.co/BestWishYsh/Helios-Distilled) 🤖 [ModelScope](https://modelscope.cn/models/BestWishYSH/Helios-Distilled) | T2V ✅ I2V ✅ V2V ✅ Interactive ✅ | Best Efficiency, with x0-prediction and custom HeliosDMDScheduler. | + + + +> 💡Note: +> * All three models share the same architecture, but Helios-Mid and Helios-Distilled use a more aggressive multi-scale sampling pipeline to achieve better efficiency. +> * Helios-Mid is an intermediate checkpoint generated in the process of distilling Helios-Base into Helios-Distilled, and may not meet expected quality. +> * For Image-to-Video or Video-to-Video, since training is based on Text-to-Video, these two functions may be slightly inferior to Text-to-Video. You may enable `is_skip_first_chunk` if you find the first few chunks are static or imporve the value of `image_noise_sigma_min`, `image_noise_sigma_max`, `video_noise_sigma_min`, and `video_noise_sigma_max`. + + +Download models using huggingface-cli: +``` sh +pip install "huggingface_hub[cli]" +huggingface-cli download BestWishYSH/Helios-Base --local-dir BestWishYSH/Helios-Base +huggingface-cli download BestWishYSH/Helios-Mid --local-dir BestWishYSH/Helios-Mid +huggingface-cli download BestWishYSH/Helios-Distilled --local-dir BestWishYSH/Helios-Distilled +``` + +Download models using modelscope-cli: +``` sh +pip install modelscope +modelscope download BestWishYSH/Helios-Base --local_dir BestWishYSH/Helios-Base +modelscope download BestWishYSH/Helios-Mid --local_dir BestWishYSH/Helios-Mid +modelscope download BestWishYSH/Helios-Distilled --local_dir BestWishYSH/Helios-Distilled +``` + + +## 🚀 Inference + + +Helios uses an autoregressive approach that generates **33 frames per chunk**. For optimal performance, `num_frames` should be set to a multiple of `33`. If a non-multiple value is provided, it will be automatically rounded up to the nearest multiple of 33. + +**Example frame counts for different video lengths:** + +| num_frames | Adjusted Frames | 24 FPS | 16 FPS | +|------------|-----------------|--------|--------| +| 1449 | 1452 (33×44) | ~60s (1min) | ~90s (1min 30s) | +| 720 | 726 (33×22) | ~30s | ~45s | +| 240 | 264 (33×8) | ~11s | ~16s | +| 129 | 132 (33×4) | ~5.5s | ~8s | + +### Sanity Check + +Before trying your own inputs, we highly recommend going through the sanity check to find out if any hardware or software went wrong. + +| Task | **Helios-Base** | **Helios-Mid** | **Helios-Distilled** | +| ------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| **T2V** | | | | +| **V2V** | | | | + + +### ✨ Group Offloading to Save VRAM + +Helios supports group offloading to significantly reduce VRAM consumption, allowing you to run on GPU with limited memory footprint. For more details on the underlying mechanics, please refer to the [documentation](https://huggingface.co/docs/diffusers/main/en/optimization/memory#group-offloading). + +The Helios model below requires `~6GB of VRAM`. + +
+ Click to expand the code + + ```bash + CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Distilled" \ + --transformer_path "BestWishYsh/Helios-Distilled" \ + --sample_type "t2v" \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --num_frames 240 \ + --guidance_scale 1.0 \ + --is_enable_stage2 \ + --pyramid_num_inference_steps_list 2 2 2 \ + --is_amplify_first_chunk \ + --output_folder "./output_helios/helios-distilled" \ + --enable_low_vram_mode \ + --group_offloading_type "leaf_level" + ``` + +
+ +### ✨ Context Parallelism on Multiple GPUs +Helios supports various Context Parallelism mechanisms, including `Ulysses Attention`, `Ring Attention`, `Unified Attention`, and `Ulysses Anything Attention`. For more details, please refer to the [documentation](https://huggingface.co/docs/diffusers/main/en/training/distributed_inference#context-parallelism). + +For example, let's take Helios-Base with 4 GPUs. + +
+ Click to expand the code + + ```bash + CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 infer_helios.py \ + --enable_parallelism \ # remember to enable this config + --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + --base_model_path "BestWishYsh/Helios-Base" \ + --transformer_path "BestWishYsh/Helios-Base" \ + --sample_type "t2v" \ + --num_frames 99 \ + --fps 24 \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --guidance_scale 5.0 \ + --output_folder "./output_helios/helios-base" + ``` + +
+ + +### ✨ Diffusers Pipeline + +Install diffusers from source: +```bash +pip install git+https://github.com/huggingface/diffusers.git +``` + +For example, let's take Helios-Distilled (**Standard Pipeline**). + +
+ Click to expand the code + + ```bash + import torch + from diffusers import AutoModel, HeliosPyramidPipeline + from diffusers.utils import export_to_video, load_video, load_image + + vae = AutoModel.from_pretrained("BestWishYsh/Helios-Distilled", subfolder="vae", torch_dtype=torch.float32) + + pipeline = HeliosPyramidPipeline.from_pretrained( + "BestWishYsh/Helios-Distilled", + vae=vae, + torch_dtype=torch.bfloat16 + ) + pipeline.to("cuda") + + negative_prompt = """ + Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, + low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, + misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards + """ + + # --- T2V --- + prompt = """ + A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue + and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with + a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, + allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades + of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and + the vivid colors of its surroundings. A close-up shot with dynamic movement. + """ + + output = pipeline( + prompt=prompt, + negative_prompt=negative_prompt, + num_frames=240, + pyramid_num_inference_steps_list=[2, 2, 2], + guidance_scale=1.0, + is_amplify_first_chunk=True, + generator=torch.Generator("cuda").manual_seed(42), + ).frames[0] + export_to_video(output, "helios_distilled_t2v_output.mp4", fps=24) + + # --- I2V --- + i2v_prompt = """ + A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, + illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, + casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes + apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and + relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and + respect for nature’s might. + """ + image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg" + + output = pipeline( + prompt=i2v_prompt, + negative_prompt=negative_prompt, + image=load_image(image_path).resize((640, 384)), + num_frames=240, + pyramid_num_inference_steps_list=[2, 2, 2], + guidance_scale=1.0, + is_amplify_first_chunk=True, + generator=torch.Generator("cuda").manual_seed(42), + ).frames[0] + export_to_video(output, "helios_distilled_i2v_output.mp4", fps=24) + + # --- V2V --- + v2v_prompt = """ + A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees + under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, + emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to + the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. + A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery. + """ + video_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4" + + output = pipeline( + prompt=v2v_prompt, + negative_prompt=negative_prompt, + video=load_video(video_path), + num_frames=240, + pyramid_num_inference_steps_list=[2, 2, 2], + guidance_scale=1.0, + is_amplify_first_chunk=True, + generator=torch.Generator("cuda").manual_seed(42), + ).frames[0] + export_to_video(output, "helios_distilled_v2v_output.mp4", fps=24) + ``` + +
+ +For example, let's take Helios-Distilled (**Modular Pipeline**). + +
+ Click to expand the code + + ```bash + import torch + from diffusers import ModularPipeline, ClassifierFreeGuidance + from diffusers.utils import export_to_video, load_image, load_video + + mod_pipe = ModularPipeline.from_pretrained("BestWishYsh/Helios-Distilled") + mod_pipe.load_components(torch_dtype=torch.bfloat16) + mod_pipe.to("cuda") + + # we need to upload guider to the model repo, so each checkpoint will be able to config their guidance differently + guider = ClassifierFreeGuidance(guidance_scale=1.0) + mod_pipe.update_components(guider=guider) + + # --- T2V --- + print("=== T2V ===") + prompt = ( + "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. " + "The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving " + "fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and " + "sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef " + "itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures " + "the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. " + "A close-up shot with dynamic movement." + ) + + output = mod_pipe( + prompt=prompt, + height=384, + width=640, + num_frames=240, + pyramid_num_inference_steps_list=[2, 2, 2], + is_amplify_first_chunk=True, + generator=torch.Generator("cuda").manual_seed(42), + output="videos", + ) + + export_to_video(output[0], "helios_distilled_modular_t2v_output.mp4", fps=24) + print(f"T2V max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB") + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + + # --- I2V --- + print("=== I2V ===") + image = load_image( + "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg" + ) + i2v_prompt = ( + "A towering emerald wave surges forward, its crest curling with raw power and energy. " + "Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave's body." + ) + + output = mod_pipe( + prompt=i2v_prompt, + image=image, + height=384, + width=640, + num_frames=240, + pyramid_num_inference_steps_list=[2, 2, 2], + is_amplify_first_chunk=True, + generator=torch.Generator("cuda").manual_seed(42), + output="videos", + ) + + export_to_video(output[0], "helios_distilled_modular_i2v_output.mp4", fps=24) + print(f"I2V max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB") + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + + # --- V2V --- + print("=== V2V ===") + video = load_video( + "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4" + ) + v2v_prompt = ( + "A dynamic time-lapse video showing the rapidly moving scenery from the window of a speeding train. " + "The camera captures various elements such as lush green fields, towering trees, quaint countryside houses, " + "and distant mountain ranges passing by quickly." + ) + + output = mod_pipe( + prompt=v2v_prompt, + video=video, + height=384, + width=640, + num_frames=240, + pyramid_num_inference_steps_list=[2, 2, 2], + is_amplify_first_chunk=True, + generator=torch.Generator("cuda").manual_seed(42), + output="videos", + ) + + export_to_video(output[0], "helios_distilled_modular_v2v_output.mp4", fps=24) + print(f"V2V max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB") + ``` + +
+ +### ✨ vLLM-Omni Pipeline + +Install vllm-omni from source: +```bash +pip install git+https://github.com/vllm-project/vllm-omni.git +``` + +For example, let's take Text-to-Video. + +
+ Click to expand the code + + ```bash + cd vllm-omni + + # Helios-Base + python3 examples/offline_inference/helios/end2end.py \ + --sample-type t2v \ + --model ./Helios-Base \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --num-frames 99 \ + --seed 42 \ + --output helios_t2v_base.mp4 + + # Helios-Mid + python examples/offline_inference/helios/end2end.py \ + --model ./Helios-Mid --sample-type t2v \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --guidance-scale 5.0 --is-enable-stage2 \ + --pyramid-num-inference-steps-list 20 20 20 \ + --num-frames 99 \ + --use-cfg-zero-star --use-zero-init --zero-steps 1 \ + --output helios_t2v_mid.mp4 + + # Helios-Distilled + python examples/offline_inference/helios/end2end.py \ + --model ./Helios-Distilled --sample-type t2v \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --num-frames 240 --guidance-scale 1.0 --is-enable-stage2 \ + --pyramid-num-inference-steps-list 2 2 2 \ + --is-amplify-first-chunk --output helios_t2v_distilled.mp4 + ``` +
+ +### ✨ SGLang-Diffusion Pipeline + +Install sglang-diffusion from source: +```bash +pip install git+https://github.com/sgl-project/sglang.git +``` + +For example, let's take Helios-Base. **(Native Support)** + +
+ Click to expand the code + + ```bash + sglang generate \ + --model-path BestWishYsh/Helios-Base \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --negative-prompt "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" \ + --height 384 \ + --width 640 \ + --num-frames 99 \ + --num-inference-steps 50 \ + --guidance-scale 5.0 + ``` +
+ +For example, let's take Helios-Base. **(Diffusers Backend)** + +
+ Click to expand the code + + ```bash + sglang generate \ + --model-path BestWishYsh/Helios-Base \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --negative-prompt "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" \ + --height 384 \ + --width 640 \ + --num-frames 99 \ + --num-inference-steps 50 \ + --guidance-scale 5.0 \ + --backend diffusers + ``` +
+ +## 🙌 Description + +- **Repository:** [Code](https://github.com/PKU-YuanGroup/Helios), [Page](https://pku-yuangroup.github.io/Helios-Page/) +- **Paper:** [https://huggingface.co/papers/2603.04379](https://huggingface.co/papers/2603.04379) +- **Point of Contact:** [Shenghai Yuan](shyuan-cs@hotmail.com) + +## ✏️ Citation + +If you find our paper and code useful in your research, please consider giving a star ⭐ and citation 📝: + +```BibTeX +@article{helios, + title={Helios: Real Real-Time Long Video Generation Model}, + author={Yuan, Shenghai and Yin, Yuanyang and Li, Zongjian and Huang, Xinwei and Yang, Xiao and Yuan, Li}, + journal={arXiv preprint arXiv:2603.04379}, + year={2026} +} +``` \ No newline at end of file diff --git a/Helios/eval_moviebench/checkpoints/get_checkpoints.sh b/Helios/eval_moviebench/checkpoints/get_checkpoints.sh new file mode 100644 index 0000000000000000000000000000000000000000..473c4970f5f9d1be6effd7f0dd8414eff4118604 --- /dev/null +++ b/Helios/eval_moviebench/checkpoints/get_checkpoints.sh @@ -0,0 +1 @@ +hf download BestWishYsh/HeliosBench-Weights --local-dir ./ \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/helios_t2v_prompts.csv b/Helios/eval_moviebench/playground/helios_t2v_prompts.csv new file mode 100644 index 0000000000000000000000000000000000000000..0e8a10943b3e9d06b82f5e6c567cdd80b99ed088 --- /dev/null +++ b/Helios/eval_moviebench/playground/helios_t2v_prompts.csv @@ -0,0 +1,241 @@ +id,prompt,duration +1,"A stylish woman strolls down a bustling Tokyo street, the warm glow of neon lights and animated city signs casting vibrant reflections. She wears a sleek black leather jacket paired with a flowing red dress and black boots, her black purse slung over her shoulder. Sunglasses perched on her nose and a bold red lipstick add to her confident, casual demeanor. The street is damp and reflective, creating a mirror-like effect that enhances the colorful lights and shadows. Pedestrians move about, adding to the lively atmosphere. The scene is captured in a dynamic medium shot with the woman walking slightly to one side, highlighting her graceful strides.",1440 +2,"A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity.",240 +3,"A movie trailer in a classic cinematic style, featuring the adventurous journey of a 30-year-old space man wearing a vibrant red wool knitted motorcycle helmet. The scene unfolds against a vast blue sky and a desolate salt desert landscape. Shot on 35mm film, the trailer showcases vivid and rich colors, capturing the hero as he navigates through the harsh terrain with determination. His helmet glints under the sun, adding to the dramatic effect. The background is a mix of sweeping desert vistas and distant horizons, with the occasional shimmer of light reflecting off the salt flats. A dynamic medium shot with a sweeping overhead angle, emphasizing the hero's resilience and the vastness of his adventure.",1440 +4,"A drone view of waves crashing against the rugged cliffs along Big Sur’s Garay Point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore, casting long shadows. In the distance, a small island with a lighthouse stands tall, its beam piercing the twilight. Green shrubbery covers the cliff’s edge, and the steep drop from the road down to the beach is a dramatic feat, with the cliff’s edges jutting out over the sea. The camera angle provides a bird's-eye view, capturing the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway. The scene is bathed in a warm, golden hue, highlighting the textures and details of the rocky terrain.",240 +5,"A close-up 3D animated scene of a short, fluffy monster kneeling beside a melting red candle. The monster has large, wide eyes and an open mouth, gazing at the flame with a look of wonder and curiosity. Its soft, fluffy fur contrasts with the warm, dramatic lighting that highlights every detail of its gentle, innocent expression. The pose conveys a sense of playfulness and exploration, as if the creature is discovering the world for the first time. The background features a cozy, warmly lit room with subtle hints of a fireplace and soft furnishings, enhancing the overall atmosphere. The use of warm colors and dramatic lighting creates a captivating and inviting scene.",240 +6,"A beautifully detailed papercraft illustration of a vibrant coral reef teeming with colorful fish and sea creatures. The coral formations are intricately designed, with each polyp and branch meticulously crafted. Schools of tropical fish swim gracefully among the corals, their scales shimmering in hues of turquoise, orange, and purple. Sea turtles glide smoothly over the reef, while a school of clownfish dart playfully around an anemone. The background features a soft, pastel-colored ocean with gentle waves and a hint of sunlight breaking through. The entire scene is rendered with a lifelike and textured papercraft style, capturing the essence of a thriving underwater ecosystem. A close-up view from a slightly elevated angle.",720 +7,"A close-up shot of a Victoria crowned pigeon in a naturalistic wildlife photography style, showcasing its striking blue plumage and red chest. The bird’s crest is adorned with delicate, lacy feathers, and its eye is a striking red color, adding to its regal and majestic appearance. The pigeon’s head is tilted slightly to the side, giving it a regal gaze. The background is blurred, emphasizing the bird’s striking beauty against a soft, muted backdrop. The lighting highlights the bird’s feathers, creating a vibrant and lifelike image.",720 +8,"A photorealistic closeup video of two pirate ships battling each other as they sail inside a steaming cup of coffee. The ships are intricately detailed, with wooden planks, sails flapping in the breeze, and cannons aimed at each other. The crew members, wearing authentic pirate attire, brandish swords and pistols, their expressions fierce and determined. The coffee foam creates a frothy, turbulent sea, with ripples and waves realistically depicted. The background is a blurred, warm brown coffee surface, with steam rising gently. The camera angle is slightly elevated, capturing the intense action from above.",240 +9,"A vibrant anime illustration in a thick painting style featuring a young man in his 20s sitting on a fluffy white cloud in the sky, engrossed in reading a classic leather-bound book. He has short, messy black hair and expressive brown eyes, wearing a casual white t-shirt and blue jeans. His posture is relaxed yet attentive, with one leg crossed over the other. The background is a vivid sky with cotton-like clouds and a soft sunset glow, casting a warm orange hue. The scene has a dreamy and ethereal quality. A medium shot with a slightly downward angle.",1440 +10,"A historical footage style photograph depicting a bustling gold rush town in California. The scene captures miners panning for gold in a stream, their faces weathered and determined. Behind them, makeshift wooden shacks and tents line the streets, with smoke rising from chimneys. A man in a dusty hat and tattered clothes stands near a sluice box, his hand on his hip, looking out towards the camera with a mix of hope and hardship. The background features rolling hills and dense forests, with a few oxen-drawn wagons in the distance. The photo has a sepia tone and a grainy texture, capturing the essence of the era. A medium shot with a slightly tilted angle.",1440 +11,"A close-up view of a glass sphere containing a tranquil Zen garden. Inside, a small Eastern dwarf with weathered skin and a serene expression is raking the sand, meticulously creating intricate patterns with a bamboo rake. His movements are deliberate and meditative, enhancing the peaceful atmosphere of the scene. The background is blurred, revealing only hints of greenery and rocks, adding to the serene setting. The sphere itself is polished, reflecting the surroundings subtly. The camera angle captures the dwarf from a slightly elevated position, emphasizing his focused and contemplative pose.",240 +12,"A cinematic film shot in 70mm, capturing an extreme close-up of a 24-year-old woman's eye as it blinks. The scene takes place during magic hour in Marrakech, with the vibrant colors of the setting sun casting warm hues over the bustling streets. The depth of field emphasizes the intricate details of her almond-shaped eyes, which reflect the lively atmosphere of the city. Her eyes, framed by long, dark lashes, are set against a backdrop of bustling market stalls, ornate architecture, and the soft shadows of the setting sun. The background features a blend of rich textures and vibrant colors, creating a sense of depth and immersion. A medium shot with a slightly elevated perspective, highlighting the natural movement of her eye.",240 +13,"A vibrant cartoon-style illustration depicting a kangaroo performing a lively disco dance. The kangaroo has a joyful expression, with large, expressive eyes and a mischievous grin. It wears a colorful sequined outfit with sparkles, including a glittery top and matching pants. Its tail is fluffed out and swaying rhythmically. The kangaroo moves with natural fluidity, one foot lifted and the other stepping forward. The background features a blurred dance floor with colorful lights and dancing figures, creating a festive atmosphere. The illustration has a smooth, hand-drawn style with exaggerated proportions. A dynamic close-up shot from a slightly elevated angle.",1440 +14,"A beautifully crafted homemade video set in Lagos, Nigeria in the year 2056, captured with a mobile phone camera. The footage showcases diverse people going about their daily lives in a vibrant and bustling urban environment. The camera captures various individuals: a group of young Nigerian women in colorful traditional attire walking down a crowded street, a man in a smart business suit hurrying past a futuristic billboard, and a family gathered around a street vendor selling fresh fruits. The background features modern skyscrapers, traditional market stalls, and electric vehicles zipping by. The video has a warm, nostalgic feel, with occasional blurs and graininess reminiscent of mobile phone recording. A series of handheld shots and close-ups capture the dynamic energy of the city.",720 +15,"A high-resolution digital artwork in a realistic botanical style, showcasing a petri dish where a miniature bamboo forest thrives, complete with tiny red pandas running around. The bamboo stalks are slender and green, with delicate leaves swaying gently. The red pandas, with their distinctive reddish-brown fur and black legs, move playfully among the bamboo, sometimes climbing up the stalks or nibbling on leaves. The petri dish is filled with nutrient-rich soil, and the background is a blurred but recognizable forest landscape, with hints of distant mountains and clear blue skies. The entire scene exudes a sense of harmony and tranquility, capturing the wonder of nature in a microscopic world. A macro shot from a low angle, emphasizing the intricate details of the red pandas and the bamboo.",1440 +16,"A rotating camera view inside a large New York museum gallery, showcasing a towering stack of vintage televisions, each displaying different programs from the 1950s and 1970s. The televisions show a mix of 1950s sci-fi movies, horror films, news broadcasts, static, and a 1970s sitcom. The gallery space is filled with the nostalgic glow of the old TV screens, their edges worn and frames aged. The background features other vintage exhibits and artifacts, adding to the historical ambiance. The televisions are arranged in a dynamic, almost chaotic pattern, creating a sense of visual interest and movement. A wide-angle shot capturing the entire stack and the surrounding gallery space.",720 +17,"A 3D animation of a small, round, fluffy creature with big, expressive eyes exploring a vibrant, enchanted forest. The creature, a whimsical blend of a rabbit and a squirrel, has soft blue fur and a bushy, striped tail. It hops along a sparkling stream, its eyes wide with wonder. The forest is alive with magical elements: flowers that glow and change colors, trees with leaves in shades of purple and silver, and small floating lights that resemble fireflies. The creature stops to interact playfully with a group of tiny, fairy-like beings dancing around a mushroom ring. The creature looks up in awe at a large, glowing tree that seems to be the heart of the forest. The scene is rendered in a detailed, fantasy style, with a soft, ethereal lighting that enhances the enchantment. The camera follows the creature as it moves, capturing its playful interactions and the magical ambiance of the forest. A medium shot with a dynamic angle that highlights the creature's expressions and the enchanting environment.",1440 +18,"A dynamic shot from behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by towering redwood trees on a rugged mountain slope. Dust kicks up from its tires, and the sunlight shines on the SUV, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other vehicles in sight. The trees on either side are dense redwoods, with patches of greenery scattered throughout. The car navigates the curve with ease, making it seem as if it is on a thrilling drive through the rugged terrain. The dirt road is framed by steep hills and mountains, with a clear blue sky above and wispy clouds drifting by. The camera captures the vehicle from the rear, emphasizing its powerful and adventurous journey.",1440 +19,"A detailed digital painting in the style of a realistic Japanese manga, capturing reflections in the window of a train traveling through the Tokyo suburbs. The train moves smoothly, passing through lush green fields and dense forests. Outside the window, the scenery blurs into a series of vivid colors—emerald greens, deep browns, and vibrant yellows. Inside the train, a young woman with long black hair and traditional Japanese clothing sits with a contemplative expression, gazing out the window. Her kimono is adorned with intricate patterns, and she wears a simple obi sash tied neatly. The train cabin is dimly lit, with soft shadows playing across the wooden seats. The background features a blurred yet recognizable landscape, with hints of Tokyo skyscrapers and cherry blossoms in the distance. A medium shot from a slightly tilted angle, emphasizing the reflection and the woman's serene expression.",720 +20,"A stunning aerial photograph captured from a drone, circling around a majestic historic church perched atop a rocky outcropping along the Amalfi Coast. The camera captures the intricate architectural details and tiered pathways and patios that adorn the church, with waves crashing against the rocks below. The view extends to the horizon, showcasing the coastal waters and the rolling hills of the Amalfi Coast in Italy. Distant figures can be seen leisurely walking and enjoying the dramatic ocean views from the patios. The warm glow of the afternoon sun bathes the scene in a magical and romantic light, creating a breathtaking and serene atmosphere. The photo has a high-resolution, detailed quality that highlights every texture and color of the landscape. A wide-angle shot from a dynamic aerial perspective.",240 +21,"A wide-angle underwater photograph captures a large orange octopus resting on the ocean floor, its tentacles spread out around its body and eyes closed. The octopus blends seamlessly with the sandy and rocky terrain. Behind a rock, a brown and spiny king crab is crawling towards it, its claws raised and ready to strike. The crab has long legs and antennae, adding to its menacing appearance. The scene is set in a clear, blue ocean with rays of sunlight filtering through, creating a vivid contrast. The photo is sharp and crisp, with a high dynamic range, emphasizing the octopus and the crab in focus while the background is slightly blurred, enhancing the sense of depth.",1440 +22,"A vibrant illustration in a whimsical cartoon style depicting a flock of paper airplanes fluttering through a dense jungle. The airplanes, resembling small birds, weave gracefully around towering trees, their wings fluttering gently. The jungle is lush and vibrant, with a variety of exotic plants and colorful flowers. The airplanes seem to migrate through the forest, creating a mesmerizing aerial dance. The background is rich with detailed textures, including sunlight filtering through the canopy, casting dappled shadows on the ground. A dynamic overhead view capturing the mid-flight action of the airplanes.",240 +23,"A charming comic-style illustration depicting a cozy living room scene where a fluffy gray cat is waking up its sleeping owner, who lies on the couch with a sleepy, resigned expression. The cat, with large, round eyes and a mischievous look, is pawing at the owner's face and meowing insistently. The owner attempts to ignore the cat, turning away slightly, but the cat persists, jumping onto the owner's chest and nuzzling their hand. Finally, the owner, unable to resist, reaches under the pillow and pulls out a small bag of treats, offering it to the cat with a playful smile. The background shows soft, warm lighting from a nearby lamp, with scattered books and a blanket on the couch. A medium shot from a slightly elevated angle, capturing both the cat and the owner's interaction.",240 +24,"A nature photography style photo capturing a family of orangutans along the Kinabatangan River in Borneo. The mother orangutan, with long reddish-brown fur and expressive brown eyes, is holding her baby tightly. The baby orangutan, with smaller size and lighter fur, is clinging to its mother’s chest, both gazing curiously at the camera. The father orangutan, larger and more muscular, is standing nearby, looking contemplative. The riverbank is lush with green foliage, and the water reflects the surrounding tropical rainforest. The photo has a vivid and naturalistic style, with the orangutans in focus against a slightly blurred background of dense jungle. A medium shot from a slightly elevated angle, capturing the interaction between the family.",720 +25,"A vibrant and lively Chinese Lunar New Year celebration video featuring a majestic Chinese dragon performing traditional dance moves. The dragon, made of colorful silk and adorned with intricate patterns, has flowing scales and a fierce expression, moving gracefully with fluid movements. It dances amidst a sea of joyful people in festive red and gold attire, accompanied by drummers and musicians playing traditional instruments. The background showcases bustling streets filled with lanterns, paper decorations, and colorful stalls. The video has a dynamic and energetic feel, capturing the essence of the festival. A wide-angle shot with dynamic camera movements following the dragon's path.",1440 +26,"A dynamic and lively tour through an art gallery, showcasing a diverse array of beautiful works in various styles. The gallery is filled with paintings, sculptures, and installations, each piece telling its own story. One section features impressionistic landscapes with soft brushstrokes and vibrant colors, capturing serene lakes and rolling hills. Nearby, there are realistic portraits with intricate details and lifelike expressions. In another corner, abstract artworks with bold colors and geometric shapes create a sense of movement and energy. The gallery itself has a modern, open design with high ceilings and large windows allowing natural light to flood in. Visitors move gracefully through the space, pausing occasionally to admire the works. The camera captures the gallery from multiple angles—wide shots of the entire room, close-ups of individual pieces, and sweeping pans to show the flow of visitors. The overall atmosphere is one of inspiration and wonder.",720 +27,"A dynamic and vibrant anime illustration in a flowing watercolor style, capturing the bustling snowy streets of Tokyo. The camera moves smoothly through the city, following several people joyfully enjoying the snow and shopping at nearby stalls. Gorgeous sakura petals dance through the air, swirling with snowflakes. The scene features traditional Japanese architecture, with shops and lanterns illuminated by the soft winter light. People are bundled up in warm coats and scarves, their faces lit with smiles. The background shows blurred, snowy rooftops and distant cherry blossom trees, creating a serene yet lively atmosphere. A medium shot with a sweeping camera motion, highlighting the natural movement of both people and petals.",1440 +28,"A stop motion animation in a charming hand-drawn style, depicting a flower slowly growing out of the windowsill of a suburban house. The flower is a vibrant sunflower, with its petals unfurling gracefully. The windowsill is adorned with small potted plants and a few scattered books. The house has a cozy exterior, with a red door and white shutters, and the surrounding area features neatly trimmed bushes and a small garden path. The animation captures the natural growth process, with the sunflower stem bending slightly as it stretches upward. A close-up shot from a low angle, emphasizing the delicate details of the flower's growth.",240 +29,"A cyberpunk-style illustration depicting a lone robot navigating a neon-lit cityscape. The robot stands tall with sleek, metallic armor, adorned with blinking lights and wires. Its eyes, glowing with a deep blue hue, scan the surroundings with curiosity. The background features towering skyscrapers, holographic advertisements, and crowded streets filled with various cyborgs and humans. The air is thick with smoke and the hum of technology. A medium shot from a high-angle perspective, capturing both the robot and the bustling city environment.",720 +30,"A cinematic 35mm film-style extreme close-up of a gray-haired man in his 60s, deeply engrossed in thought about the history of the universe as he sits at a Parisian café. His weathered face, adorned with a full beard, conveys a professorial air. His eyes are fixed on people walking off-screen, lost in contemplation. He is dressed in a woolen suit coat and a button-down shirt, wearing a brown beret and glasses. The background showcases the bustling Parisian streets and cityscape, with golden light illuminating the scene. The depth of field creates a sense of depth, and the lighting is cinematic, highlighting his subtle, closed-mouth smile as if he has just discovered the answer to life's mysteries. A medium shot with a slight overhead angle.",720 +31,"A beautifully animated silhouette scene depicts a lone wolf standing on a rocky hilltop, howling at the full moon, its expression filled with loneliness and longing. As the wolf's howl echoes across the night, it suddenly notices a distant silhouette of another wolf, signaling the beginning of its journey to rejoin its pack. The background is a detailed, moonlit landscape with rolling hills, dense forests, and a clear, starry sky. The animation has a smooth, fluid motion, capturing the natural movements of the wolves. The camera starts with a close-up of the lone wolf, then gradually pans out to show the entire scene, creating a sense of connection and movement.",720 +32,"A surreal and dreamlike scene in the style of a cyberpunk film, depicting New York City submerged underwater, resembling the mythical city of Atlantis. Fish, whales, sea turtles, and sharks swim through the bustling streets, which now resemble underwater landscapes. The buildings are partially submerged, their facades covered in algae and marine growth. The water is murky and filled with sunlight filtering through from above, casting colorful hues. Pedestrians, now merfolk, move gracefully through the water, interacting with the aquatic creatures. The camera angle is from a low, sweeping shot, capturing the vast expanse of this submerged metropolis.",240 +33,"A winter scene in a snowy forest, where a litter of playful golden retriever puppies emerge from the snow. Their heads pop out, their fluffy fur glistening in the sunlight, and they wag their tails joyfully. They are covered in snow, with some paw prints leading away into the deep snow. One puppy is burying its nose in the snow, while another chases a small ball that has rolled nearby. The background shows dense evergreen trees and a gentle slope leading up to a clearing. The air is crisp and cold, with tiny snowflakes falling gently. A close-up shot from a slightly elevated angle, capturing the lively and energetic moment.",720 +34,"A cinematic film shot in 35mm capturing a dynamic step-printing scene of a person running. The runner is a young man with short, tousled brown hair and determined eyes, sprinting down a city street lined with tall buildings and neon signs. His arms are pumped vigorously, and he looks focused and energetic. The background features blurred motion with the cityscape gradually fading into a soft, sepia tone. The camera follows him closely, capturing his every stride and movement. The scene has a nostalgic and vintage film texture, enhancing the dramatic intensity of the run. A close-up shot from a slightly behind-the-subject angle.",720 +35,"A nature-inspired illustration in a soft watercolor style depicting five playful gray wolf pups frolicking and chasing each other along a remote gravel road. The pups run and leap, their tails wagging joyfully as they chase and nip at one another. They are covered in a fine layer of dirt and grass, adding to their lively energy. The background is filled with tall grass swaying gently in the breeze, with a few wildflowers scattered about. The sun casts warm, golden light over the scene, creating a serene and natural atmosphere. A dynamic close-up from a low angle, capturing the wolves' playful antics.",240 +36,"A dynamic and explosive basketball moment captured in a high-energy action style, showcasing a basketball flying through the hoop with a burst of fireworks exploding behind it. The basketball is vividly depicted, with realistic textures and reflections. The hoop is made of shiny black metal, and the net is taut and stretched. Behind the hoop, a spectacular explosion of fireworks fills the sky, creating a dazzling display of colors and sparks. The camera angle is from the side, capturing the intense moment with a sense of movement and excitement. The background features blurred spectators and a sports arena with standing figures, adding to the lively atmosphere. A medium shot with a slight upward angle.",720 +37,"A realistic archaeological excavation scene in a vast desert, where archeologists meticulously uncover a generic plastic chair buried under layers of sand. They carefully brush away the dust, their focused expressions conveying the importance of their discovery. The chair, though simple, appears slightly worn and faded. The background showcases the harsh, barren landscape of the desert, with dunes stretching into the distance. The sun is setting, casting long shadows and adding a sense of timelessness to the scene. A close-up shot from a slightly lower angle, emphasizing the detailed work of the archeologists and the weathered chair.",240 +38,"A cinematic photograph in the style of a warm family moment, capturing a grandmother with neatly combed grey hair standing behind a colorful birthday cake adorned with numerous pink frosting candles and sprinkles. She leans forward with a gentle puff, extinguishing the flickering candles with a joyful expression, her eyes sparkling with happiness. The grandmother wears a light blue blouse adorned with delicate floral patterns, and the scene is filled with several happy friends and family members gathered at the wooden dining room table, their faces illuminated by soft, warm lighting. The background is slightly out of focus, emphasizing the intimate and celebratory atmosphere. A 3/4 view shot, highlighting the grandmother's warm and loving demeanor, with a beautiful blend of natural light and color tones.",240 +39,"A vibrant and lively scene in Burano, Italy, captured in a direct camera angle. The colorful buildings with their distinctive pastel hues dominate the background, creating a picturesque Venetian atmosphere. On the ground floor, a cute Dalmatian peers out through a window, its curious gaze catching the attention of passersby. Pedestrians and cyclists move gracefully along the canal streets in front of the buildings, adding to the bustling yet charming ambiance. The photo has a warm, nostalgic feel, with the Dalmatian standing out against the vivid backdrop. A medium shot capturing the street life and the building details.",240 +40,"A scenic photograph capturing the moment a steam train departs from the Glenfinnan Viaduct, a historic railway bridge in Scotland. The train moves gracefully over the arch-covered viaduct, its smoke billowing into the air. The landscape is lush with greenery, and towering rocky mountains frame the scene, creating a picturesque backdrop. The sky is a clear, bright blue with the sun shining down, casting a warm glow on the train and the surrounding scenery. The viaduct itself is a striking feature, with intricate ironwork and a verdant setting. The photo has a classic, nostalgic feel, emphasizing the natural beauty and historical charm of the location. A wide-angle shot from a slightly elevated angle, capturing both the train and the expansive landscape.",720 +41,"A charming 3D digital render art style image showcasing an adorable and happy otter confidently standing on a surfboard, wearing a bright yellow lifejacket. The otter is depicted with a joyful expression, its fur soft and detailed, and it appears to glide gracefully through turquoise tropical waters. The background features lush tropical islands with vibrant green foliage and palm trees, creating a serene and picturesque setting. The water is crystal clear, with gentle waves and sunlight filtering through, adding a sense of tranquility and vibrancy to the scene. A medium shot capturing the otter mid-glide, with a slight tilt to the camera angle emphasizing its playful and adventurous spirit.",1440 +42,"A close-up shot in the style of a nature documentary, featuring a chameleon with its body contorted in an intriguing pose, showcasing its striking color-changing capabilities. The chameleon's skin shifts between vibrant shades of green, blue, and yellow, with intricate patterns and textures. Its large, round eyes focus intently on the viewer, and its long, sticky tongue is partially extended, ready to catch prey. The background is blurred, emphasizing the chameleon's vivid colors and detailed patterns, with hints of a lush, tropical forest environment. The photo has a crisp, high-resolution quality, highlighting the reptile's natural movements and vibrant hues. A close-up shot from a slightly elevated angle.",1440 +43,"A vibrant and lively vlog-style photo of a corgi in tropical Maui, showcasing the dog energetically filming itself on a sandy beach. The corgi stands on the shore, one paw slightly lifted, with a joyful and curious expression. It wears a colorful collar and a small backpack camera slung over its neck. The background features a lush, palm-fringed beach with clear turquoise waters and a bright blue sky. The photo has a warm, natural lighting effect, capturing the corgi from a slightly elevated angle, emphasizing its playful and adventurous spirit.",240 +44,"A cinematic and grainy photograph captures a white and orange tabby cat joyfully darting through a dense garden, as if chasing something. The cat’s eyes are wide and filled with happiness as it jogs forward, scanning the branches, flowers, and leaves. The narrow path winds between the lush greenery, and the scene is captured from a ground-level angle, providing a low and intimate perspective. The image has warm tones and a subtle grainy texture, with scattered daylight filtering through the leaves and plants above, creating a warm contrast that highlights the cat’s orange fur. The shot is clear and sharp, with a shallow depth of field that focuses solely on the cat’s movements and expressions.",240 +45,"An aerial view of Santorini during the blue hour, capturing the stunning architecture of white Cycladic buildings with blue domes against the twilight sky. The caldera views are breathtaking, with the volcanic cliffs and sea below creating a dramatic contrast. The lighting casts a soft, warm glow, enhancing the serene atmosphere. The image has a dreamy, almost ethereal quality, emphasizing the beauty of the setting. A bird's-eye view with a wide-angle lens, focusing on the intricate details of the buildings and the vast expanse of the caldera.",1440 +46,"A tilt-shift photograph of a bustling construction site, capturing the essence of a busy work environment. Workers in hard hats and safety gear are scattered throughout the scene, operating various pieces of heavy machinery and equipment. The site is filled with cranes, bulldozers, and excavators, each piece of machinery adding to the dynamic atmosphere. The background features partially constructed buildings and scaffolding, creating a sense of progress and ongoing development. The overall texture of the photo gives it a miniature-like quality, emphasizing the scale and activity of the site. A medium shot with a slightly downward angle, highlighting the intricate details and movements of the workers and machines.",240 +47,"A dramatic, epic fantasy-style illustration depicting a towering, giant cloud shaped like a man, with thunderous lightning bolts emanating from his outstretched arms and striking the ground below. The cloud-man has a fierce, determined expression, with stormy gray clouds cascading down his form, giving him a menacing presence. His eyes glow with an intense, electric blue light, and his arms are spread wide, ready to unleash more bolts. The background shows a dark, stormy sky with heavy rain and distant lightning, creating a foreboding atmosphere. The scene is rendered in a dynamic, high-detailed style with a mix of realistic and fantastical elements. A high-angle shot capturing the full figure of the cloud-man in action.",1440 +48,"A vibrant and dynamic illustration in the style of a futuristic sci-fi comic, depicting two playful dogs, a Samoyed and a Golden Retriever, running through a neon-lit city at night. The dogs' fur gleams under the vibrant glow of the city's neon lights, casting colorful reflections. They move energetically, tails wagging, with the Samoyed having a fluffy white coat and the Golden Retriever sporting a golden one. The cityscape is filled with towering skyscrapers adorned with flickering neon signs, creating a mesmerizing visual spectacle. The background features blurred outlines of the city's architecture, with hints of glowing streets and distant buildings. The camera angle captures a medium shot of the dogs from a slightly elevated perspective, emphasizing their joyful movements.",240 +49,"A dynamic scene captured in the style of a vibrant food photography, showcasing a chef skillfully chopping onions in a bustling kitchen. The chef, a middle-aged man with a weathered face and determined expression, skillfully slices the onions with quick, practiced movements. He wears a white apron tied neatly around his waist and a chef's hat perched atop his head. The background is a well-equipped kitchen, with stainless steel appliances and countertops cluttered with various cooking tools and ingredients. Steam rises from a pot on the stove, and sunlight filters through the window, casting a warm glow. A medium shot with the chef at the center, capturing the intensity of his work.",720 +50,"A detailed digital painting style illustration of a small man with a cheerful expression, holding several colorful building blocks, visiting an art gallery. He has round glasses and a warm smile, with his hands gently holding the blocks. The gallery features various paintings on the walls, with a mix of modern abstract and classic artworks. The floor is covered in polished wooden tiles, and there are comfortable chairs and tables nearby. The man is standing near a large painting of a serene landscape, with his gaze focused on it. The background has a soft, warm lighting, highlighting the textures of the artwork and the man's clothes. A medium shot from a slightly lower angle, capturing both the man and the gallery scene.",720 +51,"A vibrant and dynamic illustration in a cartoon style depicting a white cat sitting comfortably behind the wheel of a toy car, driving through a bustling downtown street. The cat has large, round eyes and a mischievous grin, with fur that appears soft and fluffy. Tall skyscrapers and a mix of people walking briskly fill the background, adding to the lively urban setting. The car's tires spin as it moves, and the wind flows through the cat's ears. The illustration has a bright color palette and a smooth, cartoony texture. The camera angle is slightly elevated, capturing both the cat and the vibrant street scene below.",240 +52,"A macro shot of a volcanic eruption in a coffee cup, capturing the dramatic moment in vivid detail. The coffee cup is filled with rich, dark brown liquid, and the surface is suddenly disrupted by a burst of foam and steam, mimicking the intense heat and pressure of a real volcanic eruption. The foam rises and spreads across the surface, creating a chaotic yet mesmerizing pattern. The cup itself is made of ceramic, with intricate patterns etched into the sides, adding texture and depth to the scene. The background is a blurred gradient of warm browns and grays, enhancing the focus on the erupting foam. The lighting is dramatic, casting shadows and highlighting the dynamic movement of the foam. A close-up shot from a low angle, emphasizing the explosive nature of the eruption.",1440 +53,"A highly detailed close-up shot in HD, focusing on dew droplets glistening on the delicate petals of a blue rose. The petals are soft and velvety, with intricate patterns and subtle color gradients. Each dew drop sparkles like tiny diamonds, catching the light and creating a mesmerizing effect. The background is blurred, emphasizing the dew and petals, with a soft focus on the edges. The photo has a clear, crisp texture, highlighting the beauty and fragility of nature.",720 +54,"A Chinese boy wearing glasses sits in a fast food restaurant, enjoying a delicious cheeseburger with his eyes closed. His hair is neatly combed, and he has a slightly dreamy expression. He holds the cheeseburger with both hands, taking a big bite. The background shows other diners and a colorful menu board with various fast food items. The lighting is warm and inviting, creating a cozy atmosphere. A close-up shot from a slightly lower angle, capturing the boy's joyful moment.",720 +55,"A tropical island beach scene in a vibrant and lively illustration style, featuring a corgi wearing stylish sunglasses walking along the sandy shore. The corgi has a playful expression, its fur glistening in the bright sunlight. It strides confidently, its tail wagging as it explores the soft sand. The background showcases a clear turquoise sea with palm trees swaying gently in the breeze. A few seagulls fly overhead, adding to the serene yet lively atmosphere. The corgi’s sunglasses add a touch of whimsy and fun to the scene. A medium shot with the corgi at the center, captured from a slightly elevated angle.",1440 +56,"A traditional Chinese dining scene in a dimly lit restaurant, capturing a middle-aged Chinese man sitting at a small round table. He is attentively eating noodles with chopsticks, his face reflecting contentment and focus. His attire is casual yet neat, with a light blue shirt and black pants. The background features blurred details of other diners and tables, hinting at a bustling yet cozy atmosphere. The lighting casts soft shadows, enhancing the warm and inviting ambiance. A close-up shot from a slightly overhead angle, emphasizing the man's engaged expression and the textures of the food.",720 +57,"A romantic scene in a nighttime cityscape where a man and a woman walk hand in hand under a starry sky, their faces illuminated by the soft glow of streetlights. They are dressed in casual yet elegant attire, the man in a dark blue suit and the woman in a light green dress. A wooden bucket is placed on the ground nearby, adding a touch of rustic charm. The couple’s expressions are filled with happiness and affection, as they gaze into each other’s eyes. The background features tall buildings with windows lit up, creating a warm and cozy atmosphere. The stars above twinkle brightly, enhancing the serene and intimate mood. The scene is captured in a medium shot with a slightly upward angle, capturing both the couple and the surrounding environment.",1440 +58,"A close-up shot of a steaming cappuccino in a ceramic cup, with a rich brown foam on top and a slight milk swirl pattern. The cup has a simple yet elegant design, with a white handle and a light brown body. The background is a cozy café with warm lighting, wooden tables, and a few patrons chatting in the corner. The cappuccino is freshly made, with a hint of steam rising from the surface, capturing the essence of a perfect morning beverage.",1440 +59,"A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement.",240 +60,"A photograph in a warm and nostalgic style, capturing chimneys against a setting sun. The chimneys stand tall and sturdy, casting long shadows across a peaceful rural landscape. The sun is low in the sky, painting the scene in soft orange and pink hues. The background features a serene countryside with fields, trees, and distant hills. The chimneys are surrounded by a haze of golden light, creating a sense of warmth and tranquility. A wide-angle shot with the chimneys in the foreground, capturing the entire sunset scene.",720 +61,"An astronaut runs smoothly and appears almost weightless on the lunar surface, as seen from a low-angle shot that highlights the vast, desolate background of the moon. The moon's craters and rocky terrain are clearly visible, creating a stark contrast against the running astronaut who moves with graceful, fluid motions. The background features a muted, grayscale texture with subtle shadows and highlights, emphasizing the lunar landscape's rugged beauty. The astronaut wears a classic spacesuit with reflective fabric, adding to the sense of lightness and movement. A dynamic medium shot capturing the astronaut's forward momentum.",240 +62,"A dynamic photograph capturing a little boy riding his bike through a garden that transitions through the changing seasons—fall leaves crunch underfoot, winter snow blankets the ground, spring flowers bloom, and summer sunshine sparkles through the foliage. The boy, with curly brown hair and a joyful smile, pedals energetically, his arms outstretched in excitement. The garden backdrop features trees with branches adorned in each season’s distinctive foliage. A series of shots taken from various angles, starting with a wide shot of the boy entering the garden in spring, transitioning to a mid-shot of him biking through the colorful autumn leaves, then a close-up of him riding through a snowy path, and finally a wide-angle view of him enjoying the warm summer sun. The photo has a natural, documentary style, emphasizing the boy’s natural movements and the vibrant colors of the changing seasons.",720 +63,"A close-up shot of someone carefully pouring milk into a cup, with the milk flowing smoothly and filling the cup with a milky white color. The person's hand is steady, guiding the milk into the cup with precision. The background is blurred, showing a subtle kitchen setting with hints of cabinets and countertops. The photo has a soft, natural lighting effect, emphasizing the smoothness and elegance of the pouring action.",240 +64,"A detailed oil painting in a romantic style, showcasing a young woman standing amidst a vibrant garden filled with blooming flowers. She wears a floral-patterned dress, her hair loosely tied with wildflowers adorning it. Her expression is one of serene joy, with a gentle smile on her lips. She is framed by a variety of colorful blooms, including roses, tulips, and daisies, which surround her in a natural, organic arrangement. The background features a soft, pastel-colored sky with fluffy clouds, and a gentle breeze rustling through the petals. A medium shot with a slightly tilted angle, capturing the essence of spring and renewal.",240 +65,"A cinematic scene from a classic western movie, featuring a rugged man riding a powerful horse through the vast Gobi Desert at sunset. The man, dressed in a dusty cowboy hat and a worn leather jacket, reins tightly on the horse's neck as he gallops across the golden sands. The sun sets dramatically behind them, casting long shadows and warm hues across the landscape. The background is filled with rolling dunes and sparse, rocky outcrops, emphasizing the harsh beauty of the desert. A dynamic wide shot from a low angle, capturing both the man and the expansive desert vista.",1440 +66,"A vibrant and lively illustration in a cartoon style of a panda playing the guitar. The panda has black and white fur, with round eyes and a friendly expression. It sits comfortably on a small stool, strumming the guitar with one paw while the other rests on its knee. The guitar is a small acoustic model, and the strings are plucked with precision. The background features a cozy room with a few plants and colorful decorations, adding a warm and inviting atmosphere. The camera angle is slightly from above, capturing the panda's joyful and focused performance.",720 +67,"A dramatic sunset landscape photograph captured in a cinematic style, featuring a car with its side mirrors reflecting the vibrant hues of the setting sun. The car is parked on a winding road, with one of its side mirrors perfectly capturing the warm orange and pink tones of the sky. The sun is just below the horizon, casting long shadows and creating a golden glow over the landscape. The background includes rolling hills and a few trees silhouetted against the sky. The photo has a rich, film noir texture, enhancing the mood and atmosphere. A wide-angle shot from a low angle, emphasizing the reflection in the mirror and the vastness of the landscape.",240 +68,"A dynamic rally car speeding through a tight turn on a winding track, tires screeching as it navigates the curves with precision. The car is a sleek, racing machine with a vibrant red body and black accents, its headlights glowing brightly in the night. The driver, a determined-looking man with focused eyes, grips the steering wheel tightly, his muscles tensed. The background is blurred, showing glimpses of the track ahead and behind, with lights reflecting off the wet pavement. The camera angle is from slightly above, capturing the car's movement and the intense energy of the moment.",240 +69,"A charming illustration in a watercolor style of a young white rabbit wearing glasses and reading a newspaper. The rabbit has soft fur, large round ears, and gentle, curious eyes. It sits upright on a cozy armchair, one paw holding the newspaper and the other resting on its knee. The background features a warm living room with a fireplace, a few books on a side table, and a blurred view of a window with falling leaves. The rabbit's expression is one of focused interest, with a slight smile playing on its lips. A close-up shot from a slightly elevated angle, capturing the rabbit's detailed features and the newspaper's headlines.",240 +70,"A close-up shot of a bright blue parrot's shimmering feathers, capturing the unique and vibrant colors in the light. The parrot's feathers glisten with a metallic sheen, showcasing a mix of deep indigos, vivid greens, and rich blues. Its eyes sparkle with curiosity, and it appears lively and alert, perched on a branch. The background is blurred, highlighting the parrot against a soft, warm environment. The photo has a naturalistic and lifelike quality, emphasizing the bird's detailed plumage and natural movements.",1440 +71,"A subtle and elegant photograph in a Japanese style, capturing a woman with gentle, contemplative eyes and flowing dark hair sitting by the window of a high-speed train. The train moves rapidly through a bustling cityscape, with blurred reflections of the city lights and buildings on the window pane. The woman appears serene, her hands resting gently on her lap. The background features a blend of traditional Japanese architecture and modern skyscrapers, with a soft, muted color palette. The photo has a vintage film texture, emphasizing the movement and energy of the scene. A medium shot from a slightly angled perspective, highlighting the woman's thoughtful gaze and the dynamic motion of the train.",1440 +72,"An astronaut running through a narrow alley in Rio de Janeiro, Brazil. The astronaut is dressed in a bright white spacesuit with a helmet that reflects sunlight. The spacesuit is adorned with various technical patches and has a reflective texture. The astronaut's movements are energetic and dynamic, with one hand on their hip and the other reaching forward for balance. The background features colorful street art, vibrant buildings, and people bustling about. The alley is dimly lit, with shadows cast by the narrow walls. A mid-shot with the astronaut running from a low-angle perspective, capturing the excitement and contrast between the urban environment and the space exploration gear.",240 +73,"A dynamic FPV aerial view of a vibrant underwater suburban neighborhood, where colorful corals line the streets. The camera moves swiftly, capturing the intricate details of the coral formations and the diverse marine life swimming around. The streets are bustling with colorful fish and schools of tropical fish, creating a lively and energetic atmosphere. The water is crystal clear, with sunlight filtering through, casting a warm glow on the scene. The camera angle shifts slightly, providing a sense of depth and movement, as if the viewer is flying through this underwater world. A fast-paced, first-person view shot with a vivid and lifelike underwater setting.",720 +74,"A dynamic and surreal scene from a conceptual digital art piece, showcasing an empty warehouse where flora suddenly bursts forth from the ground, transforming the space. The warehouse walls remain exposed brick, but green vines and flowers rapidly cover the floors and walls, creating a chaotic yet vibrant explosion of nature. The camera angle is from a low, sweeping perspective, capturing the full extent of the transformation. The background features a mix of old machinery and newer plant life, with sunlight filtering through gaps in the roof, casting a dappled light pattern on the scene. The overall style is hyper-realistic with a touch of magical realism, emphasizing the sudden and dramatic change.",1440 +75,"A close-up shot of a living flame wisp darting through a bustling fantasy market at night. The wisp, flickering with an ethereal glow, moves swiftly among the stalls and vendors. The market is filled with colorful lanterns, glowing signs, and various magical items. The background features a crowded scene with people in exotic attire, bustling about their business under the soft light of the full moon. The air is filled with the scent of spices and incense. The camera angle is slightly elevated, capturing the dynamic movement of the wisp as it weaves through the market, creating a sense of wonder and enchantment.",720 +76,"A handheld tracking shot following a red balloon floating above the ground in an abandoned street. The balloon drifts gracefully, its bright red color contrasting sharply against the decaying urban backdrop. The street is littered with debris and graffiti-covered walls, with broken windows and rusted cars scattered about. Shadows dance across the scene as sunlight filters through gaps in the buildings. The camera moves fluidly, capturing the balloon's gentle ascent and descent, emphasizing its playful motion. A close-up of the balloon transitions to a wider shot, showcasing the desolate environment.",1440 +77,"A first-person view (FPV) shot zooming through a narrow tunnel, transitioning into a vibrant underwater world. The tunnel walls are illuminated by colorful lights, creating a mesmerizing effect. Inside the tunnel, bubbles rise gently, and seaweed sways gracefully. The underwater space is filled with a variety of colorful fish swimming around, including neon blue tangs and vibrant orange clownfish. Coral reefs in shades of pink, purple, and green add depth and texture to the scene. The water is clear, allowing visibility of the diverse marine life. The camera angle is slightly tilted, capturing the excitement and adventure of the journey.",720 +78,"A wide symmetrical shot of a painting in a museum, with the camera gradually zooming in for a closer look. The painting depicts a serene landscape featuring a tranquil lake surrounded by lush greenery and towering trees. The composition is balanced, with soft, pastel colors dominating the scene. In the foreground, a bridge spans the lake, leading to a small island adorned with blooming flowers. The background showcases rolling hills and a distant mountain range, creating a harmonious and peaceful atmosphere. The texture of the canvas is visible, adding to the authenticity of the artwork. A close-up shot with a slight tilt to the right.",1440 +79,"An ultra-fast disorienting hyperlapse photograph capturing a car racing through a tunnel, transitioning into a chaotic labyrinth of rapidly growing vines. The car's headlights illuminate the tunnel walls, which are adorned with peeling paint and graffiti. As the tunnel ends, the camera speeds into a dense forest of vines, their leaves and tendrils swaying wildly. The vines grow at an alarming rate, forming a maze-like structure that twists and turns. The car appears to be navigating this treacherous path, with the driver focused intently on the winding route. The background is filled with blurred, green foliage and twisted branches, creating a sense of urgency and chaos. The photo has a gritty, hyperrealistic texture, emphasizing the dynamic movement and intense visual effects. A wide-angle shot from a low angle, capturing the car's rapid descent into the vine-laden labyrinth.",720 +80,"A high-speed FPV (First Person View) shot inside the locomotive cab of a vintage European train, moving at hyper-speed through the bustling streets of an old European city. The cab is filled with intricate mechanical details, including dials, switches, and controls, with steam and smoke swirling around. The train's windows show blurred, colorful buildings and narrow cobblestone streets passing by quickly. The camera angle provides a dynamic, immersive view, capturing the intense motion and the rich architectural details of the cityscape. The overall style is detailed and realistic, emphasizing the speed and energy of the journey.",720 +81,"A hyper-realistic macro photograph capturing the intricate details of a dandelion, zooming in at an incredible speed to reveal a dream-like, abstract world. The petals are softly blurred, creating a mesmerizing effect that blends reality with fantasy. Each fiber and grain of pollen is vividly detailed, giving the image a surreal texture. The background fades into a gradient of soft pastel colors, enhancing the ethereal quality of the scene. The dandelion appears almost otherworldly, with its delicate structure and vibrant colors standing out against the blurred, abstract surroundings. A close-up shot with a dynamic zoom-in motion.",240 +82,"A hyper-realistic digital art piece capturing an internal window view inside a high-speed train moving through an old European city. The train interior is sleek and modern, with passengers seated in comfortable leather seats, some reading books or using laptops. The window frame is clear, showing the bustling streets and historic buildings of the city rushing past at incredible speed. The cityscape features ancient cobblestone streets, ornate facades, and spires of medieval churches, with people walking hurriedly and horse-drawn carriages passing by. The train's motion is vividly depicted, creating a sense of dynamic movement and adventure. The background is richly detailed, with the cityscape blurred and streaked, emphasizing the train's speed. The overall atmosphere is both futuristic and nostalgic, blending modern technology with historical charm. A wide-angle shot from inside the train, capturing the motion and the cityscape outside.",720 +83,"A handheld camera moving quickly captures the flickering light from a flashlight shining on a dilapidated white wall in an old alley at night. The wall is covered with a large, faded black graffiti that reads 'Runway'. The flashlight casts dynamic shadows, highlighting the rough texture of the wall and the worn-out letters. The background shows the dim, narrow alley with occasional glimpses of neighboring buildings and dark, shadowy figures in the distance. The photo has a gritty, documentary-style texture, emphasizing the movement and the eerie atmosphere of the scene. A low-angle, handheld shot capturing the dynamic interaction between the flashlight and the graffiti.",720 +84,"A dynamic super fast zoom-out shot starting from the peak of a majestic frozen mountain where a lone hiker is making their final push to reach the summit. The hiker, bundled in thick winter gear, trudges through the snow-covered terrain with determination etched on their face. Their breath forms visible clouds in the frigid air. As the camera pulls back, the vast, icy landscape unfolds, revealing rugged peaks and valleys, with distant snow-capped mountains stretching into the horizon. The sky is a stark, deep blue, filled with wisps of cloud. The overall scene captures the raw beauty and harshness of nature. A sweeping aerial view transitioning to a wide-angle shot.",720 +85,"A surreal first-person point-of-view shot rapidly flies through open doors, capturing the moment when the viewer suddenly finds themselves in the midst of a living room transformed into a dreamlike scene. At the center of this room stands a breathtaking waterfall, water cascading down from the ceiling and walls, creating a mesmerizing mist that fills the space. The living room is adorned with floating plants and ethereal lights, casting a soft, otherworldly glow. The camera angle shifts, providing a dynamic and immersive experience as it adjusts to the surreal environment.",1440 +86,"A dynamic first-person point-of-view shot rapidly zooms towards a house's front door at 10x speed, capturing the excitement and urgency of the scene. The camera angle is from the perspective of someone running towards the door, with the door and its surroundings quickly coming into focus. The front door is old and wooden, with a brass knocker and a small peephole. The background shows a garden with blooming flowers and green bushes, and a path leading up to the door. The scene has a gritty, realistic texture, emphasizing the speed and intensity of the movement. The camera angle is slightly tilted, giving a sense of depth and immediacy.",240 +87,"A pencil sketch in a classic architectural drafting style, depicting a detailed floor plan of a grand mansion. The drawing includes intricate lines and measurements, with a focus on the mansion's layout, including hallways, rooms, and windows. The building features ornate columns, arched doorways, and a large central staircase. The background is a blurred view of a sunny day, with hints of greenery and trees outside the mansion's windows. The pencil strokes are soft and precise, creating a realistic and detailed representation. A close-up shot from a slightly elevated angle.",720 +88,"An extreme close-up shot of an ant emerging from its nest, capturing the moment of its journey with vivid detail. The ant is small but resilient, with its body glistening slightly in the sunlight. As the camera pulls back, we see a picturesque neighborhood beyond the hill, with rows of houses and trees in the background. The hill itself is covered in lush green grass and wildflowers, adding to the natural setting. The scene has a warm, natural lighting effect, highlighting the tiny yet significant action of the ant. A gradual pull-back shot, emphasizing both the ant's movement and the broader landscape.",1440 +89,"A dramatic and dynamic scene in the style of a disaster movie, depicting a powerful tsunami rushing through a narrow alley in Bulgaria. The water is turbulent and chaotic, with waves crashing violently against the walls and buildings on either side. The alley is lined with old, weathered houses, their facades partially submerged and splintered. The camera angle is low, capturing the full force of the tsunami as it surges forward, creating a sense of urgency and danger. People can be seen running frantically, adding to the chaos. The background features a distant horizon, hinting at the larger scale of the tsunami. A dynamic, sweeping shot from a low-angle perspective, emphasizing the movement and intensity of the event.",720 +90,"An FPV drone shot capturing a majestic castle perched on a rocky cliff. The camera moves swiftly, revealing intricate stone walls, towering towers, and detailed gargoyles. The castle is partially shrouded in mist, adding a sense of mystery and grandeur. The cliff backdrop features jagged rocks and lush greenery, with patches of sunlight breaking through the clouds. The overall scene has a vivid and dynamic feel, with the camera angle emphasizing the height and imposing presence of the castle.",720 +91,"A cinematic wide-angle portrait of a man with his face illuminated by the warm glow of a TV screen. The man, with a rugged yet determined expression, leans forward slightly against a vintage wooden armchair. His dark hair is slightly disheveled, and he wears a worn leather jacket over a plain white shirt. The background features a cluttered living room with old books, newspapers, and a few framed photos scattered around. The TV shows static, with a faint image of a news broadcast flickering in the corner. The overall scene has a nostalgic and gritty feel, with a rich color palette and a soft, grainy texture. A wide-angle shot capturing the man's intense gaze and the warm ambiance of the room.",1440 +92,"A close-up portrait of a woman, her face illuminated by the side lighting, capturing her delicate features and expressive eyes. As the camera slowly pulls back, it reveals her sitting gracefully in a cozy armchair, her hair falling softly over her shoulders. She wears a elegant evening gown in a deep shade of blue, adorned with intricate lace and sparkling jewels. The background features a warm, candlelit room with soft shadows and a faint hint of a fireplace. The photo has a romantic and timeless quality, reminiscent of a classic Hollywood portrait. A medium shot transitioning to a wider view.",240 +93,"A zoom-in shot focusing on the face of a young woman sitting on a bench in the middle of an empty school gym. The woman has long wavy brown hair cascading down her shoulders and soft, warm hazel eyes. She wears a simple white t-shirt and blue jeans, her hands resting gently on her knees. Her expression is serene, with a slight smile playing on her lips. The gymnasium is mostly empty, with only a few scattered bleachers and a basketball hoop in the background. The lighting is soft and natural, creating gentle shadows under her eyes and nose. The overall atmosphere is peaceful and contemplative.",720 +94,"A close-up of an older man standing in a dimly lit warehouse, his weathered face etched with lines of experience. His eyes, though weary, hold a steady gaze, looking directly at the viewer. He wears a worn leather jacket over a faded t-shirt and blue jeans, his hands resting casually in his pockets. The background shows stacks of crates and old machinery, with light filtering in through dusty windows, casting long shadows. The camera gradually zooms out, revealing the vast, industrial space around him. The overall atmosphere is one of quiet resilience and endurance. A medium shot transitioning to a wider view.",1440 +95,"A classic black-and-white photograph style image of an older man playing the piano. The man, with a weathered face and kind eyes, sits at an antique piano with his fingers gracefully moving over the keys. The lighting comes from the side, casting dramatic shadows on his face and emphasizing the texture of his hands. His posture is upright and focused, conveying a sense of deep concentration and passion for music. The background is blurred, revealing only hints of a cozy room with wooden floors and old furniture. A close-up shot from a slightly elevated angle, capturing both the man and the piano in detail.",1440 +96,"A macro shot focusing on the face of a young woman with freckles, her expression intense as she looks intently for something. Her freckles are scattered across her cheeks and nose, adding a playful charm to her face. Her eyes are wide and slightly squinted, peering closely at the object of her search. Her hair is loose, framing her face gently, with strands falling over her forehead. The background is blurred, but you can make out the faint outline of a table or desk where she is searching. The texture of her skin is smooth and细腻,带有淡淡的红润。A close-up shot from a very close angle, capturing the natural and focused expression of the young woman.",720 +97,"An astronaut in a sleek, white spacesuit walks between two ancient stone buildings, their surfaces adorned with intricate carvings and moss. The astronaut's helmet reflects the dim, otherworldly light casting shadows across the worn stones. The buildings loom large, creating a narrow passage that seems to stretch into the distance. The background shows a barren landscape with distant, rocky hills and a pale, orange sky. The astronaut moves with a determined gait, one hand on the building's surface, the other holding a small device. The photo has a realistic, high-resolution texture, capturing the astronaut's focused expression and the textures of the ancient architecture. A medium shot from a slightly elevated angle, emphasizing the contrast between the modern astronaut and the ancient structures.",720 +98,"A dramatic moment captured in a realistic photographic style, depicting a middle-aged man transitioning from sadness to happiness. Initially, he appears solemn and bald, with a slightly downcast expression. Suddenly, a curly wig and sunglasses fall onto his head from above, transforming his appearance instantly. His face lights up with joy and surprise, his eyes widening and a broad smile forming. The background is a cluttered office space with scattered papers and a desk lamp casting shadows, creating a contrast between the man’s emotional shift and the mundane setting. The photo is taken from a low-angle perspective, emphasizing the dramatic change.",240 +99,"An ultra-wide shot of a colossal stone hand emerging from a chaotic pile of rocks at the base of a towering mountain. The hand is massive, with rough, weathered fingers and a palm as wide as a small room. It seems to be reaching out, as if grasping something unseen. The surrounding rocks are jagged and varied, creating a rugged landscape. In the distance, the mountain peaks rise sharply, shrouded in mist, adding a sense of mystery and grandeur. The texture of the stones is detailed, with subtle shadows highlighting their uneven surfaces. A dramatic and eerie atmosphere pervades the scene, with a mix of sunlight filtering through the clouds, casting long shadows.",240 +100,"An aerial view shot of a cloaked figure soaring through the sky amidst towering skyscrapers. The figure is partially concealed by the cloak, with only their outstretched arms and determined expression visible. The cityscape below is a blur of glass and steel, with lights twinkling in the distance. The background showcases a mix of bright city lights and a hint of a cloudy night sky. The figure seems to be mid-flight, with dynamic motion and a sense of freedom. A high-angle shot capturing the figure in motion.",720 +101,"An oil painting-style natural forest scene with a rich blend of autumn colors, featuring vibrant maple trees casting vivid hues across the landscape. The painting employs a cinematic parallax technique, creating a deep and immersive visual depth. In the foreground, the leaves of the maple trees are vividly colored, ranging from deep red to bright orange, while in the midground, the trees stand tall and majestic, their branches reaching towards the sky. The background reveals a misty distance with softer shades of green and brown, enhancing the sense of depth. The overall atmosphere is warm and inviting, with a soft golden light filtering through the canopy. The composition is a layered, panoramic view, capturing the essence of a serene autumn forest. A wide-angle shot with a slight tilt to the right.",1440 +102,"A nighttime scene from a vintage film-style photograph, depicting a giant, otherworldly creature slowly walking down a desolate, rundown city street. Only one dim streetlamp casts flickering shadows, illuminating the creature's massive, imposing form. Its skin is rough and covered in peculiar growths, with glowing eyes that reflect the dim light. The creature's steps echo in the empty alleyways, creating a sense of eerie quiet. The background features crumbling buildings, broken windows, and trash-strewn sidewalks. The photo has a grainy texture and a muted color palette, capturing the haunting atmosphere of the scene. A medium shot with a slight tilt to the camera, emphasizing the creature's movement and presence.",720 +103,"A full-body shot of a man crafted entirely from rocks, walking through a dense forest. His rocky form is rugged and textured, with various shades of gray and brown. He strides confidently, his steps creating small ripples in the forest floor. The forest behind him is vibrant with greenery, sunlight filtering through the canopy, casting dappled shadows. The background features tall trees with intricate bark patterns and wildflowers peeking through the underbrush. The scene has a mystical and ancient feel, reminiscent of a fantasy landscape.",1440 +104,"A slow cinematic push-in on an ostrich standing in a 1980s kitchen, the camera gradually zooming in to reveal the bird's curious expression. The kitchen is adorned with vintage appliances and Formica countertops, with a muted color palette of pastel greens and yellows. The ostrich, with its distinctive long neck and feathered plumage, stands confidently, one foot slightly raised. Its large brown eyes peer curiously at the viewer, as if pondering the strange surroundings. The background features blurred details of old newspapers scattered on the floor and a faded floral wallpaper. The lighting is warm and soft, casting gentle shadows. A close-up shot from a slightly lower angle.",1440 +105,"A vibrant and whimsical digital illustration in a cartoon style, depicting a giant humanoid figure composed of fluffy blue cotton candy. The humanoid is stomping its feet on the ground, causing a playful disturbance, while roaring towards the clear blue sky. The background features a bright, cloudless sky with soft, pastel tones, enhancing the dreamlike quality of the scene. The humanoid has expressive eyes and a mischievous smile, with arms and legs made of swirling cotton candy. A dynamic, full-body shot from a slightly elevated angle, capturing the energetic movement and playful nature of the creature.",1440 +106,"A dynamic night-time scene in a dark forest, captured in a high-speed aerial shot. Neon-lit flora glows brightly, casting an otherworldly glow through the dense canopy. The camera zooms through the forest, capturing the intricate details of glowing flowers and bioluminescent leaves. The forest floor is shrouded in shadows, with only patches of neon light illuminating the path ahead. The air is filled with the soft rustling of leaves and the distant hum of nocturnal insects. A vivid, surreal landscape with a focus on movement and vibrant colors.",720 +107,"A dynamic urban alleyway scene capturing the chaos of a cyclone of broken glass swirling through the narrow space. The glass pieces twirl and scatter in all directions, creating a mesmerizing and dangerous vortex. The alley is dimly lit, with flickering shadows dancing across the walls. The camera angle is low, emphasizing the height of the glass cyclone and the towering buildings that frame the scene. The background shows graffiti-covered brick walls and a few discarded trash cans, adding to the gritty urban atmosphere. The glass shatters and glints in the dim light, reflecting fragments of the surrounding environment. A close-up shot with fast-paced motion blur, capturing the frenzied movement of the glass storm.",1440 +108,"A dramatic photo in a gritty, realistic style of a middle-aged man standing in front of a partially collapsed, burning building. He gives a thumbs up sign, his face showing determination and resolve despite the danger. His weathered face and rugged, fire-resistant clothing suggest he is a firefighter or emergency responder. The background is a chaotic mix of flames, smoke, and debris, with emergency vehicles in the distance. The scene is captured from a low-angle perspective, emphasizing the man's bravery and the intensity of the situation.",240 +109,"A highly detailed close-up photograph in a scientific documentary style, focusing on a single bacterium under a microscope. The bacterium is spherical with a smooth, translucent outer membrane, revealing internal structures such as ribosomes and a nucleus. It is floating in a clear liquid medium, with some cellular components visible inside. The background is a blurred microscopic field with faint grids and scales. The photo has a crisp, high-resolution texture, emphasizing the intricate details of the microorganism. A macro shot from a slight angle, capturing the subject's natural movement and texture.",720 +110,"A Japanese animated film-style scene of a young woman standing on a ship, looking back at the camera with a gentle smile. She has long black hair tied in a loose ponytail and wears a traditional Japanese kimono with intricate patterns and vibrant colors. Her expression is serene and slightly contemplative. The ship is mid-ocean, with waves gently lapping against the sides, and the background shows a vast blue sea with distant clouds and a setting sun. The scene has a soft, dreamy quality, capturing the tranquility of the moment. A medium shot from a slightly elevated angle, emphasizing her graceful posture and the serene ocean backdrop.",1440 +111,"A close-up shot of a young woman driving a car, lost in thought as she gazes ahead. Raindrops blur the view of a green forest through the car window. She wears a sleek raincoat and sunglasses, her expression contemplative. Her hands gently grip the steering wheel, and her fingers tap rhythmically against it. The interior of the car is dimly lit, with water droplets clinging to the windshield. The blurred green forest and rain create a sense of mystery and introspection. The photo has a cinematic quality, capturing the moment just before a decision is made. A close-up shot from inside the car, focusing on the driver.",1440 +112,"An aerial shot of a fast-moving drone flying through a dense green jungle, capturing the vibrant foliage and lush canopy below. The drone glides smoothly, showcasing the intricate network of vines and towering trees. The background features a mix of bright green leaves and dappled sunlight filtering through the branches. The drone's path is dynamic, suggesting a sense of speed and movement. A high-angle aerial view with a clear focus on the drone's flight path.",240 +113,"A hyperlapse video shot through a long, narrow corridor with flashing lights, capturing the movement of a silver fabric billowing and flowing gracefully through the space. The fabric moves quickly, creating a dynamic and fluid effect against the backdrop of flickering lights. The camera follows the fabric, capturing its intricate folds and movements in vivid detail. The corridor is dimly lit, with the flashing lights creating a surreal and dramatic atmosphere. The fabric appears almost ethereal, reflecting the lights and casting shadows as it moves. A series of wide-angle shots with a slight tilt to the frame, emphasizing the continuous motion and the textures of the fabric.",240 +114,"An aerial shot of the ocean, capturing a mesmerizing maelstrom forming in the water, swirling violently before revealing the fiery depths below. The water churns with intense energy, creating a whirlpool effect that stretches from the surface to the murky depths. The swirling currents illuminate the underwater landscape, showcasing a vivid array of colors and textures, as if the ocean floor is alight with hidden fires. The camera angle provides a dramatic overhead view, emphasizing the dynamic motion and the vastness of the ocean.",240 +115,"A dynamic push shot through an ocean research outpost, capturing the bustling activity within. The camera moves through the entrance, revealing scientists in lab coats working at various stations, their faces focused and determined. The background shows rows of advanced scientific equipment, tanks filled with marine life, and large screens displaying complex data. The walls are adorned with charts and posters, adding to the academic atmosphere. The lighting shifts between the bright, fluorescent lights of the labs and the natural light streaming in from large windows overlooking the ocean. The outpost has a modern, utilitarian design, with sleek metal and glass structures. The camera angle provides a sense of movement and urgency, emphasizing the importance of the ongoing research.",1440 +116,"A vibrant concert stage scene in the style of a music video, featuring a woman in the spotlight, singing passionately. She stands confidently on the stage, microphone in hand, with a captivating expression on her face. The bright light behind her creates a dramatic silhouette, casting a warm glow over her. She wears a stylish, form-fitting black dress with intricate silver embroidery, emphasizing her graceful movements. The background features a blurred stage with colorful lights and banners advertising the event. A dynamic medium shot capturing the singer from a slightly elevated angle, highlighting her performance and the dramatic lighting effects.",1440 +117,"An over-the-shoulder shot of a determined woman in a white sports bra and black running shorts sprinting down a dusty trail, her gaze fixed on a rocket launching into the sky in the distance. Her hair flows behind her, and she pumps her arms for extra speed and momentum. The background shows a vast landscape with rolling hills and sparse trees, and the rocket trails a bright white plume against the clear blue sky. The camera angle captures her focused determination and the expansive scenery, emphasizing both her movement and the grandeur of the launch.",1440 +118,"A vibrant and dynamic illustration in the style of a nature documentary, featuring a dragon-toucan walking gracefully through the vast grasslands of the Serengeti. The dragon-toucan has iridescent green and blue feathers, with a long, curved beak and large, expressive eyes. It strides confidently across the savannah, its wings slightly spread for balance. The background showcases a rich tapestry of African wildlife, with zebras, gazelles, and elephants in the distance. The sun is setting, casting a warm golden glow over the landscape. The camera angle is from a low, ground-level perspective, capturing the dragon-toucan in motion as it moves through the grass.",1440 +119,"A dramatic and surreal photograph in a realistic style, capturing an abandoned warehouse where vibrant flowers are blooming from the cracked concrete walls. The flowers are diverse, ranging from wild daisies to delicate roses, their colors vivid and varied. The space is dimly lit, with shadows cast by the uneven concrete surfaces. The camera angle is low, emphasizing the growth and生命力, with a sense of nature reclaiming the urban environment. The background shows the remnants of old machinery and graffiti, adding to the desolate yet hopeful atmosphere. A close-up shot from a slightly downward angle, highlighting the contrast between the harsh industrial setting and the blooming flowers.",1440 +120,"A side profile shot of a woman with a dramatic backdrop of fireworks exploding in the distance. The woman has long flowing hair cascading down her back, and she gazes intently into the distance, her expression filled with a mix of wonder and excitement. She wears a elegant red dress with intricate lace detailing and a fitted bodice. The fireworks create a vibrant display of colors and light, casting a magical glow on her face. The background is blurred, capturing the burst of colors and smoke from the explosions. The photo has a dynamic and celebratory atmosphere. A medium shot with a slight tilt to the camera angle.",1440 +121,"A vibrant anime illustration in a dynamic motion style of a pink pig running rapidly towards the camera in a narrow alley in Tokyo. The pig has large, round eyes and a playful expression, with its ears perked up and body slightly hunched forward. It is wearing a small, pink bow tie, adding a cute touch to its appearance. The background showcases the bustling Tokyo alley, with colorful signs and neon lights reflecting off the wet pavement. The scene is captured from a low-angle perspective, emphasizing the pig's energetic movement.",720 +122,"A surreal digital art piece depicting a majestic bird gently landing on the surface of a tranquil lake, transforming into a sleek fish mid-mutation. The bird has vibrant plumage, with long wings spread wide as it touches the water. As it transforms, its body elongates and turns silver, fins forming from its wings and legs. The fish retains some bird-like features, such as large eyes and a curved beak. The background showcases a serene lakeside, with soft ripples on the water and gentle sunlight casting a warm glow. The scene has a dreamy, ethereal quality, with a slight blur effect on the surroundings. A medium shot from a slightly elevated angle, capturing the transformation in motion.",240 +123,"A dynamic tennis photograph in a realistic sports style, capturing a powerful serve from a determined woman. She stands tall and focused, her right arm extended forward with a tennis racket, about to hit the ball with fierce determination. Her left hand steadies the racket, and her legs are slightly bent, ready for the next move. She wears a white tennis outfit with a red trim, and her hair flows behind her as she pivots to make contact. The background shows a tennis court with blurred spectators in the stands, and the net is clearly visible. The sun casts a bright spotlight on her, highlighting her athletic form. A mid-shot from a slightly elevated angle, emphasizing her powerful motion.",240 +124,"A high-resolution photograph in a realistic style, capturing a green lizard in the act of catching a bug. The lizard has a vibrant green body with small black spots, and its sharp, reptilian eyes are focused intently on its prey. It is perched on a leaf, with its tail coiled around the stem for balance. The bug, likely a cricket or similar small insect, is just within reach, and the lizard's tongue is extended, poised to snatch it. The background is a lush, tropical forest with dense foliage and sunlight filtering through the leaves, creating dappled shadows. The photo has a crisp, clear texture, emphasizing the natural movement and detail. A medium shot from a slightly elevated angle, highlighting the lizard's dynamic action.",240 +125,"A dramatic and surreal scene in the style of a fantasy comic, a lightning bolt strikes a turtle in the middle of a tranquil lake, instantly transforming it into a fierce alligator. The alligator, now with the distinctive features of an alligator, including a longer snout and sharper teeth, stands in the water, its body contorted from the shock. The lake background shows ripples and splashes, with the water reflecting the stormy sky. The alligator's eyes are wide with surprise, and its skin is covered in tiny scales. The lighting is intense, with flashes of lightning illuminating the scene. A dynamic close-up from a slightly elevated angle, capturing the transformation and the alligator's immediate reaction.",240 +126,"A cyberpunk-style digital illustration of a metal skull growing muscle tendons and flesh, set in a dystopian urban environment. The skull's bones are partially covered by newly formed muscle tissue and skin, giving it a grotesque yet almost lifelike appearance. The background features a blurred cityscape with neon lights, rusted buildings, and graffiti-covered walls. The scene has a gritty, high-contrast texture. The perspective is from a low angle, capturing the skull in a close-up shot.",240 +127,"A dynamic action shot in the style of a high-energy sports illustration, depicting a fencer in mid-sprint, blade raised, and feet barely touching the ground. The fencer, a young man with taut muscles and focused expression, swings his sword with precision and speed. His hair flows behind him, and his eyes lock onto his opponent. The background is a blurred arena, with spectators in the distance, creating a sense of urgency and excitement. The fencer's clothing is a sleek black fencing outfit, and his face is partially obscured by his mask. A close-up shot from a low angle, emphasizing the intensity of the moment.",1440 +128,"A whimsical illustration in a soft watercolor style of a curious cat peeking out from a cozy, woven basket hidden behind a pile of fluffy cushions. The cat has large, expressive green eyes and a fluffy white fur coat with a black tipped tail. It is perched on one paw, ears pricked up, and its whiskers twitch as it gazes intently at something just beyond the viewer's line of sight. The background features a warm, inviting living room with hints of sunlight filtering through a window, casting a gentle glow on the scene. The basket is intricately detailed with patterns and textures. A close-up shot from a slightly lower angle, capturing the cat's entire body and the subtle play of light on its fur.",720 +129,"A vintage drag racing scene in a classic film noir style, featuring a group of six muscle cars lined up at the starting line of a straight asphalt strip. Each car, adorned with chrome accents and distinctive paint jobs, revs its engine loudly, smoke billowing from their exhausts. The cars are positioned side by side, ready to race, with the front wheels slightly lifted in anticipation. The background is a blurred, sunlit highway with faded road markings and distant buildings. A wide-angle shot captures the intense moment just before the race begins, emphasizing the dynamic movement and the roaring engines.",1440 +130,"A detailed realistic photograph captures a German Shepherd gently placing a butterfly that landed on its nose onto a colorful flower. The dog, with its alert and curious expression, appears tender and gentle. Its fur is short and sleek, with a brown and white coat, and it stands in a slightly crouched position, focusing intently on the flower. The background features a lush garden with green foliage and other flowers, creating a harmonious and natural setting. The photo has a clear and crisp focus, highlighting the interaction between the dog and the butterfly. A close-up shot from a low angle.",1440 +131,"A hyperrealistic portrait of a monstrous creature with its mouth closing, rendered in a detailed photorealistic style. The monster has a large, elongated snout with sharp fangs and a rough, textured skin that resembles old leather. Its eyes are wide and intense, with pupils narrowing as it closes its mouth. The creature's jaw muscles flex as it moves, adding to its dynamic expression. The background is a blurred forest scene with dense foliage and sunlight filtering through the leaves, creating a mysterious and eerie atmosphere. A medium shot with a slightly angled perspective.",1440 +132,"A high-resolution photograph capturing a pole vaulter in mid-flight, showcasing perfect form and precision. The athlete, a tall and muscular individual with a focused expression, leaps gracefully over the bar. The pole is bent sharply as it transfers energy, propelling the vaulter upwards. The background is blurred, revealing only a hint of the indoor track with a vaulting pit below. The scene has a dynamic, athletic feel, emphasizing the fluidity and power of the jump. The camera angle is from a slight angle, highlighting the vertical trajectory of the vaulter.",240 +133,"A vibrant and dynamic illustration in the style of a children's fantasy book, depicting a brown bear sitting in a vintage car, looking out the window with a curious expression. The bear has fluffy fur, big round eyes, and a small nose. It wears a red scarf and gloves, and its paws rest on the steering wheel. The car is an old-fashioned model with a wooden exterior and shiny chrome accents. The background features a forest landscape with tall trees, wildflowers, and a winding road leading to the horizon. The sky is clear with fluffy clouds. The scene captures the bear's playful and adventurous spirit, with a medium shot from a slightly behind-the-car angle, highlighting the bear's interaction with the vehicle.",1440 +134,"A whimsical digital art piece in a cartoon style depicting a cactus with googly eyes dancing gracefully in the breeze. The cactus is adorned with vibrant green spines and large, round, black googly eyes that seem to sparkle. It stands upright with its arms outstretched, swaying gently as if it were a lively dancer. The background features a soft, pastel landscape with patches of wildflowers and a gentle, flowing breeze. The scene is filled with natural movement, capturing the cactus in mid-dance. The camera angle is from a slight overhead view, emphasizing the dynamic pose and the playful spirit of the cactus.",720 +135,"A dramatic and dynamic moment captured in a realistic photographic style, featuring a golden retriever dog leaping into a pool to rescue a child. The dog is mid-jump, its legs stretched forward and its fur glistening in the sunlight. It appears determined and heroic. The child, partially submerged in the water, looks up at the dog with gratitude and relief. The pool is clear and blue, with ripples creating a splash effect. The background shows a sunny backyard with a wooden deck and some greenery. A high-angle shot captures the action from above, emphasizing the heroic effort of the dog.",720 +136,"A dramatic digital painting in the style of an epic fantasy, depicting humans walking into a dragon's open jaws as they descend into the underworld. The dragon has a massive, scaled body with a deep emerald green hue, and its teeth are sharp and menacing. The humans are small figures, one male and one female, dressed in ancient robes, their expressions filled with fear and determination. They hold torches, casting flickering shadows on the dragon's inner walls. The background features a dark, cavernous underworld with glowing red eyes of fireflies and jagged rocks. The scene is rendered in a high-detailed, cinematic style with a sense of depth and movement. The camera angle is from below, looking up at the dragon's open jaws, capturing the dramatic descent into the underworld.",720 +137,"A dramatic action scene in the style of a Hollywood crime thriller, a police helicopter hovers above a high-speed chase through a city street. The helicopter's rotors spin rapidly, creating a whirlwind effect. The suspect, a male in a dark hoodie and jeans, speeds away in a black sedan, tires screeching. Officers on the ground, armed and alert, follow closely behind, their faces tense and focused. The background features a bustling cityscape with tall buildings and neon signs, the streets filled with cars and pedestrians. The helicopter's camera angle provides a bird's-eye view, capturing the intense moment of pursuit. The scene is rendered in high-definition, with sharp contrasts and dynamic lighting. A medium shot from a low-angle overhead perspective.",240 +138,"An American-style promotional poster featuring a woman in a green jacket and brown boots practicing her archery skills at an outdoor range. She stands with a focused expression, holding a recurve bow and a quiver of arrows on her back. Her hair flows naturally behind her as she aims at the target. The background shows a blurred outdoor setting with a clear blue sky, patches of grass, and some trees in the distance. A slight wind blows, adding a dynamic element to the scene. The photo has a high-resolution, realistic texture. A medium shot from a slightly elevated angle capturing her determined pose.",1440 +139,"A dynamic action shot in a rugged mountainous landscape, a woman in a vibrant red parka leaps over a brown bear standing on its hind legs. The woman's long, wavy hair flows behind her as she mid-jump, her face filled with determination and excitement. The bear has a fierce expression, with its mouth open in a growl. The background features dense forest with tall trees and patches of sunlight filtering through the canopy. The photo has a dramatic, high contrast style, capturing the raw energy and tension of the moment. A high-angle shot emphasizing the woman's leap.",240 +140,"A dynamic action shot of a futsal squad displaying their skills on an indoor court. The team consists of five players, each wearing vibrant uniforms with their team logos prominently displayed. The players are in various positions: one player is mid-kick, another is about to receive the ball, a third is dribbling skillfully, and two others are preparing for a quick pass. The court is clearly marked with lines, and the ball bounces smoothly across the surface. The lighting highlights the intense focus and determination on their faces. The background shows a blurred indoor arena with spectators in the stands, creating a lively atmosphere. The photo captures the energy and teamwork of the squad, with a slightly elevated camera angle providing a clear view of the action.",720 +141,"A vibrant and dynamic illustration in the style of a children's storybook, depicting a kangaroo leaping through a bustling cityscape. The kangaroo is energetic and agile, with a playful expression and soft, furry brown fur. It is mid-jump, its hind legs stretched out and its front paws slightly off the ground, tail swishing behind it. The city is alive with tall skyscrapers, colorful advertisements, and busy streets filled with people and vehicles. The background shows a mix of bright neon lights and the occasional green tree, creating a lively and vibrant urban environment. The kangaroo's movements are fluid and natural, capturing the essence of its lively nature. A dynamic side-angle shot, emphasizing the kangaroo's motion.",720 +142,"A lively and dynamic digital illustration in a cartoon style of a squirrel leaping gracefully from one tree branch to another. The squirrel has fluffy brown fur, large round eyes, and a bushy tail that swishes as it moves. It appears alert and agile, mid-jump with its front paws extended towards the next branch. The background showcases a dense forest with tall trees, green leaves, and dappled sunlight filtering through. A bird is perched on a nearby branch, adding to the natural scene. The squirrel’s movements are fluid and natural, capturing the essence of its lively nature. A medium shot with a slight upward angle.",240 +143,"A dynamic illustration in a manga style depicting two cats and dogs engaged in a fierce sword fight. One cat, with sleek black fur and green eyes, holds a silver sword aloft, while the other, a fluffy white dog with brown eyes, lunges forward with a wooden sword. Both animals display intense focus and determination, their bodies tensed and ready for action. The background features a blurred garden setting with hints of green foliage and flowers. The scene is captured from a low-angle perspective, emphasizing the movement and energy of the battle.",720 +144,"A dynamic and lively scene in the style of a watercolor painting, where a fish leaps out of a glass fish tank and swims gracefully around a person's head mid-air. The fish has vibrant scales and gills flapping, creating ripples in the imaginary water droplets around it. The person appears surprised and amused, with an open-mouthed expression and slightly tilted head, looking up at the airborne fish. The background features a blurred aquarium with hints of colorful aquatic plants and a few other fish swimming calmly below. The lighting is soft and diffused, adding a dreamy quality to the scene. The camera angle is from a low, upward perspective, capturing the moment of the fish's leap.",720 +145,"A realistic photograph in a gritty urban setting, capturing a tow truck expertly pulling a stranded car onto its platform. The tow truck driver, wearing a rugged work uniform and a determined expression, operates the crane with precision. The car, with its hood slightly open, appears to have mechanical issues. The background shows a busy city street with other vehicles and pedestrians in the distance, giving the scene a dynamic and bustling atmosphere. The tow truck is positioned at a slight angle, highlighting the tension and effort required to lift the car. The photo has a high-resolution, documentary-style texture. A medium shot with the tow truck in the foreground and the cityscape in the background.",720 +146,"A vibrant and dynamic cooking scene in the style of a lively food documentary, featuring a skilled cook expertly flipping golden pancakes on a griddle. The cook, a middle-aged man with a warm smile and neat chef's hat, moves confidently with each flip, the pancakes sizzling and releasing a delightful aroma. His apron is slightly stained with flour, and he holds a spatula poised for another flip. The background shows a bustling kitchen with countertops filled with ingredients and appliances, and a blurred view of other chefs working behind him. The lighting highlights the cook's movements and the golden-brown pancakes, creating a warm and inviting atmosphere. A dynamic medium shot capturing the cook from a slightly elevated angle, emphasizing his fluid and energetic movements.",240 +147,"A realistic photograph capturing a dynamic scene where a sleek black cat with piercing green eyes is energetically chasing a tiny brown mouse across a lush green field. The mouse scampers towards an underground burrow, its tail flicking behind it as it frantically tries to escape. The cat's expression shifts from focused determination to disappointment as it realizes the mouse has disappeared into the hole. The field is dotted with wildflowers and tall grasses swaying gently in the breeze. The background is blurred, highlighting the tension and movement of the moment. A medium shot from a slightly elevated angle, emphasizing the cat's hopeful pursuit and the mouse's desperate dash.",240 +148,"A heartwarming family moment captured in a gentle, soft focus photograph. A parent, likely a mother, stands behind a young child, both laughing and enjoying the simple joy of swinging. The mother wears a warm, casual outfit suitable for a sunny day at the park, her expression full of love and joy. The child, with bright, curious eyes, leans back in the swing, arms outstretched. The background features a clear blue sky with fluffy clouds, and a few trees providing a natural frame. The swing set is old but sturdy, adding to the nostalgic feel. The camera angle is slightly elevated, capturing the interaction between the two in a medium shot, emphasizing their shared happiness and bond.",240 +149,"A dramatic action scene in the style of a classic adventure film, featuring a man standing confidently on a small fishing boat, battling a massive fish that thrashes wildly in the water. The man, with rugged facial features and determined expression, grips a fishing rod tightly, his muscles strained. The fish, with a shimmering silver body and fierce eyes, leaps out of the water, creating a splash. The boat rocks violently, adding tension to the scene. The background shows turbulent waters and a cloudy sky, with distant waves breaking against the shore. The photo has a gritty, realistic texture, capturing the raw power and struggle between man and nature. A dynamic medium shot from a slightly elevated angle, emphasizing the intensity of the moment.",720 +150,"A detailed and vibrant illustration in the style of a nature documentary, depicting a dragonfly gracefully flying over a delicate pink flower, with its wings glistening in the sunlight. Beside it, a hummingbird perches on another nearby flower, its feathers shimmering in various hues of green and purple. The dragonfly has large, transparent wings and a slender body, while the hummingbird is small and agile, with a long, thin beak. The background features a lush garden with soft green leaves and colorful wildflowers, creating a serene and harmonious environment. The camera angle captures the dragonfly from below, while the hummingbird is shown from a side view, emphasizing their natural movements and interactions.",240 +151,"A vibrant and dynamic street art illustration depicting a chimpanzee performing a backflip on a skateboard on a bustling city sidewalk. The chimp is agile and energetic, mid-air with its legs extended and arms outstretched, showcasing its acrobatic skills. It has a playful expression, with mischievous eyes and a slight grin. The skateboard is colorful and adorned with stickers, adding to the lively scene. The background features a busy cityscape with tall buildings, people walking, and cars passing by, creating a lively urban environment. The chimp is wearing a small, round cap and a backpack. A close-up shot from a slightly elevated angle, capturing the excitement and movement.",1440 +152,"A dynamic seal training scene in a vibrant water park style, capturing a large, playful seal eagerly catching a fish tossed by its trainer. The seal has a sleek, black coat and bright, curious eyes, leaping gracefully out of the water to catch the fish mid-air. The trainer, wearing a colorful aquatic outfit, stands beside the pool, tossing the fish with enthusiasm. The background features a clear, shimmering pool with rippling water and some aquatic plants. A close-up shot from a slightly elevated angle, emphasizing the seal's agile movements and joyful expression.",1440 +153,"A whimsical and surreal illustration in the style of a modern comic, depicting a fish walking confidently into a cozy coffee shop. The fish is depicted with large, expressive eyes and a friendly smile, wearing a small, stylish hat. It holds a piece of paper with a handwritten note that reads, ""Can I please have a cup of coffee?"" The background features a warm, inviting coffee shop with wooden tables, comfortable chairs, and a barista preparing drinks behind the counter. The shop is filled with the aroma of freshly brewed coffee and the soft hum of conversation. The fish's tail moves naturally as it walks, creating ripples in the water droplets clinging to its scales. A close-up shot from a slightly elevated angle, capturing the fish's interaction with the shop's patrons.",240 +154,"A vibrant underwater scene in the style of a marine biology illustration, featuring a trio of seahorses gracefully holding onto seagrass with their tails. Each seahorse has a distinctive pattern on its body, ranging from deep blues and greens to lighter aquas and whites. Their tails wrap tightly around the swaying seagrass, which moves gently in the current. The seahorses have expressive eyes and small, delicate fins that flutter softly. The background showcases a rich variety of marine life, including colorful coral and various fish swimming around. The water is clear and filled with tiny bubbles rising to the surface. A close-up shot from a slightly elevated angle, capturing the intricate details of the seahorses and their environment.",720 +155,"A high-end culinary photography style shot of a skilled chef meticulously drizzling a glossy red sauce onto a pristine white plate. The chef, a middle-aged man with a neatly trimmed beard and a focused expression, holds a fine bottle in one hand and a sharp knife in the other. His movements are precise and deliberate, each drop of sauce landing perfectly on the plate. The background is a clean, modern kitchen with stainless steel appliances and sleek countertops, providing a stark contrast to the vibrant sauce. The lighting is soft yet dramatic, highlighting the texture and shine of the sauce. A close-up shot from a slightly elevated angle, capturing both the chef's hands and the final result.",240 +156,"A whimsical cartoon illustration in a vibrant and colorful style, depicting a small green frog leaping into a magical kiss, transforming mid-air into a creamy chocolate milkshake. The frog's legs and arms stretch out as if frozen in time, while its eyes widen in surprise. The milkshake is richly colored, with swirls of chocolate and foam on top, and a sprinkle of chocolate chips. The background is a fantastical, dreamlike landscape with floating clouds and twinkling stars. A dynamic aerial view, capturing the moment of transformation.",720 +157,"A synchronized diving photo in a realistic sports style, capturing two young divers performing a synchronized dive into a clear blue pool. Both divers are in mid-air, their bodies perfectly aligned and streamlined, arms and legs extended. Their expressions are focused and determined. One diver is wearing a black cap and a blue swimsuit, while the other is in a white cap and a red swimsuit. The water around them is blurred, creating a sense of speed and fluidity. The background shows the edge of the pool with spectators in the stands, creating a vibrant and energetic atmosphere. A high-angle shot emphasizing the synchronization and grace of the dive.",720 +158,"A dramatic and fiery scene from a sci-fi concept art piece, where a guitar is being swallowed by a volcanic eruption, engulfed in intense magma. The guitar, made of dark wood and adorned with intricate carvings, struggles against the molten lava that flows around it. The volcano's crater is wide open, with steam and ash rising into the air, casting an ominous shadow over the molten landscape. The camera angle is from a low, ground-level perspective, capturing the raw power and chaos of the eruption. The background features rugged, rocky terrain and glowing hot lava flows, creating a surreal and awe-inspiring environment. The texture of the magma is vivid and realistic, highlighting the intense heat and movement of the molten rock. A close-up shot emphasizing the struggle of the guitar within the erupting volcano.",240 +159,"A dynamic and lively hamster illustration in a bright cartoon style, capturing the hamster energetically running on a spinning wheel. The hamster has a playful expression, with round cheeks and alert eyes focused on the wheel. It is wearing a small, colorful harness that matches its cheerful demeanor. The background features a cozy, wooden cage with a checkered floor and some toys scattered around, adding to the hamster’s homey environment. The spinning wheel is intricately detailed, with spokes and a small door that opens and closes as it turns. The scene is captured from a slightly elevated angle, emphasizing the hamster’s movement and the intricate details of its surroundings.",240 +160,"A dynamic photograph in a realistic documentary style captures a yellow school bus chugging up a steep hill. The bus's engine roars loudly as it conquers the incline, smoke billowing from the exhaust. The bus is filled with children and teachers, their expressions a mix of excitement and concentration. The hillside is rugged with patches of green grass and wildflowers, and the trees on either side stretch towards the sky. The sunlight casts a golden glow on the scene, highlighting the bus and its passengers. The camera angle is slightly elevated, providing a clear view of the bus's determined climb.",240 +161,"A mystical Chinese ink painting depicting a crescent blue moon slowly rising over a serene mountain landscape. The moon appears ethereal and glowing, casting a soft, bluish light on the tranquil scene. Mountains in the distance are outlined in ink, with a few pine trees standing tall against the night sky. The foreground features a small stream with ripples reflecting the moonlight. A few bamboo shoots are scattered around, adding to the serene atmosphere. The sky transitions from deep indigo to lighter shades of blue as dawn approaches. A bird can be seen flying towards the moon, adding a sense of movement and life to the composition. A medium shot with a slightly upward angle.",1440 +162,"A dynamic and action-packed illustration in a cartoony yet realistic style, depicting a group of bears figuring out how to launch a rocket. The bears are diverse in appearance—some are brown, others are black, and one is even a polar bear. They stand around a small, partially assembled rocket, with tools and parts scattered around them. The bears look excited and determined, with various expressions ranging from concentration to anticipation. One bear is using a wrench, another is adjusting a circuit board, and a third is pointing towards the rocket, gesturing enthusiastically. The background shows a forest setting with tall trees, undergrowth, and a clear sky with fluffy clouds. The scene captures a moment of intense focus and teamwork. The camera angle is slightly elevated, providing a bird's-eye view of the bears and their work.",240 +163,"A whimsical, cartoon-style illustration depicting dogs as poker players at The World Series of Poker. The dogs are drinking large bowls of water in a very sloppy manner, causing water to splash onto the cards and the green felt of the poker table. One dog, with a tilted head in confusion, looks up at the camera. The background features a blurred casino setting with slot machines and poker chips scattered about. The dogs have playful expressions and are dressed in small, oversized suits. A close-up shot from a slightly elevated angle, capturing the chaotic and humorous scene.",1440 +164,"A dynamic scene captured in the style of a vibrant food photography shoot, showcasing a chef expertly tossing a salad in a large ceramic bowl. The chef, with a lively expression and focused intensity, moves with grace and precision, the salad spinning gracefully in the air before landing back in the bowl with a satisfying clatter. The chef is dressed in a crisp white chef's coat and black pants, with a white hat perched on his head. The background is a clean, modern kitchen with stainless steel appliances and a backdrop of warm, soft lighting that highlights the freshness of the ingredients. A mid-shot from a slightly elevated angle, capturing both the chef's action and the vibrant salad.",1440 +165,"A high-energy motorcycle stunt scene, capturing a daring backflip mid-air over a ramp. The stunt rider, wearing a black helmet and racing服, soars through the air with intense concentration and a fierce expression. The motorcycle spins gracefully, its wheels barely touching the ramp as it executes the backflip. The background features a blurred outdoor setting with a bright blue sky and distant mountains, emphasizing the dynamic movement and the thrill of the stunt. A dynamic shot from a low-angle perspective, highlighting the rider's momentum and the dramatic arc of the flip.",720 +166,"A serene night scene in traditional Chinese countryside style, depicting a rural road under a starry sky with the full moon hanging high. The road winds through lush fields, with the leaves and grass on both sides swaying gently, intermittently, and slowly in the breeze. The stars twinkle brightly overhead, casting a soft glow over the landscape. The path is quiet and peaceful, with a gentle rustling of leaves and grass creating a soothing ambiance. A wide-angle shot capturing the vastness of the night sky and the tranquil road.",720 +167,"A charming photograph in a soft, warm lighting style, capturing a toddler sitting on a cozy carpet, happily sharing a chocolate chip cookie with a cute teddy bear. The toddler has rosy cheeks, big bright eyes, and a gentle smile, reaching out to offer the cookie to the bear, which also has a friendly expression, leaning in to accept it. The teddy bear is dressed in a small red shirt and blue pants, adding to the whimsical scene. The background features a simple, wooden coffee table with a few colorful toys scattered around, and a large window letting in soft sunlight. A medium shot with a slight angle emphasizing the interaction between the child and the bear.",1440 +168,"A dynamic beach scene captured in a vibrant watercolor style, depicting a man standing at the shoreline, tossing a brown stick into the waves. The man, with tousled sandy blonde hair and a casual summer shirt, has a joyful expression as he throws the stick. His cat, a sleek gray tabby with green eyes, leaps excitedly towards the stick, mid-jump, tail flicking energetically. The background features clear blue skies, rolling waves, and a few seagulls flying overhead. Sand dunes stretch out behind them, with a few other beachgoers in the distance. A mid-shot from a slightly elevated angle, capturing both the man and the cat in action.",240 +169,"A dynamic photograph capturing a marathon runner in the final moments of a grueling race, crossing the finish line. The runner, a young man with a determined expression, is sprinting with arms pumping and legs striding forcefully. His face is flushed, and he is breathing heavily, sweat glistening on his forehead and body. He is wearing a white sports jersey with ""Marathon"" printed on the back, and black running shorts with sponsor logos. The background is blurred, revealing a crowd cheering and a banner reading ""Finish Line."" The finish line itself is marked by a colorful tape, and the runner's shadow stretches out behind him, emphasizing his momentum. The photo has a vibrant and energetic feel, capturing the intense moment of victory. A medium shot from a slightly elevated angle, focusing on the runner's determined expression and the blur of the crowd.",1440 +170,"A dramatic and surreal scene in a post-apocalyptic style, depicting a crumbling building slowly sinking into a pool of molten lava. The building is a dilapidated structure with cracked walls and broken windows, covered in soot and ash. The lava is a deep, glowing red with small bubbles rising to the surface, casting flickering shadows on the building. The air is thick with smoke and steam, creating a hazy, otherworldly atmosphere. The camera angle is from a low, ground-level perspective, emphasizing the vastness of the lava and the impending doom of the building.",720 +171,"A dramatic and dynamic moment captured in the style of a wildlife documentary, featuring a penguin flying into the open mouth of a blue whale as it breaks the surface of the ocean. The penguin is in mid-flight, wings spread wide, with a determined look on its face. The blue whale’s massive mouth is wide open, revealing its cavernous interior and rows of baleen plates. The background is a vast, deep blue sea with ripples caused by the whale’s breach, and a few seagulls flying overhead. The scene is bathed in natural sunlight, casting a warm glow on the water. The camera angle is from below, looking up at the action.",1440 +172,"A dramatic space scene in the style of a sci-fi movie poster, featuring a sleek silver spaceship being forcefully pulled into a swirling black hole. The spaceship is engulfed in a bright glow, with its hull reflecting the intense gravitational pull. The black hole is surrounded by a halo of shimmering particles and distorted starlight, creating a surreal and terrifying atmosphere. The background shows a vast cosmic void with distant galaxies and nebulae faintly visible. The spaceship is in a low-angle shot, emphasizing its struggle against the powerful gravitational force.",1440 +173,"A dynamic and chaotic scene in a dense forest during a heavy rainstorm, capturing a real girl frantically running through the foliage. Her wild hair flows behind her as she sprints, her arms flailing and her face contorted in fear and desperation. Behind her, various animals—rabbits, deer, and birds—are also running, creating a frenzied atmosphere. The girl's clothes are soaked, clinging to her body, and she is screaming and shouting as she tries to escape. The background is a blur of greenery and rain-drenched trees, with occasional glimpses of the darkening sky. A wide-angle shot from a low angle, emphasizing the urgency and chaos of the moment.",720 +174,"A detailed golfing scene in the style of a professional tournament photo, capturing a golfer sinking a long putt on the green. The golfer, a well-built Caucasian man with a focused expression, stands confidently with his left foot slightly forward, his right knee bent, and his club poised just behind the ball. His eyes are fixed intently on the ball, which sits on the edge of the cup. The green is lush and well-manicured, with a subtle slope leading to the cup. The background shows other greens, fairways, and trees in the distance, with a clear blue sky overhead. The golfer's stance is dynamic, with his arms extended and muscles tense, ready to make the perfect stroke. A medium shot from a slightly elevated angle, emphasizing the golfer's determined pose and the challenge of the putt.",1440 +175,"A traditional Chinese painting-style portrait of a middle-aged woman sipping a steaming cup of tea. She has warm, golden-brown skin and gentle, kind eyes that reflect the warmth of the moment. Her long black hair is tied back in a loose bun, and she wears a simple yet elegant qipao with intricate floral embroidery. She sits gracefully on a bamboo stool, her fingers gently cradling the porcelain cup. The background features a serene teahouse interior with wooden floors, paper lanterns hanging from the ceiling, and a small bonsai tree in a corner. A low-angle shot capturing her thoughtful expression as she enjoys her tea.",240 +176,"A dynamic photograph in a naturalistic style captures an orange cat leaping onto a kitchen counter. The cat's fur glistens in the warm light, and its eyes gleam with excitement as it spots the butter. It arches its back and extends its front paws to grasp the edge of the counter, mid-jump. The background shows a partially blurred kitchen scene with countertops, utensils, and appliances, hinting at a busy home environment. A close-up shot from a slightly lower angle, emphasizing the cat's playful and determined expression.",720 +177,"A dynamic softball game photograph capturing a player sliding safely into second base. The player, a young woman with short blonde hair and determined expression, moves with swift momentum, her legs bent and arms outstretched. Her uniform, a bright red jersey with white sleeves and black shorts, is taut against her athletic frame. She wears protective knee pads and cleats, her hands gripping the ball securely. The background shows a blurred baseball field with spectators in the stands, cheering and waving flags. The camera angle is slightly from behind, capturing the intense moment of her feet touching the base. The photo has a crisp, high-definition quality, emphasizing the action and emotion. A mid-shot with a slight upward angle.",240 +178,"A dynamic skate park scene in the style of a high-energy action sports video, capturing a group of skilled skateboarders performing impressive tricks on ramps and rails. The lead skateboarder, a young man with short brown hair and a determined expression, is mid-air, doing a flip over a metal rail, his board arcing gracefully through the air. Another skateboarder, a teenage girl with long blonde hair flowing behind her, is grinding smoothly along a wooden ramp, her body slightly crouched and her arms outstretched for balance. A third skateboarder, a boy with a skateboard helmet and a mischievous grin, is sliding down a steep concrete ramp, his board gliding effortlessly. The background features a bustling skate park with other skaters in the distance, a few onlookers cheering, and a graffiti-covered wall in the backdrop. The camera angle captures the action from a low, slightly elevated position, emphasizing the height and speed of the tricks.",240 +179,"A dynamic and lively scene in the style of a children's picture book, featuring a playful ferret tossing a red rubber ball with its mouth. The ferret has a sleek, brown coat and curious, mischievous eyes, standing on all fours with a joyful expression. Behind the ferret, a cute and energetic golden retriever puppy is chasing the ball with wagging tail and pricked ears. The puppy runs with bounding steps, its white fur contrasting against the green grass. The background shows a lush, sunny garden with blooming flowers and a few birds perched on branches. The photo has a warm and cheerful feel, capturing the moment of pure joy and companionship. A medium shot from a slightly elevated angle, focusing on the interaction between the two animals.",720 +180,"A vibrant and lively illustration in a whimsical cartoon style depicts a small golden retriever dog dancing joyfully in a sparkling pink tutu. The dog lifts one paw while wagging its tail, with a mischievous grin on its face. It strides confidently down a bustling city street, surrounded by tall buildings and busy pedestrians. The background features a colorful mix of street signs, parked cars, and passing bicycles. A dynamic mid-shot from a slightly elevated angle captures the dog's energetic movement and playful expression.",1440 +181,"A bustling ancient Chinese marketplace filled with lively activity. Merchants sell colorful spices and intricately patterned fabrics from large woven baskets and bolts. The air is rich with the scent of exotic spices like cinnamon and cardamom. Stalls are lined up side by side, each offering a variety of goods. Customers haggle with sellers, their voices blending into a harmonious cacophony. The background features a vibrant mix of red lanterns hanging overhead, wooden stalls with intricate carvings, and a bustling crowd in traditional attire. The scene is captured in a dynamic, high-angle shot, capturing the energy and movement of the marketplace.",120 +182,"A stunning Santorini landscape photo captured during the blue hour, featuring a red panda and a toucan strolling hand-in-hand through the picturesque village. The red panda, with its distinctive reddish-brown fur and large round eyes, carries a small backpack, while the toucan, with its vibrant orange and black feathers and a large curved beak, holds a colorful flower. They walk along a winding cobblestone path, passing by whitewashed buildings with blue doors and windows. The setting sun casts a soft golden glow, creating a warm and serene atmosphere. The sky is painted with shades of blue and purple, with a few twinkling stars beginning to appear. A wide-angle shot from a slightly elevated angle, capturing the intimate moment between these two unlikely friends.",120 +183,"A surreal scene in the style of a magical realism painting, featuring a person drinking tea from a cup made of ice that never melts. The person, a young woman with fair skin and wavy brown hair tied in a loose bun, has a serene and contemplative expression. She wears a simple white blouse and black pants, sitting on a wooden stool under a large, ancient tree with shimmering leaves. The background is filled with floating snowflakes and misty clouds, creating a dreamlike atmosphere. The cup, made of an ethereal, glowing ice, catches the light and reflects it back in mesmerizing patterns. A close-up shot from a slightly elevated angle, capturing the intricate details of the ice cup and the woman's tranquil face.",120 +184,"A photograph in a warm, candid style captures a middle-aged man's joyful face illuminated with genuine happiness as he receives a heartfelt compliment. The man, with a friendly smile and twinkling eyes, appears to be standing in a cozy living room, perhaps at a social gathering. He wears a casual shirt and jeans, his hair neatly combed but with a few loose strands falling over his forehead. The background is blurred, revealing soft lighting and a few other guests in the background, adding to the intimate and welcoming atmosphere. A close-up shot from a slightly lower angle, emphasizing his delighted expression.",120 +185,"A dramatic scene in the style of an action movie, where gold coins spill out as the elevator doors open. The elevator interior is sleek and modern, with metallic panels and a few flickering lights. A man in a business suit steps out, looking surprised and pleased. The coins fall in a cascade, creating a glittering shower. The background features a blurred view of the hallway, with a faint outline of office doors and a distant fluorescent light. The camera angle is from below, capturing the man's reaction and the falling coins. A close-up shot with dynamic motion.",120 +186,"A vibrant and lively street scene in Boston, captured in a whimsical comic book style, features a giant duck strutting confidently through the city. The duck has a golden yellow body with black feathers and a wide orange bill. It waddles with a playful gait, its feet leaving small splashes in the puddles. The duck wears a tiny bow tie and sunglasses, adding a touch of humor. The background shows blurred images of iconic Boston landmarks like the Boston Common and the Massachusetts State House, with the skyline visible in the distance. Pedestrians and cars are seen in the background, creating a bustling city atmosphere. The duck looks directly at the viewer, its expression full of curiosity and mischief. A medium shot from a slightly elevated angle.",120 +187,"An old man in blue jeans and a white t-shirt taking a pleasant stroll in Johannesburg, South Africa, during a vibrant and colorful festival. He walks with a gentle sway, his weathered face reflecting a sense of contentment. The festival is bustling with activity, featuring multicolored decorations, lively music, and people in festive attire. The background showcases a mix of traditional African and modern elements, with colorful banners and street vendors. The old man's hands rest casually in his pockets, and he looks around, enjoying the lively atmosphere. The scene is captured in a warm and inviting style, with a slight focus on the old man from a medium shot angle.",120 +188,"A dynamic urban scene in a realistic photography style, capturing a large truck navigating through a bustling city street during rush hour. The truck is moving smoothly with its wheels spinning slightly, following the flow of traffic and pedestrians. The driver looks focused, with the steering wheel turned slightly to the right. The background features a mix of tall buildings, crowded sidewalks, and cars honking in the dense traffic. Pedestrians hurry past, some carrying shopping bags or briefcases. The air is filled with the sounds of horns and chatter, creating a lively atmosphere. The photo has a sharp focus and a natural color palette, emphasizing the movement and energy of the city. A medium shot from a slightly elevated angle, capturing both the truck and the surrounding environment.",120 +189,"A bustling train station in the heart of a vibrant city, captured in the style of a vibrant urban street scene. The station is packed with people in various outfits, rushing to catch their trains or waiting anxiously. A young man in a casual shirt and jeans stands near a large digital clock, checking his phone. His expression is a mix of impatience and curiosity. The background features a mix of modern architectural elements, including sleek glass buildings and colorful advertisements. The lighting is warm and inviting, with natural sunlight streaming through large windows. A dynamic medium shot with a slightly elevated angle, capturing the energy and movement of the crowd.",120 +190,"A vibrant and lively scene in Johannesburg, South Africa, captured in a colorful festival atmosphere. A woman wearing purple overalls and cowboy boots takes a pleasant stroll, her steps rhythmic and joyful. Her face is filled with delight, and she carries a small bag slung over one shoulder. The festival is bustling with activity, featuring colorful decorations, vibrant costumes, and lively music. People of various ethnicities mingle, their laughter and chatter adding to the festive mood. The background is a blend of traditional African patterns and modern cityscapes, with bright lights and stalls selling local crafts and foods. The camera angle captures her from behind, showing her full stride and the joyous expressions of those around her. The overall scene is captured in a warm and dynamic style, emphasizing the energy and spirit of the festival. A mid-shot from a slightly elevated angle.",120 +191,"A high-fantasy painting style depiction of a young artist wearing a hooded cloak and holding a spray paint can, standing on the side of a flying spaceship. The artist has messy brown hair and intense, determined eyes, focused intently on their work. The spaceship has intricate designs and glowing lights, with wings spread wide and a trail of sparks behind it. The background features swirling cosmic clouds and distant galaxies, creating a surreal and ethereal atmosphere. The artist is mid-spray, with paint splatters flying in the air, capturing a dynamic moment of action. A close-up shot from a slightly elevated angle.",120 +192,"A close-up shot of sparkling water being poured into a glass, capturing the detailed flow and bubbles as they rise and burst on the surface. The glass is clear and tall, with a slender stem. The water flows smoothly, creating ripples and tiny bubbles that dance and scatter across the liquid's surface. The background is blurred, showcasing a soft, warm ambient light that highlights the vibrant play of light and shadow on the water. The scene has a crisp, high-definition texture, emphasizing the dynamic movement of the water.",120 +193,"A macro realistic style photograph of an elderly man wearing an antique diving helmet with dark glass and a jetpack. He stands on the intricate veins of a large, lush leaf, his steps deliberate and steady. The man has a weathered face with deep wrinkles and a determined expression. His arms are slightly bent, supporting the jetpack, which adds a sense of balance and purpose. The leaf's veins are detailed and vibrant, with hints of green and brown, creating a striking contrast with the man's attire. The background is blurred, showing a hint of sunlight filtering through, casting dappled shadows. A close-up macro shot from a slightly elevated angle.",120 +194,"A vibrant and dynamic scene capturing a young man's eyes widening in amazement as he steps into a surprise party. The man, with lively brown eyes and a youthful, open expression, stands in the center of a room filled with friends and family, all dressed in colorful party attire. He wears a casual white t-shirt and jeans, with a slight smile spreading across his face. The background features a mix of decorations, including balloons, streamers, and a banner that reads ""Surprise!"" in bold letters. The room is brightly lit, with warm, ambient lighting creating a festive atmosphere. The camera angle is from below, capturing the man's reaction with a sense of excitement and joy.",120 +195,"A clay model being slowly deformed as it is pressed and molded into a new shape by hand. The clay is a rich brown color, and the model, originally a simple figure, is gradually taking on a more complex form. The sculptor, a middle-aged man with weathered hands and focused expression, gently presses and molds the clay with precision. His movements are deliberate and steady, and the clay yields to his touch, revealing intricate details like folds and textures. The background is a dimly lit studio with shelves filled with various tools and other clay models. The camera angle is from the side, capturing both the sculptor's hands and the transformation of the clay. A close-up shot with a slight tilt to emphasize the process.",120 +196,"A dynamic hip-hop dance scene in a vibrant urban style, featuring an Asian girl in a bright yellow T-shirt and white pants. She is mid-dance move, arms stretched out and feet rhythmically stepping, exuding energy and confidence. Her hair is tied up in a ponytail, and she has a mischievous smile on her face. The background shows a bustling city street with blurred reflections of tall buildings and passing cars. The scene captures the lively and energetic atmosphere of a hip-hop performance, with a slightly grainy texture. A medium shot from a low-angle perspective.",120 +197,"A dynamic action shot in the style of a high-energy sports photo, capturing a base jumper accelerating after leaping off a cliff. The jumper is mid-air, arms extended and legs bent, body tilted forward in free-fall. The sky is vast and blue, with clouds in the distance, creating a dramatic contrast against the rugged cliff edge below. The background features blurred rocky terrain and dense forest, adding depth to the scene. The jumper's expression is intense and focused, conveying the thrill and adrenaline of the moment. A high-angle shot emphasizing the vastness of the sky and the sheer drop below.",120 +198,"A cinematic landscape in the style of a romantic drama, capturing a couple walking hand in hand along a sandy beach as the sun sets over the vast ocean. The man, with tousled brown hair and a gentle smile, wears a casual white shirt and jeans, while the woman, with flowing blonde hair and a serene expression, is dressed in a light blue sundress. They walk towards the horizon, their shadows elongating as the sky turns a gradient of pinks, oranges, and purples. The beach is lined with seagulls and scattered shells, and the water reflects the golden hues of the setting sun. The camera slowly zooms out, providing a sweeping view of the entire scene, emphasizing the tranquility and romance of the moment. A wide-angle shot from a slightly elevated perspective.",120 +199,"A serene and tranquil photo-style image of a pedestal rising from the surface of a pond, breaking the surface tension to reveal the lily pads and their reflections. The pedestal is slightly weathered, with moss growing along its edges. The lily pads float gracefully on the water, their green surfaces glistening under the sunlight. The reflections in the water create a mirror-like effect, doubling the beauty of the scene. The background features a lush green environment with tall reeds and aquatic plants, and a few ducks swimming nearby. The water ripples gently, adding a sense of movement and life to the composition. A medium shot from a slightly elevated angle, capturing both the pedestal and the surrounding water and reflections.",120 +200,"An adorable kangaroo, wearing blue jeans and a white t-shirt, takes a pleasant stroll through the streets of Mumbai, India, during a winter storm. The kangaroo moves gracefully, its pouch empty but ready. The cityscape is blurred in the background, with tall buildings and narrow lanes visible through the swirling snow. The kangaroo's fur is slightly damp from the rain, and it occasionally stops to sniff the air. The storm adds a dramatic flair, with lightning illuminating the scene and strong winds creating a sense of movement. The photo has a vibrant, almost surreal quality, capturing both the unexpected and the whimsical. A dynamic shot from a slightly elevated angle, emphasizing the kangaroo's natural and joyful movement.",120 +201,"A dynamic and bustling first-person experience of walking through a vibrant market, with colorful stalls lining both sides of the narrow alleyway. The scene is filled with the lively chatter and enthusiastic calls of vendors selling fruits, vegetables, spices, and textiles. The air is thick with the sweet scent of ripe mangoes and the pungent aroma of freshly ground spices. People move past you, their faces animated with the excitement of haggling and bargaining. The camera follows your path, capturing the vibrant array of goods displayed on each stall—brightly colored fabrics, exotic fruits piled high, and aromatic herbs arranged in neat rows. The background is a chaotic yet harmonious blend of bustling activity, with the sun casting warm, golden hues through the gaps in the canopy overhead. A series of medium shots from various angles, emphasizing the energy and movement of the crowd.",120 +202,"A vibrant and lively celebration scene in the style of a music festival photo. A group of diverse people, including East Asians, Africans, and Caucasians, are enthusiastically clapping and cheering. They have joyful expressions, with some smiling widely and others raising their hands in excitement. The crowd is standing in a semi-circle around a stage, with a DJ booth and a large speaker system visible. The background features colorful balloons, banners with ""Happy Anniversary"" written in bold letters, and a backdrop of fireworks in the distance. The camera angle is from slightly above, capturing the dynamic energy of the crowd.",120 +203,"A winter storm scene in Johannesburg, South Africa, where a woman walks leisurely with a gentle breeze blowing. She wears a vibrant green dress and a sun hat, adding a pop of color against the gloomy sky. Her steps are steady and graceful, and she carries an umbrella, shielding herself from the rain. The background features tall buildings and bustling streets, with blurred silhouettes of people and vehicles in the distance. The sky is overcast, with dark clouds and occasional flashes of lightning, creating a dramatic yet serene atmosphere. A medium shot capturing her walking down the street from a slightly elevated angle.",120 +204,"A dynamic and chaotic scene captured in the style of a realistic action photo, depicting a shopping cart careening down a steep hill, its wheels spinning rapidly. The cart collides with a parked car, causing groceries to scatter across the ground. The shopping cart is filled with various items, including fruits, vegetables, and canned goods, spilling out in a messy pile. The car is slightly dented from the impact, with its doors partially open. The background shows a residential street with blurred houses and trees in the distance, suggesting a busy neighborhood. The photo captures the moment of collision from a low-angle perspective, emphasizing the movement and chaos.",120 +205,"A macro shot in realistic style of a man wearing an antique diving helmet with dark glass and a jetpack, standing on a molten lava surface. He strides confidently, his body slightly bent forward, with a determined expression. Behind him, a majestic dragon soars through the sky, its wings spreading wide and scales glistening in the flickering light. The background is a dramatic landscape with smoldering volcanic peaks and swirling clouds, creating a sense of otherworldly danger and adventure. The man’s muscles are flexed, and his arms are outstretched as he walks, adding a dynamic quality to the scene. A medium shot with a slight tilt upwards, emphasizing both the man and the flying dragon.",120 +206,"A vintage-style illustration of a Rocket Man in a spacesuit, complete with a black glass face shield, sitting inside a sleek, retro-futuristic spaceship. The spaceship is flying through a large, intricate blood vessel, with the interior of the vessel filled with large, pulsating red blood cells. The Rocket Man appears determined, with a focused expression, and his hands are placed firmly on the control panel. The background shows the walls of the blood vessel with detailed, swirling patterns, giving the scene a dynamic and vivid feel. The spaceship has a smooth, metallic surface with subtle pinstripes and a few dents, adding to its vintage charm. The camera angle is slightly from below, capturing the Rocket Man and the spaceship mid-flight through the blood vessel.",120 +207,"A dynamic and lively moment captured in a vibrant pop art style, showing a young woman jumping up and down with joy, her movements full of energy and excitement. She dances energetically, her arms flailing and legs kicking in the air. Her face is filled with happiness and a wide smile. She wears a colorful floral dress that flows with her movements. The background features a blurred cityscape with hints of tall buildings and bright lights, giving the scene a bustling urban feel. A mid-shot from a slightly low angle, capturing the full range of her joyful dance.",120 +208,"A serene autumn landscape photo, capturing the gentle filtering of sunlight through a dense canopy of colorful leaves. The leaves, a mix of golden, orange, and crimson hues, create a warm, dappled pattern on the forest floor below. The scene is bathed in soft, natural light, enhancing the rich, vibrant colors. A medium shot from a slightly elevated angle, emphasizing the intricate play of light and shadow.",120 +209,"A dark neon-inspired rainforest scene, glowing with fantastical fauna and animals. The forest is lush and dense, with towering trees covered in bioluminescent moss and vines. Neon hues of green, blue, and purple illuminate the area, casting a surreal glow on the creatures within. Various exotic and fantastical animals, including glowing butterflies, neon frogs, and luminescent birds, flit about the forest, adding to its otherworldly charm. The camera captures a medium shot, focusing on a group of these magical creatures as they interact in the vibrant, glowing environment.",120 +210,"A realistic photograph capturing a middle-aged woman coughing into her hand, her eyes squinting due to the force of the cough. She has a concerned and slightly pained expression, her face slightly flushed. Her hands are covered in a light layer of dust from the cough, and she appears to be standing in a dimly lit room with peeling wallpaper and a few old, broken pieces of furniture. The background is blurry, revealing only faint shadows of a cluttered space. A close-up shot from a slightly lower angle, emphasizing her distressed facial expression.",120 +211,"A dynamic camera arc shot capturing a golden retriever barking fiercely at a scurrying gray squirrel in the garden. The dog stands alert, its tail wagging nervously, while its expressive brown eyes focus intently on the tiny rodent. The squirrel pauses mid-jump, turning to face the dog with quick, curious movements. The background features a lush green lawn dotted with wildflowers and a few scattered trees. The air is filled with the scent of freshly cut grass and the sound of distant birds chirping. The photo has a vibrant, naturalistic style, emphasizing the lively interaction between the two animals.",120 +212,"A vibrant and dynamic digital art piece in the style of a modern dance performance, depicting a person dancing energetically under the moonlight. The dancer, with flowing, flowing black hair and glowing skin, is performing a graceful yet powerful routine. Their shadow, which has come to life, dances alongside them, distorted and elongated, creating a surreal and captivating scene. The background features a blurred night sky with stars and a crescent moon, adding to the ethereal atmosphere. The camera angle is from a slightly elevated position, capturing both the dancer and their animated shadow in a medium shot.",120 +213,"A high-energy action shot of a skier racing down a steep slope during a downhill competition. The skier, a fit and determined individual with a helmet and goggles, is in mid-ski with both poles planted firmly in the snow. They are wearing a bright red ski suit with white stripes, exuding confidence and speed. The background is a blurred mix of snowy trees and distant mountains, with the sky starting to lighten, indicating early morning conditions. The camera angle is from below, capturing the dynamic motion and the thrill of the race.",120 +214,"An old man in vibrant purple overalls and sturdy cowboy boots takes a leisurely stroll through Antarctica during a lively and colorful festival. His weathered face and twinkling eyes reflect a sense of joy and wonder. The festival is filled with vibrant decorations and people in festive attire, creating a unique blend of warmth and cold. The background shows the stark yet beautiful Antarctic landscape, with icebergs and snow-covered mountains in the distance. The sky is painted with hues of orange, pink, and purple, adding to the festive atmosphere. The old man moves with a gentle sway, his hands clasped behind his back, enjoying the moment. The scene is captured from a slightly elevated angle, emphasizing the contrast between the man and the vast, icy landscape.",120 +215,"A realistic style paper origami dragon riding a boat through waves, with intricate folds and textures. The dragon has a fierce expression, its eyes glowing with intensity, and its scales shimmering in the sunlight. It is perched on the edge of the boat, wings partially spread, ready to take flight. The boat bobs up and down with the waves, creating a dynamic motion. The water is choppy, with ripples and splashes around the boat, adding to the sense of movement. The background features a clear blue sky with fluffy clouds, and a few seagulls flying overhead. A mid-shot capturing the dragon's powerful stance and the boat's motion.",120 +216,"A vibrant anime illustration in a dynamic, thick-line painting style of a young girl blowing a kiss to the camera. She has long flowing hair that cascades down her back, framed by soft bangs that partially cover her eyes. The girl wears a colorful floral dress with ruffled sleeves and a delicate belt. She has bright, sparkling eyes and a sweet, joyful smile. Her lips are parted, and she blows a kiss towards the camera with a playful and innocent expression. The background is a blurred outdoor setting with a gentle sunset, highlighting warm hues of orange and pink. A close-up shot from a slightly tilted angle, capturing the moment of her kiss.",120 +217,"A close-up shot of a baby with wide-open eyes sucking on a pacifier. The baby has soft, rosy cheeks and a small nose with a hint of down. The baby's eyes are full of wonder and curiosity, looking directly at the viewer. The pacifier is securely held between the baby's lips, and the baby's tiny hands rest gently on the cheeks. The background is softly blurred, revealing a warm and cozy nursery with pastel-colored walls and a few toys scattered on the floor. The overall atmosphere is gentle and serene, capturing the innocence and joy of early childhood.",120 +218,"A cinematic trailer in the style of a heartwarming coming-of-age film, showcasing a group of playful Samoyed puppies learning to become chefs. The puppies, with their fluffy white coats and bright eyes, gather around a colorful kitchen filled with pots, pans, and ingredients. They wag their tails excitedly as they attempt to mix batter and fold dough under the watchful eye of a wise, elderly dog. The puppies’ expressions range from determined to mischievous, with one puppy accidentally knocking over a stack of plates. The background transitions between warm, inviting kitchen scenes and glimpses of the puppies’ playful antics outside. The camera angles vary from wide shots of the puppies working together to close-ups capturing their joyful faces. A soft, uplifting score plays in the background, enhancing the sense of adventure and growth.",120 +219,"A serene watercolor painting depicting a mother otter floating gracefully on her back in a tranquil river. The otter cradles her playful pup on her stomach, gently keeping it warm and safe in the gentle current. The pup's small paws dangle in the water, while the mother's fur glistens in the soft sunlight. The background features a lush forest with tall trees reflected in the river, and a few wildflowers dotting the banks. The water has a soft, ethereal quality, emphasizing the peacefulness of the scene. A medium shot capturing the tender interaction between the mother and her pup from a slightly overhead angle.",120 +220,"A realistic photograph of a princess riding a horse across a river. The princess, with fair skin and delicate features, wears a flowing white gown with intricate lace detailing and a long veil. She sits gracefully on a sturdy, brown horse, her hands firmly gripping the reins. The horse's mane flows freely in the breeze, and its hooves kick up small splashes of water as it gallops across the river. The riverbank is lined with tall grasses and wildflowers, with a few trees providing shade. The background shows a misty landscape, with distant hills and a hint of blue sky peeking through the clouds. The photo captures a moment of natural movement, with the princess and horse seeming almost weightless as they cross the river. A medium shot from a slightly elevated angle, emphasizing the princess's determined expression and the horse's powerful stride.",120 +221,"A dynamic action shot in the style of a high-speed photography sequence, capturing a rubber band being stretched to its maximum length and then suddenly released. The rubber band snaps back to its original shape with a burst of energy, creating a vivid visual effect. The background is blurred, focusing attention on the rapid movement and tension release. The camera angle is from the side, emphasizing the elasticity and power of the rubber band.",120 +222,"A slow-motion video capturing the intricate process of pouring a drink into a classic martini glass, showcasing the detailed flow and splashes of the liquid as it cascades down the rim. The camera angle is slightly elevated, allowing viewers to see the fine droplets clinging to the glass and the ripples spreading across the surface. The background is a dimly lit bar, with soft lighting casting shadows and highlighting the elegance of the glass. The video has a cinematic quality, emphasizing the fluidity and artistry of the pour. A medium shot with dynamic camera movement following the flowing liquid.",120 +223,"A cinematic pull-out from a close-up of a beautifully handwritten letter, gradually revealing a person sitting at a wooden desk, lost in deep thought. The letter, penned in elegant cursive, is placed on the desk, partially folded. The person, with slightly furrowed brows and a faraway gaze, appears engrossed in the contents of the letter. The background shows a cluttered but organized workspace, with books, papers, and a half-filled cup of coffee nearby. The lighting is soft and warm, casting gentle shadows. A medium shot with a slightly elevated camera angle, capturing both the letter and the person’s contemplative expression.",120 +224,"A close-up shot of a pair of chopsticks delicately picking up a piece of sushi and dipping it into a small dish of soy sauce. The chopsticks are held by a person with skilled fingers, their hands steady and precise. The sushi is fresh and colorful, with a slice of fish and rice perfectly balanced. The soy sauce dish is ceramic, with a glossy finish and a slight reflection of the chopsticks. The background is a traditional Japanese dining room, with a low table and ornate decorations. The lighting is soft and warm, highlighting the textures and colors. A medium close-up with a slight tilt, capturing the moment of the chopsticks touching the soy sauce.",120 +225,"A winter storm rages in Antarctica, with fierce winds and heavy snow creating a dramatic backdrop. A woman in a green dress and a sun hat takes a pleasant stroll, her steps steady and confident. Her dress flows slightly with the wind, and she holds her sun hat securely in place with one hand. The snow-covered landscape is blurred and ethereal, with distant mountains and icebergs peeking through the storm. The woman's face is slightly tilted向上,眼中闪烁着坚定与从容。A medium shot capturing her walking through the storm, with the camera angle slightly elevated to emphasize her resilience.",120 +226,"A whimsical illustration in a cartoon style, depicting a fluffy white rabbit with large floppy ears holding a glowing crescent moon on its back. The rabbit has big, round eyes and a small nose, with a playful smile on its face. It is mid-flight, wings slightly spread, moving gracefully through the night sky. The background features a starry night with a full moon and twinkling stars, creating a serene and magical atmosphere. A dynamic aerial view capturing the rabbit in mid-flight.",120 +227,"A soft and intimate moment captured in a warm and cozy living room setting. A woman with long flowing brown hair sings gently to a baby swaddled in a soft blanket. Her lips move softly, forming tender words as she holds the baby close. The woman wears a simple yet elegant dress, with a gentle smile on her face. The baby, with wide-eyed curiosity, listens intently. The background features a few scattered toys and a fireplace with a warm glow. The lighting is soft and diffused, creating a warm and inviting atmosphere. A close-up shot from a slightly lower angle, capturing both the woman and the baby.",120 +228,"A dramatic skydiving scene in a realistic photographic style, capturing a skydiver accelerating during free fall. The skydiver, a young man with a determined expression, is mid-air with arms outstretched and legs extended. His body is in dynamic motion, creating a sense of speed and tension. The background features a vast blue sky with fluffy clouds, contrasting sharply with the intense focus on the skydiver. The camera angle is from below, looking up at the skydiver as he descends rapidly, emphasizing his powerful leap. The photo has a high-resolution, sharp texture, highlighting every detail of his athletic form and the rush of air around him. A medium shot with a slight downward angle.",120 +229,"A dynamic action shot in the style of a professional martial arts film, showcasing a young Asian martial artist delivering a powerful punch to break a wooden board. The martial artist is dressed in traditional black gi with white stripes down the sides, emphasizing his strength and agility. His expression is intense and focused, with a slight grimace as he connects with the board. His muscles are taut, and his stance is firm and balanced. The board splits cleanly in half, creating a satisfying crack. The background features a blurred indoor dojo with a wooden floor and hanging martial arts flags, adding to the authenticity of the scene. The camera angle is from the side, capturing the full power of the punch.",120 +230,"A dramatic tilt-down shot from a magnificent chandelier in a grand hall, showcasing the ornate decor and people mingling below. The chandelier itself is intricately designed with crystal prisms and gold filigree, casting a sparkling light on the room. The hall is lavishly decorated with gilded columns, intricate murals, and plush carpets. Guests in elegant attire are seen conversing and sipping cocktails, their faces illuminated by the soft, warm lighting. The background features a large, arched window with a view of the night sky, adding depth to the scene. The overall style is opulent and classical, reminiscent of a high society gala.",120 +231,"An adorable kangaroo wearing purple overalls and cowboy boots takes a pleasant stroll through the bustling streets of Mumbai, India, during a winter storm. The kangaroo's fur is soft and fluffy, with large, expressive eyes and a playful smile. It hops along confidently, its overalls and boots adding a touch of whimsy to the scene. The background features a mix of colorful Indian street vendors, rickshaws, and tall buildings, with the storm clouds casting dramatic shadows. The storm is fierce yet beautiful, with heavy rain and strong winds, creating a dynamic and enchanting atmosphere. The kangaroo pauses occasionally to inspect its surroundings, adding a sense of curiosity and wonder. A mid-shot with a slightly elevated camera angle, capturing both the kangaroo and the vibrant cityscape.",120 +232,"A close-up shot of a Chinese child eagerly eating dumplings. The child has dark, curly hair tied into a ponytail and large, curious eyes. They wear a traditional red and gold jacket with intricate embroidery, and their face is framed by a delicate, round face. The dumplings are steaming hot, with visible fillings peeking out, and the child's fingers are stained with sauce. The background shows a cluttered dining table with other dishes and toys, creating a warm and cozy home environment. The photo has a soft, natural lighting and a warm color palette. A close-up shot capturing the child's joyful expression and the food.",120 +233,"A vibrant and dynamic illustration in the style of a fairy tale, depicting a person conducting an orchestra of flowers. Each flower is blooming and playing a different musical note, their petals moving gracefully in time with the music. The person, dressed in a flowing, pastel-colored gown, has a serene and focused expression, arms elegantly extended to guide the flowers. The background is a lush, enchanted garden with intricate patterns and magical elements, such as glowing mushrooms and sparkling dewdrops. The scene is bathed in soft, warm lighting, creating a dreamlike atmosphere. A medium shot with a slightly elevated angle, capturing both the conductor and the orchestra of flowers.",120 +234,"A fairy tale-style illustration depicting a person walking on a path of glowing floating lily pads. The person wears a flowing white gown with intricate floral patterns and holds a lantern that casts a warm, golden glow. Each lily pad lights up with a soft, ethereal light as they step on it, creating a magical effect. The background features a tranquil pond with lotus flowers and serene water lilies, reflecting a peaceful twilight sky. The scene is rendered in a detailed, fantasy art style with smooth brushstrokes and a dreamy atmosphere. The camera angle is slightly elevated, capturing the person's graceful walk and the glowing lily pads beneath their feet.",120 +235,"A surreal and whimsical scene in the style of a fantasy illustration, depicting a person standing on a rooftop, their feet barely touching the ground as they plant flowers upside down into the ceiling. The person wears a colorful floral dress with intricate patterns and a mischievous smile, their hands deftly placing seeds and soil into small pots attached to the ceiling. The flowers grow upwards, their petals facing downwards, creating a vibrant and inverted garden. The background shows a city skyline with distant buildings and a clear blue sky, adding to the fantastical atmosphere. The lighting is soft and ethereal, highlighting the unusual setting. A close-up shot from a slightly elevated angle, capturing the person's joyful expression and the upside-down flowers.",120 +236,"A vibrant and lively photograph capturing a young woman with rosy cheeks and a delighted expression as she savoring a sumptuous meal. She has long flowing brown hair tied in a loose bun, with strands framing her face. Her eyes sparkle with joy, and her lips are curved into a warm smile. She is seated at a rustic wooden table, with a plate of steaming food in front of her. The background features a cozy dining room with soft lighting, warm wooden walls, and a few scattered books on a nearby shelf. The scene is filled with the aroma of delicious food, creating a warm and inviting atmosphere. A close-up shot from a slightly angled perspective, emphasizing her joyful expression and the mouth-watering meal.",120 +237,"A winter landscape photograph capturing the subtle beauty of a person exhaling in the chilly air. The foggy breath forms tiny clouds that condense and disperse with each exhale, creating a mesmerizing effect against the backdrop of a snowy forest. The person stands still, their breath creating intricate patterns in the air, casting a soft mist over the surrounding trees and bushes. The air is crisp and cold, with a hint of frost on the ground. The photo has a soft, ethereal quality, emphasizing the transient nature of the moment. A close-up shot from a slightly elevated angle, focusing on the interaction between the person and the environment.",120 +238,"A dramatic moment captured in a dynamic aerial photography style, showcasing a drone mid-air collision with a grand stone statue. The drone's propellers and body are shattered, pieces scattering in various directions. The statue, made of weathered stone, remains mostly intact but shows cracks along its surface. The background features a bustling cityscape with skyscrapers and busy streets, creating a stark contrast between the modern and ancient elements. The camera angle is from below, looking up at the collision from a low altitude, emphasizing the scale and impact of the event.",120 +239,"An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man.",120 +240,"A melancholic scene from a vintage film-style photograph captures a woman's lips trembling with sadness as she reads a farewell letter. Her eyes are filled with tears, and her expression conveys deep sorrow. She is seated at a wooden table, surrounded by old books and papers, creating a somber ambiance. The background is blurred, revealing only hints of a dimly lit room with a fireplace in the distance. The letter, held tightly in her hand, is partially visible, adding to the emotional intensity. A medium shot with a soft focus on her face.",120 diff --git a/Helios/eval_moviebench/playground/results/all_models_merged.json b/Helios/eval_moviebench/playground/results/all_models_merged.json new file mode 100644 index 0000000000000000000000000000000000000000..60e84bbeadd7f060b20babd6b2b7389087cec565 --- /dev/null +++ b/Helios/eval_moviebench/playground/results/all_models_merged.json @@ -0,0 +1,31 @@ +{ + "num_models": 1, + "score_type": "rating", + "metrics": [ + "aesthetic", + "drifting_aesthetic", + "drifting_motion_smoothness", + "drifting_naturalness", + "drifting_semantic", + "motion_amplitude", + "motion_smoothness", + "naturalness", + "semantic", + "total_weighted_rating" + ], + "models": { + "toy-video": { + "aesthetic": 9, + "motion_amplitude": 3, + "motion_smoothness": 10, + "naturalness": 7, + "semantic": 8, + "drifting_aesthetic": 8, + "drifting_motion_smoothness": 10, + "drifting_naturalness": 10, + "drifting_semantic": 10, + "total_weighted_rating": 8.247 + } + }, + "rating_scale": 10 +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/aesthetic_results.json b/Helios/eval_moviebench/playground/results/toy-video/aesthetic_results.json new file mode 100644 index 0000000000000000000000000000000000000000..9a3679d8ff2cd3b0921d60e4a8667b80f43d9b58 --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/aesthetic_results.json @@ -0,0 +1,17 @@ +{ + "metric": "aesthetic", + "average_score": 0.6564263701438904, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "aesthetic_score": 0.6802743077278137 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "aesthetic_score": 0.632578432559967 + } + ] +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/drifting_aesthetic_results.json b/Helios/eval_moviebench/playground/results/toy-video/drifting_aesthetic_results.json new file mode 100644 index 0000000000000000000000000000000000000000..226fe467060e42542696d5b7217e56cc27e2bd7d --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/drifting_aesthetic_results.json @@ -0,0 +1,22 @@ +{ + "metric": "drifting_aesthetic", + "description": "Start-end contrast of aesthetic (first/last 15% frames)", + "average_drift_score": 0.027865678071975708, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "drift_aesthetic_score": 0.002410709857940674, + "start_aesthetic_score": 0.6802361011505127, + "end_aesthetic_score": 0.677825391292572 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "drift_aesthetic_score": 0.05332064628601074, + "start_aesthetic_score": 0.6535003185272217, + "end_aesthetic_score": 0.6001796722412109 + } + ] +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/drifting_motion_smoothness_results.json b/Helios/eval_moviebench/playground/results/toy-video/drifting_motion_smoothness_results.json new file mode 100644 index 0000000000000000000000000000000000000000..92b33c049519425420f3fd6500ca8f08577f81e9 --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/drifting_motion_smoothness_results.json @@ -0,0 +1,22 @@ +{ + "metric": "drifting_motion_smoothness", + "description": "Start-end contrast of motion smoothness (first/last 15% frames)", + "average_drift_score": 0.0009624073235373065, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "drift_motion_smoothness_score": 0.0016874511579993978, + "start_motion_smoothness_score": 0.9880413336530265, + "end_motion_smoothness_score": 0.9897287848110259 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "drift_motion_smoothness_score": 0.0002373634890752152, + "start_motion_smoothness_score": 0.9948747067013198, + "end_motion_smoothness_score": 0.995112070190395 + } + ] +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/drifting_naturalness_results.json b/Helios/eval_moviebench/playground/results/toy-video/drifting_naturalness_results.json new file mode 100644 index 0000000000000000000000000000000000000000..d36a8a7eccdae8ab584b1cf9b762016fd4882812 --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/drifting_naturalness_results.json @@ -0,0 +1,27 @@ +{ + "metric": "drifting_naturalness", + "description": "Start-end contrast of naturalness (first/last 15% frames)", + "average_drift_score": 0.0, + "num_videos": 2, + "model_name": "gpt-5.2-2025-12-11", + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "drift_naturalness_score": 0.0, + "start_naturalness_score": 0.0, + "end_naturalness_score": 0.0, + "start_raw_score": "1", + "end_raw_score": "1" + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "drift_naturalness_score": 0.0, + "start_naturalness_score": 0.75, + "end_naturalness_score": 0.75, + "start_raw_score": "4", + "end_raw_score": "4" + } + ] +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/drifting_semantic_results.json b/Helios/eval_moviebench/playground/results/toy-video/drifting_semantic_results.json new file mode 100644 index 0000000000000000000000000000000000000000..84cb138ed4cfafa00bbcadb2e4f0cf238f798448 --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/drifting_semantic_results.json @@ -0,0 +1,24 @@ +{ + "metric": "drifting_semantic", + "description": "Start-end contrast of semantic consistency (first/last 15% frames)", + "average_drift_score": 0.006637156009674072, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "prompt": "A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity.", + "drift_semantic_score": 0.0044051408767700195, + "start_semantic_score": 0.2939550578594208, + "end_semantic_score": 0.2983601987361908 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "prompt": "An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man.", + "drift_semantic_score": 0.008869171142578125, + "start_semantic_score": 0.2703956365585327, + "end_semantic_score": 0.2615264654159546 + } + ] +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/merged_results.json b/Helios/eval_moviebench/playground/results/toy-video/merged_results.json new file mode 100644 index 0000000000000000000000000000000000000000..1c62e1a2796f06ccb95f6417c53ad2f83fa12f81 --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/merged_results.json @@ -0,0 +1,74 @@ +{ + "rating_scale": 10, + "summary": { + "non_drifting": { + "aesthetic": { + "name": "Aesthetic", + "raw_score": 0.6564263701438904, + "normalized_score": 0.6564263701438904, + "rating": 9, + "num_videos": 2 + }, + "motion_amplitude": { + "name": "Motion Amplitude", + "raw_score": 0.12899818271398544, + "normalized_score": 0.12899818271398544, + "rating": 3, + "num_videos": 2 + }, + "motion_smoothness": { + "name": "Motion Smoothness", + "raw_score": 0.9922347277689807, + "normalized_score": 0.9922347277689807, + "rating": 10, + "num_videos": 2 + }, + "naturalness": { + "name": "Naturalness", + "raw_score": 0.5, + "normalized_score": 0.5, + "rating": 7, + "num_videos": 2 + }, + "semantic": { + "name": "Semantic", + "raw_score": 0.2817579507827759, + "normalized_score": 0.2817579507827759, + "rating": 8, + "num_videos": 2 + } + }, + "drifting": { + "drifting_aesthetic": { + "name": "Drifting Aesthetic", + "raw_score": 0.027865678071975708, + "normalized_score": 0.027865678071975708, + "rating": 8, + "num_videos": 2 + }, + "drifting_motion_smoothness": { + "name": "Drifting Motion Smoothness", + "raw_score": 0.0009624073235373065, + "normalized_score": 0.0009624073235373065, + "rating": 10, + "num_videos": 2 + }, + "drifting_naturalness": { + "name": "Drifting Naturalness", + "raw_score": 0.0, + "normalized_score": 0.0, + "rating": 10, + "num_videos": 2 + }, + "drifting_semantic": { + "name": "Drifting Semantic", + "raw_score": 0.006637156009674072, + "normalized_score": 0.006637156009674072, + "rating": 10, + "num_videos": 2 + } + }, + "total_weighted_rating": 8.247 + }, + "per_video": {} +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/motion_amplitude_results.json b/Helios/eval_moviebench/playground/results/toy-video/motion_amplitude_results.json new file mode 100644 index 0000000000000000000000000000000000000000..8b701beb32e0ab3a5e68e81e74c03399a73d0adf --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/motion_amplitude_results.json @@ -0,0 +1,17 @@ +{ + "metric": "motion_fb", + "average_score": 0.12899818271398544, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "motion_fb": 0.19912056624889374 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "motion_fb": 0.05887579917907715 + } + ] +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/motion_smoothness_results.json b/Helios/eval_moviebench/playground/results/toy-video/motion_smoothness_results.json new file mode 100644 index 0000000000000000000000000000000000000000..b93bbfe7df38a3ee9b1f2303dcb3088b9d98c8bd --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/motion_smoothness_results.json @@ -0,0 +1,17 @@ +{ + "metric": "motion_smoothness", + "average_score": 0.9922347277689807, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "motion_smoothness_score": 0.9896801291593404 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "motion_smoothness_score": 0.9947893263786209 + } + ] +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/naturalness_results.json b/Helios/eval_moviebench/playground/results/toy-video/naturalness_results.json new file mode 100644 index 0000000000000000000000000000000000000000..8fdfc668e72eda738a55d926c366e156e5eaa627 --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/naturalness_results.json @@ -0,0 +1,21 @@ +{ + "metric": "naturalness", + "average_score": 0.5, + "num_videos": 2, + "model_name": "gpt-5.2-2025-12-11", + "num_frames_per_video": 16, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "naturalness_score": 0.25, + "raw_score": "2" + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "naturalness_score": 0.75, + "raw_score": "4" + } + ] +} \ No newline at end of file diff --git a/Helios/eval_moviebench/playground/results/toy-video/semantic_results.json b/Helios/eval_moviebench/playground/results/toy-video/semantic_results.json new file mode 100644 index 0000000000000000000000000000000000000000..39dc928ed3dea09c0b1b8e6830094237f5e9f089 --- /dev/null +++ b/Helios/eval_moviebench/playground/results/toy-video/semantic_results.json @@ -0,0 +1,19 @@ +{ + "metric": "semantic", + "average_score": 0.2817579507827759, + "num_videos": 2, + "per_video_results": [ + { + "id": 2, + "video_name": "2_240_ori81.mp4", + "prompt": "A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity.", + "semantic_score": 0.29471662640571594 + }, + { + "id": 239, + "video_name": "239_120_ori129.mp4", + "prompt": "An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man.", + "semantic_score": 0.2687992751598358 + } + ] +} \ No newline at end of file diff --git a/Helios/eval_moviebench/utils/convert_json_to_excel.py b/Helios/eval_moviebench/utils/convert_json_to_excel.py new file mode 100644 index 0000000000000000000000000000000000000000..ccde57bcead51bd544c8d429ead41c0725af6d62 --- /dev/null +++ b/Helios/eval_moviebench/utils/convert_json_to_excel.py @@ -0,0 +1,136 @@ +import argparse +import json + +import pandas as pd + + +CUSTOM_ORDER = [ + "total_weighted_rating", + "aesthetic", + "motion_amplitude", + "motion_smoothness", + "semantic", + "naturalness", + "drifting_aesthetic", + "drifting_motion_smoothness", + "drifting_semantic", + "drifting_naturalness", +] + +SELECTED_METRICS = [ + "total_weighted_rating", + "aesthetic", + "motion_amplitude", + "motion_smoothness", + "semantic", + "naturalness", +] + + +def json_to_excel(json_path, excel_path=None, use_selected_metrics=False, show_raw_values=False, score_type=""): + with open(json_path, "r") as f: + data = json.load(f) + + models_data = data["models"] + df = pd.DataFrame.from_dict(models_data, orient="index") + + df.reset_index(inplace=True) + df.rename(columns={"index": "model_name"}, inplace=True) + + if use_selected_metrics: + available_cols = ["model_name"] + [col for col in SELECTED_METRICS if col in df.columns] + df = df[available_cols] + print(f"Selected {len(available_cols) - 1} metrics from available metrics") + + valid_order = ["model_name"] + [col for col in CUSTOM_ORDER if col in df.columns] + df = df[valid_order] + print(f"Kept {len(valid_order) - 1} metrics as specified in CUSTOM_ORDER") + + if excel_path is None: + excel_path = json_path.rsplit(".", 1)[0] + f"_{score_type}" + ".xlsx" + + with pd.ExcelWriter(excel_path, engine="openpyxl") as writer: + df.to_excel(writer, sheet_name="Models", index=False) + + metadata = pd.DataFrame( + { + "Property": ["timestamp", "num_models", "num_metrics", "filtered", "format"], + "Value": [ + data.get("timestamp", "N/A"), + data.get("num_models", len(models_data)), + len(df.columns) - 1, + "Yes" if use_selected_metrics else "No", + "Raw Values" if show_raw_values else "Percentage", + ], + } + ) + metadata.to_excel(writer, sheet_name="Metadata", index=False) + + worksheet = writer.sheets["Models"] + for idx, col in enumerate(df.columns): + max_length = max(df[col].astype(str).apply(len).max(), len(col)) + if idx < 26: + col_letter = chr(65 + idx) + else: + col_letter = chr(65 + idx // 26 - 1) + chr(65 + idx % 26) + worksheet.column_dimensions[col_letter].width = min(max_length + 2, 50) + + if col != "model_name" and pd.api.types.is_numeric_dtype(df[col]): + for row in range(2, len(df) + 2): # Start from row 2 (after header) + cell = worksheet[f"{col_letter}{row}"] + if cell.value is not None: + if col == "total_weighted_rating": + cell.number_format = "0.00" + elif show_raw_values: + cell.number_format = "0" + else: + cell.value = cell.value * 100 + cell.number_format = '0.00"%"' + + print(f"Conversion successful! Output file: {excel_path}") + print(f"Processed {len(df)} models with {len(df.columns) - 1} metrics") + print(f"Format: {'Raw values' if show_raw_values else 'Percentage'}") + + return excel_path + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + parser.add_argument("--json_file", type=str, required=True, help="Input JSON file path") + parser.add_argument( + "--excel_file", + type=str, + required=True, + help="Output Excel file path (optional, defaults to input filename.xlsx)", + ) + parser.add_argument("--filter", action="store_true", help="Use only metrics defined in SELECTED_METRICS list") + parser.add_argument( + "--score_type", + type=str, + choices=["raw", "normalized", "rating"], + default="rating", + help="Type of scores to use: 'raw', 'normalized', or 'rating'", + ) + + args = parser.parse_args() + + if args.score_type == "rating": + raw_value = True + else: + raw_value = False + + try: + json_to_excel( + args.json_file, + args.excel_file, + use_selected_metrics=args.filter, + show_raw_values=raw_value, + score_type=args.score_type, + ) + except FileNotFoundError: + print(f"Error: File not found {args.json_file}") + except json.JSONDecodeError: + print(f"Error: {args.json_file} is not a valid JSON file") + except Exception as e: + print(f"Error: {e}") diff --git a/Helios/eval_moviebench/utils/extract_short_from_long.py b/Helios/eval_moviebench/utils/extract_short_from_long.py new file mode 100644 index 0000000000000000000000000000000000000000..74ee4eb755721ed98e0c6c27a769e58bb8ac1ec3 --- /dev/null +++ b/Helios/eval_moviebench/utils/extract_short_from_long.py @@ -0,0 +1,97 @@ +import argparse +import os +import subprocess +from pathlib import Path + + +def extract_first_n_frames(input_root, output_root, num_frames=81): + input_path = Path(input_root) + output_path = Path(output_root) + + for subfolder in input_path.iterdir(): + if not subfolder.is_dir(): + continue + + print(f"Processing folder: {subfolder.name}") + + output_subfolder = output_path / subfolder.name + output_subfolder.mkdir(parents=True, exist_ok=True) + + video_files = list(subfolder.glob("*.mp4")) + + for i, video_file in enumerate(video_files, 1): + original_name = video_file.stem + if "_ori" in original_name: + new_name = original_name.rsplit("_ori", 1)[0] + f"_ori{num_frames}.mp4" + else: + new_name = video_file.name + + output_file = output_subfolder / new_name + if os.path.exists(output_file): + print(f"Skipping existing file: {output_file}") + continue + + cmd = [ + "ffmpeg", + "-i", + str(video_file), + "-vframes", + str(num_frames), # Extract only first N frames + "-map", + "0", # Copy all streams (video + audio) + "-c", + "copy", # Try direct copy (fastest, preserves all parameters) + "-y", + str(output_file), + ] + + try: + result = subprocess.run(cmd, capture_output=True) + + if result.returncode != 0: + print(f" Direct copy failed for {video_file.name}, re-encoding...") + cmd = [ + "ffmpeg", + "-i", + str(video_file), + "-vframes", + str(num_frames), + "-c:v", + "libx264", # Re-encode video + "-qp", + "0", # Lossless quality + "-c:a", + "copy", # Copy audio directly + "-map", + "0", # Copy all streams + "-y", + str(output_file), + ] + subprocess.run(cmd, check=True, capture_output=True) + + print(f" [{i}/{len(video_files)}] {video_file.name} -> {new_name}") + except subprocess.CalledProcessError as e: + print(f" Error processing {video_file.name}: {e}") + continue + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Extract first N frames from videos") + parser.add_argument( + "--input", + type=str, + default="long", + help="Input root directory (default: current directory)", + ) + parser.add_argument( + "--output", + type=str, + default="short/0_from_long", + help="Output root directory (default: ./output_frames)", + ) + parser.add_argument("--frames", type=int, default=81, help="Number of frames to extract (default: 81)") + + args = parser.parse_args() + + extract_first_n_frames(args.input, args.output, args.frames) + print("\nDone!") diff --git a/Helios/eval_moviebench/utils/third_party/ViCLIP/__init__.py b/Helios/eval_moviebench/utils/third_party/ViCLIP/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/ViCLIP/simple_tokenizer.py b/Helios/eval_moviebench/utils/third_party/ViCLIP/simple_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..b705017efb1bdb4818db44604b4bb4197c76cd60 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/ViCLIP/simple_tokenizer.py @@ -0,0 +1,147 @@ +import gzip +import html +import os +import subprocess +from functools import lru_cache + +import ftfy +import regex as re + + +def default_bpe(): + tokenizer_file = os.path.join("checkpoints", "ViCLIP/bpe_simple_vocab_16e6.txt.gz") + if not os.path.exists(tokenizer_file): + print(f"Downloading ViCLIP tokenizer to {tokenizer_file}") + wget_command = [ + "wget", + "https://raw.githubusercontent.com/openai/CLIP/main/clip/bpe_simple_vocab_16e6.txt.gz", + "-P", + os.path.dirname(tokenizer_file), + ] + subprocess.run(wget_command) + return tokenizer_file + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = ( + list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) + ) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8 + n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r"\s+", " ", text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe()): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split("\n") + merges = merges[1 : 49152 - 256 - 2 + 1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v + "" for v in vocab] + for merge in merges: + vocab.append("".join(merge)) + vocab.extend(["<|startoftext|>", "<|endoftext|>"]) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {"<|startoftext|>": "<|startoftext|>", "<|endoftext|>": "<|endoftext|>"} + self.pat = re.compile( + r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", + re.IGNORECASE, + ) + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + (token[-1] + "",) + pairs = get_pairs(word) + + if not pairs: + return token + "" + + while True: + bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except Exception: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word) - 1 and word[i + 1] == second: + new_word.append(first + second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = " ".join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = "".join(self.byte_encoder[b] for b in token.encode("utf-8")) + bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")) + return bpe_tokens + + def decode(self, tokens): + text = "".join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors="replace").replace("", " ") + return text diff --git a/Helios/eval_moviebench/utils/third_party/ViCLIP/viclip.py b/Helios/eval_moviebench/utils/third_party/ViCLIP/viclip.py new file mode 100644 index 0000000000000000000000000000000000000000..835fdbf59c2172442a99b98e20a8cb89d5911342 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/ViCLIP/viclip.py @@ -0,0 +1,216 @@ +import logging +import os + +import torch +from torch import nn + +from .simple_tokenizer import SimpleTokenizer as _Tokenizer +from .viclip_text import clip_text_l14 +from .viclip_vision import clip_joint_l14 + + +logger = logging.getLogger(__name__) + + +class ViCLIP(nn.Module): + """docstring for ViCLIP""" + + def __init__( + self, + tokenizer=None, + pretrain=os.path.join(os.path.dirname(os.path.abspath(__file__)), "ViClip-InternVid-10M-FLT.pth"), + freeze_text=True, + ): + super(ViCLIP, self).__init__() + if tokenizer: + self.tokenizer = tokenizer + else: + self.tokenizer = _Tokenizer() + self.max_txt_l = 32 + + self.vision_encoder_name = "vit_l14" + + self.vision_encoder_pretrained = False + self.inputs_image_res = 224 + self.vision_encoder_kernel_size = 1 + self.vision_encoder_center = True + self.video_input_num_frames = 8 + self.vision_encoder_drop_path_rate = 0.1 + self.vision_encoder_checkpoint_num = 24 + self.is_pretrain = pretrain + self.vision_width = 1024 + self.text_width = 768 + self.embed_dim = 768 + self.masking_prob = 0.9 + + self.text_encoder_name = "vit_l14" + self.text_encoder_pretrained = False #'bert-base-uncased' + self.text_encoder_d_model = 768 + + self.text_encoder_vocab_size = 49408 + + # create modules. + self.vision_encoder = self.build_vision_encoder() + self.text_encoder = self.build_text_encoder() + + self.temp = nn.parameter.Parameter(torch.ones([]) * 1 / 100.0) + self.temp_min = 1 / 100.0 + + if pretrain: + logger.info(f"Load pretrained weights from {pretrain}") + state_dict = torch.load(pretrain, map_location="cpu", weights_only=False)["model"] + self.load_state_dict(state_dict) + + # Freeze weights + if freeze_text: + self.freeze_text() + + def freeze_text(self): + """freeze text encoder""" + for p in self.text_encoder.parameters(): + p.requires_grad = False + + def no_weight_decay(self): + ret = {"temp"} + ret.update({"vision_encoder." + k for k in self.vision_encoder.no_weight_decay()}) + ret.update({"text_encoder." + k for k in self.text_encoder.no_weight_decay()}) + + return ret + + def forward(self, image, text, raw_text, idx, log_generation=None, return_sims=False): + """forward and calculate loss. + + Args: + image (torch.Tensor): The input images. Shape: [B,T,C,H,W]. + text (dict): TODO + idx (torch.Tensor): TODO + + Returns: TODO + + """ + self.clip_contrastive_temperature() + + vision_embeds = self.encode_vision(image) + text_embeds = self.encode_text(raw_text) + if return_sims: + sims = torch.nn.functional.normalize(vision_embeds, dim=-1) @ torch.nn.functional.normalize( + text_embeds, dim=-1 + ).transpose(0, 1) + return sims + + # calculate loss + + ## VTC loss + loss_vtc = self.clip_loss.vtc_loss(vision_embeds, text_embeds, idx, self.temp, all_gather=True) + + return { + "loss_vtc": loss_vtc, + } + + def encode_vision(self, image, test=False): + """encode image / videos as features. + + Args: + image (torch.Tensor): The input images. + test (bool): Whether testing. + + Returns: tuple. + - vision_embeds (torch.Tensor): The features of all patches. Shape: [B,T,L,C]. + - pooled_vision_embeds (torch.Tensor): The pooled features. Shape: [B,T,C]. + + """ + if image.ndim == 5: + image = image.permute(0, 2, 1, 3, 4).contiguous() + else: + image = image.unsqueeze(2) + + if not test and self.masking_prob > 0.0: + return self.vision_encoder(image, masking_prob=self.masking_prob) + + return self.vision_encoder(image) + + def encode_text(self, text): + """encode text. + Args: + text (dict): The output of huggingface's `PreTrainedTokenizer`. contains keys: + - input_ids (torch.Tensor): Token ids to be fed to a model. Shape: [B,L]. + - attention_mask (torch.Tensor): The mask indicate padded tokens. Shape: [B,L]. 0 is padded token. + - other keys refer to "https://huggingface.co/docs/transformers/v4.21.2/en/main_classes/tokenizer#transformers.PreTrainedTokenizer.__call__". + Returns: tuple. + - text_embeds (torch.Tensor): The features of all tokens. Shape: [B,L,C]. + - pooled_text_embeds (torch.Tensor): The pooled features. Shape: [B,C]. + + """ + device = next(self.text_encoder.parameters()).device + text = self.text_encoder.tokenize(text, context_length=self.max_txt_l).to(device) + text_embeds = self.text_encoder(text) + return text_embeds + + @torch.no_grad() + def clip_contrastive_temperature(self, min_val=0.001, max_val=0.5): + """Seems only used during pre-training""" + self.temp.clamp_(min=self.temp_min) + + def build_vision_encoder(self): + """build vision encoder + Returns: (vision_encoder, vision_layernorm). Each is a `nn.Module`. + + """ + encoder_name = self.vision_encoder_name + if encoder_name != "vit_l14": + raise ValueError(f"Not implemented: {encoder_name}") + vision_encoder = clip_joint_l14( + pretrained=self.vision_encoder_pretrained, + input_resolution=self.inputs_image_res, + kernel_size=self.vision_encoder_kernel_size, + center=self.vision_encoder_center, + num_frames=self.video_input_num_frames, + drop_path=self.vision_encoder_drop_path_rate, + checkpoint_num=self.vision_encoder_checkpoint_num, + ) + return vision_encoder + + def build_text_encoder(self): + """build text_encoder and possiblly video-to-text multimodal fusion encoder. + Returns: nn.Module. The text encoder + + """ + encoder_name = self.text_encoder_name + if encoder_name != "vit_l14": + raise ValueError(f"Not implemented: {encoder_name}") + text_encoder = clip_text_l14( + pretrained=self.text_encoder_pretrained, + embed_dim=self.text_encoder_d_model, + context_length=self.max_txt_l, + vocab_size=self.text_encoder_vocab_size, + checkpoint_num=0, + ) + + return text_encoder + + def get_text_encoder(self): + """get text encoder, used for text and cross-modal encoding""" + encoder = self.text_encoder + return encoder.bert if hasattr(encoder, "bert") else encoder + + def get_text_features(self, input_text, tokenizer, text_feature_dict={}): + if input_text in text_feature_dict: + return text_feature_dict[input_text] + text_template = f"{input_text}" + with torch.no_grad(): + # text_token = tokenizer.encode(text_template).cuda() + text_features = self.encode_text(text_template).float() + text_features /= text_features.norm(dim=-1, keepdim=True) + text_feature_dict[input_text] = text_features + return text_features + + def get_vid_features(self, input_frames): + with torch.no_grad(): + clip_feat = self.encode_vision(input_frames, test=True).float() + clip_feat /= clip_feat.norm(dim=-1, keepdim=True) + return clip_feat + + def get_predict_label(self, clip_feature, text_feats_tensor, top=5): + label_probs = (100.0 * clip_feature @ text_feats_tensor.T).softmax(dim=-1) + top_probs, top_labels = label_probs.cpu().topk(top, dim=-1) + return top_probs, top_labels diff --git a/Helios/eval_moviebench/utils/third_party/ViCLIP/viclip_text.py b/Helios/eval_moviebench/utils/third_party/ViCLIP/viclip_text.py new file mode 100644 index 0000000000000000000000000000000000000000..9aed79c9f2d5ecb8022cb1608ca988a88ad3a28d --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/ViCLIP/viclip_text.py @@ -0,0 +1,260 @@ +import functools +import logging +import os +from collections import OrderedDict + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +from pkg_resources import packaging +from torch import nn + +from .simple_tokenizer import SimpleTokenizer as _Tokenizer + + +logger = logging.getLogger(__name__) + + +MODEL_PATH = "https://huggingface.co/laion/CLIP-ViT-L-14-DataComp.XL-s13B-b90K" +_MODELS = { + "ViT-L/14": os.path.join(MODEL_PATH, "vit_l14_text.pth"), +} + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16.""" + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + ret = super().forward(x.type(torch.float32)) + return ret.type(orig_type) + + +class QuickGELU(nn.Module): + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class ResidualAttentionBlock(nn.Module): + def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): + super().__init__() + + self.attn = nn.MultiheadAttention(d_model, n_head) + self.ln_1 = LayerNorm(d_model) + self.mlp = nn.Sequential( + OrderedDict( + [ + ("c_fc", nn.Linear(d_model, d_model * 4)), + ("gelu", QuickGELU()), + ("c_proj", nn.Linear(d_model * 4, d_model)), + ] + ) + ) + self.ln_2 = LayerNorm(d_model) + self.attn_mask = attn_mask + + def attention(self, x: torch.Tensor): + self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None + return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] + + def forward(self, x: torch.Tensor): + x = x + self.attention(self.ln_1(x)) + x = x + self.mlp(self.ln_2(x)) + return x + + +class Transformer(nn.Module): + def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None, checkpoint_num: int = 0): + super().__init__() + self.width = width + self.layers = layers + self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) + + self.checkpoint_num = checkpoint_num + + def forward(self, x: torch.Tensor): + if self.checkpoint_num > 0: + segments = min(self.checkpoint_num, len(self.resblocks)) + return checkpoint.checkpoint_sequential(self.resblocks, segments, x) + else: + return self.resblocks(x) + + +class CLIP_TEXT(nn.Module): + def __init__( + self, + embed_dim: int, + context_length: int, + vocab_size: int, + transformer_width: int, + transformer_heads: int, + transformer_layers: int, + checkpoint_num: int, + ): + super().__init__() + + self.context_length = context_length + self._tokenizer = _Tokenizer() + + self.transformer = Transformer( + width=transformer_width, + layers=transformer_layers, + heads=transformer_heads, + attn_mask=self.build_attention_mask(), + checkpoint_num=checkpoint_num, + ) + + self.vocab_size = vocab_size + self.token_embedding = nn.Embedding(vocab_size, transformer_width) + self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) + self.ln_final = LayerNorm(transformer_width) + + self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) + + def no_weight_decay(self): + return {"token_embedding", "positional_embedding"} + + @functools.lru_cache(maxsize=None) + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.context_length, self.context_length) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def tokenize(self, texts, context_length=77, truncate=True): + """ + Returns the tokenized representation of given input string(s) + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + truncate: bool + Whether to truncate the text in case its encoding is longer than the context length + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]. + We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long. + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = self._tokenizer.encoder["<|startoftext|>"] + eot_token = self._tokenizer.encoder["<|endoftext|>"] + all_tokens = [[sot_token] + self._tokenizer.encode(text) + [eot_token] for text in texts] + if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"): + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + else: + result = torch.zeros(len(all_tokens), context_length, dtype=torch.int) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + if truncate: + tokens = tokens[:context_length] + tokens[-1] = eot_token + else: + raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") + result[i, : len(tokens)] = torch.tensor(tokens) + + return result + + def forward(self, text): + x = self.token_embedding(text) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + + return x + + +def clip_text_b16( + embed_dim=512, + context_length=77, + vocab_size=49408, + transformer_width=512, + transformer_heads=8, + transformer_layers=12, +): + raise NotImplementedError + model = CLIP_TEXT(embed_dim, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers) + pretrained = _MODELS["ViT-B/16"] + logger.info(f"Load pretrained weights from {pretrained}") + state_dict = torch.load(pretrained, map_location="cpu") + model.load_state_dict(state_dict, strict=False) + return model.eval() + + +def clip_text_l14( + embed_dim=768, + context_length=77, + vocab_size=49408, + transformer_width=768, + transformer_heads=12, + transformer_layers=12, + checkpoint_num=0, + pretrained=True, +): + model = CLIP_TEXT( + embed_dim, + context_length, + vocab_size, + transformer_width, + transformer_heads, + transformer_layers, + checkpoint_num, + ) + if pretrained: + if isinstance(pretrained, str) and pretrained != "bert-base-uncased": + pretrained = _MODELS[pretrained] + else: + pretrained = _MODELS["ViT-L/14"] + logger.info(f"Load pretrained weights from {pretrained}") + state_dict = torch.load(pretrained, map_location="cpu") + if context_length != state_dict["positional_embedding"].size(0): + # assert context_length < state_dict["positional_embedding"].size(0), "Cannot increase context length." + print(f"Resize positional embedding from {state_dict['positional_embedding'].size(0)} to {context_length}") + if context_length < state_dict["positional_embedding"].size(0): + state_dict["positional_embedding"] = state_dict["positional_embedding"][:context_length] + else: + state_dict["positional_embedding"] = F.pad( + state_dict["positional_embedding"], + (0, 0, 0, context_length - state_dict["positional_embedding"].size(0)), + value=0, + ) + + message = model.load_state_dict(state_dict, strict=False) + print(f"Load pretrained weights from {pretrained}: {message}") + return model.eval() + + +def clip_text_l14_336( + embed_dim=768, + context_length=77, + vocab_size=49408, + transformer_width=768, + transformer_heads=12, + transformer_layers=12, +): + raise NotImplementedError + model = CLIP_TEXT(embed_dim, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers) + pretrained = _MODELS["ViT-L/14_336"] + logger.info(f"Load pretrained weights from {pretrained}") + state_dict = torch.load(pretrained, map_location="cpu") + model.load_state_dict(state_dict, strict=False) + return model.eval() + + +def build_clip(config): + model_cls = config.text_encoder.clip_teacher + model = eval(model_cls)() + return model diff --git a/Helios/eval_moviebench/utils/third_party/ViCLIP/viclip_vision.py b/Helios/eval_moviebench/utils/third_party/ViCLIP/viclip_vision.py new file mode 100644 index 0000000000000000000000000000000000000000..20eabbf3038947c2fd80690c0ea650349743ee3e --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/ViCLIP/viclip_vision.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python +import logging +import os +from collections import OrderedDict + +import torch +import torch.utils.checkpoint as checkpoint +from einops import rearrange +from timm.layers import DropPath +from timm.models import register_model +from torch import nn + + +logger = logging.getLogger(__name__) + + +def load_temp_embed_with_mismatch(temp_embed_old, temp_embed_new, add_zero=True): + """ + Add/Remove extra temporal_embeddings as needed. + https://arxiv.org/abs/2104.00650 shows adding zero paddings works. + + temp_embed_old: (1, num_frames_old, 1, d) + temp_embed_new: (1, num_frames_new, 1, d) + add_zero: bool, if True, add zero, else, interpolate trained embeddings. + """ + # TODO zero pad + num_frms_new = temp_embed_new.shape[1] + num_frms_old = temp_embed_old.shape[1] + logger.info(f"Load temporal_embeddings, lengths: {num_frms_old}-->{num_frms_new}") + if num_frms_new > num_frms_old: + if add_zero: + temp_embed_new[:, :num_frms_old] = temp_embed_old # untrained embeddings are zeros. + else: + pass + # temp_embed_new = interpolate_temporal_pos_embed(temp_embed_old, num_frms_new) + elif num_frms_new < num_frms_old: + temp_embed_new = temp_embed_old[:, :num_frms_new] + else: # = + temp_embed_new = temp_embed_old + return temp_embed_new + + +MODEL_PATH = "https://pjlab-gvm-data.oss-cn-shanghai.aliyuncs.com/internvideo/viclip/" +_MODELS = { + "ViT-L/14": os.path.join(MODEL_PATH, "ViClip-InternVid-10M-FLT.pth"), +} + + +class QuickGELU(nn.Module): + def forward(self, x): + return x * torch.sigmoid(1.702 * x) + + +class ResidualAttentionBlock(nn.Module): + def __init__(self, d_model, n_head, drop_path=0.0, attn_mask=None, dropout=0.0): + super().__init__() + + self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.attn = nn.MultiheadAttention(d_model, n_head, dropout=dropout) + self.ln_1 = nn.LayerNorm(d_model) + self.mlp = nn.Sequential( + OrderedDict( + [ + ("c_fc", nn.Linear(d_model, d_model * 4)), + ("gelu", QuickGELU()), + ("drop1", nn.Dropout(dropout)), + ("c_proj", nn.Linear(d_model * 4, d_model)), + ("drop2", nn.Dropout(dropout)), + ] + ) + ) + self.ln_2 = nn.LayerNorm(d_model) + self.attn_mask = attn_mask + + def attention(self, x): + self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None + return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] + + def forward(self, x): + x = x + self.drop_path1(self.attention(self.ln_1(x))) + x = x + self.drop_path2(self.mlp(self.ln_2(x))) + return x + + +class Transformer(nn.Module): + def __init__(self, width, layers, heads, drop_path=0.0, checkpoint_num=0, dropout=0.0): + super().__init__() + dpr = [x.item() for x in torch.linspace(0, drop_path, layers)] + self.resblocks = nn.ModuleList() + for idx in range(layers): + self.resblocks.append(ResidualAttentionBlock(width, heads, drop_path=dpr[idx], dropout=dropout)) + self.checkpoint_num = checkpoint_num + + def forward(self, x): + for idx, blk in enumerate(self.resblocks): + if idx < self.checkpoint_num: + x = checkpoint.checkpoint(blk, x, use_reentrant=False) + else: + x = blk(x) + return x + + +class VisionTransformer(nn.Module): + def __init__( + self, + input_resolution, + patch_size, + width, + layers, + heads, + output_dim=None, + kernel_size=1, + num_frames=8, + drop_path=0, + checkpoint_num=0, + dropout=0.0, + temp_embed=True, + ): + super().__init__() + self.output_dim = output_dim + self.conv1 = nn.Conv3d( + 3, + width, + (kernel_size, patch_size, patch_size), + (kernel_size, patch_size, patch_size), + (0, 0, 0), + bias=False, + ) + + scale = width**-0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) + self.ln_pre = nn.LayerNorm(width) + if temp_embed: + self.temporal_positional_embedding = nn.Parameter(torch.zeros(1, num_frames, width)) + + self.transformer = Transformer( + width, layers, heads, drop_path=drop_path, checkpoint_num=checkpoint_num, dropout=dropout + ) + + self.ln_post = nn.LayerNorm(width) + if output_dim is not None: + self.proj = nn.Parameter(torch.empty(width, output_dim)) + else: + self.proj = None + + self.dropout = nn.Dropout(dropout) + + def get_num_layers(self): + return len(self.transformer.resblocks) + + @torch.jit.ignore + def no_weight_decay(self): + return {"positional_embedding", "class_embedding", "temporal_positional_embedding"} + + def mask_tokens(self, inputs, masking_prob=0.0): + B, L, _ = inputs.shape + + # This is different from text as we are masking a fix number of tokens + Lm = int(masking_prob * L) + masked_indices = torch.zeros(B, L) + indices = torch.argsort(torch.rand_like(masked_indices), dim=-1)[:, :Lm] + batch_indices = torch.arange(masked_indices.shape[0]).unsqueeze(-1).expand_as(indices) + masked_indices[batch_indices, indices] = 1 + + masked_indices = masked_indices.bool() + + return inputs[~masked_indices].reshape(B, -1, inputs.shape[-1]) + + def forward(self, x, masking_prob=0.0): + x = self.conv1(x) # shape = [*, width, grid, grid] + B, C, T, H, W = x.shape + x = x.permute(0, 2, 3, 4, 1).reshape(B * T, H * W, C) + + x = torch.cat( + [ + self.class_embedding.to(x.dtype) + + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), + x, + ], + dim=1, + ) # shape = [*, grid ** 2 + 1, width] + x = x + self.positional_embedding.to(x.dtype) + + # temporal pos + cls_tokens = x[:B, :1, :] + x = x[:, 1:] + x = rearrange(x, "(b t) n m -> (b n) t m", b=B, t=T) + if hasattr(self, "temporal_positional_embedding"): + if x.size(1) == 1: + # This is a workaround for unused parameter issue + x = x + self.temporal_positional_embedding.mean(1) + else: + x = x + self.temporal_positional_embedding + x = rearrange(x, "(b n) t m -> b (n t) m", b=B, t=T) + + if masking_prob > 0.0: + x = self.mask_tokens(x, masking_prob) + + x = torch.cat((cls_tokens, x), dim=1) + + x = self.ln_pre(x) + + x = x.permute(1, 0, 2) # BND -> NBD + x = self.transformer(x) + + x = self.ln_post(x) + + if self.proj is not None: + x = self.dropout(x[0]) @ self.proj + else: + x = x.permute(1, 0, 2) # NBD -> BND + + return x + + +def inflate_weight(weight_2d, time_dim, center=True): + logger.info(f"Init center: {center}") + if center: + weight_3d = torch.zeros(*weight_2d.shape) + weight_3d = weight_3d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1) + middle_idx = time_dim // 2 + weight_3d[:, :, middle_idx, :, :] = weight_2d + else: + weight_3d = weight_2d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1) + weight_3d = weight_3d / time_dim + return weight_3d + + +def load_state_dict(model, state_dict, input_resolution=224, patch_size=16, center=True): + state_dict_3d = model.state_dict() + for k in state_dict.keys(): + if k in state_dict_3d.keys() and state_dict[k].shape != state_dict_3d[k].shape: + if len(state_dict_3d[k].shape) <= 2: + logger.info(f"Ignore: {k}") + continue + logger.info(f"Inflate: {k}, {state_dict[k].shape} => {state_dict_3d[k].shape}") + time_dim = state_dict_3d[k].shape[2] + state_dict[k] = inflate_weight(state_dict[k], time_dim, center=center) + + pos_embed_checkpoint = state_dict["positional_embedding"] + embedding_size = pos_embed_checkpoint.shape[-1] + num_patches = (input_resolution // patch_size) ** 2 + orig_size = int((pos_embed_checkpoint.shape[-2] - 1) ** 0.5) + new_size = int(num_patches**0.5) + if orig_size != new_size: + logger.info(f"Pos_emb from {orig_size} to {new_size}") + extra_tokens = pos_embed_checkpoint[:1] + pos_tokens = pos_embed_checkpoint[1:] + pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) + pos_tokens = torch.nn.functional.interpolate( + pos_tokens, size=(new_size, new_size), mode="bicubic", align_corners=False + ) + pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(0, 2) + new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=0) + state_dict["positional_embedding"] = new_pos_embed + + message = model.load_state_dict(state_dict, strict=False) + logger.info(f"Load pretrained weights: {message}") + + +@register_model +def clip_joint_b16(pretrained=True, input_resolution=224, kernel_size=1, center=True, num_frames=8, drop_path=0.0): + model = VisionTransformer( + input_resolution=input_resolution, + patch_size=16, + width=768, + layers=12, + heads=12, + output_dim=512, + kernel_size=kernel_size, + num_frames=num_frames, + drop_path=drop_path, + ) + raise NotImplementedError + if pretrained: + logger.info("load pretrained weights") + state_dict = torch.load(_MODELS["ViT-B/16"], map_location="cpu") + load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=16, center=center) + return model.eval() + + +@register_model +def clip_joint_l14( + pretrained=False, + input_resolution=224, + kernel_size=1, + center=True, + num_frames=8, + drop_path=0.0, + checkpoint_num=0, + dropout=0.0, +): + model = VisionTransformer( + input_resolution=input_resolution, + patch_size=14, + width=1024, + layers=24, + heads=16, + output_dim=768, + kernel_size=kernel_size, + num_frames=num_frames, + drop_path=drop_path, + checkpoint_num=checkpoint_num, + dropout=dropout, + ) + if pretrained: + if isinstance(pretrained, str): + model_name = pretrained + else: + model_name = "ViT-L/14" + logger.info("load pretrained weights") + state_dict = torch.load(_MODELS[model_name], map_location="cpu") + load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=14, center=center) + return model.eval() + + +@register_model +def clip_joint_l14_336(pretrained=True, input_resolution=336, kernel_size=1, center=True, num_frames=8, drop_path=0.0): + raise NotImplementedError + model = VisionTransformer( + input_resolution=input_resolution, + patch_size=14, + width=1024, + layers=24, + heads=16, + output_dim=768, + kernel_size=kernel_size, + num_frames=num_frames, + drop_path=drop_path, + ) + if pretrained: + logger.info("load pretrained weights") + state_dict = torch.load(_MODELS["ViT-L/14_336"], map_location="cpu") + load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=14, center=center) + return model.eval() + + +def interpolate_pos_embed_vit(state_dict, new_model): + key = "vision_encoder.temporal_positional_embedding" + if key in state_dict: + vision_temp_embed_new = new_model.state_dict()[key] + vision_temp_embed_new = vision_temp_embed_new.unsqueeze(2) # [1, n, d] -> [1, n, 1, d] + vision_temp_embed_old = state_dict[key] + vision_temp_embed_old = vision_temp_embed_old.unsqueeze(2) + + state_dict[key] = load_temp_embed_with_mismatch( + vision_temp_embed_old, vision_temp_embed_new, add_zero=False + ).squeeze(2) + + key = "text_encoder.positional_embedding" + if key in state_dict: + text_temp_embed_new = new_model.state_dict()[key] + text_temp_embed_new = text_temp_embed_new.unsqueeze(0).unsqueeze(2) # [n, d] -> [1, n, 1, d] + text_temp_embed_old = state_dict[key] + text_temp_embed_old = text_temp_embed_old.unsqueeze(0).unsqueeze(2) + + state_dict[key] = ( + load_temp_embed_with_mismatch(text_temp_embed_old, text_temp_embed_new, add_zero=False) + .squeeze(2) + .squeeze(0) + ) + return state_dict diff --git a/Helios/eval_moviebench/utils/third_party/amt/LICENSE b/Helios/eval_moviebench/utils/third_party/amt/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c9cecbde136da03a4ceb1a6e90230900cd33828d --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/LICENSE @@ -0,0 +1,176 @@ +## creative commons + +# Attribution-NonCommercial 4.0 International + +Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +### Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). + +* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). + +## Creative Commons Attribution-NonCommercial 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +### Section 1 – Definitions. + +a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + +b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + +c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + +e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + +f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + +g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + +h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. + +i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. + +j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + +k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + +l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +### Section 2 – Scope. + +a. ___License grant.___ + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and + + B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. + + 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. __Term.__ The term of this Public License is specified in Section 6(a). + + 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. __Downstream recipients.__ + + A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + +b. ___Other rights.___ + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. + +### Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + +a. ___Attribution.___ + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. + +### Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; + +b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and + +c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +### Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ + +b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ + +c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +### Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + +c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + +d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +### Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +### Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + +b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + +c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. +> +> Creative Commons may be contacted at creativecommons.org + + +### Commercial licensing opportunities +For commercial uses of the Model & Software, please send email to cmm[AT]nankai.edu.cn + +Citation: + +@inproceedings{licvpr23amt, + title = {AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation}, + author = {Li, Zhen and Zhu, Zuo-Liang and Han, Ling-Hao and Hou, Qibin and Guo, Chun-Le and Cheng, Ming-Ming}, + booktitle = {IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, + year = {2023} +} + +Copyright (c) 2023 MCG-NKU \ No newline at end of file diff --git a/Helios/eval_moviebench/utils/third_party/amt/README.md b/Helios/eval_moviebench/utils/third_party/amt/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2f3224318fa319dc39b86e6bf9ec74ce3dee2e3e --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/README.md @@ -0,0 +1,167 @@ +# AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation + + +This repository contains the official implementation of the following paper: +> **AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation**
+> [Zhen Li](https://paper99.github.io/)\*, [Zuo-Liang Zhu](https://nk-cs-zzl.github.io/)\*, [Ling-Hao Han](https://scholar.google.com/citations?user=0ooNdgUAAAAJ&hl=en), [Qibin Hou](https://scholar.google.com/citations?hl=en&user=fF8OFV8AAAAJ&view_op=list_works), [Chun-Le Guo](https://scholar.google.com/citations?hl=en&user=RZLYwR0AAAAJ), [Ming-Ming Cheng](https://mmcheng.net/cmm)
+> (\* denotes equal contribution)
+> Nankai University
+> In CVPR 2023
+ +[[Paper](https://arxiv.org/abs/2304.09790)] +[[Project Page](https://nk-cs-zzl.github.io/projects/amt/index.html)] +[[Web demos](#web-demos)] +[Video] + +AMT is a **lightweight, fast, and accurate** algorithm for Frame Interpolation. +It aims to provide practical solutions for **video generation** from **a few given frames (at least two frames)**. + +![Demo gif](assets/amt_demo.gif) +* More examples can be found in our [project page](https://nk-cs-zzl.github.io/projects/amt/index.html). + +## Web demos +Integrated into [Hugging Face Spaces 🤗](https://huggingface.co/spaces) using [Gradio](https://github.com/gradio-app/gradio). Try out the Web Demo: [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/NKU-AMT/AMT) + +Try AMT to interpolate between two or more images at [![PyTTI-Tools:FILM](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1IeVO5BmLouhRh6fL2z_y18kgubotoaBq?usp=sharing) + + +## Change Log +- **Apr 20, 2023**: Our code is publicly available. + + +## Method Overview +![pipeline](https://user-images.githubusercontent.com/21050959/229420451-65951bd0-732c-4f09-9121-f291a3862d6e.png) + +For technical details, please refer to the [method.md](docs/method.md) file, or read the full report on [arXiv](https://arxiv.org/abs/2304.09790). + +## Dependencies and Installation +1. Clone Repo + + ```bash + git clone https://github.com/MCG-NKU/AMT.git + ``` + +2. Create Conda Environment and Install Dependencies + + ```bash + conda env create -f environment.yaml + conda activate amt + ``` +3. Download pretrained models for demos from [Pretrained Models](#pretrained-models) and place them to the `pretrained` folder + +## Quick Demo + +**Note that the selected pretrained model (`[CKPT_PATH]`) needs to match the config file (`[CFG]`).** + + > Creating a video demo, increasing $n$ will slow down the motion in the video. (With $m$ input frames, `[N_ITER]` $=n$ corresponds to $2^n\times (m-1)+1$ output frames.) + + + ```bash + python demos/demo_2x.py -c [CFG] -p [CKPT] -n [N_ITER] -i [INPUT] -o [OUT_PATH] -r [FRAME_RATE] + # e.g. [INPUT] + # -i could be a video / a regular expression / a folder contains multiple images + # -i demo.mp4 (video)/img_*.png (regular expression)/img0.png img1.png (images)/demo_input (folder) + + # e.g. a simple usage + python demos/demo_2x.py -c cfgs/AMT-S.yaml -p pretrained/amt-s.pth -n 6 -i assets/quick_demo/img0.png assets/quick_demo/img1.png + + ``` + + + Note: Please enable `--save_images` for saving the output images (Save speed will be slowed down if there are too many output images) + + Input type supported: `a video` / `a regular expression` / `multiple images` / `a folder containing input frames`. + + Results are in the `[OUT_PATH]` (default is `results/2x`) folder. + +## Pretrained Models + +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dataset :link: Download Links Config file Trained on Arbitrary/Fixed
AMT-S [Google Driver][Baidu Cloud][Hugging Face] [cfgs/AMT-S] Vimeo90kFixed
AMT-L[Google Driver][Baidu Cloud][Hugging Face] [cfgs/AMT-L] Vimeo90kFixed
AMT-G[Google Driver][Baidu Cloud][Hugging Face] [cfgs/AMT-G] Vimeo90kFixed
AMT-S[Google Driver][Baidu Cloud][Hugging Face] [cfgs/AMT-S_gopro] GoProArbitrary
+ +## Training and Evaluation + +Please refer to [develop.md](docs/develop.md) to learn how to benchmark the AMT and how to train a new AMT model from scratch. + + +## Citation + If you find our repo useful for your research, please consider citing our paper: + + ```bibtex + @inproceedings{licvpr23amt, + title={AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation}, + author={Li, Zhen and Zhu, Zuo-Liang and Han, Ling-Hao and Hou, Qibin and Guo, Chun-Le and Cheng, Ming-Ming}, + booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, + year={2023} + } + ``` + + +## License +This code is licensed under the [Creative Commons Attribution-NonCommercial 4.0 International](https://creativecommons.org/licenses/by-nc/4.0/) for non-commercial use only. +Please note that any commercial use of this code requires formal permission prior to use. + +## Contact + +For technical questions, please contact `zhenli1031[AT]gmail.com` and `nkuzhuzl[AT]gmail.com`. + +For commercial licensing, please contact `cmm[AT]nankai.edu.cn` + +## Acknowledgement + +We thank Jia-Wen Xiao, Zheng-Peng Duan, Rui-Qi Wu, and Xin Jin for proof reading. +We thank [Zhewei Huang](https://github.com/hzwer) for his suggestions. + +Here are some great resources we benefit from: + +- [IFRNet](https://github.com/ltkong218/IFRNet) and [RIFE](https://github.com/megvii-research/ECCV2022-RIFE) for data processing, benchmarking, and loss designs. +- [RAFT](https://github.com/princeton-vl/RAFT), [M2M-VFI](https://github.com/feinanshan/M2M_VFI), and [GMFlow](https://github.com/haofeixu/gmflow) for inspirations. +- [FILM](https://github.com/google-research/frame-interpolation) for Web demo reference. + + +**If you develop/use AMT in your projects, welcome to let us know. We will list your projects in this repository.** + +We also thank all of our contributors. + + + + + diff --git a/Helios/eval_moviebench/utils/third_party/amt/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/benchmarks/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/benchmarks/adobe240.py b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/adobe240.py new file mode 100644 index 0000000000000000000000000000000000000000..20598d711fb25a9fdbcf6991369f9afe77bb24b9 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/adobe240.py @@ -0,0 +1,65 @@ +import argparse +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from datasets.adobe_datasets import Adobe240_Dataset +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Adobe240 evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S_gopro.yaml") +parser.add_argument( + "-p", + "--ckpt", + default="pretrained/gopro_amt-s.pth", +) +parser.add_argument( + "-r", + "--root", + default="data/Adobe240/test_frames", +) +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +dataset = Adobe240_Dataset(dataset_dir=root, augment=False) + +psnr_list = [] +ssim_list = [] +pbar = tqdm.tqdm(dataset, total=len(dataset)) +for data in pbar: + input_dict = {} + for k, v in data.items(): + input_dict[k] = v.to(device).unsqueeze(0) + with torch.no_grad(): + imgt_pred = model(**input_dict)["imgt_pred"] + psnr = calculate_psnr(imgt_pred, input_dict["imgt"]) + ssim = calculate_ssim(imgt_pred, input_dict["imgt"]) + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/Adobe240] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval_moviebench/utils/third_party/amt/benchmarks/gopro.py b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/gopro.py new file mode 100644 index 0000000000000000000000000000000000000000..27897013ca50baea29992f7b070434da6799b464 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/gopro.py @@ -0,0 +1,65 @@ +import argparse +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from datasets.gopro_datasets import GoPro_Test_Dataset +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg + + +parser = argparse.ArgumentParser( + prog="AMT", + description="GOPRO evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S_gopro.yaml") +parser.add_argument( + "-p", + "--ckpt", + default="pretrained/gopro_amt-s.pth", +) +parser.add_argument( + "-r", + "--root", + default="data/GOPRO", +) +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +dataset = GoPro_Test_Dataset(dataset_dir=root) + +psnr_list = [] +ssim_list = [] +pbar = tqdm.tqdm(dataset, total=len(dataset)) +for data in pbar: + input_dict = {} + for k, v in data.items(): + input_dict[k] = v.to(device).unsqueeze(0) + with torch.no_grad(): + imgt_pred = model(**input_dict)["imgt_pred"] + psnr = calculate_psnr(imgt_pred, input_dict["imgt"]) + ssim = calculate_ssim(imgt_pred, input_dict["imgt"]) + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/GOPRO] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval_moviebench/utils/third_party/amt/benchmarks/snu_film.py b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/snu_film.py new file mode 100644 index 0000000000000000000000000000000000000000..ec0417ee4ba7fe0d52da939d5977f55315f125d0 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/snu_film.py @@ -0,0 +1,76 @@ +import argparse +import os +import os.path as osp +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import InputPadder, img2tensor, read + + +def parse_path(path): + path_list = path.split("/") + new_path = osp.join(*path_list[-3:]) + return new_path + + +parser = argparse.ArgumentParser( + prog="AMT", + description="SNU-FILM evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument("-p", "--ckpt", default="pretrained/amt-s.pth") +parser.add_argument("-r", "--root", default="data/SNU_FILM") +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +divisor = 20 +scale_factor = 0.8 +splits = ["easy", "medium", "hard", "extreme"] +for split in splits: + with open(os.path.join(root, f"test-{split}.txt"), "r") as fr: + file_list = [l.strip().split(" ") for l in fr.readlines()] + pbar = tqdm.tqdm(file_list, total=len(file_list)) + + psnr_list = [] + ssim_list = [] + for name in pbar: + img0 = img2tensor(read(osp.join(root, parse_path(name[0])))).to(device) + imgt = img2tensor(read(osp.join(root, parse_path(name[1])))).to(device) + img1 = img2tensor(read(osp.join(root, parse_path(name[2])))).to(device) + padder = InputPadder(img0.shape, divisor) + img0, img1 = padder.pad(img0, img1) + + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + imgt_pred = model(img0, img1, embt, scale_factor=scale_factor, eval=True)["imgt_pred"] + imgt_pred = padder.unpad(imgt_pred) + + psnr = calculate_psnr(imgt_pred, imgt).detach().cpu().numpy() + ssim = calculate_ssim(imgt_pred, imgt).detach().cpu().numpy() + + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/SNU-FILM] [{split}] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval_moviebench/utils/third_party/amt/benchmarks/speed_parameters.py b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/speed_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..be6d4569f0f55e36f244d61ee537dcf4bbd05a62 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/speed_parameters.py @@ -0,0 +1,41 @@ +import argparse +import sys +import time + +import torch +from omegaconf import OmegaConf + + +sys.path.append(".") +from utils.build_utils import build_from_cfg + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Speed¶meter benchmark", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +args = parser.parse_args() + +cfg_path = args.config +network_cfg = OmegaConf.load(cfg_path).network +model = build_from_cfg(network_cfg) +model = model.cuda() +model.eval() + +img0 = torch.randn(1, 3, 256, 448).cuda() +img1 = torch.randn(1, 3, 256, 448).cuda() +embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).cuda() + +with torch.no_grad(): + for i in range(100): + out = model(img0, img1, embt, eval=True) + torch.cuda.synchronize() + time_stamp = time.time() + for i in range(1000): + out = model(img0, img1, embt, eval=True) + torch.cuda.synchronize() + print("Time: {:.5f}s".format((time.time() - time_stamp) / 1)) + +total = sum([param.nelement() for param in model.parameters()]) +print("Parameters: {:.2f}M".format(total / 1e6)) diff --git a/Helios/eval_moviebench/utils/third_party/amt/benchmarks/ucf101.py b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/ucf101.py new file mode 100644 index 0000000000000000000000000000000000000000..7741c19d4c6ba2f8e46d7d1725119a7ef07b61c6 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/ucf101.py @@ -0,0 +1,63 @@ +import argparse +import os +import os.path as osp +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import img2tensor, read + + +parser = argparse.ArgumentParser( + prog="AMT", + description="UCF101 evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument("-p", "--ckpt", default="pretrained/amt-s.pth") +parser.add_argument("-r", "--root", default="data/ucf101_interp_ours") +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +dirs = sorted(os.listdir(root)) +psnr_list = [] +ssim_list = [] +pbar = tqdm.tqdm(dirs, total=len(dirs)) +for d in pbar: + dir_path = osp.join(root, d) + I0 = img2tensor(read(osp.join(dir_path, "frame_00.png"))).to(device) + I1 = img2tensor(read(osp.join(dir_path, "frame_01_gt.png"))).to(device) + I2 = img2tensor(read(osp.join(dir_path, "frame_02.png"))).to(device) + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + + I1_pred = model(I0, I2, embt, eval=True)["imgt_pred"] + + psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy() + ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy() + + psnr_list.append(psnr) + ssim_list.append(ssim) + + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/UCF101] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval_moviebench/utils/third_party/amt/benchmarks/vimeo90k.py b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/vimeo90k.py new file mode 100644 index 0000000000000000000000000000000000000000..d70e1e32b21d459d6ccb633d29796819bfa730ac --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/vimeo90k.py @@ -0,0 +1,75 @@ +import argparse +import os.path as osp +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import img2tensor, read + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Vimeo90K evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument( + "-p", + "--ckpt", + default="pretrained/amt-s.pth", +) +parser.add_argument( + "-r", + "--root", + default="data/vimeo_triplet", +) +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +with open(osp.join(root, "tri_testlist.txt"), "r") as fr: + file_list = fr.readlines() + +psnr_list = [] +ssim_list = [] + +pbar = tqdm.tqdm(file_list, total=len(file_list)) +for name in pbar: + name = str(name).strip() + if len(name) <= 1: + continue + dir_path = osp.join(root, "sequences", name) + I0 = img2tensor(read(osp.join(dir_path, "im1.png"))).to(device) + I1 = img2tensor(read(osp.join(dir_path, "im2.png"))).to(device) + I2 = img2tensor(read(osp.join(dir_path, "im3.png"))).to(device) + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + + I1_pred = model(I0, I2, embt, scale_factor=1.0, eval=True)["imgt_pred"] + + psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy() + ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy() + + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/Vimeo90K] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval_moviebench/utils/third_party/amt/benchmarks/vimeo90k_tta.py b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/vimeo90k_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..af6c91f079a9942b0b66f89ecff173821e938864 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/vimeo90k_tta.py @@ -0,0 +1,76 @@ +import argparse +import os.path as osp +import sys + +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import img2tensor, read + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Vimeo90K evaluation (with Test-Time Augmentation)", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument( + "p", + "--ckpt", + default="pretrained/amt-s.pth", +) +parser.add_argument( + "-r", + "--root", + default="data/vimeo_triplet", +) +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"]) +model = model.to(device) +model.eval() + +with open(osp.join(root, "tri_testlist.txt"), "r") as fr: + file_list = fr.readlines() + +psnr_list = [] +ssim_list = [] + +pbar = tqdm.tqdm(file_list, total=len(file_list)) +for name in pbar: + name = str(name).strip() + if len(name) <= 1: + continue + dir_path = osp.join(root, "sequences", name) + I0 = img2tensor(read(osp.join(dir_path, "im1.png"))).to(device) + I1 = img2tensor(read(osp.join(dir_path, "im2.png"))).to(device) + I2 = img2tensor(read(osp.join(dir_path, "im3.png"))).to(device) + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + + I1_pred1 = model(I0, I2, embt, scale_factor=1.0, eval=True)["imgt_pred"] + I1_pred2 = model(torch.flip(I0, [2]), torch.flip(I2, [2]), embt, scale_factor=1.0, eval=True)["imgt_pred"] + I1_pred = I1_pred1 / 2 + torch.flip(I1_pred2, [2]) / 2 + psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy() + ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy() + + psnr_list.append(psnr) + ssim_list.append(ssim) + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + desc_str = f"[{network_name}/Vimeo90K] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + pbar.set_description_str(desc_str) diff --git a/Helios/eval_moviebench/utils/third_party/amt/benchmarks/xiph.py b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/xiph.py new file mode 100644 index 0000000000000000000000000000000000000000..7f134a0ec17ffdab73eff431bb10216242e282d5 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/benchmarks/xiph.py @@ -0,0 +1,117 @@ +import argparse +import glob +import os +import os.path as osp +import sys + +import cv2 +import numpy as np +import torch +import tqdm +from omegaconf import OmegaConf + + +sys.path.append(".") +from metrics.psnr_ssim import calculate_psnr, calculate_ssim + +from utils.build_utils import build_from_cfg +from utils.utils import InputPadder, img2tensor, read + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Xiph evaluation", +) +parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml") +parser.add_argument("-p", "--ckpt", default="pretrained/amt-s.pth") +parser.add_argument("-r", "--root", default="data/xiph") +args = parser.parse_args() + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +cfg_path = args.config +ckpt_path = args.ckpt +root = args.root + +network_cfg = OmegaConf.load(cfg_path).network +network_name = network_cfg.name +model = build_from_cfg(network_cfg) +ckpt = torch.load(ckpt_path) +model.load_state_dict(ckpt["state_dict"], False) +model = model.to(device) +model.eval() + +############################################# Prepare Dataset ############################################# +download_links = [ + "https://media.xiph.org/video/derf/ElFuente/Netflix_BoxingPractice_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_Crosswalk_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/Chimera/Netflix_DrivingPOV_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket2_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_RitualDance_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_SquareAndTimelapse_4096x2160_60fps_10bit_420.y4m", + "https://media.xiph.org/video/derf/ElFuente/Netflix_Tango_4096x2160_60fps_10bit_420.y4m", +] +file_list = [ + "BoxingPractice", + "Crosswalk", + "DrivingPOV", + "FoodMarket", + "FoodMarket2", + "RitualDance", + "SquareAndTimelapse", + "Tango", +] + +for file_name, link in zip(file_list, download_links): + data_dir = osp.join(root, file_name) + if osp.exists(data_dir) is False: + os.makedirs(data_dir) + if len(glob.glob(f"{data_dir}/*.png")) < 100: + os.system(f"ffmpeg -i {link} -pix_fmt rgb24 -vframes 100 {data_dir}/%03d.png") +############################################### Prepare End ############################################### + + +divisor = 32 +scale_factor = 0.5 +for category in ["resized-2k", "cropped-4k"]: + psnr_list = [] + ssim_list = [] + pbar = tqdm.tqdm(file_list, total=len(file_list)) + for flie_name in pbar: + dir_name = osp.join(root, flie_name) + for intFrame in range(2, 99, 2): + img0 = read(f"{dir_name}/{intFrame - 1:03d}.png") + img1 = read(f"{dir_name}/{intFrame + 1:03d}.png") + imgt = read(f"{dir_name}/{intFrame:03d}.png") + + if category == "resized-2k": + img0 = cv2.resize(src=img0, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA) + img1 = cv2.resize(src=img1, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA) + imgt = cv2.resize(src=imgt, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA) + + elif category == "cropped-4k": + img0 = img0[540:-540, 1024:-1024, :] + img1 = img1[540:-540, 1024:-1024, :] + imgt = imgt[540:-540, 1024:-1024, :] + img0 = img2tensor(img0).to(device) + imgt = img2tensor(imgt).to(device) + img1 = img2tensor(img1).to(device) + embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device) + + padder = InputPadder(img0.shape, divisor) + img0, img1 = padder.pad(img0, img1) + + with torch.no_grad(): + imgt_pred = model(img0, img1, embt, scale_factor=scale_factor, eval=True)["imgt_pred"] + imgt_pred = padder.unpad(imgt_pred) + + psnr = calculate_psnr(imgt_pred, imgt) + ssim = calculate_ssim(imgt_pred, imgt) + + avg_psnr = np.mean(psnr_list) + avg_ssim = np.mean(ssim_list) + psnr_list.append(psnr) + ssim_list.append(ssim) + desc_str = f"[{network_name}/Xiph] [{category}/{flie_name}] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}" + + pbar.set_description_str(desc_str) diff --git a/Helios/eval_moviebench/utils/third_party/amt/cfgs/AMT-G.yaml b/Helios/eval_moviebench/utils/third_party/amt/cfgs/AMT-G.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b3bb39bda6b41dc5cdc3300ffccb7b4e7d537ce --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/cfgs/AMT-G.yaml @@ -0,0 +1,62 @@ +exp_name: floloss1e-2_300epoch_bs24_lr1p5e-4 +seed: 2023 +epochs: 300 +distributed: true +lr: 1.5e-4 +lr_min: 2e-5 +weight_decay: 0.0 +resume_state: null +save_dir: work_dir +eval_interval: 1 + +network: + name: networks.AMT-G.Model + params: + corr_radius: 3 + corr_lvls: 4 + num_flows: 5 +data: + train: + name: datasets.vimeo_datasets.Vimeo90K_Train_Dataset + params: + dataset_dir: data/vimeo_triplet + val: + name: datasets.vimeo_datasets.Vimeo90K_Test_Dataset + params: + dataset_dir: data/vimeo_triplet + train_loader: + batch_size: 24 + num_workers: 12 + val_loader: + batch_size: 24 + num_workers: 3 + +logger: + use_wandb: true + resume_id: null + +losses: + - { + name: losses.loss.CharbonnierLoss, + nickname: l_rec, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.TernaryLoss, + nickname: l_ter, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.MultipleFlowLoss, + nickname: l_flo, + params: { + loss_weight: 0.005, + keys: [flow0_pred, flow1_pred, flow] + } + } diff --git a/Helios/eval_moviebench/utils/third_party/amt/cfgs/AMT-L.yaml b/Helios/eval_moviebench/utils/third_party/amt/cfgs/AMT-L.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0cd60ce868ad98a9dea74dd77227f556738715e8 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/cfgs/AMT-L.yaml @@ -0,0 +1,62 @@ +exp_name: floloss1e-2_300epoch_bs24_lr2e-4 +seed: 2023 +epochs: 300 +distributed: true +lr: 2e-4 +lr_min: 2e-5 +weight_decay: 0.0 +resume_state: null +save_dir: work_dir +eval_interval: 1 + +network: + name: networks.AMT-L.Model + params: + corr_radius: 3 + corr_lvls: 4 + num_flows: 5 +data: + train: + name: datasets.vimeo_datasets.Vimeo90K_Train_Dataset + params: + dataset_dir: data/vimeo_triplet + val: + name: datasets.vimeo_datasets.Vimeo90K_Test_Dataset + params: + dataset_dir: data/vimeo_triplet + train_loader: + batch_size: 24 + num_workers: 12 + val_loader: + batch_size: 24 + num_workers: 3 + +logger: + use_wandb: true + resume_id: null + +losses: + - { + name: losses.loss.CharbonnierLoss, + nickname: l_rec, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.TernaryLoss, + nickname: l_ter, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.MultipleFlowLoss, + nickname: l_flo, + params: { + loss_weight: 0.002, + keys: [flow0_pred, flow1_pred, flow] + } + } diff --git a/Helios/eval_moviebench/utils/third_party/amt/cfgs/AMT-S_gopro.yaml b/Helios/eval_moviebench/utils/third_party/amt/cfgs/AMT-S_gopro.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb50cfb04ed509e7766bbd279e0308d03db98d62 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/cfgs/AMT-S_gopro.yaml @@ -0,0 +1,56 @@ +exp_name: wofloloss_400epoch_bs24_lr2e-4 +seed: 2023 +epochs: 400 +distributed: true +lr: 2e-4 +lr_min: 2e-5 +weight_decay: 0.0 +resume_state: null +save_dir: work_dir +eval_interval: 1 + +network: + name: networks.AMT-S.Model + params: + corr_radius: 3 + corr_lvls: 4 + num_flows: 3 + +data: + train: + name: datasets.gopro_datasets.GoPro_Train_Dataset + params: + dataset_dir: data/GOPRO + val: + name: datasets.gopro_datasets.GoPro_Test_Dataset + params: + dataset_dir: data/GOPRO + train_loader: + batch_size: 24 + num_workers: 12 + val_loader: + batch_size: 24 + num_workers: 3 + +logger: + use_wandb: false + resume_id: null + +losses: + - { + name: losses.loss.CharbonnierLoss, + nickname: l_rec, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.TernaryLoss, + nickname: l_ter, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + diff --git a/Helios/eval_moviebench/utils/third_party/amt/cfgs/IFRNet.yaml b/Helios/eval_moviebench/utils/third_party/amt/cfgs/IFRNet.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ce67ca48901e501956ea0d07b2373b5d7af74df --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/cfgs/IFRNet.yaml @@ -0,0 +1,67 @@ +exp_name: floloss1e-2_geoloss1e-2_300epoch_bs24_lr1e-4 +seed: 2023 +epochs: 300 +distributed: true +lr: 1e-4 +lr_min: 1e-5 +weight_decay: 1e-6 +resume_state: null +save_dir: work_dir +eval_interval: 1 + +network: + name: networks.IFRNet.Model + +data: + train: + name: datasets.datasets.Vimeo90K_Train_Dataset + params: + dataset_dir: data/vimeo_triplet + val: + name: datasets.datasets.Vimeo90K_Test_Dataset + params: + dataset_dir: data/vimeo_triplet + train_loader: + batch_size: 24 + num_workers: 12 + val_loader: + batch_size: 24 + num_workers: 3 + +logger: + use_wandb: true + resume_id: null + +losses: + - { + name: losses.loss.CharbonnierLoss, + nickname: l_rec, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.TernaryLoss, + nickname: l_ter, + params: { + loss_weight: 1.0, + keys: [imgt_pred, imgt] + } + } + - { + name: losses.loss.IFRFlowLoss, + nickname: l_flo, + params: { + loss_weight: 0.01, + keys: [flow0_pred, flow1_pred, flow] + } + } + - { + name: losses.loss.GeometryLoss, + nickname: l_geo, + params: { + loss_weight: 0.01, + keys: [ft_pred, ft_gt] + } + } diff --git a/Helios/eval_moviebench/utils/third_party/amt/datasets/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/datasets/adobe_datasets.py b/Helios/eval_moviebench/utils/third_party/amt/datasets/adobe_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..cf543ab88cf72c6ee6118d8cc192aba8b7d7cea0 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/datasets/adobe_datasets.py @@ -0,0 +1,77 @@ +import os +import sys + +import numpy as np +import torch +from torch.utils.data import Dataset + + +sys.path.append(".") +from datasets.gopro_datasets import ( + center_crop_woflow, + random_crop_woflow, + random_horizontal_flip_woflow, + random_resize_woflow, + random_reverse_channel_woflow, + random_reverse_time_woflow, + random_rotate_woflow, + random_vertical_flip_woflow, +) + +from utils.utils import img2tensor, read + + +class Adobe240_Dataset(Dataset): + def __init__(self, dataset_dir="data/adobe240/test_frames", interFrames=7, augment=True): + super().__init__() + self.augment = augment + self.interFrames = interFrames + self.setLength = interFrames + 2 + self.dataset_dir = os.path.join(dataset_dir) + video_list = os.listdir(self.dataset_dir)[9::10] + self.frames_list = [] + self.file_list = [] + for video in video_list: + frames = sorted(os.listdir(os.path.join(self.dataset_dir, video))) + n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1 + videoInputs = [ + frames[(interFrames + 1) * i : (interFrames + 1) * i + self.setLength] for i in range(n_sets) + ] + videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs] + self.file_list.extend(videoInputs) + + def __getitem__(self, idx): + clip_idx = idx // self.interFrames + embt_idx = idx % self.interFrames + imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]] + pick_idxs = list(range(0, self.setLength, self.interFrames + 1)) + imgt_beg = self.setLength // 2 - self.interFrames // 2 + imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2 + imgt_idx = list(range(imgt_beg, imgt_end)) + input_paths = [imgpaths[idx] for idx in pick_idxs] + imgt_paths = [imgpaths[idx] for idx in imgt_idx] + + img0 = np.array(read(input_paths[0])) + imgt = np.array(read(imgt_paths[embt_idx])) + img1 = np.array(read(input_paths[1])) + embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)).reshape(1, 1, 1).astype(np.float32)) + + if self.augment: + img0, imgt, img1 = random_resize_woflow(img0, imgt, img1, p=0.1) + img0, imgt, img1 = random_crop_woflow(img0, imgt, img1, crop_size=(224, 224)) + img0, imgt, img1 = random_reverse_channel_woflow(img0, imgt, img1, p=0.5) + img0, imgt, img1 = random_vertical_flip_woflow(img0, imgt, img1, p=0.3) + img0, imgt, img1 = random_horizontal_flip_woflow(img0, imgt, img1, p=0.5) + img0, imgt, img1 = random_rotate_woflow(img0, imgt, img1, p=0.05) + img0, imgt, img1, embt = random_reverse_time_woflow(img0, imgt, img1, embt=embt, p=0.5) + else: + img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)) + + img0 = img2tensor(img0).squeeze(0) + imgt = img2tensor(imgt).squeeze(0) + img1 = img2tensor(img1).squeeze(0) + + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "embt": embt} + + def __len__(self): + return len(self.file_list) * self.interFrames diff --git a/Helios/eval_moviebench/utils/third_party/amt/datasets/gopro_datasets.py b/Helios/eval_moviebench/utils/third_party/amt/datasets/gopro_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..9c5acb441a449af2d2ae1a7d6b0bd3bd9e093d30 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/datasets/gopro_datasets.py @@ -0,0 +1,213 @@ +import os +import random + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from utils.utils import img2tensor, read + + +def random_resize_woflow(img0, imgt, img1, p=0.1): + if random.uniform(0, 1) < p: + img0 = cv2.resize(img0, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + imgt = cv2.resize(imgt, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + img1 = cv2.resize(img1, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + return img0, imgt, img1 + + +def random_crop_woflow(img0, imgt, img1, crop_size=(224, 224)): + h, w = crop_size[0], crop_size[1] + ih, iw, _ = img0.shape + x = np.random.randint(0, ih - h + 1) + y = np.random.randint(0, iw - w + 1) + img0 = img0[x : x + h, y : y + w, :] + imgt = imgt[x : x + h, y : y + w, :] + img1 = img1[x : x + h, y : y + w, :] + return img0, imgt, img1 + + +def center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)): + h, w = crop_size[0], crop_size[1] + ih, iw, _ = img0.shape + img0 = img0[ih // 2 - h // 2 : ih // 2 + h // 2, iw // 2 - w // 2 : iw // 2 + w // 2, :] + imgt = imgt[ih // 2 - h // 2 : ih // 2 + h // 2, iw // 2 - w // 2 : iw // 2 + w // 2, :] + img1 = img1[ih // 2 - h // 2 : ih // 2 + h // 2, iw // 2 - w // 2 : iw // 2 + w // 2, :] + return img0, imgt, img1 + + +def random_reverse_channel_woflow(img0, imgt, img1, p=0.5): + if random.uniform(0, 1) < p: + img0 = img0[:, :, ::-1] + imgt = imgt[:, :, ::-1] + img1 = img1[:, :, ::-1] + return img0, imgt, img1 + + +def random_vertical_flip_woflow(img0, imgt, img1, p=0.3): + if random.uniform(0, 1) < p: + img0 = img0[::-1] + imgt = imgt[::-1] + img1 = img1[::-1] + return img0, imgt, img1 + + +def random_horizontal_flip_woflow(img0, imgt, img1, p=0.5): + if random.uniform(0, 1) < p: + img0 = img0[:, ::-1] + imgt = imgt[:, ::-1] + img1 = img1[:, ::-1] + return img0, imgt, img1 + + +def random_rotate_woflow(img0, imgt, img1, p=0.05): + if random.uniform(0, 1) < p: + img0 = img0.transpose((1, 0, 2)) + imgt = imgt.transpose((1, 0, 2)) + img1 = img1.transpose((1, 0, 2)) + return img0, imgt, img1 + + +def random_reverse_time_woflow(img0, imgt, img1, embt, p=0.5): + if random.uniform(0, 1) < p: + tmp = img1 + img1 = img0 + img0 = tmp + embt = 1 - embt + return img0, imgt, img1, embt + + +class GoPro_Train_Dataset(Dataset): + def __init__(self, dataset_dir="data/GOPRO", interFrames=7, augment=True): + self.dataset_dir = dataset_dir + "/train" + self.interFrames = interFrames + self.augment = augment + self.setLength = interFrames + 2 + video_list = [ + "GOPR0372_07_00", + "GOPR0374_11_01", + "GOPR0378_13_00", + "GOPR0384_11_01", + "GOPR0384_11_04", + "GOPR0477_11_00", + "GOPR0868_11_02", + "GOPR0884_11_00", + "GOPR0372_07_01", + "GOPR0374_11_02", + "GOPR0379_11_00", + "GOPR0384_11_02", + "GOPR0385_11_00", + "GOPR0857_11_00", + "GOPR0871_11_01", + "GOPR0374_11_00", + "GOPR0374_11_03", + "GOPR0380_11_00", + "GOPR0384_11_03", + "GOPR0386_11_00", + "GOPR0868_11_01", + "GOPR0881_11_00", + ] + self.frames_list = [] + self.file_list = [] + for video in video_list: + frames = sorted(os.listdir(os.path.join(self.dataset_dir, video))) + n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1 + videoInputs = [ + frames[(interFrames + 1) * i : (interFrames + 1) * i + self.setLength] for i in range(n_sets) + ] + videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs] + self.file_list.extend(videoInputs) + + def __len__(self): + return len(self.file_list) * self.interFrames + + def __getitem__(self, idx): + clip_idx = idx // self.interFrames + embt_idx = idx % self.interFrames + imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]] + pick_idxs = list(range(0, self.setLength, self.interFrames + 1)) + imgt_beg = self.setLength // 2 - self.interFrames // 2 + imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2 + imgt_idx = list(range(imgt_beg, imgt_end)) + input_paths = [imgpaths[idx] for idx in pick_idxs] + imgt_paths = [imgpaths[idx] for idx in imgt_idx] + + embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)).reshape(1, 1, 1).astype(np.float32)) + img0 = np.array(read(input_paths[0])) + imgt = np.array(read(imgt_paths[embt_idx])) + img1 = np.array(read(input_paths[1])) + + if self.augment: + img0, imgt, img1 = random_resize_woflow(img0, imgt, img1, p=0.1) + img0, imgt, img1 = random_crop_woflow(img0, imgt, img1, crop_size=(224, 224)) + img0, imgt, img1 = random_reverse_channel_woflow(img0, imgt, img1, p=0.5) + img0, imgt, img1 = random_vertical_flip_woflow(img0, imgt, img1, p=0.3) + img0, imgt, img1 = random_horizontal_flip_woflow(img0, imgt, img1, p=0.5) + img0, imgt, img1 = random_rotate_woflow(img0, imgt, img1, p=0.05) + img0, imgt, img1, embt = random_reverse_time_woflow(img0, imgt, img1, embt=embt, p=0.5) + else: + img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)) + + img0 = img2tensor(img0.copy()).squeeze(0) + imgt = img2tensor(imgt.copy()).squeeze(0) + img1 = img2tensor(img1.copy()).squeeze(0) + + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "embt": embt} + + +class GoPro_Test_Dataset(Dataset): + def __init__(self, dataset_dir="data/GOPRO", interFrames=7): + self.dataset_dir = dataset_dir + "/test" + self.interFrames = interFrames + self.setLength = interFrames + 2 + video_list = [ + "GOPR0384_11_00", + "GOPR0385_11_01", + "GOPR0410_11_00", + "GOPR0862_11_00", + "GOPR0869_11_00", + "GOPR0881_11_01", + "GOPR0384_11_05", + "GOPR0396_11_00", + "GOPR0854_11_00", + "GOPR0868_11_00", + "GOPR0871_11_00", + ] + self.frames_list = [] + self.file_list = [] + for video in video_list: + frames = sorted(os.listdir(os.path.join(self.dataset_dir, video))) + n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1 + videoInputs = [ + frames[(interFrames + 1) * i : (interFrames + 1) * i + self.setLength] for i in range(n_sets) + ] + videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs] + self.file_list.extend(videoInputs) + + def __len__(self): + return len(self.file_list) * self.interFrames + + def __getitem__(self, idx): + clip_idx = idx // self.interFrames + embt_idx = idx % self.interFrames + imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]] + pick_idxs = list(range(0, self.setLength, self.interFrames + 1)) + imgt_beg = self.setLength // 2 - self.interFrames // 2 + imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2 + imgt_idx = list(range(imgt_beg, imgt_end)) + input_paths = [imgpaths[idx] for idx in pick_idxs] + imgt_paths = [imgpaths[idx] for idx in imgt_idx] + + img0 = np.array(read(input_paths[0])) + imgt = np.array(read(imgt_paths[embt_idx])) + img1 = np.array(read(input_paths[1])) + + img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)) + + img0 = img2tensor(img0).squeeze(0) + imgt = img2tensor(imgt).squeeze(0) + img1 = img2tensor(img1).squeeze(0) + + embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)).reshape(1, 1, 1).astype(np.float32)) + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "embt": embt} diff --git a/Helios/eval_moviebench/utils/third_party/amt/datasets/vimeo_datasets.py b/Helios/eval_moviebench/utils/third_party/amt/datasets/vimeo_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..c792a210ff57e960eab33200a9c0d27c692a76b1 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/datasets/vimeo_datasets.py @@ -0,0 +1,168 @@ +import os +import random + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from utils.utils import read + + +def random_resize(img0, imgt, img1, flow, p=0.1): + if random.uniform(0, 1) < p: + img0 = cv2.resize(img0, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + imgt = cv2.resize(imgt, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + img1 = cv2.resize(img1, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) + flow = cv2.resize(flow, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) * 2.0 + return img0, imgt, img1, flow + + +def random_crop(img0, imgt, img1, flow, crop_size=(224, 224)): + h, w = crop_size[0], crop_size[1] + ih, iw, _ = img0.shape + x = np.random.randint(0, ih - h + 1) + y = np.random.randint(0, iw - w + 1) + img0 = img0[x : x + h, y : y + w, :] + imgt = imgt[x : x + h, y : y + w, :] + img1 = img1[x : x + h, y : y + w, :] + flow = flow[x : x + h, y : y + w, :] + return img0, imgt, img1, flow + + +def random_reverse_channel(img0, imgt, img1, flow, p=0.5): + if random.uniform(0, 1) < p: + img0 = img0[:, :, ::-1] + imgt = imgt[:, :, ::-1] + img1 = img1[:, :, ::-1] + return img0, imgt, img1, flow + + +def random_vertical_flip(img0, imgt, img1, flow, p=0.3): + if random.uniform(0, 1) < p: + img0 = img0[::-1] + imgt = imgt[::-1] + img1 = img1[::-1] + flow = flow[::-1] + flow = np.concatenate((flow[:, :, 0:1], -flow[:, :, 1:2], flow[:, :, 2:3], -flow[:, :, 3:4]), 2) + return img0, imgt, img1, flow + + +def random_horizontal_flip(img0, imgt, img1, flow, p=0.5): + if random.uniform(0, 1) < p: + img0 = img0[:, ::-1] + imgt = imgt[:, ::-1] + img1 = img1[:, ::-1] + flow = flow[:, ::-1] + flow = np.concatenate((-flow[:, :, 0:1], flow[:, :, 1:2], -flow[:, :, 2:3], flow[:, :, 3:4]), 2) + return img0, imgt, img1, flow + + +def random_rotate(img0, imgt, img1, flow, p=0.05): + if random.uniform(0, 1) < p: + img0 = img0.transpose((1, 0, 2)) + imgt = imgt.transpose((1, 0, 2)) + img1 = img1.transpose((1, 0, 2)) + flow = flow.transpose((1, 0, 2)) + flow = np.concatenate((flow[:, :, 1:2], flow[:, :, 0:1], flow[:, :, 3:4], flow[:, :, 2:3]), 2) + return img0, imgt, img1, flow + + +def random_reverse_time(img0, imgt, img1, flow, p=0.5): + if random.uniform(0, 1) < p: + tmp = img1 + img1 = img0 + img0 = tmp + flow = np.concatenate((flow[:, :, 2:4], flow[:, :, 0:2]), 2) + return img0, imgt, img1, flow + + +class Vimeo90K_Train_Dataset(Dataset): + def __init__(self, dataset_dir="data/vimeo_triplet", flow_dir=None, augment=True, crop_size=(224, 224)): + self.dataset_dir = dataset_dir + self.augment = augment + self.crop_size = crop_size + self.img0_list = [] + self.imgt_list = [] + self.img1_list = [] + self.flow_t0_list = [] + self.flow_t1_list = [] + if flow_dir is None: + flow_dir = "flow" + with open(os.path.join(dataset_dir, "tri_trainlist.txt"), "r") as f: + for i in f: + name = str(i).strip() + if len(name) <= 1: + continue + self.img0_list.append(os.path.join(dataset_dir, "sequences", name, "im1.png")) + self.imgt_list.append(os.path.join(dataset_dir, "sequences", name, "im2.png")) + self.img1_list.append(os.path.join(dataset_dir, "sequences", name, "im3.png")) + self.flow_t0_list.append(os.path.join(dataset_dir, flow_dir, name, "flow_t0.flo")) + self.flow_t1_list.append(os.path.join(dataset_dir, flow_dir, name, "flow_t1.flo")) + + def __len__(self): + return len(self.imgt_list) + + def __getitem__(self, idx): + img0 = read(self.img0_list[idx]) + imgt = read(self.imgt_list[idx]) + img1 = read(self.img1_list[idx]) + flow_t0 = read(self.flow_t0_list[idx]) + flow_t1 = read(self.flow_t1_list[idx]) + flow = np.concatenate((flow_t0, flow_t1), 2).astype(np.float64) + + if self.augment: + img0, imgt, img1, flow = random_resize(img0, imgt, img1, flow, p=0.1) + img0, imgt, img1, flow = random_crop(img0, imgt, img1, flow, crop_size=self.crop_size) + img0, imgt, img1, flow = random_reverse_channel(img0, imgt, img1, flow, p=0.5) + img0, imgt, img1, flow = random_vertical_flip(img0, imgt, img1, flow, p=0.3) + img0, imgt, img1, flow = random_horizontal_flip(img0, imgt, img1, flow, p=0.5) + img0, imgt, img1, flow = random_rotate(img0, imgt, img1, flow, p=0.05) + img0, imgt, img1, flow = random_reverse_time(img0, imgt, img1, flow, p=0.5) + + img0 = torch.from_numpy(img0.transpose((2, 0, 1)).astype(np.float32) / 255.0) + imgt = torch.from_numpy(imgt.transpose((2, 0, 1)).astype(np.float32) / 255.0) + img1 = torch.from_numpy(img1.transpose((2, 0, 1)).astype(np.float32) / 255.0) + flow = torch.from_numpy(flow.transpose((2, 0, 1)).astype(np.float32)) + embt = torch.from_numpy(np.array(1 / 2).reshape(1, 1, 1).astype(np.float32)) + + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "flow": flow.float(), "embt": embt} + + +class Vimeo90K_Test_Dataset(Dataset): + def __init__(self, dataset_dir="data/vimeo_triplet"): + self.dataset_dir = dataset_dir + self.img0_list = [] + self.imgt_list = [] + self.img1_list = [] + self.flow_t0_list = [] + self.flow_t1_list = [] + with open(os.path.join(dataset_dir, "tri_testlist.txt"), "r") as f: + for i in f: + name = str(i).strip() + if len(name) <= 1: + continue + self.img0_list.append(os.path.join(dataset_dir, "sequences", name, "im1.png")) + self.imgt_list.append(os.path.join(dataset_dir, "sequences", name, "im2.png")) + self.img1_list.append(os.path.join(dataset_dir, "sequences", name, "im3.png")) + self.flow_t0_list.append(os.path.join(dataset_dir, "flow", name, "flow_t0.flo")) + self.flow_t1_list.append(os.path.join(dataset_dir, "flow", name, "flow_t1.flo")) + + def __len__(self): + return len(self.imgt_list) + + def __getitem__(self, idx): + img0 = read(self.img0_list[idx]) + imgt = read(self.imgt_list[idx]) + img1 = read(self.img1_list[idx]) + flow_t0 = read(self.flow_t0_list[idx]) + flow_t1 = read(self.flow_t1_list[idx]) + flow = np.concatenate((flow_t0, flow_t1), 2) + + img0 = torch.from_numpy(img0.transpose((2, 0, 1)).astype(np.float32) / 255.0) + imgt = torch.from_numpy(imgt.transpose((2, 0, 1)).astype(np.float32) / 255.0) + img1 = torch.from_numpy(img1.transpose((2, 0, 1)).astype(np.float32) / 255.0) + flow = torch.from_numpy(flow.transpose((2, 0, 1)).astype(np.float32)) + embt = torch.from_numpy(np.array(1 / 2).reshape(1, 1, 1).astype(np.float32)) + + return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "flow": flow.float(), "embt": embt} diff --git a/Helios/eval_moviebench/utils/third_party/amt/docs/develop.md b/Helios/eval_moviebench/utils/third_party/amt/docs/develop.md new file mode 100644 index 0000000000000000000000000000000000000000..e927e97632041b7da0adca95e944d9570cfe440c --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/docs/develop.md @@ -0,0 +1,239 @@ +# Development for evaluation and training + +- [Datasets](#Datasets) +- [Pretrained Models](#pretrained-models) +- [Evaluation](#evaluation) +- [Training](#training) + +## Datasets

+First, please prepare standard datasets for evaluation and training. + +We present most of prevailing datasets in video frame interpolation, though some are not used in our project. Hope this collection could help your research. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dataset :link: Source Train/Eval Arbitrary/Fixed
Vimeo90kToFlow (IJCV 2019)BothFixed
ATD-12KAnimeInterp (CVPR 2021)BothFixed
SNU-FILMCAIN (AAAI 2021)EvalFixed
UCF101Google DriverEvalFixed
HDMEMC-Net (TPAMI 2018)/Google DriverEvalFixed
Xiph-2k/-4kSoftSplat (CVPR 2020)EvalFixed
MiddleBuryMiddleBuryEvalFixed
GoProGoProBothArbitrary
Adobe240fpsDBN (CVPR 2017)BothArbitrary
X4K1000FPSXVFI (ICCV 2021)BothArbitrary
+ + +## Pretrained Models + +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dataset :link: Download Links Config file Trained on Arbitrary/Fixed
AMT-S [Google Driver][Baidu Cloud] [cfgs/AMT-S] Vimeo90kFixed
AMT-L[Google Driver][Baidu Cloud] [cfgs/AMT-L] Vimeo90kFixed
AMT-G[Google Driver][Baidu Cloud] [cfgs/AMT-G] Vimeo90kFixed
AMT-S[Google Driver][Baidu Cloud] [cfgs/AMT-S_gopro] GoProArbitrary
+ +## Evaluation +Before evaluation, you should: + +1. Check the dataroot is organized as follows: + +```shell +./data +├── Adobe240 +│ ├── original_high_fps_videos +│ └── test_frames # using ffmpeg to extract 240 fps frames from `original_high_fps_videos` +├── GOPRO +│ ├── test +│ └── train +├── SNU_FILM +│ ├── GOPRO_test +│ ├── test-easy.txt +│ ├── test-extreme.txt +│ ├── test-hard.txt +│ ├── test-medium.txt +│ └── YouTube_test +├── ucf101_interp_ours +│ ├── 1 +│ ├── 1001 +│ └── ... +└── vimeo_triplet + ├── readme.txt + ├── sequences + ├── tri_testlist.txt + └── tri_trainlist.txt +``` + +2. Download the provided [pretrained models](#pretrained-models). + +Then, you can perform evaluation as follows: + ++ Run all benchmarks for fixed-time models. + + ```shell + sh ./scripts/benchmark_fixed.sh [CFG] [CKPT_PATH] + ## e.g. + sh ./scripts/benchmark_fixed.sh cfgs/AMT-S.yaml pretrained/amt-s.pth + ``` + ++ Run all benchmarks for arbitrary-time models. + + ```shell + sh ./scripts/benchmark_arbitrary.sh [CFG] [CKPT_PATH] + ## e.g. + sh ./scripts/benchmark_arbitrary.sh cfgs/AMT-S.yaml pretrained/gopro_amt-s.pth + ``` + ++ Run a single benchmark for fixed-time models. *You can custom data paths in this case*. + + ```shell + python [BENCHMARK] -c [CFG] -p [CKPT_PATH] -r [DATAROOT] + ## e.g. + python benchmarks/vimeo90k.py -c cfgs/AMT-S.yaml -p pretrained/amt-s.pth -r data/vimeo_triplet + ``` + ++ Run the inference speed & model size comparisons using: + + ```shell + python speed_parameters.py -c [CFG] + ## e.g. + python speed_parameters.py -c cfgs/AMT-S.yaml + ``` + + +## Training + +Before training, please first prepare the optical flows (which are used for supervision). + +We need to install `cupy` first before flow generation: + +```shell +conda activate amt # satisfying `requirement.txt` +conda install -c conda-forge cupy +``` + + +After installing `cupy`, we can generate optical flows by the following command: + +```shell +python flow_generation/gen_flow.py -r [DATA_ROOT] +## e.g. +python flow_generation/gen_flow.py -r data/vimeo_triplet +``` + +After obtaining the optical flow of the training data, +run the following commands for training (DDP mode): + +```shell + sh ./scripts/train.sh [NUM_GPU] [CFG] [MASTER_PORT] + ## e.g. + sh ./scripts/train.sh 2 cfgs/AMT-S.yaml 14514 +``` + +Our training configuration files are provided in [`cfgs`](../cfgs). Please carefully check the `dataset_dir` is suitable for you. + + +Note: + +- If you intend to turn off DDP training, you can switch the key `distributed` from `true` +to `false` in the config file. + +- If you do not use wandb, you can switch the key `logger.use_wandb` from `true` +to `false` in the config file. \ No newline at end of file diff --git a/Helios/eval_moviebench/utils/third_party/amt/docs/method.md b/Helios/eval_moviebench/utils/third_party/amt/docs/method.md new file mode 100644 index 0000000000000000000000000000000000000000..1343649b503f807a0e6c46f0895d78c3fc6f4e79 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/docs/method.md @@ -0,0 +1,126 @@ +# Illustration of AMT + +

+ +

+ +### :rocket: Highlights: + ++ [**Good tradeoff**](#good-tradeoff) between performance and efficiency. + ++ [**All-pairs correlation**](#all-pairs-correlation) for modeling large motions during interpolation. + ++ A [**plug-and-play operator**](#multi-field-refinement) to improve the diversity of predicted task-oriented flows, further **boosting the interpolation performance**. + + +## Good Tradeoff + +

+ +

+ +We examine the proposed AMT on several public benchmarks with different model scales, showing strong performance and high efficiency in contrast to the SOTA methods (see Figure). Our small model outperforms [IFRNet-B](https://arxiv.org/abs/2205.14620), a SOTA lightweight model, by **\+0.17dB PSNR** on Vimeo90K with **only 60% of its FLOPs and parameters**. For large-scale setting, our AMT exceeds the previous SOTA (i.e., [IFRNet-L](https://arxiv.org/abs/2205.14620)) by **+0.15 dB PSNR** on Vimeo90K with **75% of its FLOPs and 65% of its parameters**. Besides, we provide a huge model for comparison +with the SOTA transformer-based method [VFIFormer](https://arxiv.org/abs/2205.07230). Our convolution-based AMT shows a **comparable performance** but only needs **nearly 23× less computational cost** compared to VFIFormer. + +Considering its effectiveness, we hope our AMT could bring a new perspective for the architecture design in efficient frame interpolation. + +## All-pairs correlation + +We build all-pairs correlation to effectively model large motions during interpolation. + +Here is an example about the update operation at a single scale in AMT: + +```python + # Construct bidirectional correlation volumes + fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [B, C, H//8, W//8] + corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels) + + # Correlation scaled lookup (bilateral -> bidirectional) + t1_scale = 1. / embt + t0_scale = 1. / (1. - embt) + coord = coords_grid(b, h // 8, w // 8, img0.device) + corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale) + corr = torch.cat([corr0, corr1], dim=1) + flow = torch.cat([flow0, flow1], dim=1) + + # Update both intermediate feature and bilateral flows + delta_feat, delta_flow = self.update(feat, flow, corr) + delta_flow0, delta_flow1 = torch.chunk(delta_flow, 2, 1) + flow0 = flow0 + delta_flow0 + flow1= flow1 + delta_flow1 + feat = feat + delta_feat + +``` + +Note: we extend above operations to each pyramid scale (except for the last one), which guarantees the consistency of flows on the coarse scale. + +### ⏫ performance gain +| | Vimeo 90k | Hard | Extreme | +|-------------------------|-----------|-------|---------| +| Baseline | 35.60 | 30.39 | 25.06 | +| + All-pairs correlation | 35.97 (**+0.37**) | 30.60 (**+0.21**) | 25.30 (**+0.24**) | + +More ablations can be found in the [paper](https://arxiv.org/abs/2304.09790). + +## Multi-field Refinement + +For most frame interpolation methods which are based on backward warping, the common formulation for +interpolating the final intermediate frame $I_{t}$ is: + +$I_{t} = M \odot \mathcal{W}(I_{0}, F_{t\rightarrow 0}) + (1 - M) \odot \mathcal{W}(I_{1}, F_{t\rightarrow 1}) + R$ + +Above formualtion only utilizes **one set of** bilateral optical flows $F_{t\rightarrow 0}$ and $F_{t\rightarrow 1}$, occulusion masks $M$, and residuals $R$. + +Multi-field refinement aims to improve the common formulation of backward warping. +Specifically, we first predict **multiple** bilateral optical flows (accompanied by the corresponding masks and residuals) through simply enlarging the output channels of the last decoder. +Then, we use aforementioned equation to genearate each interpolated candidate frame. Finally, we obtain the final interpolated frame through combining candidate frames using stacked convolutional layers. + +Please refer to [this code snippet](../networks/blocks/multi_flow.py#L46) for the details of the first step. +Please refer to [this code snippet](../networks/blocks/multi_flow.py#L10) for the details of the last two steps. + +### 🌟 easy to use +The proposed multi-field refinement can be **easily migrated to any frame interpolation model** to improve the performance. + +Code examples are shown below: + +```python + +# (At the __init__ stage) Initialize a decoder that predicts multiple flow fields (accompanied by the corresponding masks and residuals) +self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows) +... + +# (At the forward stage) Predict multiple flow fields (accompanied by the corresponding masks and residuals) +up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) +# Merge multiple predictions +imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, # self.comb_block stacks two convolutional layers + mask, img_res, mean_) + +``` + +### ⏫ performance gain + +| # Number of flow pairs | Vimeo 90k | Hard | Extreme | +|------------------------|---------------|---------------|---------------| +| Baseline (1 pair) | 35.84 | 30.52 | 25.25 | +| 3 pairs | 35.97 (**+0.13**) | 30.60 (**+0.08**) | 25.30 (**+0.05**) | +| 5 pairs | 36.00 (**+0.16**) | 30.63 (**+0.11**) | 25.33 (**+0.08**) | + +## Comparison with SOTA methods +

+ +

+ + +## Discussions + +We encountered the challenges about the novelty issue during the rebuttal process. + +We are ready to clarify again here: + +1. We consider the estimation of task-oriented flows from **the perspective of architecture formulation rather than loss function designs** in previous works. The detailed analysis can be found in Sec. 1 of the main paper. We introduce all-pairs correlation to strengthen the ability +in motion modeling, which guarantees **the consistency of flows on the coarse scale**. We employ multi-field refinement to **ensure diversity for the flow regions that need to be task-specific at the finest scale**. The two designs also enable our AMT to capture large motions and successfully handle occlusion regions with high efficiency. As a consequence, they both bring noticeable performance improvements, as shown in the ablations. +2. The frame interpolation task is closely related to the **motion modeling**. We strongly believe that a [RAFT-style](https://arxiv.org/abs/2003.12039) approach to motion modeling would be beneficial for the frame interpolation task. However, such style **has not been well studied** in the recent frame interpolation literature. Experimental results show that **all-pairs correlation is very important for the performance gain**. We also involve many novel and task-specific designs +beyond the original RAFT. For other task-related design choices, our volume design, scaled lookup strategy, content update, and cross-scale update way have good performance gains on challenging cases (i.e., Hard and Extreme). Besides, if we discard all design choices (but remaining multi-field refinement) and follow the original RAFT to retrain a new model, **the PSNR values will dramatically decrease** (-0.20dB on Vimeo, -0.33dB on Hard, and -0.39dB on Extreme). +3. [M2M-VFI](https://arxiv.org/abs/2204.03513) is the most relevant to our multi-field refinement. It also generates multiple flows through the decoder and prepares warped candidates in the image domain. However, there are **five key differences** between our multi-field refinement and M2M-VFI. **First**, our method generates the candidate frames by backward warping rather than forward warping in M2M-VFI. The proposed multi-field refinement aims to improve the common formulation of backward warping (see Eqn.~(4) in the main paper). **Second**, while M2M-VFI predicts multiple flows to overcome the hole issue and artifacts in overlapped regions caused by forward warping, we aim to alleviate the ambiguity issue in the occluded areas and motion boundaries by enhancing the diversity of flows. **Third**, M2M-VFI needs to estimate bidirectional flows first through an off-the-shelf optical flow estimator and then predict multiple bilateral flows through a motion refinement network. On the contrary, we directly estimate multiple bilateral flows in a one-stage network. In this network, we first estimate one pair of bilateral flows at the coarse scale and then derive multiple groups of fine-grained bilateral flows from the coarse flow pairs. **Fourth**, M2M-VFI jointly estimates two reliability maps together with all pairs of bilateral flows, which can be further used to fuse the overlapping pixels caused by forward warping. As shown in Eqn. (5) of the main paper, we estimate not only an occlusion mask but a residual content for cooperating with each pair of bilateral flows. The residual content is used to compensate for the unreliable details after warping. This design has been investigated in Tab. 2e of the main paper. **Fifth**, we stack two convolutional layers to adaptively merge candidate frames, while M2M-VFI normalizes the sum of all candidate frames through a pre-computed weighting map + +More discussions and details can be found in the [appendix](https://arxiv.org/abs/2304.09790) of our paper. diff --git a/Helios/eval_moviebench/utils/third_party/amt/environment.yaml b/Helios/eval_moviebench/utils/third_party/amt/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd402d0bcdc80996e6ef504a7ef607b3d3e840f3 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/environment.yaml @@ -0,0 +1,19 @@ +name: amt +channels: + - pytorch + - conda-forge + - defaults +dependencies: + - python=3.8.5 + - pip=20.3 + - cudatoolkit=11.3 + - pytorch=1.11.0 + - torchvision=0.12.0 + - numpy=1.21.5 + - pip: + - opencv-python==4.1.2.30 + - imageio==2.19.3 + - omegaconf==2.3.0 + - Pillow==9.4.0 + - tqdm==4.64.1 + - wandb==0.12.21 \ No newline at end of file diff --git a/Helios/eval_moviebench/utils/third_party/amt/flow_generation/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/flow_generation/gen_flow.py b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/gen_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..75e2d7e7940fb95b47e22faec3629293745064a2 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/gen_flow.py @@ -0,0 +1,76 @@ +import argparse +import os +import os.path as osp +import sys + +import torch + + +sys.path.append(".") +from flow_generation.liteflownet.run import estimate + +from utils.utils import read, write + + +parser = argparse.ArgumentParser( + prog="AMT", + description="Flow generation", +) +parser.add_argument("-r", "--root", default="data/vimeo_triplet") +args = parser.parse_args() + +vimeo90k_dir = args.root +vimeo90k_sequences_dir = osp.join(vimeo90k_dir, "sequences") +vimeo90k_flow_dir = osp.join(vimeo90k_dir, "flow") + + +def pred_flow(img1, img2): + img1 = torch.from_numpy(img1).float().permute(2, 0, 1) / 255.0 + img2 = torch.from_numpy(img2).float().permute(2, 0, 1) / 255.0 + + flow = estimate(img1, img2) + + flow = flow.permute(1, 2, 0).cpu().numpy() + return flow + + +print("Built Flow Path") +if not osp.exists(vimeo90k_flow_dir): + os.makedirs(vimeo90k_flow_dir) + +for sequences_path in sorted(os.listdir(vimeo90k_sequences_dir)): + vimeo90k_sequences_path_dir = osp.join(vimeo90k_sequences_dir, sequences_path) + vimeo90k_flow_path_dir = osp.join(vimeo90k_flow_dir, sequences_path) + if not osp.exists(vimeo90k_flow_path_dir): + os.mkdir(vimeo90k_flow_path_dir) + + for sequences_id in sorted(os.listdir(vimeo90k_sequences_path_dir)): + vimeo90k_flow_id_dir = osp.join(vimeo90k_flow_path_dir, sequences_id) + if not osp.exists(vimeo90k_flow_id_dir): + os.mkdir(vimeo90k_flow_id_dir) + +for sequences_path in sorted(os.listdir(vimeo90k_sequences_dir)): + vimeo90k_sequences_path_dir = os.path.join(vimeo90k_sequences_dir, sequences_path) + vimeo90k_flow_path_dir = os.path.join(vimeo90k_flow_dir, sequences_path) + + for sequences_id in sorted(os.listdir(vimeo90k_sequences_path_dir)): + vimeo90k_sequences_id_dir = os.path.join(vimeo90k_sequences_path_dir, sequences_id) + vimeo90k_flow_id_dir = os.path.join(vimeo90k_flow_path_dir, sequences_id) + + img0_path = vimeo90k_sequences_id_dir + "/im1.png" + imgt_path = vimeo90k_sequences_id_dir + "/im2.png" + img1_path = vimeo90k_sequences_id_dir + "/im3.png" + flow_t0_path = vimeo90k_flow_id_dir + "/flow_t0.flo" + flow_t1_path = vimeo90k_flow_id_dir + "/flow_t1.flo" + + img0 = read(img0_path) + imgt = read(imgt_path) + img1 = read(img1_path) + + flow_t0 = pred_flow(imgt, img0) + flow_t1 = pred_flow(imgt, img1) + + write(flow_t0_path, flow_t0) + write(flow_t1_path, flow_t1) + + print("Written Sequences {}".format(sequences_path)) diff --git a/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/README.md b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9511ad984f0209048ad912250b611f8e0459668b --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/README.md @@ -0,0 +1,45 @@ +# pytorch-liteflownet +This is a personal reimplementation of LiteFlowNet [1] using PyTorch. Should you be making use of this work, please cite the paper accordingly. Also, make sure to adhere to the licensing terms of the authors. Should you be making use of this particular implementation, please acknowledge it appropriately [2]. + +Paper + +For the original Caffe version of this work, please see: https://github.com/twhui/LiteFlowNet +
+Other optical flow implementations from me: [pytorch-pwc](https://github.com/sniklaus/pytorch-pwc), [pytorch-unflow](https://github.com/sniklaus/pytorch-unflow), [pytorch-spynet](https://github.com/sniklaus/pytorch-spynet) + +## setup +The correlation layer is implemented in CUDA using CuPy, which is why CuPy is a required dependency. It can be installed using `pip install cupy` or alternatively using one of the provided [binary packages](https://docs.cupy.dev/en/stable/install.html#installing-cupy) as outlined in the CuPy repository. If you would like to use Docker, you can take a look at [this](https://github.com/sniklaus/pytorch-liteflownet/pull/43) pull request to get started. + +## usage +To run it on your own pair of images, use the following command. You can choose between three models, please make sure to see their paper / the code for more details. + +``` +python run.py --model default --one ./images/one.png --two ./images/two.png --out ./out.flo +``` + +I am afraid that I cannot guarantee that this reimplementation is correct. However, it produced results pretty much identical to the implementation of the original authors in the examples that I tried. There are some numerical deviations that stem from differences in the `DownsampleLayer` of Caffe and the `torch.nn.functional.interpolate` function of PyTorch. Please feel free to contribute to this repository by submitting issues and pull requests. + +## comparison +

Comparison

+ +## license +As stated in the licensing terms of the authors of the paper, their material is provided for research purposes only. Please make sure to further consult their licensing terms. + +## references +``` +[1] @inproceedings{Hui_CVPR_2018, + author = {Tak-Wai Hui and Xiaoou Tang and Chen Change Loy}, + title = {{LiteFlowNet}: A Lightweight Convolutional Neural Network for Optical Flow Estimation}, + booktitle = {IEEE Conference on Computer Vision and Pattern Recognition}, + year = {2018} + } +``` + +``` +[2] @misc{pytorch-liteflownet, + author = {Simon Niklaus}, + title = {A Reimplementation of {LiteFlowNet} Using {PyTorch}}, + year = {2019}, + howpublished = {\url{https://github.com/sniklaus/pytorch-liteflownet}} + } +``` \ No newline at end of file diff --git a/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/correlation/README.md b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/correlation/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e80f923bfa484ff505366c30f66fa88da0bfd566 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/correlation/README.md @@ -0,0 +1 @@ +This is an adaptation of the FlowNet2 implementation in order to compute cost volumes. Should you be making use of this work, please make sure to adhere to the licensing terms of the original authors. Should you be making use or modify this particular implementation, please acknowledge it appropriately. \ No newline at end of file diff --git a/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/correlation/correlation.py b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/correlation/correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..c1efcfcf120f0d10784f67427a7f40788d25f54e --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/correlation/correlation.py @@ -0,0 +1,446 @@ +#!/usr/bin/env python + +import math +import re + +import cupy +import torch + + +kernel_Correlation_rearrange = """ + extern "C" __global__ void kernel_Correlation_rearrange( + const int n, + const float* input, + float* output + ) { + int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; + if (intIndex >= n) { + return; + } + int intSample = blockIdx.z; + int intChannel = blockIdx.y; + float fltValue = input[(((intSample * SIZE_1(input)) + intChannel) * SIZE_2(input) * SIZE_3(input)) + intIndex]; + __syncthreads(); + int intPaddedY = (intIndex / SIZE_3(input)) + 3*{{intStride}}; + int intPaddedX = (intIndex % SIZE_3(input)) + 3*{{intStride}}; + int intRearrange = ((SIZE_3(input) + 6*{{intStride}}) * intPaddedY) + intPaddedX; + output[(((intSample * SIZE_1(output) * SIZE_2(output)) + intRearrange) * SIZE_1(input)) + intChannel] = fltValue; + } +""" + +kernel_Correlation_updateOutput = """ + extern "C" __global__ void kernel_Correlation_updateOutput( + const int n, + const float* rbot0, + const float* rbot1, + float* top + ) { + extern __shared__ char patch_data_char[]; + float *patch_data = (float *)patch_data_char; + // First (upper left) position of kernel upper-left corner in current center position of neighborhood in image 1 + int x1 = (blockIdx.x + 3) * {{intStride}}; + int y1 = (blockIdx.y + 3) * {{intStride}}; + int item = blockIdx.z; + int ch_off = threadIdx.x; + // Load 3D patch into shared shared memory + for (int j = 0; j < 1; j++) { // HEIGHT + for (int i = 0; i < 1; i++) { // WIDTH + int ji_off = (j + i) * SIZE_3(rbot0); + for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS + int idx1 = ((item * SIZE_1(rbot0) + y1+j) * SIZE_2(rbot0) + x1+i) * SIZE_3(rbot0) + ch; + int idxPatchData = ji_off + ch; + patch_data[idxPatchData] = rbot0[idx1]; + } + } + } + __syncthreads(); + __shared__ float sum[32]; + // Compute correlation + for (int top_channel = 0; top_channel < SIZE_1(top); top_channel++) { + sum[ch_off] = 0; + int s2o = (top_channel % 7 - 3) * {{intStride}}; + int s2p = (top_channel / 7 - 3) * {{intStride}}; + for (int j = 0; j < 1; j++) { // HEIGHT + for (int i = 0; i < 1; i++) { // WIDTH + int ji_off = (j + i) * SIZE_3(rbot0); + for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS + int x2 = x1 + s2o; + int y2 = y1 + s2p; + int idxPatchData = ji_off + ch; + int idx2 = ((item * SIZE_1(rbot0) + y2+j) * SIZE_2(rbot0) + x2+i) * SIZE_3(rbot0) + ch; + sum[ch_off] += patch_data[idxPatchData] * rbot1[idx2]; + } + } + } + __syncthreads(); + if (ch_off == 0) { + float total_sum = 0; + for (int idx = 0; idx < 32; idx++) { + total_sum += sum[idx]; + } + const int sumelems = SIZE_3(rbot0); + const int index = ((top_channel*SIZE_2(top) + blockIdx.y)*SIZE_3(top))+blockIdx.x; + top[index + item*SIZE_1(top)*SIZE_2(top)*SIZE_3(top)] = total_sum / (float)sumelems; + } + } + } +""" + +kernel_Correlation_updateGradOne = """ + #define ROUND_OFF 50000 + extern "C" __global__ void kernel_Correlation_updateGradOne( + const int n, + const int intSample, + const float* rbot0, + const float* rbot1, + const float* gradOutput, + float* gradOne, + float* gradTwo + ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) { + int n = intIndex % SIZE_1(gradOne); // channels + int l = (intIndex / SIZE_1(gradOne)) % SIZE_3(gradOne) + 3*{{intStride}}; // w-pos + int m = (intIndex / SIZE_1(gradOne) / SIZE_3(gradOne)) % SIZE_2(gradOne) + 3*{{intStride}}; // h-pos + // round_off is a trick to enable integer division with ceil, even for negative numbers + // We use a large offset, for the inner part not to become negative. + const int round_off = ROUND_OFF; + const int round_off_s1 = {{intStride}} * round_off; + // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior: + int xmin = (l - 3*{{intStride}} + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}}) / {{intStride}} + int ymin = (m - 3*{{intStride}} + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}}) / {{intStride}} + // Same here: + int xmax = (l - 3*{{intStride}} + round_off_s1) / {{intStride}} - round_off; // floor (l - 3*{{intStride}}) / {{intStride}} + int ymax = (m - 3*{{intStride}} + round_off_s1) / {{intStride}} - round_off; // floor (m - 3*{{intStride}}) / {{intStride}} + float sum = 0; + if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) { + xmin = max(0,xmin); + xmax = min(SIZE_3(gradOutput)-1,xmax); + ymin = max(0,ymin); + ymax = min(SIZE_2(gradOutput)-1,ymax); + for (int p = -3; p <= 3; p++) { + for (int o = -3; o <= 3; o++) { + // Get rbot1 data: + int s2o = {{intStride}} * o; + int s2p = {{intStride}} * p; + int idxbot1 = ((intSample * SIZE_1(rbot0) + (m+s2p)) * SIZE_2(rbot0) + (l+s2o)) * SIZE_3(rbot0) + n; + float bot1tmp = rbot1[idxbot1]; // rbot1[l+s2o,m+s2p,n] + // Index offset for gradOutput in following loops: + int op = (p+3) * 7 + (o+3); // index[o,p] + int idxopoffset = (intSample * SIZE_1(gradOutput) + op); + for (int y = ymin; y <= ymax; y++) { + for (int x = xmin; x <= xmax; x++) { + int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p] + sum += gradOutput[idxgradOutput] * bot1tmp; + } + } + } + } + } + const int sumelems = SIZE_1(gradOne); + const int bot0index = ((n * SIZE_2(gradOne)) + (m-3*{{intStride}})) * SIZE_3(gradOne) + (l-3*{{intStride}}); + gradOne[bot0index + intSample*SIZE_1(gradOne)*SIZE_2(gradOne)*SIZE_3(gradOne)] = sum / (float)sumelems; + } } +""" + +kernel_Correlation_updateGradTwo = """ + #define ROUND_OFF 50000 + extern "C" __global__ void kernel_Correlation_updateGradTwo( + const int n, + const int intSample, + const float* rbot0, + const float* rbot1, + const float* gradOutput, + float* gradOne, + float* gradTwo + ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) { + int n = intIndex % SIZE_1(gradTwo); // channels + int l = (intIndex / SIZE_1(gradTwo)) % SIZE_3(gradTwo) + 3*{{intStride}}; // w-pos + int m = (intIndex / SIZE_1(gradTwo) / SIZE_3(gradTwo)) % SIZE_2(gradTwo) + 3*{{intStride}}; // h-pos + // round_off is a trick to enable integer division with ceil, even for negative numbers + // We use a large offset, for the inner part not to become negative. + const int round_off = ROUND_OFF; + const int round_off_s1 = {{intStride}} * round_off; + float sum = 0; + for (int p = -3; p <= 3; p++) { + for (int o = -3; o <= 3; o++) { + int s2o = {{intStride}} * o; + int s2p = {{intStride}} * p; + //Get X,Y ranges and clamp + // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior: + int xmin = (l - 3*{{intStride}} - s2o + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}} - s2o) / {{intStride}} + int ymin = (m - 3*{{intStride}} - s2p + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}} - s2o) / {{intStride}} + // Same here: + int xmax = (l - 3*{{intStride}} - s2o + round_off_s1) / {{intStride}} - round_off; // floor (l - 3*{{intStride}} - s2o) / {{intStride}} + int ymax = (m - 3*{{intStride}} - s2p + round_off_s1) / {{intStride}} - round_off; // floor (m - 3*{{intStride}} - s2p) / {{intStride}} + if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) { + xmin = max(0,xmin); + xmax = min(SIZE_3(gradOutput)-1,xmax); + ymin = max(0,ymin); + ymax = min(SIZE_2(gradOutput)-1,ymax); + // Get rbot0 data: + int idxbot0 = ((intSample * SIZE_1(rbot0) + (m-s2p)) * SIZE_2(rbot0) + (l-s2o)) * SIZE_3(rbot0) + n; + float bot0tmp = rbot0[idxbot0]; // rbot1[l+s2o,m+s2p,n] + // Index offset for gradOutput in following loops: + int op = (p+3) * 7 + (o+3); // index[o,p] + int idxopoffset = (intSample * SIZE_1(gradOutput) + op); + for (int y = ymin; y <= ymax; y++) { + for (int x = xmin; x <= xmax; x++) { + int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p] + sum += gradOutput[idxgradOutput] * bot0tmp; + } + } + } + } + } + const int sumelems = SIZE_1(gradTwo); + const int bot1index = ((n * SIZE_2(gradTwo)) + (m-3*{{intStride}})) * SIZE_3(gradTwo) + (l-3*{{intStride}}); + gradTwo[bot1index + intSample*SIZE_1(gradTwo)*SIZE_2(gradTwo)*SIZE_3(gradTwo)] = sum / (float)sumelems; + } } +""" + + +def cupy_kernel(strFunction, objVariables): + strKernel = globals()[strFunction].replace("{{intStride}}", str(objVariables["intStride"])) + + while True: + objMatch = re.search(r"(SIZE_)([0-4])(\()([^\)]*)(\))", strKernel) + + if objMatch is None: + break + # end + + intArg = int(objMatch.group(2)) + + strTensor = objMatch.group(4) + intSizes = objVariables[strTensor].size() + + strKernel = strKernel.replace( + objMatch.group(), + str(intSizes[intArg] if not torch.is_tensor(intSizes[intArg]) else intSizes[intArg].item()), + ) + # end + + while True: + objMatch = re.search(r"(VALUE_)([0-4])(\()([^\)]+)(\))", strKernel) + + if objMatch is None: + break + # end + + intArgs = int(objMatch.group(2)) + strArgs = objMatch.group(4).split(",") + + strTensor = strArgs[0] + intStrides = objVariables[strTensor].stride() + strIndex = [ + "((" + + strArgs[intArg + 1].replace("{", "(").replace("}", ")").strip() + + ")*" + + str(intStrides[intArg] if not torch.is_tensor(intStrides[intArg]) else intStrides[intArg].item()) + + ")" + for intArg in range(intArgs) + ] + + strKernel = strKernel.replace(objMatch.group(0), strTensor + "[" + str.join("+", strIndex) + "]") + # end + + return strKernel + + +# end + + +@cupy.memoize(for_each_device=True) +def cupy_launch(strFunction, strKernel): + return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction) + + +# end + + +class _FunctionCorrelation(torch.autograd.Function): + @staticmethod + def forward(self, one, two, intStride): + rbot0 = one.new_zeros( + [one.shape[0], one.shape[2] + (6 * intStride), one.shape[3] + (6 * intStride), one.shape[1]] + ) + rbot1 = one.new_zeros( + [one.shape[0], one.shape[2] + (6 * intStride), one.shape[3] + (6 * intStride), one.shape[1]] + ) + + self.intStride = intStride + + one = one.contiguous() + assert one.is_cuda + two = two.contiguous() + assert two.is_cuda + + output = one.new_zeros( + [one.shape[0], 49, int(math.ceil(one.shape[2] / intStride)), int(math.ceil(one.shape[3] / intStride))] + ) + + if one.is_cuda: + n = one.shape[2] * one.shape[3] + cupy_launch( + "kernel_Correlation_rearrange", + cupy_kernel( + "kernel_Correlation_rearrange", {"intStride": self.intStride, "input": one, "output": rbot0} + ), + )( + grid=(int((n + 16 - 1) / 16), one.shape[1], one.shape[0]), + block=(16, 1, 1), + args=[cupy.int32(n), one.data_ptr(), rbot0.data_ptr()], + ) + + n = two.shape[2] * two.shape[3] + cupy_launch( + "kernel_Correlation_rearrange", + cupy_kernel( + "kernel_Correlation_rearrange", {"intStride": self.intStride, "input": two, "output": rbot1} + ), + )( + grid=(int((n + 16 - 1) / 16), two.shape[1], two.shape[0]), + block=(16, 1, 1), + args=[cupy.int32(n), two.data_ptr(), rbot1.data_ptr()], + ) + + n = output.shape[1] * output.shape[2] * output.shape[3] + cupy_launch( + "kernel_Correlation_updateOutput", + cupy_kernel( + "kernel_Correlation_updateOutput", + {"intStride": self.intStride, "rbot0": rbot0, "rbot1": rbot1, "top": output}, + ), + )( + grid=(output.shape[3], output.shape[2], output.shape[0]), + block=(32, 1, 1), + shared_mem=one.shape[1] * 4, + args=[cupy.int32(n), rbot0.data_ptr(), rbot1.data_ptr(), output.data_ptr()], + ) + + elif not one.is_cuda: + raise NotImplementedError() + + # end + + self.save_for_backward(one, two, rbot0, rbot1) + + return output + + # end + + @staticmethod + def backward(self, gradOutput): + one, two, rbot0, rbot1 = self.saved_tensors + + gradOutput = gradOutput.contiguous() + assert gradOutput.is_cuda + + gradOne = ( + one.new_zeros([one.shape[0], one.shape[1], one.shape[2], one.shape[3]]) + if self.needs_input_grad[0] + else None + ) + gradTwo = ( + one.new_zeros([one.shape[0], one.shape[1], one.shape[2], one.shape[3]]) + if self.needs_input_grad[1] + else None + ) + + if one.is_cuda: + if gradOne is not None: + for intSample in range(one.shape[0]): + n = one.shape[1] * one.shape[2] * one.shape[3] + cupy_launch( + "kernel_Correlation_updateGradOne", + cupy_kernel( + "kernel_Correlation_updateGradOne", + { + "intStride": self.intStride, + "rbot0": rbot0, + "rbot1": rbot1, + "gradOutput": gradOutput, + "gradOne": gradOne, + "gradTwo": None, + }, + ), + )( + grid=(int((n + 512 - 1) / 512), 1, 1), + block=(512, 1, 1), + args=[ + cupy.int32(n), + intSample, + rbot0.data_ptr(), + rbot1.data_ptr(), + gradOutput.data_ptr(), + gradOne.data_ptr(), + None, + ], + ) + # end + # end + + if gradTwo is not None: + for intSample in range(one.shape[0]): + n = one.shape[1] * one.shape[2] * one.shape[3] + cupy_launch( + "kernel_Correlation_updateGradTwo", + cupy_kernel( + "kernel_Correlation_updateGradTwo", + { + "intStride": self.intStride, + "rbot0": rbot0, + "rbot1": rbot1, + "gradOutput": gradOutput, + "gradOne": None, + "gradTwo": gradTwo, + }, + ), + )( + grid=(int((n + 512 - 1) / 512), 1, 1), + block=(512, 1, 1), + args=[ + cupy.int32(n), + intSample, + rbot0.data_ptr(), + rbot1.data_ptr(), + gradOutput.data_ptr(), + None, + gradTwo.data_ptr(), + ], + ) + # end + # end + + elif not one.is_cuda: + raise NotImplementedError() + + # end + + return gradOne, gradTwo, None + + # end + + +# end + + +def FunctionCorrelation(tenOne, tenTwo, intStride): + return _FunctionCorrelation.apply(tenOne, tenTwo, intStride) + + +# end + + +class ModuleCorrelation(torch.nn.Module): + def __init__(self): + super().__init__() + + # end + + def forward(self, tenOne, tenTwo, intStride): + return _FunctionCorrelation.apply(tenOne, tenTwo, intStride) + + # end + + +# end diff --git a/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/run.py b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/run.py new file mode 100644 index 0000000000000000000000000000000000000000..4444ede7163d773125e904724622561c4b06e7b5 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/flow_generation/liteflownet/run.py @@ -0,0 +1,602 @@ +#!/usr/bin/env python + +import getopt +import math +import sys + +import numpy +import PIL +import PIL.Image +import torch + + +try: + from .correlation import correlation # the custom cost volume layer +except Exception: + sys.path.insert(0, "./correlation") + import correlation # you should consider upgrading python +# end + +########################################################## + +assert int(str("").join(torch.__version__.split(".")[0:2])) >= 13 # requires at least pytorch version 1.3.0 + +torch.set_grad_enabled(False) # make sure to not compute gradients for computational performance + +torch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance + +########################################################## + +arguments_strModel = "default" # 'default', or 'kitti', or 'sintel' +arguments_strOne = "./images/one.png" +arguments_strTwo = "./images/two.png" +arguments_strOut = "./out.flo" + +for strOption, strArgument in getopt.getopt( + sys.argv[1:], "", [strParameter[2:] + "=" for strParameter in sys.argv[1::2]] +)[0]: + if strOption == "--model" and strArgument != "": + arguments_strModel = strArgument # which model to use + if strOption == "--one" and strArgument != "": + arguments_strOne = strArgument # path to the first frame + if strOption == "--two" and strArgument != "": + arguments_strTwo = strArgument # path to the second frame + if strOption == "--out" and strArgument != "": + arguments_strOut = strArgument # path to where the output should be stored +# end + +########################################################## + +backwarp_tenGrid = {} + + +def backwarp(tenInput, tenFlow): + if str(tenFlow.shape) not in backwarp_tenGrid: + tenHor = ( + torch.linspace(-1.0 + (1.0 / tenFlow.shape[3]), 1.0 - (1.0 / tenFlow.shape[3]), tenFlow.shape[3]) + .view(1, 1, 1, -1) + .repeat(1, 1, tenFlow.shape[2], 1) + ) + tenVer = ( + torch.linspace(-1.0 + (1.0 / tenFlow.shape[2]), 1.0 - (1.0 / tenFlow.shape[2]), tenFlow.shape[2]) + .view(1, 1, -1, 1) + .repeat(1, 1, 1, tenFlow.shape[3]) + ) + + backwarp_tenGrid[str(tenFlow.shape)] = torch.cat([tenHor, tenVer], 1).cuda() + # end + + tenFlow = torch.cat( + [ + tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), + tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0), + ], + 1, + ) + + return torch.nn.functional.grid_sample( + input=tenInput, + grid=(backwarp_tenGrid[str(tenFlow.shape)] + tenFlow).permute(0, 2, 3, 1), + mode="bilinear", + padding_mode="zeros", + align_corners=False, + ) + + +# end + +########################################################## + + +class Network(torch.nn.Module): + def __init__(self): + super().__init__() + + class Features(torch.nn.Module): + def __init__(self): + super().__init__() + + self.netOne = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=3, out_channels=32, kernel_size=7, stride=1, padding=3), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netTwo = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netThr = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netFou = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netFiv = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + self.netSix = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=128, out_channels=192, kernel_size=3, stride=2, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + # end + + def forward(self, tenInput): + tenOne = self.netOne(tenInput) + tenTwo = self.netTwo(tenOne) + tenThr = self.netThr(tenTwo) + tenFou = self.netFou(tenThr) + tenFiv = self.netFiv(tenFou) + tenSix = self.netSix(tenFiv) + + return [tenOne, tenTwo, tenThr, tenFou, tenFiv, tenSix] + + # end + + # end + + class Matching(torch.nn.Module): + def __init__(self, intLevel): + super().__init__() + + self.fltBackwarp = [0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625][intLevel] + + if intLevel != 2: + self.netFeat = torch.nn.Sequential() + + elif intLevel == 2: + self.netFeat = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=1, stride=1, padding=0), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + # end + + if intLevel == 6: + self.netUpflow = None + + elif intLevel != 6: + self.netUpflow = torch.nn.ConvTranspose2d( + in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1, bias=False, groups=2 + ) + + # end + + if intLevel >= 4: + self.netUpcorr = None + + elif intLevel < 4: + self.netUpcorr = torch.nn.ConvTranspose2d( + in_channels=49, out_channels=49, kernel_size=4, stride=2, padding=1, bias=False, groups=49 + ) + + # end + + self.netMain = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=49, out_channels=128, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d( + in_channels=32, + out_channels=2, + kernel_size=[0, 0, 7, 5, 5, 3, 3][intLevel], + stride=1, + padding=[0, 0, 3, 2, 2, 1, 1][intLevel], + ), + ) + + # end + + def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow): + tenFeaturesOne = self.netFeat(tenFeaturesOne) + tenFeaturesTwo = self.netFeat(tenFeaturesTwo) + + if tenFlow is not None: + tenFlow = self.netUpflow(tenFlow) + # end + + if tenFlow is not None: + tenFeaturesTwo = backwarp(tenInput=tenFeaturesTwo, tenFlow=tenFlow * self.fltBackwarp) + # end + + if self.netUpcorr is None: + tenCorrelation = torch.nn.functional.leaky_relu( + input=correlation.FunctionCorrelation( + tenOne=tenFeaturesOne, tenTwo=tenFeaturesTwo, intStride=1 + ), + negative_slope=0.1, + inplace=False, + ) + + elif self.netUpcorr is not None: + tenCorrelation = self.netUpcorr( + torch.nn.functional.leaky_relu( + input=correlation.FunctionCorrelation( + tenOne=tenFeaturesOne, tenTwo=tenFeaturesTwo, intStride=2 + ), + negative_slope=0.1, + inplace=False, + ) + ) + + # end + + return (tenFlow if tenFlow is not None else 0.0) + self.netMain(tenCorrelation) + + # end + + # end + + class Subpixel(torch.nn.Module): + def __init__(self, intLevel): + super().__init__() + + self.fltBackward = [0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625][intLevel] + + if intLevel != 2: + self.netFeat = torch.nn.Sequential() + + elif intLevel == 2: + self.netFeat = torch.nn.Sequential( + torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=1, stride=1, padding=0), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + # end + + self.netMain = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=[0, 0, 130, 130, 194, 258, 386][intLevel], + out_channels=128, + kernel_size=3, + stride=1, + padding=1, + ), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d( + in_channels=32, + out_channels=2, + kernel_size=[0, 0, 7, 5, 5, 3, 3][intLevel], + stride=1, + padding=[0, 0, 3, 2, 2, 1, 1][intLevel], + ), + ) + + # end + + def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow): + tenFeaturesOne = self.netFeat(tenFeaturesOne) + tenFeaturesTwo = self.netFeat(tenFeaturesTwo) + + if tenFlow is not None: + tenFeaturesTwo = backwarp(tenInput=tenFeaturesTwo, tenFlow=tenFlow * self.fltBackward) + # end + + return (tenFlow if tenFlow is not None else 0.0) + self.netMain( + torch.cat([tenFeaturesOne, tenFeaturesTwo, tenFlow], 1) + ) + + # end + + # end + + class Regularization(torch.nn.Module): + def __init__(self, intLevel): + super().__init__() + + self.fltBackward = [0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625][intLevel] + + self.intUnfold = [0, 0, 7, 5, 5, 3, 3][intLevel] + + if intLevel >= 5: + self.netFeat = torch.nn.Sequential() + + elif intLevel < 5: + self.netFeat = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=[0, 0, 32, 64, 96, 128, 192][intLevel], + out_channels=128, + kernel_size=1, + stride=1, + padding=0, + ), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + # end + + self.netMain = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=[0, 0, 131, 131, 131, 131, 195][intLevel], + out_channels=128, + kernel_size=3, + stride=1, + padding=1, + ), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1), + torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), + ) + + if intLevel >= 5: + self.netDist = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=32, + out_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], + kernel_size=[0, 0, 7, 5, 5, 3, 3][intLevel], + stride=1, + padding=[0, 0, 3, 2, 2, 1, 1][intLevel], + ) + ) + + elif intLevel < 5: + self.netDist = torch.nn.Sequential( + torch.nn.Conv2d( + in_channels=32, + out_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], + kernel_size=([0, 0, 7, 5, 5, 3, 3][intLevel], 1), + stride=1, + padding=([0, 0, 3, 2, 2, 1, 1][intLevel], 0), + ), + torch.nn.Conv2d( + in_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], + out_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], + kernel_size=(1, [0, 0, 7, 5, 5, 3, 3][intLevel]), + stride=1, + padding=(0, [0, 0, 3, 2, 2, 1, 1][intLevel]), + ), + ) + + # end + + self.netScaleX = torch.nn.Conv2d( + in_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], out_channels=1, kernel_size=1, stride=1, padding=0 + ) + self.netScaleY = torch.nn.Conv2d( + in_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], out_channels=1, kernel_size=1, stride=1, padding=0 + ) + + # eny + + def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow): + tenDifference = ( + ((tenOne - backwarp(tenInput=tenTwo, tenFlow=tenFlow * self.fltBackward)) ** 2) + .sum(1, True) + .sqrt() + .detach() + ) + + tenDist = self.netDist( + self.netMain( + torch.cat( + [ + tenDifference, + tenFlow + - tenFlow.view(tenFlow.shape[0], 2, -1).mean(2, True).view(tenFlow.shape[0], 2, 1, 1), + self.netFeat(tenFeaturesOne), + ], + 1, + ) + ) + ) + tenDist = (tenDist**2).neg() + tenDist = (tenDist - tenDist.max(1, True)[0]).exp() + + tenDivisor = tenDist.sum(1, True).reciprocal() + + tenScaleX = ( + self.netScaleX( + tenDist + * torch.nn.functional.unfold( + input=tenFlow[:, 0:1, :, :], + kernel_size=self.intUnfold, + stride=1, + padding=int((self.intUnfold - 1) / 2), + ).view_as(tenDist) + ) + * tenDivisor + ) + tenScaleY = ( + self.netScaleY( + tenDist + * torch.nn.functional.unfold( + input=tenFlow[:, 1:2, :, :], + kernel_size=self.intUnfold, + stride=1, + padding=int((self.intUnfold - 1) / 2), + ).view_as(tenDist) + ) + * tenDivisor + ) + + return torch.cat([tenScaleX, tenScaleY], 1) + + # end + + # end + + self.netFeatures = Features() + self.netMatching = torch.nn.ModuleList([Matching(intLevel) for intLevel in [2, 3, 4, 5, 6]]) + self.netSubpixel = torch.nn.ModuleList([Subpixel(intLevel) for intLevel in [2, 3, 4, 5, 6]]) + self.netRegularization = torch.nn.ModuleList([Regularization(intLevel) for intLevel in [2, 3, 4, 5, 6]]) + + self.load_state_dict( + { + strKey.replace("module", "net"): tenWeight + for strKey, tenWeight in torch.hub.load_state_dict_from_url( + url="http://content.sniklaus.com/github/pytorch-liteflownet/network-" + + arguments_strModel + + ".pytorch" + ).items() + } + ) + # self.load_state_dict(torch.load('./liteflownet/network-default.pth')) + + # end + + def forward(self, tenOne, tenTwo): + tenOne[:, 0, :, :] = tenOne[:, 0, :, :] - 0.411618 + tenOne[:, 1, :, :] = tenOne[:, 1, :, :] - 0.434631 + tenOne[:, 2, :, :] = tenOne[:, 2, :, :] - 0.454253 + + tenTwo[:, 0, :, :] = tenTwo[:, 0, :, :] - 0.410782 + tenTwo[:, 1, :, :] = tenTwo[:, 1, :, :] - 0.433645 + tenTwo[:, 2, :, :] = tenTwo[:, 2, :, :] - 0.452793 + + tenFeaturesOne = self.netFeatures(tenOne) + tenFeaturesTwo = self.netFeatures(tenTwo) + + tenOne = [tenOne] + tenTwo = [tenTwo] + + for intLevel in [1, 2, 3, 4, 5]: + tenOne.append( + torch.nn.functional.interpolate( + input=tenOne[-1], + size=(tenFeaturesOne[intLevel].shape[2], tenFeaturesOne[intLevel].shape[3]), + mode="bilinear", + align_corners=False, + ) + ) + tenTwo.append( + torch.nn.functional.interpolate( + input=tenTwo[-1], + size=(tenFeaturesTwo[intLevel].shape[2], tenFeaturesTwo[intLevel].shape[3]), + mode="bilinear", + align_corners=False, + ) + ) + # end + + tenFlow = None + + for intLevel in [-1, -2, -3, -4, -5]: + tenFlow = self.netMatching[intLevel]( + tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow + ) + tenFlow = self.netSubpixel[intLevel]( + tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow + ) + tenFlow = self.netRegularization[intLevel]( + tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow + ) + # end + + return tenFlow * 20.0 + + # end + + +# end + +netNetwork = None + +########################################################## + + +def estimate(tenOne, tenTwo): + global netNetwork + + if netNetwork is None: + netNetwork = Network().cuda().eval() + # end + + assert tenOne.shape[1] == tenTwo.shape[1] + assert tenOne.shape[2] == tenTwo.shape[2] + + intWidth = tenOne.shape[2] + intHeight = tenOne.shape[1] + + # assert(intWidth == 1024) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue + # assert(intHeight == 436) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue + + tenPreprocessedOne = tenOne.cuda().view(1, 3, intHeight, intWidth) + tenPreprocessedTwo = tenTwo.cuda().view(1, 3, intHeight, intWidth) + + intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 32.0) * 32.0)) + intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 32.0) * 32.0)) + + tenPreprocessedOne = torch.nn.functional.interpolate( + input=tenPreprocessedOne, + size=(intPreprocessedHeight, intPreprocessedWidth), + mode="bilinear", + align_corners=False, + ) + tenPreprocessedTwo = torch.nn.functional.interpolate( + input=tenPreprocessedTwo, + size=(intPreprocessedHeight, intPreprocessedWidth), + mode="bilinear", + align_corners=False, + ) + + tenFlow = torch.nn.functional.interpolate( + input=netNetwork(tenPreprocessedOne, tenPreprocessedTwo), + size=(intHeight, intWidth), + mode="bilinear", + align_corners=False, + ) + + tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth) + tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight) + + return tenFlow[0, :, :, :].cpu() + + +# end + +########################################################## + +if __name__ == "__main__": + tenOne = torch.FloatTensor( + numpy.ascontiguousarray( + numpy.array(PIL.Image.open(arguments_strOne))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) + * (1.0 / 255.0) + ) + ) + tenTwo = torch.FloatTensor( + numpy.ascontiguousarray( + numpy.array(PIL.Image.open(arguments_strTwo))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) + * (1.0 / 255.0) + ) + ) + + tenOutput = estimate(tenOne, tenTwo) + + objOutput = open(arguments_strOut, "wb") + + numpy.array([80, 73, 69, 72], numpy.uint8).tofile(objOutput) + numpy.array([tenOutput.shape[2], tenOutput.shape[1]], numpy.int32).tofile(objOutput) + numpy.array(tenOutput.numpy().transpose(1, 2, 0), numpy.float32).tofile(objOutput) + + objOutput.close() +# end diff --git a/Helios/eval_moviebench/utils/third_party/amt/losses/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/losses/loss.py b/Helios/eval_moviebench/utils/third_party/amt/losses/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..36d9f3ab20da3dd919418e4fed07f4511161d8e7 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/losses/loss.py @@ -0,0 +1,201 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class Loss(nn.Module): + def __init__(self, loss_weight, keys, mapping=None) -> None: + """ + mapping: map the kwargs keys into desired ones. + """ + super().__init__() + self.loss_weight = loss_weight + self.keys = keys + self.mapping = mapping + if isinstance(mapping, dict): + self.mapping = {k: v for k, v in mapping if v in keys} + + def forward(self, **kwargs): + params = {k: v for k, v in kwargs.items() if k in self.keys} + if self.mapping is not None: + for k, v in kwargs.items(): + if self.mapping.get(k) is not None: + params[self.mapping[k]] = v + + return self._forward(**params) * self.loss_weight + + def _forward(self, **kwargs): + pass + + +class CharbonnierLoss(Loss): + def __init__(self, loss_weight, keys) -> None: + super().__init__(loss_weight, keys) + + def _forward(self, imgt_pred, imgt): + diff = imgt_pred - imgt + loss = ((diff**2 + 1e-6) ** 0.5).mean() + return loss + + +class AdaCharbonnierLoss(Loss): + def __init__(self, loss_weight, keys) -> None: + super().__init__(loss_weight, keys) + + def _forward(self, imgt_pred, imgt, weight): + alpha = weight / 2 + epsilon = 10 ** (-(10 * weight - 1) / 3) + + diff = imgt_pred - imgt + loss = ((diff**2 + epsilon**2) ** alpha).mean() + return loss + + +class TernaryLoss(Loss): + def __init__(self, loss_weight, keys, patch_size=7): + super().__init__(loss_weight, keys) + self.patch_size = patch_size + out_channels = patch_size * patch_size + self.w = np.eye(out_channels).reshape((patch_size, patch_size, 1, out_channels)) + self.w = np.transpose(self.w, (3, 2, 0, 1)) + self.w = torch.tensor(self.w, dtype=torch.float32) + + def transform(self, tensor): + self.w = self.w.to(tensor.device) + tensor_ = tensor.mean(dim=1, keepdim=True) + patches = F.conv2d(tensor_, self.w, padding=self.patch_size // 2, bias=None) + loc_diff = patches - tensor_ + loc_diff_norm = loc_diff / torch.sqrt(0.81 + loc_diff**2) + return loc_diff_norm + + def valid_mask(self, tensor): + padding = self.patch_size // 2 + b, c, h, w = tensor.size() + inner = torch.ones(b, 1, h - 2 * padding, w - 2 * padding).type_as(tensor) + mask = F.pad(inner, [padding] * 4) + return mask + + def _forward(self, imgt_pred, imgt): + loc_diff_x = self.transform(imgt_pred) + loc_diff_y = self.transform(imgt) + diff = loc_diff_x - loc_diff_y.detach() + dist = (diff**2 / (0.1 + diff**2)).mean(dim=1, keepdim=True) + mask = self.valid_mask(imgt_pred) + loss = (dist * mask).mean() + return loss + + +class GeometryLoss(Loss): + def __init__(self, loss_weight, keys, patch_size=3): + super().__init__(loss_weight, keys) + self.patch_size = patch_size + out_channels = patch_size * patch_size + self.w = np.eye(out_channels).reshape((patch_size, patch_size, 1, out_channels)) + self.w = np.transpose(self.w, (3, 2, 0, 1)) + self.w = torch.tensor(self.w).float() + + def transform(self, tensor): + b, c, h, w = tensor.size() + self.w = self.w.to(tensor.device) + tensor_ = tensor.reshape(b * c, 1, h, w) + patches = F.conv2d(tensor_, self.w, padding=self.patch_size // 2, bias=None) + loc_diff = patches - tensor_ + loc_diff_ = loc_diff.reshape(b, c * (self.patch_size**2), h, w) + loc_diff_norm = loc_diff_ / torch.sqrt(0.81 + loc_diff_**2) + return loc_diff_norm + + def valid_mask(self, tensor): + padding = self.patch_size // 2 + b, c, h, w = tensor.size() + inner = torch.ones(b, 1, h - 2 * padding, w - 2 * padding).type_as(tensor) + mask = F.pad(inner, [padding] * 4) + return mask + + def _forward(self, ft_pred, ft_gt): + loss = 0.0 + for pred, gt in zip(ft_pred, ft_gt): + loc_diff_x = self.transform(pred) + loc_diff_y = self.transform(gt) + diff = loc_diff_x - loc_diff_y + dist = (diff**2 / (0.1 + diff**2)).mean(dim=1, keepdim=True) + mask = self.valid_mask(pred) + loss = loss + (dist * mask).mean() + return loss + + +class IFRFlowLoss(Loss): + def __init__(self, loss_weight, keys, beta=0.3) -> None: + super().__init__(loss_weight, keys) + self.beta = beta + self.ada_cb_loss = AdaCharbonnierLoss(1.0, ["imgt_pred", "imgt", "weight"]) + + def _forward(self, flow0_pred, flow1_pred, flow): + robust_weight0 = self.get_robust_weight(flow0_pred[0], flow[:, 0:2]) + robust_weight1 = self.get_robust_weight(flow1_pred[0], flow[:, 2:4]) + loss = 0 + for lvl in range(1, len(flow0_pred)): + scale_factor = 2**lvl + loss = loss + self.ada_cb_loss( + **{ + "imgt_pred": self.resize(flow0_pred[lvl], scale_factor), + "imgt": flow[:, 0:2], + "weight": robust_weight0, + } + ) + loss = loss + self.ada_cb_loss( + **{ + "imgt_pred": self.resize(flow1_pred[lvl], scale_factor), + "imgt": flow[:, 2:4], + "weight": robust_weight1, + } + ) + return loss + + def resize(self, x, scale_factor): + return scale_factor * F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False) + + def get_robust_weight(self, flow_pred, flow_gt): + epe = ((flow_pred.detach() - flow_gt) ** 2).sum(dim=1, keepdim=True) ** 0.5 + robust_weight = torch.exp(-self.beta * epe) + return robust_weight + + +class MultipleFlowLoss(Loss): + def __init__(self, loss_weight, keys, beta=0.3) -> None: + super().__init__(loss_weight, keys) + self.beta = beta + self.ada_cb_loss = AdaCharbonnierLoss(1.0, ["imgt_pred", "imgt", "weight"]) + + def _forward(self, flow0_pred, flow1_pred, flow): + robust_weight0 = self.get_mutli_flow_robust_weight(flow0_pred[0], flow[:, 0:2]) + robust_weight1 = self.get_mutli_flow_robust_weight(flow1_pred[0], flow[:, 2:4]) + loss = 0 + for lvl in range(1, len(flow0_pred)): + scale_factor = 2**lvl + loss = loss + self.ada_cb_loss( + **{ + "imgt_pred": self.resize(flow0_pred[lvl], scale_factor), + "imgt": flow[:, 0:2], + "weight": robust_weight0, + } + ) + loss = loss + self.ada_cb_loss( + **{ + "imgt_pred": self.resize(flow1_pred[lvl], scale_factor), + "imgt": flow[:, 2:4], + "weight": robust_weight1, + } + ) + return loss + + def resize(self, x, scale_factor): + return scale_factor * F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False) + + def get_mutli_flow_robust_weight(self, flow_pred, flow_gt): + b, num_flows, c, h, w = flow_pred.shape + flow_pred = flow_pred.view(b, num_flows, c, h, w) + flow_gt = flow_gt.repeat(1, num_flows, 1, 1).view(b, num_flows, c, h, w) + epe = ((flow_pred.detach() - flow_gt) ** 2).sum(dim=2, keepdim=True).max(1)[0] ** 0.5 + robust_weight = torch.exp(-self.beta * epe) + return robust_weight diff --git a/Helios/eval_moviebench/utils/third_party/amt/metrics/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/metrics/psnr_ssim.py b/Helios/eval_moviebench/utils/third_party/amt/metrics/psnr_ssim.py new file mode 100644 index 0000000000000000000000000000000000000000..157dbf75541ab4fc8361ecdfd41645aa32f14ad9 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/metrics/psnr_ssim.py @@ -0,0 +1,142 @@ +from math import exp + +import torch +import torch.nn.functional as F + + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + +def gaussian(window_size, sigma): + gauss = torch.Tensor([exp(-((x - window_size // 2) ** 2) / float(2 * sigma**2)) for x in range(window_size)]) + return gauss / gauss.sum() + + +def create_window(window_size, channel=1): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0).to(device) + window = _2D_window.expand(channel, 1, window_size, window_size).contiguous() + return window + + +def create_window_3d(window_size, channel=1): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()) + _3D_window = _2D_window.unsqueeze(2) @ (_1D_window.t()) + window = _3D_window.expand(1, channel, window_size, window_size, window_size).contiguous().to(device) + return window + + +def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None): + if val_range is None: + if torch.max(img1) > 128: + max_val = 255 + else: + max_val = 1 + + if torch.min(img1) < -0.5: + min_val = -1 + else: + min_val = 0 + L = max_val - min_val + else: + L = val_range + + padd = 0 + (_, channel, height, width) = img1.size() + if window is None: + real_size = min(window_size, height, width) + window = create_window(real_size, channel=channel).to(img1.device) + + mu1 = F.conv2d(F.pad(img1, (5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=channel) + mu2 = F.conv2d(F.pad(img2, (5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv2d(F.pad(img1 * img1, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu1_sq + sigma2_sq = F.conv2d(F.pad(img2 * img2, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu2_sq + sigma12 = F.conv2d(F.pad(img1 * img2, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu1_mu2 + + C1 = (0.01 * L) ** 2 + C2 = (0.03 * L) ** 2 + + v1 = 2.0 * sigma12 + C2 + v2 = sigma1_sq + sigma2_sq + C2 + cs = torch.mean(v1 / v2) + + ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2) + + if size_average: + ret = ssim_map.mean() + else: + ret = ssim_map.mean(1).mean(1).mean(1) + + if full: + return ret, cs + return ret + + +def calculate_ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None): + if val_range is None: + if torch.max(img1) > 128: + max_val = 255 + else: + max_val = 1 + + if torch.min(img1) < -0.5: + min_val = -1 + else: + min_val = 0 + L = max_val - min_val + else: + L = val_range + + padd = 0 + (_, _, height, width) = img1.size() + if window is None: + real_size = min(window_size, height, width) + window = create_window_3d(real_size, channel=1).to(img1.device) + + img1 = img1.unsqueeze(1) + img2 = img2.unsqueeze(1) + + mu1 = F.conv3d(F.pad(img1, (5, 5, 5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=1) + mu2 = F.conv3d(F.pad(img2, (5, 5, 5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=1) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv3d(F.pad(img1 * img1, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu1_sq + sigma2_sq = F.conv3d(F.pad(img2 * img2, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu2_sq + sigma12 = F.conv3d(F.pad(img1 * img2, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu1_mu2 + + C1 = (0.01 * L) ** 2 + C2 = (0.03 * L) ** 2 + + v1 = 2.0 * sigma12 + C2 + v2 = sigma1_sq + sigma2_sq + C2 + cs = torch.mean(v1 / v2) + + ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2) + + if size_average: + ret = ssim_map.mean() + else: + ret = ssim_map.mean(1).mean(1).mean(1) + + if full: + return ret, cs + return ret.detach().cpu().numpy() + + +def calculate_psnr(img1, img2): + psnr = -10 * torch.log10(((img1 - img2) * (img1 - img2)).mean()) + return psnr.detach().cpu().numpy() + + +def calculate_ie(img1, img2): + ie = torch.abs(torch.round(img1 * 255.0) - torch.round(img2 * 255.0)).mean() + return ie.detach().cpu().numpy() diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/AMT-G.py b/Helios/eval_moviebench/utils/third_party/amt/networks/AMT-G.py new file mode 100644 index 0000000000000000000000000000000000000000..16bc9e645f829c3bb9d83543a9ade114c2f4923f --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/networks/AMT-G.py @@ -0,0 +1,156 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.feat_enc import LargeEncoder +from utils.third_party.amt.networks.blocks.ifrnet import Encoder, InitDecoder, IntermediateDecoder, resize +from utils.third_party.amt.networks.blocks.multi_flow import MultiFlowDecoder, multi_flow_combine +from utils.third_party.amt.networks.blocks.raft import BasicUpdateBlock, BidirCorrBlock, coords_grid + + +class Model(nn.Module): + def __init__(self, corr_radius=3, corr_lvls=4, num_flows=5, channels=[84, 96, 112, 128], skip_channels=84): + super(Model, self).__init__() + self.radius = corr_radius + self.corr_levels = corr_lvls + self.num_flows = num_flows + + self.feat_encoder = LargeEncoder(output_dim=128, norm_fn="instance", dropout=0.0) + self.encoder = Encoder(channels, large=True) + self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels) + self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels) + self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels) + self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows) + + self.update4 = self._get_updateblock(112, None) + self.update3_low = self._get_updateblock(96, 2.0) + self.update2_low = self._get_updateblock(84, 4.0) + + self.update3_high = self._get_updateblock(96, None) + self.update2_high = self._get_updateblock(84, None) + + self.comb_block = nn.Sequential( + nn.Conv2d(3 * self.num_flows, 6 * self.num_flows, 7, 1, 3), + nn.PReLU(6 * self.num_flows), + nn.Conv2d(6 * self.num_flows, 3, 7, 1, 3), + ) + + def _get_updateblock(self, cdim, scale_factor=None): + return BasicUpdateBlock( + cdim=cdim, + hidden_dim=192, + flow_dim=64, + corr_dim=256, + corr_dim2=192, + fc_dim=188, + scale_factor=scale_factor, + corr_levels=self.corr_levels, + radius=self.radius, + ) + + def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1): + # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0 + # based on linear assumption + t1_scale = 1.0 / embt + t0_scale = 1.0 / (1.0 - embt) + if downsample != 1: + inv = 1 / downsample + flow0 = inv * resize(flow0, scale_factor=inv) + flow1 = inv * resize(flow1, scale_factor=inv) + + corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale) + corr = torch.cat([corr0, corr1], dim=1) + flow = torch.cat([flow0, flow1], dim=1) + return corr, flow + + def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs): + mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True) + img0 = img0 - mean_ + img1 = img1 - mean_ + img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0 + img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1 + b, _, h, w = img0_.shape + coord = coords_grid(b, h // 8, w // 8, img0.device) + + fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8] + corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels) + + # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4] + # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16] + f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_) + f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_) + + ######################################### the 4th decoder ######################################### + up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt) + corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord, up_flow0_4, up_flow1_4, embt, downsample=1) + + # residue update with lookup corr + delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4) + delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1) + up_flow0_4 = up_flow0_4 + delta_flow0_4 + up_flow1_4 = up_flow1_4 + delta_flow1_4 + ft_3_ = ft_3_ + delta_ft_3_ + + ######################################### the 3rd decoder ######################################### + up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4) + corr_3, flow_3 = self._corr_scale_lookup(corr_fn, coord, up_flow0_3, up_flow1_3, embt, downsample=2) + + # residue update with lookup corr + delta_ft_2_, delta_flow_3 = self.update3_low(ft_2_, flow_3, corr_3) + delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1) + up_flow0_3 = up_flow0_3 + delta_flow0_3 + up_flow1_3 = up_flow1_3 + delta_flow1_3 + ft_2_ = ft_2_ + delta_ft_2_ + + # residue update with lookup corr (hr) + corr_3 = resize(corr_3, scale_factor=2.0) + up_flow_3 = torch.cat([up_flow0_3, up_flow1_3], dim=1) + delta_ft_2_, delta_up_flow_3 = self.update3_high(ft_2_, up_flow_3, corr_3) + ft_2_ += delta_ft_2_ + up_flow0_3 += delta_up_flow_3[:, 0:2] + up_flow1_3 += delta_up_flow_3[:, 2:4] + + ######################################### the 2nd decoder ######################################### + up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3) + corr_2, flow_2 = self._corr_scale_lookup(corr_fn, coord, up_flow0_2, up_flow1_2, embt, downsample=4) + + # residue update with lookup corr + delta_ft_1_, delta_flow_2 = self.update2_low(ft_1_, flow_2, corr_2) + delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1) + up_flow0_2 = up_flow0_2 + delta_flow0_2 + up_flow1_2 = up_flow1_2 + delta_flow1_2 + ft_1_ = ft_1_ + delta_ft_1_ + + # residue update with lookup corr (hr) + corr_2 = resize(corr_2, scale_factor=4.0) + up_flow_2 = torch.cat([up_flow0_2, up_flow1_2], dim=1) + delta_ft_1_, delta_up_flow_2 = self.update2_high(ft_1_, up_flow_2, corr_2) + ft_1_ += delta_ft_1_ + up_flow0_2 += delta_up_flow_2[:, 0:2] + up_flow1_2 += delta_up_flow_2[:, 2:4] + + ######################################### the 1st decoder ######################################### + up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) + + if scale_factor != 1.0: + up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + mask = resize(mask, scale_factor=(1.0 / scale_factor)) + img_res = resize(img_res, scale_factor=(1.0 / scale_factor)) + + # Merge multiple predictions + imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, mask, img_res, mean_) + imgt_pred = torch.clamp(imgt_pred, 0, 1) + + if eval: + return { + "imgt_pred": imgt_pred, + } + else: + up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w) + up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w) + return { + "imgt_pred": imgt_pred, + "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4], + "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4], + "ft_pred": [ft_1_, ft_2_, ft_3_], + } diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/AMT-L.py b/Helios/eval_moviebench/utils/third_party/amt/networks/AMT-L.py new file mode 100644 index 0000000000000000000000000000000000000000..fee9366ab71553d78289bb63c1cd0f85496130ea --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/networks/AMT-L.py @@ -0,0 +1,140 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.feat_enc import ( + BasicEncoder, +) +from utils.third_party.amt.networks.blocks.ifrnet import Encoder, InitDecoder, IntermediateDecoder, resize +from utils.third_party.amt.networks.blocks.multi_flow import MultiFlowDecoder, multi_flow_combine +from utils.third_party.amt.networks.blocks.raft import BasicUpdateBlock, BidirCorrBlock, coords_grid + + +class Model(nn.Module): + def __init__(self, corr_radius=3, corr_lvls=4, num_flows=5, channels=[48, 64, 72, 128], skip_channels=48): + super(Model, self).__init__() + self.radius = corr_radius + self.corr_levels = corr_lvls + self.num_flows = num_flows + + self.feat_encoder = BasicEncoder(output_dim=128, norm_fn="instance", dropout=0.0) + self.encoder = Encoder([48, 64, 72, 128], large=True) + + self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels) + self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels) + self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels) + self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows) + + self.update4 = self._get_updateblock(72, None) + self.update3 = self._get_updateblock(64, 2.0) + self.update2 = self._get_updateblock(48, 4.0) + + self.comb_block = nn.Sequential( + nn.Conv2d(3 * self.num_flows, 6 * self.num_flows, 7, 1, 3), + nn.PReLU(6 * self.num_flows), + nn.Conv2d(6 * self.num_flows, 3, 7, 1, 3), + ) + + def _get_updateblock(self, cdim, scale_factor=None): + return BasicUpdateBlock( + cdim=cdim, + hidden_dim=128, + flow_dim=48, + corr_dim=256, + corr_dim2=160, + fc_dim=124, + scale_factor=scale_factor, + corr_levels=self.corr_levels, + radius=self.radius, + ) + + def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1): + # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0 + # based on linear assumption + t1_scale = 1.0 / embt + t0_scale = 1.0 / (1.0 - embt) + if downsample != 1: + inv = 1 / downsample + flow0 = inv * resize(flow0, scale_factor=inv) + flow1 = inv * resize(flow1, scale_factor=inv) + + corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale) + corr = torch.cat([corr0, corr1], dim=1) + flow = torch.cat([flow0, flow1], dim=1) + return corr, flow + + def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs): + mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True) + img0 = img0 - mean_ + img1 = img1 - mean_ + img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0 + img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1 + b, _, h, w = img0_.shape + coord = coords_grid(b, h // 8, w // 8, img0.device) + + fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8] + corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels) + + # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4] + # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16] + f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_) + f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_) + + ######################################### the 4th decoder ######################################### + up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt) + corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord, up_flow0_4, up_flow1_4, embt, downsample=1) + + # residue update with lookup corr + delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4) + delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1) + up_flow0_4 = up_flow0_4 + delta_flow0_4 + up_flow1_4 = up_flow1_4 + delta_flow1_4 + ft_3_ = ft_3_ + delta_ft_3_ + + ######################################### the 3rd decoder ######################################### + up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4) + corr_3, flow_3 = self._corr_scale_lookup(corr_fn, coord, up_flow0_3, up_flow1_3, embt, downsample=2) + + # residue update with lookup corr + delta_ft_2_, delta_flow_3 = self.update3(ft_2_, flow_3, corr_3) + delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1) + up_flow0_3 = up_flow0_3 + delta_flow0_3 + up_flow1_3 = up_flow1_3 + delta_flow1_3 + ft_2_ = ft_2_ + delta_ft_2_ + + ######################################### the 2nd decoder ######################################### + up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3) + corr_2, flow_2 = self._corr_scale_lookup(corr_fn, coord, up_flow0_2, up_flow1_2, embt, downsample=4) + + # residue update with lookup corr + delta_ft_1_, delta_flow_2 = self.update2(ft_1_, flow_2, corr_2) + delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1) + up_flow0_2 = up_flow0_2 + delta_flow0_2 + up_flow1_2 = up_flow1_2 + delta_flow1_2 + ft_1_ = ft_1_ + delta_ft_1_ + + ######################################### the 1st decoder ######################################### + up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) + + if scale_factor != 1.0: + up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + mask = resize(mask, scale_factor=(1.0 / scale_factor)) + img_res = resize(img_res, scale_factor=(1.0 / scale_factor)) + + # Merge multiple predictions + imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, mask, img_res, mean_) + imgt_pred = torch.clamp(imgt_pred, 0, 1) + + if eval: + return { + "imgt_pred": imgt_pred, + } + else: + up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w) + up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w) + return { + "imgt_pred": imgt_pred, + "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4], + "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4], + "ft_pred": [ft_1_, ft_2_, ft_3_], + } diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/AMT-S.py b/Helios/eval_moviebench/utils/third_party/amt/networks/AMT-S.py new file mode 100644 index 0000000000000000000000000000000000000000..64a6e32340a36d6e7ba6ee4353ec3ade1c12b293 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/networks/AMT-S.py @@ -0,0 +1,139 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.feat_enc import SmallEncoder +from utils.third_party.amt.networks.blocks.ifrnet import Encoder, InitDecoder, IntermediateDecoder, resize +from utils.third_party.amt.networks.blocks.multi_flow import MultiFlowDecoder, multi_flow_combine +from utils.third_party.amt.networks.blocks.raft import BidirCorrBlock, SmallUpdateBlock, coords_grid + + +class Model(nn.Module): + def __init__(self, corr_radius=3, corr_lvls=4, num_flows=3, channels=[20, 32, 44, 56], skip_channels=20): + super(Model, self).__init__() + self.radius = corr_radius + self.corr_levels = corr_lvls + self.num_flows = num_flows + self.channels = channels + self.skip_channels = skip_channels + + self.feat_encoder = SmallEncoder(output_dim=84, norm_fn="instance", dropout=0.0) + self.encoder = Encoder(channels) + + self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels) + self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels) + self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels) + self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows) + + self.update4 = self._get_updateblock(44) + self.update3 = self._get_updateblock(32, 2) + self.update2 = self._get_updateblock(20, 4) + + self.comb_block = nn.Sequential( + nn.Conv2d(3 * num_flows, 6 * num_flows, 3, 1, 1), + nn.PReLU(6 * num_flows), + nn.Conv2d(6 * num_flows, 3, 3, 1, 1), + ) + + def _get_updateblock(self, cdim, scale_factor=None): + return SmallUpdateBlock( + cdim=cdim, + hidden_dim=76, + flow_dim=20, + corr_dim=64, + fc_dim=68, + scale_factor=scale_factor, + corr_levels=self.corr_levels, + radius=self.radius, + ) + + def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1): + # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0 + # based on linear assumption + t1_scale = 1.0 / embt + t0_scale = 1.0 / (1.0 - embt) + if downsample != 1: + inv = 1 / downsample + flow0 = inv * resize(flow0, scale_factor=inv) + flow1 = inv * resize(flow1, scale_factor=inv) + + corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale) + corr = torch.cat([corr0, corr1], dim=1) + flow = torch.cat([flow0, flow1], dim=1) + return corr, flow + + def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs): + mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True) + img0 = img0 - mean_ + img1 = img1 - mean_ + img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0 + img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1 + b, _, h, w = img0_.shape + coord = coords_grid(b, h // 8, w // 8, img0.device) + + fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8] + corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels) + + # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4] + # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16] + f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_) + f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_) + + ######################################### the 4th decoder ######################################### + up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt) + corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord, up_flow0_4, up_flow1_4, embt, downsample=1) + + # residue update with lookup corr + delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4) + delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1) + up_flow0_4 = up_flow0_4 + delta_flow0_4 + up_flow1_4 = up_flow1_4 + delta_flow1_4 + ft_3_ = ft_3_ + delta_ft_3_ + + ######################################### the 3rd decoder ######################################### + up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4) + corr_3, flow_3 = self._corr_scale_lookup(corr_fn, coord, up_flow0_3, up_flow1_3, embt, downsample=2) + + # residue update with lookup corr + delta_ft_2_, delta_flow_3 = self.update3(ft_2_, flow_3, corr_3) + delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1) + up_flow0_3 = up_flow0_3 + delta_flow0_3 + up_flow1_3 = up_flow1_3 + delta_flow1_3 + ft_2_ = ft_2_ + delta_ft_2_ + + ######################################### the 2nd decoder ######################################### + up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3) + corr_2, flow_2 = self._corr_scale_lookup(corr_fn, coord, up_flow0_2, up_flow1_2, embt, downsample=4) + + # residue update with lookup corr + delta_ft_1_, delta_flow_2 = self.update2(ft_1_, flow_2, corr_2) + delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1) + up_flow0_2 = up_flow0_2 + delta_flow0_2 + up_flow1_2 = up_flow1_2 + delta_flow1_2 + ft_1_ = ft_1_ + delta_ft_1_ + + ######################################### the 1st decoder ######################################### + up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) + + if scale_factor != 1.0: + up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + mask = resize(mask, scale_factor=(1.0 / scale_factor)) + img_res = resize(img_res, scale_factor=(1.0 / scale_factor)) + + # Merge multiple predictions + imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, mask, img_res, mean_) + imgt_pred = torch.clamp(imgt_pred, 0, 1) + + if eval: + return { + "imgt_pred": imgt_pred, + } + else: + up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w) + up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w) + return { + "imgt_pred": imgt_pred, + "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4], + "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4], + "ft_pred": [ft_1_, ft_2_, ft_3_], + } diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/IFRNet.py b/Helios/eval_moviebench/utils/third_party/amt/networks/IFRNet.py new file mode 100644 index 0000000000000000000000000000000000000000..e1edd419d53fe8780aa5ced1900d38664071d703 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/networks/IFRNet.py @@ -0,0 +1,153 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.ifrnet import ( + ResBlock, + convrelu, + resize, +) +from utils.third_party.amt.utils.flow_utils import warp + + +class Encoder(nn.Module): + def __init__(self): + super(Encoder, self).__init__() + self.pyramid1 = nn.Sequential(convrelu(3, 32, 3, 2, 1), convrelu(32, 32, 3, 1, 1)) + self.pyramid2 = nn.Sequential(convrelu(32, 48, 3, 2, 1), convrelu(48, 48, 3, 1, 1)) + self.pyramid3 = nn.Sequential(convrelu(48, 72, 3, 2, 1), convrelu(72, 72, 3, 1, 1)) + self.pyramid4 = nn.Sequential(convrelu(72, 96, 3, 2, 1), convrelu(96, 96, 3, 1, 1)) + + def forward(self, img): + f1 = self.pyramid1(img) + f2 = self.pyramid2(f1) + f3 = self.pyramid3(f2) + f4 = self.pyramid4(f3) + return f1, f2, f3, f4 + + +class Decoder4(nn.Module): + def __init__(self): + super(Decoder4, self).__init__() + self.convblock = nn.Sequential( + convrelu(192 + 1, 192), ResBlock(192, 32), nn.ConvTranspose2d(192, 76, 4, 2, 1, bias=True) + ) + + def forward(self, f0, f1, embt): + b, c, h, w = f0.shape + embt = embt.repeat(1, 1, h, w) + f_in = torch.cat([f0, f1, embt], 1) + f_out = self.convblock(f_in) + return f_out + + +class Decoder3(nn.Module): + def __init__(self): + super(Decoder3, self).__init__() + self.convblock = nn.Sequential( + convrelu(220, 216), ResBlock(216, 32), nn.ConvTranspose2d(216, 52, 4, 2, 1, bias=True) + ) + + def forward(self, ft_, f0, f1, up_flow0, up_flow1): + f0_warp = warp(f0, up_flow0) + f1_warp = warp(f1, up_flow1) + f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1) + f_out = self.convblock(f_in) + return f_out + + +class Decoder2(nn.Module): + def __init__(self): + super(Decoder2, self).__init__() + self.convblock = nn.Sequential( + convrelu(148, 144), ResBlock(144, 32), nn.ConvTranspose2d(144, 36, 4, 2, 1, bias=True) + ) + + def forward(self, ft_, f0, f1, up_flow0, up_flow1): + f0_warp = warp(f0, up_flow0) + f1_warp = warp(f1, up_flow1) + f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1) + f_out = self.convblock(f_in) + return f_out + + +class Decoder1(nn.Module): + def __init__(self): + super(Decoder1, self).__init__() + self.convblock = nn.Sequential( + convrelu(100, 96), ResBlock(96, 32), nn.ConvTranspose2d(96, 8, 4, 2, 1, bias=True) + ) + + def forward(self, ft_, f0, f1, up_flow0, up_flow1): + f0_warp = warp(f0, up_flow0) + f1_warp = warp(f1, up_flow1) + f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1) + f_out = self.convblock(f_in) + return f_out + + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + self.encoder = Encoder() + self.decoder4 = Decoder4() + self.decoder3 = Decoder3() + self.decoder2 = Decoder2() + self.decoder1 = Decoder1() + + def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs): + mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True) + img0 = img0 - mean_ + img1 = img1 - mean_ + + img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0 + img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1 + + f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_) + f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_) + + out4 = self.decoder4(f0_4, f1_4, embt) + up_flow0_4 = out4[:, 0:2] + up_flow1_4 = out4[:, 2:4] + ft_3_ = out4[:, 4:] + + out3 = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4) + up_flow0_3 = out3[:, 0:2] + 2.0 * resize(up_flow0_4, scale_factor=2.0) + up_flow1_3 = out3[:, 2:4] + 2.0 * resize(up_flow1_4, scale_factor=2.0) + ft_2_ = out3[:, 4:] + + out2 = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3) + up_flow0_2 = out2[:, 0:2] + 2.0 * resize(up_flow0_3, scale_factor=2.0) + up_flow1_2 = out2[:, 2:4] + 2.0 * resize(up_flow1_3, scale_factor=2.0) + ft_1_ = out2[:, 4:] + + out1 = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2) + up_flow0_1 = out1[:, 0:2] + 2.0 * resize(up_flow0_2, scale_factor=2.0) + up_flow1_1 = out1[:, 2:4] + 2.0 * resize(up_flow1_2, scale_factor=2.0) + up_mask_1 = torch.sigmoid(out1[:, 4:5]) + up_res_1 = out1[:, 5:] + + if scale_factor != 1.0: + up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor) + up_mask_1 = resize(up_mask_1, scale_factor=(1.0 / scale_factor)) + up_res_1 = resize(up_res_1, scale_factor=(1.0 / scale_factor)) + + img0_warp = warp(img0, up_flow0_1) + img1_warp = warp(img1, up_flow1_1) + imgt_merge = up_mask_1 * img0_warp + (1 - up_mask_1) * img1_warp + mean_ + imgt_pred = imgt_merge + up_res_1 + imgt_pred = torch.clamp(imgt_pred, 0, 1) + + if eval: + return { + "imgt_pred": imgt_pred, + } + else: + return { + "imgt_pred": imgt_pred, + "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4], + "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4], + "ft_pred": [ft_1_, ft_2_, ft_3_], + "img0_warp": img0_warp, + "img1_warp": img1_warp, + } diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/networks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/feat_enc.py b/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/feat_enc.py new file mode 100644 index 0000000000000000000000000000000000000000..479833824b8b2da7e9e3ba05c84b0359b8c79c37 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/feat_enc.py @@ -0,0 +1,335 @@ +import torch +import torch.nn as nn + + +class BottleneckBlock(nn.Module): + def __init__(self, in_planes, planes, norm_fn="group", stride=1): + super(BottleneckBlock, self).__init__() + + self.conv1 = nn.Conv2d(in_planes, planes // 4, kernel_size=1, padding=0) + self.conv2 = nn.Conv2d(planes // 4, planes // 4, kernel_size=3, padding=1, stride=stride) + self.conv3 = nn.Conv2d(planes // 4, planes, kernel_size=1, padding=0) + self.relu = nn.ReLU(inplace=True) + + num_groups = planes // 8 + + if norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes // 4) + self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes // 4) + self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + if not stride == 1: + self.norm4 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + + elif norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(planes // 4) + self.norm2 = nn.BatchNorm2d(planes // 4) + self.norm3 = nn.BatchNorm2d(planes) + if not stride == 1: + self.norm4 = nn.BatchNorm2d(planes) + + elif norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(planes // 4) + self.norm2 = nn.InstanceNorm2d(planes // 4) + self.norm3 = nn.InstanceNorm2d(planes) + if not stride == 1: + self.norm4 = nn.InstanceNorm2d(planes) + + elif norm_fn == "none": + self.norm1 = nn.Sequential() + self.norm2 = nn.Sequential() + self.norm3 = nn.Sequential() + if not stride == 1: + self.norm4 = nn.Sequential() + + if stride == 1: + self.downsample = None + + else: + self.downsample = nn.Sequential(nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm4) + + def forward(self, x): + y = x + y = self.relu(self.norm1(self.conv1(y))) + y = self.relu(self.norm2(self.conv2(y))) + y = self.relu(self.norm3(self.conv3(y))) + + if self.downsample is not None: + x = self.downsample(x) + + return self.relu(x + y) + + +class ResidualBlock(nn.Module): + def __init__(self, in_planes, planes, norm_fn="group", stride=1): + super(ResidualBlock, self).__init__() + + self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) + self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1) + self.relu = nn.ReLU(inplace=True) + + num_groups = planes // 8 + + if norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + if not stride == 1: + self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + + elif norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(planes) + self.norm2 = nn.BatchNorm2d(planes) + if not stride == 1: + self.norm3 = nn.BatchNorm2d(planes) + + elif norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(planes) + self.norm2 = nn.InstanceNorm2d(planes) + if not stride == 1: + self.norm3 = nn.InstanceNorm2d(planes) + + elif norm_fn == "none": + self.norm1 = nn.Sequential() + self.norm2 = nn.Sequential() + if not stride == 1: + self.norm3 = nn.Sequential() + + if stride == 1: + self.downsample = None + + else: + self.downsample = nn.Sequential(nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3) + + def forward(self, x): + y = x + y = self.relu(self.norm1(self.conv1(y))) + y = self.relu(self.norm2(self.conv2(y))) + + if self.downsample is not None: + x = self.downsample(x) + + return self.relu(x + y) + + +class SmallEncoder(nn.Module): + def __init__(self, output_dim=128, norm_fn="batch", dropout=0.0): + super(SmallEncoder, self).__init__() + self.norm_fn = norm_fn + + if self.norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=8, num_channels=32) + + elif self.norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(32) + + elif self.norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(32) + + elif self.norm_fn == "none": + self.norm1 = nn.Sequential() + + self.conv1 = nn.Conv2d(3, 32, kernel_size=7, stride=2, padding=3) + self.relu1 = nn.ReLU(inplace=True) + + self.in_planes = 32 + self.layer1 = self._make_layer(32, stride=1) + self.layer2 = self._make_layer(64, stride=2) + self.layer3 = self._make_layer(96, stride=2) + + self.dropout = None + if dropout > 0: + self.dropout = nn.Dropout2d(p=dropout) + + self.conv2 = nn.Conv2d(96, output_dim, kernel_size=1) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): + if m.weight is not None: + nn.init.constant_(m.weight, 1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def _make_layer(self, dim, stride=1): + layer1 = BottleneckBlock(self.in_planes, dim, self.norm_fn, stride=stride) + layer2 = BottleneckBlock(dim, dim, self.norm_fn, stride=1) + layers = (layer1, layer2) + + self.in_planes = dim + return nn.Sequential(*layers) + + def forward(self, x): + # if input is list, combine batch dimension + is_list = isinstance(x, tuple) or isinstance(x, list) + if is_list: + batch_dim = x[0].shape[0] + x = torch.cat(x, dim=0) + + x = self.conv1(x) + x = self.norm1(x) + x = self.relu1(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.conv2(x) + + if self.training and self.dropout is not None: + x = self.dropout(x) + + if is_list: + x = torch.split(x, [batch_dim, batch_dim], dim=0) + + return x + + +class BasicEncoder(nn.Module): + def __init__(self, output_dim=128, norm_fn="batch", dropout=0.0): + super(BasicEncoder, self).__init__() + self.norm_fn = norm_fn + + if self.norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) + + elif self.norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(64) + + elif self.norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(64) + + elif self.norm_fn == "none": + self.norm1 = nn.Sequential() + + self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3) + self.relu1 = nn.ReLU(inplace=True) + + self.in_planes = 64 + self.layer1 = self._make_layer(64, stride=1) + self.layer2 = self._make_layer(72, stride=2) + self.layer3 = self._make_layer(128, stride=2) + + # output convolution + self.conv2 = nn.Conv2d(128, output_dim, kernel_size=1) + + self.dropout = None + if dropout > 0: + self.dropout = nn.Dropout2d(p=dropout) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): + if m.weight is not None: + nn.init.constant_(m.weight, 1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def _make_layer(self, dim, stride=1): + layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) + layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) + layers = (layer1, layer2) + + self.in_planes = dim + return nn.Sequential(*layers) + + def forward(self, x): + # if input is list, combine batch dimension + is_list = isinstance(x, tuple) or isinstance(x, list) + if is_list: + batch_dim = x[0].shape[0] + x = torch.cat(x, dim=0) + + x = self.conv1(x) + x = self.norm1(x) + x = self.relu1(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + + x = self.conv2(x) + + if self.training and self.dropout is not None: + x = self.dropout(x) + + if is_list: + x = torch.split(x, [batch_dim, batch_dim], dim=0) + + return x + + +class LargeEncoder(nn.Module): + def __init__(self, output_dim=128, norm_fn="batch", dropout=0.0): + super(LargeEncoder, self).__init__() + self.norm_fn = norm_fn + + if self.norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) + + elif self.norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(64) + + elif self.norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(64) + + elif self.norm_fn == "none": + self.norm1 = nn.Sequential() + + self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3) + self.relu1 = nn.ReLU(inplace=True) + + self.in_planes = 64 + self.layer1 = self._make_layer(64, stride=1) + self.layer2 = self._make_layer(112, stride=2) + self.layer3 = self._make_layer(160, stride=2) + self.layer3_2 = self._make_layer(160, stride=1) + + # output convolution + self.conv2 = nn.Conv2d(self.in_planes, output_dim, kernel_size=1) + + self.dropout = None + if dropout > 0: + self.dropout = nn.Dropout2d(p=dropout) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): + if m.weight is not None: + nn.init.constant_(m.weight, 1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def _make_layer(self, dim, stride=1): + layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) + layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) + layers = (layer1, layer2) + + self.in_planes = dim + return nn.Sequential(*layers) + + def forward(self, x): + # if input is list, combine batch dimension + is_list = isinstance(x, tuple) or isinstance(x, list) + if is_list: + batch_dim = x[0].shape[0] + x = torch.cat(x, dim=0) + + x = self.conv1(x) + x = self.norm1(x) + x = self.relu1(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer3_2(x) + + x = self.conv2(x) + + if self.training and self.dropout is not None: + x = self.dropout(x) + + if is_list: + x = torch.split(x, [batch_dim, batch_dim], dim=0) + + return x diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/ifrnet.py b/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/ifrnet.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfe241523f689fad7b3f6c104a57daff30ef85e --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/ifrnet.py @@ -0,0 +1,115 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +from utils.third_party.amt.utils.flow_utils import warp + + +def resize(x, scale_factor): + return F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False) + + +def convrelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True): + return nn.Sequential( + nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias=bias), + nn.PReLU(out_channels), + ) + + +class ResBlock(nn.Module): + def __init__(self, in_channels, side_channels, bias=True): + super(ResBlock, self).__init__() + self.side_channels = side_channels + self.conv1 = nn.Sequential( + nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias), nn.PReLU(in_channels) + ) + self.conv2 = nn.Sequential( + nn.Conv2d(side_channels, side_channels, kernel_size=3, stride=1, padding=1, bias=bias), + nn.PReLU(side_channels), + ) + self.conv3 = nn.Sequential( + nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias), nn.PReLU(in_channels) + ) + self.conv4 = nn.Sequential( + nn.Conv2d(side_channels, side_channels, kernel_size=3, stride=1, padding=1, bias=bias), + nn.PReLU(side_channels), + ) + self.conv5 = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias) + self.prelu = nn.PReLU(in_channels) + + def forward(self, x): + out = self.conv1(x) + + res_feat = out[:, : -self.side_channels, ...] + side_feat = out[:, -self.side_channels :, :, :] + side_feat = self.conv2(side_feat) + out = self.conv3(torch.cat([res_feat, side_feat], 1)) + + res_feat = out[:, : -self.side_channels, ...] + side_feat = out[:, -self.side_channels :, :, :] + side_feat = self.conv4(side_feat) + out = self.conv5(torch.cat([res_feat, side_feat], 1)) + + out = self.prelu(x + out) + return out + + +class Encoder(nn.Module): + def __init__(self, channels, large=False): + super(Encoder, self).__init__() + self.channels = channels + prev_ch = 3 + for idx, ch in enumerate(channels, 1): + k = 7 if large and idx == 1 else 3 + p = 3 if k == 7 else 1 + self.register_module( + f"pyramid{idx}", nn.Sequential(convrelu(prev_ch, ch, k, 2, p), convrelu(ch, ch, 3, 1, 1)) + ) + prev_ch = ch + + def forward(self, in_x): + fs = [] + for idx in range(len(self.channels)): + out_x = getattr(self, f"pyramid{idx + 1}")(in_x) + fs.append(out_x) + in_x = out_x + return fs + + +class InitDecoder(nn.Module): + def __init__(self, in_ch, out_ch, skip_ch) -> None: + super().__init__() + self.convblock = nn.Sequential( + convrelu(in_ch * 2 + 1, in_ch * 2), + ResBlock(in_ch * 2, skip_ch), + nn.ConvTranspose2d(in_ch * 2, out_ch + 4, 4, 2, 1, bias=True), + ) + + def forward(self, f0, f1, embt): + h, w = f0.shape[2:] + embt = embt.repeat(1, 1, h, w) + out = self.convblock(torch.cat([f0, f1, embt], 1)) + flow0, flow1 = torch.chunk(out[:, :4, ...], 2, 1) + ft_ = out[:, 4:, ...] + return flow0, flow1, ft_ + + +class IntermediateDecoder(nn.Module): + def __init__(self, in_ch, out_ch, skip_ch) -> None: + super().__init__() + self.convblock = nn.Sequential( + convrelu(in_ch * 3 + 4, in_ch * 3), + ResBlock(in_ch * 3, skip_ch), + nn.ConvTranspose2d(in_ch * 3, out_ch + 4, 4, 2, 1, bias=True), + ) + + def forward(self, ft_, f0, f1, flow0_in, flow1_in): + f0_warp = warp(f0, flow0_in) + f1_warp = warp(f1, flow1_in) + f_in = torch.cat([ft_, f0_warp, f1_warp, flow0_in, flow1_in], 1) + out = self.convblock(f_in) + flow0, flow1 = torch.chunk(out[:, :4, ...], 2, 1) + ft_ = out[:, 4:, ...] + flow0 = flow0 + 2.0 * resize(flow0_in, scale_factor=2.0) + flow1 = flow1 + 2.0 * resize(flow1_in, scale_factor=2.0) + return flow0, flow1, ft_ diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/multi_flow.py b/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/multi_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..e054bccd0e4141cb99a0c14c819d995eb8a90e99 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/multi_flow.py @@ -0,0 +1,65 @@ +import torch +import torch.nn as nn + +from utils.third_party.amt.networks.blocks.ifrnet import ( + ResBlock, + convrelu, + resize, +) +from utils.third_party.amt.utils.flow_utils import warp + + +def multi_flow_combine(comb_block, img0, img1, flow0, flow1, mask=None, img_res=None, mean=None): + """ + A parallel implementation of multiple flow field warping + comb_block: An nn.Seqential object. + img shape: [b, c, h, w] + flow shape: [b, 2*num_flows, h, w] + mask (opt): + If 'mask' is None, the function conduct a simple average. + img_res (opt): + If 'img_res' is None, the function adds zero instead. + mean (opt): + If 'mean' is None, the function adds zero instead. + """ + b, c, h, w = flow0.shape + num_flows = c // 2 + flow0 = flow0.reshape(b, num_flows, 2, h, w).reshape(-1, 2, h, w) + flow1 = flow1.reshape(b, num_flows, 2, h, w).reshape(-1, 2, h, w) + + mask = mask.reshape(b, num_flows, 1, h, w).reshape(-1, 1, h, w) if mask is not None else None + img_res = img_res.reshape(b, num_flows, 3, h, w).reshape(-1, 3, h, w) if img_res is not None else 0 + img0 = torch.stack([img0] * num_flows, 1).reshape(-1, 3, h, w) + img1 = torch.stack([img1] * num_flows, 1).reshape(-1, 3, h, w) + mean = torch.stack([mean] * num_flows, 1).reshape(-1, 1, 1, 1) if mean is not None else 0 + + img0_warp = warp(img0, flow0) + img1_warp = warp(img1, flow1) + img_warps = mask * img0_warp + (1 - mask) * img1_warp + mean + img_res + img_warps = img_warps.reshape(b, num_flows, 3, h, w) + imgt_pred = img_warps.mean(1) + comb_block(img_warps.view(b, -1, h, w)) + return imgt_pred + + +class MultiFlowDecoder(nn.Module): + def __init__(self, in_ch, skip_ch, num_flows=3): + super(MultiFlowDecoder, self).__init__() + self.num_flows = num_flows + self.convblock = nn.Sequential( + convrelu(in_ch * 3 + 4, in_ch * 3), + ResBlock(in_ch * 3, skip_ch), + nn.ConvTranspose2d(in_ch * 3, 8 * num_flows, 4, 2, 1, bias=True), + ) + + def forward(self, ft_, f0, f1, flow0, flow1): + n = self.num_flows + f0_warp = warp(f0, flow0) + f1_warp = warp(f1, flow1) + out = self.convblock(torch.cat([ft_, f0_warp, f1_warp, flow0, flow1], 1)) + delta_flow0, delta_flow1, mask, img_res = torch.split(out, [2 * n, 2 * n, n, 3 * n], 1) + mask = torch.sigmoid(mask) + + flow0 = delta_flow0 + 2.0 * resize(flow0, scale_factor=2.0).repeat(1, self.num_flows, 1, 1) + flow1 = delta_flow1 + 2.0 * resize(flow1, scale_factor=2.0).repeat(1, self.num_flows, 1, 1) + + return flow0, flow1, mask, img_res diff --git a/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/raft.py b/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/raft.py new file mode 100644 index 0000000000000000000000000000000000000000..1576889201c49614224450c9a223b871e8031f2d --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/networks/blocks/raft.py @@ -0,0 +1,213 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def resize(x, scale_factor): + return F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False) + + +def bilinear_sampler(img, coords, mask=False): + """Wrapper for grid_sample, uses pixel coordinates""" + H, W = img.shape[-2:] + xgrid, ygrid = coords.split([1, 1], dim=-1) + xgrid = 2 * xgrid / (W - 1) - 1 + ygrid = 2 * ygrid / (H - 1) - 1 + + grid = torch.cat([xgrid, ygrid], dim=-1) + img = F.grid_sample(img, grid, align_corners=True) + + if mask: + mask = (xgrid > -1) & (ygrid > -1) & (xgrid < 1) & (ygrid < 1) + return img, mask.float() + + return img + + +def coords_grid(batch, ht, wd, device): + coords = torch.meshgrid(torch.arange(ht, device=device), torch.arange(wd, device=device), indexing="ij") + coords = torch.stack(coords[::-1], dim=0).float() + return coords[None].repeat(batch, 1, 1, 1) + + +class SmallUpdateBlock(nn.Module): + def __init__(self, cdim, hidden_dim, flow_dim, corr_dim, fc_dim, corr_levels=4, radius=3, scale_factor=None): + super(SmallUpdateBlock, self).__init__() + cor_planes = corr_levels * (2 * radius + 1) ** 2 + self.scale_factor = scale_factor + + self.convc1 = nn.Conv2d(2 * cor_planes, corr_dim, 1, padding=0) + self.convf1 = nn.Conv2d(4, flow_dim * 2, 7, padding=3) + self.convf2 = nn.Conv2d(flow_dim * 2, flow_dim, 3, padding=1) + self.conv = nn.Conv2d(corr_dim + flow_dim, fc_dim, 3, padding=1) + + self.gru = nn.Sequential( + nn.Conv2d(fc_dim + 4 + cdim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + ) + + self.feat_head = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, cdim, 3, padding=1), + ) + + self.flow_head = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, 4, 3, padding=1), + ) + + self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True) + + def forward(self, net, flow, corr): + net = resize(net, 1 / self.scale_factor) if self.scale_factor is not None else net + cor = self.lrelu(self.convc1(corr)) + flo = self.lrelu(self.convf1(flow)) + flo = self.lrelu(self.convf2(flo)) + cor_flo = torch.cat([cor, flo], dim=1) + inp = self.lrelu(self.conv(cor_flo)) + inp = torch.cat([inp, flow, net], dim=1) + + out = self.gru(inp) + delta_net = self.feat_head(out) + delta_flow = self.flow_head(out) + + if self.scale_factor is not None: + delta_net = resize(delta_net, scale_factor=self.scale_factor) + delta_flow = self.scale_factor * resize(delta_flow, scale_factor=self.scale_factor) + + return delta_net, delta_flow + + +class BasicUpdateBlock(nn.Module): + def __init__( + self, + cdim, + hidden_dim, + flow_dim, + corr_dim, + corr_dim2, + fc_dim, + corr_levels=4, + radius=3, + scale_factor=None, + out_num=1, + ): + super(BasicUpdateBlock, self).__init__() + cor_planes = corr_levels * (2 * radius + 1) ** 2 + + self.scale_factor = scale_factor + self.convc1 = nn.Conv2d(2 * cor_planes, corr_dim, 1, padding=0) + self.convc2 = nn.Conv2d(corr_dim, corr_dim2, 3, padding=1) + self.convf1 = nn.Conv2d(4, flow_dim * 2, 7, padding=3) + self.convf2 = nn.Conv2d(flow_dim * 2, flow_dim, 3, padding=1) + self.conv = nn.Conv2d(flow_dim + corr_dim2, fc_dim, 3, padding=1) + + self.gru = nn.Sequential( + nn.Conv2d(fc_dim + 4 + cdim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + ) + + self.feat_head = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, cdim, 3, padding=1), + ) + + self.flow_head = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1), + nn.LeakyReLU(negative_slope=0.1, inplace=True), + nn.Conv2d(hidden_dim, 4 * out_num, 3, padding=1), + ) + + self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True) + + def forward(self, net, flow, corr): + net = resize(net, 1 / self.scale_factor) if self.scale_factor is not None else net + cor = self.lrelu(self.convc1(corr)) + cor = self.lrelu(self.convc2(cor)) + flo = self.lrelu(self.convf1(flow)) + flo = self.lrelu(self.convf2(flo)) + cor_flo = torch.cat([cor, flo], dim=1) + inp = self.lrelu(self.conv(cor_flo)) + inp = torch.cat([inp, flow, net], dim=1) + + out = self.gru(inp) + delta_net = self.feat_head(out) + delta_flow = self.flow_head(out) + + if self.scale_factor is not None: + delta_net = resize(delta_net, scale_factor=self.scale_factor) + delta_flow = self.scale_factor * resize(delta_flow, scale_factor=self.scale_factor) + return delta_net, delta_flow + + +class BidirCorrBlock: + def __init__(self, fmap1, fmap2, num_levels=4, radius=4): + self.num_levels = num_levels + self.radius = radius + self.corr_pyramid = [] + self.corr_pyramid_T = [] + + corr = BidirCorrBlock.corr(fmap1, fmap2) + batch, h1, w1, dim, h2, w2 = corr.shape + corr_T = corr.clone().permute(0, 4, 5, 3, 1, 2) + + corr = corr.reshape(batch * h1 * w1, dim, h2, w2) + corr_T = corr_T.reshape(batch * h2 * w2, dim, h1, w1) + + self.corr_pyramid.append(corr) + self.corr_pyramid_T.append(corr_T) + + for _ in range(self.num_levels - 1): + corr = F.avg_pool2d(corr, 2, stride=2) + corr_T = F.avg_pool2d(corr_T, 2, stride=2) + self.corr_pyramid.append(corr) + self.corr_pyramid_T.append(corr_T) + + def __call__(self, coords0, coords1): + r = self.radius + coords0 = coords0.permute(0, 2, 3, 1) + coords1 = coords1.permute(0, 2, 3, 1) + assert coords0.shape == coords1.shape, f"coords0 shape: [{coords0.shape}] is not equal to [{coords1.shape}]" + batch, h1, w1, _ = coords0.shape + + out_pyramid = [] + out_pyramid_T = [] + for i in range(self.num_levels): + corr = self.corr_pyramid[i] + corr_T = self.corr_pyramid_T[i] + + dx = torch.linspace(-r, r, 2 * r + 1, device=coords0.device) + dy = torch.linspace(-r, r, 2 * r + 1, device=coords0.device) + delta = torch.stack(torch.meshgrid(dy, dx, indexing="ij"), axis=-1) + delta_lvl = delta.view(1, 2 * r + 1, 2 * r + 1, 2) + + centroid_lvl_0 = coords0.reshape(batch * h1 * w1, 1, 1, 2) / 2**i + centroid_lvl_1 = coords1.reshape(batch * h1 * w1, 1, 1, 2) / 2**i + coords_lvl_0 = centroid_lvl_0 + delta_lvl + coords_lvl_1 = centroid_lvl_1 + delta_lvl + + corr = bilinear_sampler(corr, coords_lvl_0) + corr_T = bilinear_sampler(corr_T, coords_lvl_1) + corr = corr.view(batch, h1, w1, -1) + corr_T = corr_T.view(batch, h1, w1, -1) + out_pyramid.append(corr) + out_pyramid_T.append(corr_T) + + out = torch.cat(out_pyramid, dim=-1) + out_T = torch.cat(out_pyramid_T, dim=-1) + return out.permute(0, 3, 1, 2).contiguous().float(), out_T.permute(0, 3, 1, 2).contiguous().float() + + @staticmethod + def corr(fmap1, fmap2): + batch, dim, ht, wd = fmap1.shape + fmap1 = fmap1.view(batch, dim, ht * wd) + fmap2 = fmap2.view(batch, dim, ht * wd) + + corr = torch.matmul(fmap1.transpose(1, 2), fmap2) + corr = corr.view(batch, ht, wd, 1, ht, wd) + return corr / torch.sqrt(torch.tensor(dim).float()) diff --git a/Helios/eval_moviebench/utils/third_party/amt/scripts/benchmark_arbitrary.sh b/Helios/eval_moviebench/utils/third_party/amt/scripts/benchmark_arbitrary.sh new file mode 100644 index 0000000000000000000000000000000000000000..108daea15e6548e276a386e34698d10d0f58981c --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/scripts/benchmark_arbitrary.sh @@ -0,0 +1,5 @@ +CFG=$1 +CKPT=$2 + +python benchmarks/gopro.py -c $CFG -p $CKPT +python benchmarks/adobe240.py -c $CFG -p $CKPT \ No newline at end of file diff --git a/Helios/eval_moviebench/utils/third_party/amt/scripts/benchmark_fixed.sh b/Helios/eval_moviebench/utils/third_party/amt/scripts/benchmark_fixed.sh new file mode 100644 index 0000000000000000000000000000000000000000..55d06b04a28a8e8456e3721c7f8731ae2e432579 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/scripts/benchmark_fixed.sh @@ -0,0 +1,7 @@ +CFG=$1 +CKPT=$2 + +python benchmarks/vimeo90k.py -c $CFG -p $CKPT +python benchmarks/ucf101.py -c $CFG -p $CKPT +python benchmarks/snu_film.py -c $CFG -p $CKPT +python benchmarks/xiph.py -c $CFG -p $CKPT \ No newline at end of file diff --git a/Helios/eval_moviebench/utils/third_party/amt/scripts/train.sh b/Helios/eval_moviebench/utils/third_party/amt/scripts/train.sh new file mode 100644 index 0000000000000000000000000000000000000000..92afb6465c444bdbd49fc6073337f96e80ae05d1 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/scripts/train.sh @@ -0,0 +1,6 @@ +NUM_GPU=$1 +CFG=$2 +PORT=$3 +python -m torch.distributed.launch \ +--nproc_per_node $NUM_GPU \ +--master_port $PORT train.py -c $CFG \ No newline at end of file diff --git a/Helios/eval_moviebench/utils/third_party/amt/train.py b/Helios/eval_moviebench/utils/third_party/amt/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2839c05b54e4285f97bb733a634a95845d82f688 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/train.py @@ -0,0 +1,69 @@ +import argparse +import datetime +import importlib +import os +from shutil import copyfile + +import torch +import torch.distributed as dist +from omegaconf import OmegaConf + +from utils.dist_utils import ( + get_world_size, +) +from utils.utils import seed_all + + +parser = argparse.ArgumentParser(description="VFI") +parser.add_argument("-c", "--config", type=str) +parser.add_argument("-p", "--port", default="23455", type=str) +parser.add_argument("--local_rank", default="0") + +args = parser.parse_args() + + +def main_worker(rank, config): + if "local_rank" not in config: + config["local_rank"] = config["global_rank"] = rank + if torch.cuda.is_available(): + print(f"Rank {rank} is available") + config["device"] = f"cuda:{rank}" + if config["distributed"]: + dist.init_process_group(backend="nccl", timeout=datetime.timedelta(seconds=5400)) + else: + config["device"] = "cpu" + + cfg_name = os.path.basename(args.config).split(".")[0] + config["exp_name"] = cfg_name + "_" + config["exp_name"] + config["save_dir"] = os.path.join(config["save_dir"], config["exp_name"]) + + if (not config["distributed"]) or rank == 0: + os.makedirs(config["save_dir"], exist_ok=True) + os.makedirs(f"{config['save_dir']}/ckpts", exist_ok=True) + config_path = os.path.join(config["save_dir"], args.config.split("/")[-1]) + if not os.path.isfile(config_path): + copyfile(args.config, config_path) + print("[**] create folder {}".format(config["save_dir"])) + + trainer_name = config.get("trainer_type", "base_trainer") + print(f"using GPU {rank} for training") + if rank == 0: + print(trainer_name) + trainer_pack = importlib.import_module("trainers." + trainer_name) + trainer = trainer_pack.Trainer(config) + + trainer.train() + + +if __name__ == "__main__": + torch.backends.cudnn.benchmark = True + cfg = OmegaConf.load(args.config) + seed_all(cfg.seed) + rank = int(args.local_rank) + torch.cuda.set_device(torch.device(f"cuda:{rank}")) + # setting distributed cfgurations + cfg["world_size"] = get_world_size() + cfg["local_rank"] = rank + if rank == 0: + print("world_size: ", cfg["world_size"]) + main_worker(rank, cfg) diff --git a/Helios/eval_moviebench/utils/third_party/amt/trainers/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/trainers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/trainers/base_trainer.py b/Helios/eval_moviebench/utils/third_party/amt/trainers/base_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..722791be5ca8d9d5ccc81ddf460ef366c5ea0f41 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/trainers/base_trainer.py @@ -0,0 +1,248 @@ +import logging +import os.path as osp +import time +from collections import OrderedDict + +import numpy as np +import torch +import wandb +from metrics.psnr_ssim import calculate_psnr +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.optim import AdamW +from torch.utils.data import DataLoader +from torch.utils.data.distributed import DistributedSampler + +from utils.build_utils import build_from_cfg +from utils.utils import AverageMeterGroups + +from .logger import CustomLogger + + +class Trainer: + def __init__(self, config): + super().__init__() + self.config = config + self.rank = self.config["local_rank"] + init_log = self._init_logger() + self._init_dataset() + self._init_loss() + self.model_name = config["exp_name"] + self.model = build_from_cfg(config.network).to(self.config.device) + + if config["distributed"]: + self.model = DDP( + self.model, + device_ids=[self.rank], + output_device=self.rank, + broadcast_buffers=True, + find_unused_parameters=False, + ) + + init_log += str(self.model) + self.optimizer = AdamW(self.model.parameters(), lr=config.lr, weight_decay=config.weight_decay) + if self.rank == 0: + print(init_log) + self.logger(init_log) + self.resume_training() + + def resume_training(self): + ckpt_path = self.config.get("resume_state") + if ckpt_path is not None: + ckpt = torch.load(self.config["resume_state"]) + if self.config["distributed"]: + self.model.module.load_state_dict(ckpt["state_dict"]) + else: + self.model.load_state_dict(ckpt["state_dict"]) + self.optimizer.load_state_dict(ckpt["optim"]) + self.resume_epoch = ckpt.get("epoch") + self.logger(f"load model from {ckpt_path} and training resumes from epoch {self.resume_epoch}") + else: + self.resume_epoch = 0 + + def _init_logger(self): + init_log = "" + console_cfg = { + "level": logging.INFO, + "format": "%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s %(message)s", + "datefmt": "%a, %d %b %Y %H:%M:%S", + "filename": f"{self.config['save_dir']}/log", + "filemode": "w", + } + tb_cfg = {"log_dir": osp.join(self.config["save_dir"], "tb_logger")} + wandb_cfg = None + use_wandb = self.config["logger"].get("use_wandb", False) + if use_wandb: + resume_id = self.config["logger"].get("resume_id", None) + if resume_id: + wandb_id = resume_id + resume = "allow" + init_log += f"Resume wandb logger with id={wandb_id}." + else: + wandb_id = wandb.util.generate_id() + resume = "never" + + wandb_cfg = { + "id": wandb_id, + "resume": resume, + "name": osp.basename(self.config["save_dir"]), + "config": self.config, + "project": "YOUR PROJECT", + "entity": "YOUR ENTITY", + "sync_tensorboard": True, + } + init_log += f"Use wandb logger with id={wandb_id}; project=[YOUR PROJECT]." + self.logger = CustomLogger(console_cfg, tb_cfg, wandb_cfg, self.rank) + return init_log + + def _init_dataset(self): + dataset_train = build_from_cfg(self.config.data.train) + dataset_val = build_from_cfg(self.config.data.val) + + self.sampler = DistributedSampler( + dataset_train, num_replicas=self.config["world_size"], rank=self.config["local_rank"] + ) + self.config.data.train_loader.batch_size //= self.config["world_size"] + self.loader_train = DataLoader( + dataset_train, **self.config.data.train_loader, pin_memory=True, drop_last=True, sampler=self.sampler + ) + + self.loader_val = DataLoader( + dataset_val, **self.config.data.val_loader, pin_memory=True, shuffle=False, drop_last=False + ) + + def _init_loss(self): + self.loss_dict = {} + for loss_cfg in self.config.losses: + loss = build_from_cfg(loss_cfg) + self.loss_dict[loss_cfg["nickname"]] = loss + + def set_lr(self, optimizer, lr): + for param_group in optimizer.param_groups: + param_group["lr"] = lr + + def get_lr(self, iters): + ratio = 0.5 * (1.0 + np.cos(iters / (self.config["epochs"] * self.loader_train.__len__()) * np.pi)) + lr = (self.config["lr"] - self.config["lr_min"]) * ratio + self.config["lr_min"] + return lr + + def train(self): + local_rank = self.config["local_rank"] + best_psnr = 0.0 + loss_group = AverageMeterGroups() + time_group = AverageMeterGroups() + iters_per_epoch = self.loader_train.__len__() + iters = self.resume_epoch * iters_per_epoch + total_iters = self.config["epochs"] * iters_per_epoch + + start_t = time.time() + total_t = 0 + for epoch in range(self.resume_epoch, self.config["epochs"]): + self.sampler.set_epoch(epoch) + for data in self.loader_train: + for k, v in data.items(): + data[k] = v.to(self.config["device"]) + data_t = time.time() - start_t + + lr = self.get_lr(iters) + self.set_lr(self.optimizer, lr) + + self.optimizer.zero_grad() + results = self.model(**data) + total_loss = torch.tensor(0.0, device=self.config["device"]) + for name, loss in self.loss_dict.items(): + l = loss(**results, **data) + loss_group.update({name: l.cpu().data}) + total_loss += l + total_loss.backward() + self.optimizer.step() + + iters += 1 + + iter_t = time.time() - start_t + total_t += iter_t + time_group.update({"data_t": data_t, "iter_t": iter_t}) + + if (iters + 1) % 100 == 0 and local_rank == 0: + tpi = total_t / (iters - self.resume_epoch * iters_per_epoch) + eta = total_iters * tpi + remainder = (total_iters - iters) * tpi + eta = self.eta_format(eta) + + remainder = self.eta_format(remainder) + log_str = f"[{self.model_name}]epoch:{epoch + 1}/{self.config['epochs']} " + log_str += f"iter:{iters + 1}/{self.config['epochs'] * iters_per_epoch} " + log_str += f"time:{time_group.avg('iter_t'):.3f}({time_group.avg('data_t'):.3f}) " + log_str += f"lr:{lr:.3e} eta:{remainder}({eta})\n" + for name in self.loss_dict.keys(): + avg_l = loss_group.avg(name) + log_str += f"{name}:{avg_l:.3e} " + self.logger(tb_msg=[f"loss/{name}", avg_l, iters]) + log_str += f"best:{best_psnr:.2f}dB\n\n" + self.logger(log_str) + loss_group.reset() + time_group.reset() + start_t = time.time() + + if (epoch + 1) % self.config["eval_interval"] == 0 and local_rank == 0: + psnr, eval_t = self.evaluate(epoch) + total_t += eval_t + self.logger(tb_msg=["eval/psnr", psnr, epoch]) + if psnr > best_psnr: + best_psnr = psnr + self.save("psnr_best.pth", epoch) + if self.logger.enable_wandb: + wandb.run.summary["best_psnr"] = best_psnr + if (epoch + 1) % 50 == 0: + self.save(f"epoch_{epoch + 1}.pth", epoch) + self.save("latest.pth", epoch) + + self.logger.close() + + def evaluate(self, epoch): + psnr_list = [] + time_stamp = time.time() + for i, data in enumerate(self.loader_val): + for k, v in data.items(): + data[k] = v.to(self.config["device"]) + + with torch.no_grad(): + results = self.model(**data, eval=True) + imgt_pred = results["imgt_pred"] + for j in range(data["img0"].shape[0]): + psnr = calculate_psnr(imgt_pred[j].detach().unsqueeze(0), data["imgt"][j].unsqueeze(0)).cpu().data + psnr_list.append(psnr) + + eval_time = time.time() - time_stamp + + self.logger( + "eval epoch:{}/{} time:{:.2f} psnr:{:.3f}".format( + epoch + 1, self.config["epochs"], eval_time, np.array(psnr_list).mean() + ) + ) + return np.array(psnr_list).mean(), eval_time + + def save(self, name, epoch): + save_path = "{}/{}/{}".format(self.config["save_dir"], "ckpts", name) + ckpt = OrderedDict(epoch=epoch) + if self.config["distributed"]: + ckpt["state_dict"] = self.model.module.state_dict() + else: + ckpt["state_dict"] = self.model.state_dict() + ckpt["optim"] = self.optimizer.state_dict() + torch.save(ckpt, save_path) + + def eta_format(self, eta): + time_str = "" + if eta >= 3600: + hours = int(eta // 3600) + eta -= hours * 3600 + time_str = f"{hours}" + + if eta >= 60: + mins = int(eta // 60) + eta -= mins * 60 + time_str = f"{time_str}:{mins:02}" + + eta = int(eta) + time_str = f"{time_str}:{eta:02}" + return time_str diff --git a/Helios/eval_moviebench/utils/third_party/amt/trainers/logger.py b/Helios/eval_moviebench/utils/third_party/amt/trainers/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..069e95275e48c100c3ced627bacc0b3fcf8fc8fa --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/trainers/logger.py @@ -0,0 +1,62 @@ +import logging +import os.path as osp +import shutil +import time + +import wandb +from torch.utils.tensorboard import SummaryWriter + + +def mv_archived_logger(name): + timestamp = time.strftime("%Y-%m-%d_%H:%M:%S_", time.localtime()) + basename = "archived_" + timestamp + osp.basename(name) + archived_name = osp.join(osp.dirname(name), basename) + shutil.move(name, archived_name) + + +class CustomLogger: + def __init__(self, common_cfg, tb_cfg=None, wandb_cfg=None, rank=0): + global global_logger + self.rank = rank + + if self.rank == 0: + self.logger = logging.getLogger("VFI") + self.logger.setLevel(logging.INFO) + format_str = logging.Formatter(common_cfg["format"]) + + console_handler = logging.StreamHandler() + console_handler.setFormatter(format_str) + + if osp.exists(common_cfg["filename"]): + mv_archived_logger(common_cfg["filename"]) + + file_handler = logging.FileHandler(common_cfg["filename"], common_cfg["filemode"]) + file_handler.setFormatter(format_str) + + self.logger.addHandler(console_handler) + self.logger.addHandler(file_handler) + self.tb_logger = None + + self.enable_wandb = False + + if wandb_cfg is not None: + self.enable_wandb = True + wandb.init(**wandb_cfg) + + if tb_cfg is not None: + self.tb_logger = SummaryWriter(**tb_cfg) + + global_logger = self + + def __call__(self, msg=None, level=logging.INFO, tb_msg=None): + if self.rank != 0: + return + if msg is not None: + self.logger.log(level, msg) + + if self.tb_logger is not None and tb_msg is not None: + self.tb_logger.add_scalar(*tb_msg) + + def close(self): + if self.rank == 0 and self.enable_wandb: + wandb.finish() diff --git a/Helios/eval_moviebench/utils/third_party/amt/utils/__init__.py b/Helios/eval_moviebench/utils/third_party/amt/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/eval_moviebench/utils/third_party/amt/utils/build_utils.py b/Helios/eval_moviebench/utils/third_party/amt/utils/build_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d4fc052d24bb57c460e173435b1ad0d575f46004 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/utils/build_utils.py @@ -0,0 +1,17 @@ +import importlib +import os +import sys + + +CUR_DIR = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(os.path.join(CUR_DIR, "../")) + + +def base_build_fn(module, cls, params): + return getattr(importlib.import_module(module, package=None), cls)(**params) + + +def build_from_cfg(config): + module, cls = config["name"].rsplit(".", 1) + params = config.get("params", {}) + return base_build_fn(module, cls, params) diff --git a/Helios/eval_moviebench/utils/third_party/amt/utils/dist_utils.py b/Helios/eval_moviebench/utils/third_party/amt/utils/dist_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d754d4fc7a6ed1a9bae246b2f895456218d815ea --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/utils/dist_utils.py @@ -0,0 +1,48 @@ +import os + +import torch + + +def get_world_size(): + """Find OMPI world size without calling mpi functions + :rtype: int + """ + if os.environ.get("PMI_SIZE") is not None: + return int(os.environ.get("PMI_SIZE") or 1) + elif os.environ.get("OMPI_COMM_WORLD_SIZE") is not None: + return int(os.environ.get("OMPI_COMM_WORLD_SIZE") or 1) + else: + return torch.cuda.device_count() + + +def get_global_rank(): + """Find OMPI world rank without calling mpi functions + :rtype: int + """ + if os.environ.get("PMI_RANK") is not None: + return int(os.environ.get("PMI_RANK") or 0) + elif os.environ.get("OMPI_COMM_WORLD_RANK") is not None: + return int(os.environ.get("OMPI_COMM_WORLD_RANK") or 0) + else: + return 0 + + +def get_local_rank(): + """Find OMPI local rank without calling mpi functions + :rtype: int + """ + if os.environ.get("MPI_LOCALRANKID") is not None: + return int(os.environ.get("MPI_LOCALRANKID") or 0) + elif os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK") is not None: + return int(os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK") or 0) + else: + return 0 + + +def get_master_ip(): + if os.environ.get("AZ_BATCH_MASTER_NODE") is not None: + return os.environ.get("AZ_BATCH_MASTER_NODE").split(":")[0] + elif os.environ.get("AZ_BATCHAI_MPI_MASTER_NODE") is not None: + return os.environ.get("AZ_BATCHAI_MPI_MASTER_NODE") + else: + return "127.0.0.1" diff --git a/Helios/eval_moviebench/utils/third_party/amt/utils/flow_utils.py b/Helios/eval_moviebench/utils/third_party/amt/utils/flow_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..059401503b5148f604488d21966c7825ef40563c --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/utils/flow_utils.py @@ -0,0 +1,126 @@ +import numpy as np +import torch +import torch.nn.functional as F +from PIL import ImageFile + + +ImageFile.LOAD_TRUNCATED_IMAGES = True + + +def warp(img, flow): + B, _, H, W = flow.shape + xx = torch.linspace(-1.0, 1.0, W).view(1, 1, 1, W).expand(B, -1, H, -1) + yy = torch.linspace(-1.0, 1.0, H).view(1, 1, H, 1).expand(B, -1, -1, W) + grid = torch.cat([xx, yy], 1).to(img) + flow_ = torch.cat([flow[:, 0:1, :, :] / ((W - 1.0) / 2.0), flow[:, 1:2, :, :] / ((H - 1.0) / 2.0)], 1) + grid_ = (grid + flow_).permute(0, 2, 3, 1) + output = F.grid_sample(input=img, grid=grid_, mode="bilinear", padding_mode="border", align_corners=True) + return output + + +def make_colorwheel(): + """ + Generates a color wheel for optical flow visualization as presented in: + Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007) + URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf + Code follows the original C++ source code of Daniel Scharstein. + Code follows the the Matlab source code of Deqing Sun. + Returns: + np.ndarray: Color wheel + """ + + RY = 15 + YG = 6 + GC = 4 + CB = 11 + BM = 13 + MR = 6 + + ncols = RY + YG + GC + CB + BM + MR + colorwheel = np.zeros((ncols, 3)) + col = 0 + + # RY + colorwheel[0:RY, 0] = 255 + colorwheel[0:RY, 1] = np.floor(255 * np.arange(0, RY) / RY) + col = col + RY + # YG + colorwheel[col : col + YG, 0] = 255 - np.floor(255 * np.arange(0, YG) / YG) + colorwheel[col : col + YG, 1] = 255 + col = col + YG + # GC + colorwheel[col : col + GC, 1] = 255 + colorwheel[col : col + GC, 2] = np.floor(255 * np.arange(0, GC) / GC) + col = col + GC + # CB + colorwheel[col : col + CB, 1] = 255 - np.floor(255 * np.arange(CB) / CB) + colorwheel[col : col + CB, 2] = 255 + col = col + CB + # BM + colorwheel[col : col + BM, 2] = 255 + colorwheel[col : col + BM, 0] = np.floor(255 * np.arange(0, BM) / BM) + col = col + BM + # MR + colorwheel[col : col + MR, 2] = 255 - np.floor(255 * np.arange(MR) / MR) + colorwheel[col : col + MR, 0] = 255 + return colorwheel + + +def flow_uv_to_colors(u, v, convert_to_bgr=False): + """ + Applies the flow color wheel to (possibly clipped) flow components u and v. + According to the C++ source code of Daniel Scharstein + According to the Matlab source code of Deqing Sun + Args: + u (np.ndarray): Input horizontal flow of shape [H,W] + v (np.ndarray): Input vertical flow of shape [H,W] + convert_to_bgr (bool, optional): Convert output image to BGR. Defaults to False. + Returns: + np.ndarray: Flow visualization image of shape [H,W,3] + """ + flow_image = np.zeros((u.shape[0], u.shape[1], 3), np.uint8) + colorwheel = make_colorwheel() # shape [55x3] + ncols = colorwheel.shape[0] + rad = np.sqrt(np.square(u) + np.square(v)) + a = np.arctan2(-v, -u) / np.pi + fk = (a + 1) / 2 * (ncols - 1) + k0 = np.floor(fk).astype(np.int32) + k1 = k0 + 1 + k1[k1 == ncols] = 0 + f = fk - k0 + for i in range(colorwheel.shape[1]): + tmp = colorwheel[:, i] + col0 = tmp[k0] / 255.0 + col1 = tmp[k1] / 255.0 + col = (1 - f) * col0 + f * col1 + idx = rad <= 1 + col[idx] = 1 - rad[idx] * (1 - col[idx]) + col[~idx] = col[~idx] * 0.75 # out of range + # Note the 2-i => BGR instead of RGB + ch_idx = 2 - i if convert_to_bgr else i + flow_image[:, :, ch_idx] = np.floor(255 * col) + return flow_image + + +def flow_to_image(flow_uv, clip_flow=None, convert_to_bgr=False): + """ + Expects a two dimensional flow image of shape. + Args: + flow_uv (np.ndarray): Flow UV image of shape [H,W,2] + clip_flow (float, optional): Clip maximum of flow values. Defaults to None. + convert_to_bgr (bool, optional): Convert output image to BGR. Defaults to False. + Returns: + np.ndarray: Flow visualization image of shape [H,W,3] + """ + assert flow_uv.ndim == 3, "input flow must have three dimensions" + assert flow_uv.shape[2] == 2, "input flow must have shape [H,W,2]" + if clip_flow is not None: + flow_uv = np.clip(flow_uv, 0, clip_flow) + u = flow_uv[:, :, 0] + v = flow_uv[:, :, 1] + rad = np.sqrt(np.square(u) + np.square(v)) + rad_max = np.max(rad) + epsilon = 1e-5 + u = u / (rad_max + epsilon) + v = v / (rad_max + epsilon) + return flow_uv_to_colors(u, v, convert_to_bgr) diff --git a/Helios/eval_moviebench/utils/third_party/amt/utils/utils.py b/Helios/eval_moviebench/utils/third_party/amt/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c784fbb8b029e2c26794e9a71c580c6a49c0a2d8 --- /dev/null +++ b/Helios/eval_moviebench/utils/third_party/amt/utils/utils.py @@ -0,0 +1,315 @@ +import random +import re +import sys + +import numpy as np +import torch +import torch.nn.functional as F +from imageio import imread, imwrite +from PIL import ImageFile + + +ImageFile.LOAD_TRUNCATED_IMAGES = True + + +class AverageMeter: + def __init__(self): + self.reset() + + def reset(self): + self.val = 0.0 + self.avg = 0.0 + self.sum = 0.0 + self.count = 0 + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + + +class AverageMeterGroups: + def __init__(self) -> None: + self.meter_dict = {} + + def update(self, dict, n=1): + for name, val in dict.items(): + if self.meter_dict.get(name) is None: + self.meter_dict[name] = AverageMeter() + self.meter_dict[name].update(val, n) + + def reset(self, name=None): + if name is None: + for v in self.meter_dict.values(): + v.reset() + else: + meter = self.meter_dict.get(name) + if meter is not None: + meter.reset() + + def avg(self, name): + meter = self.meter_dict.get(name) + if meter is not None: + return meter.avg + + +class InputPadder: + """Pads images such that dimensions are divisible by divisor""" + + def __init__(self, dims, divisor=16): + self.ht, self.wd = dims[-2:] + pad_ht = (((self.ht // divisor) + 1) * divisor - self.ht) % divisor + pad_wd = (((self.wd // divisor) + 1) * divisor - self.wd) % divisor + self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, pad_ht // 2, pad_ht - pad_ht // 2] + + def pad(self, *inputs): + if len(inputs) == 1: + return F.pad(inputs[0], self._pad, mode="replicate") + else: + return [F.pad(x, self._pad, mode="replicate") for x in inputs] + + def unpad(self, *inputs): + if len(inputs) == 1: + return self._unpad(inputs[0]) + else: + return [self._unpad(x) for x in inputs] + + def _unpad(self, x): + ht, wd = x.shape[-2:] + c = [self._pad[2], ht - self._pad[3], self._pad[0], wd - self._pad[1]] + return x[..., c[0] : c[1], c[2] : c[3]] + + +def img2tensor(img): + if img.shape[-1] > 3: + img = img[:, :, :3] + return torch.tensor(img).permute(2, 0, 1).unsqueeze(0) / 255.0 + + +def tensor2img(img_t): + return (img_t * 255.0).detach().squeeze(0).permute(1, 2, 0).cpu().numpy().clip(0, 255).astype(np.uint8) + + +def seed_all(seed): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +def read(file): + if file.endswith(".float3"): + return readFloat(file) + elif file.endswith(".flo"): + return readFlow(file) + elif file.endswith(".ppm"): + return readImage(file) + elif file.endswith(".pgm"): + return readImage(file) + elif file.endswith(".png"): + return readImage(file) + elif file.endswith(".jpg"): + return readImage(file) + elif file.endswith(".pfm"): + return readPFM(file)[0] + else: + raise Exception("don't know how to read %s" % file) + + +def write(file, data): + if file.endswith(".float3"): + return writeFloat(file, data) + elif file.endswith(".flo"): + return writeFlow(file, data) + elif file.endswith(".ppm"): + return writeImage(file, data) + elif file.endswith(".pgm"): + return writeImage(file, data) + elif file.endswith(".png"): + return writeImage(file, data) + elif file.endswith(".jpg"): + return writeImage(file, data) + elif file.endswith(".pfm"): + return writePFM(file, data) + else: + raise Exception("don't know how to write %s" % file) + + +def readPFM(file): + file = open(file, "rb") + + color = None + width = None + height = None + scale = None + endian = None + + header = file.readline().rstrip() + if header.decode("ascii") == "PF": + color = True + elif header.decode("ascii") == "Pf": + color = False + else: + raise Exception("Not a PFM file.") + + dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii")) + if dim_match: + width, height = list(map(int, dim_match.groups())) + else: + raise Exception("Malformed PFM header.") + + scale = float(file.readline().decode("ascii").rstrip()) + if scale < 0: + endian = "<" + scale = -scale + else: + endian = ">" + + data = np.fromfile(file, endian + "f") + shape = (height, width, 3) if color else (height, width) + + data = np.reshape(data, shape) + data = np.flipud(data) + return data, scale + + +def writePFM(file, image, scale=1): + file = open(file, "wb") + + color = None + + if image.dtype.name != "float32": + raise Exception("Image dtype must be float32.") + + image = np.flipud(image) + + if len(image.shape) == 3 and image.shape[2] == 3: + color = True + elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: + color = False + else: + raise Exception("Image must have H x W x 3, H x W x 1 or H x W dimensions.") + + file.write("PF\n" if color else "Pf\n".encode()) + file.write("%d %d\n".encode() % (image.shape[1], image.shape[0])) + + endian = image.dtype.byteorder + + if endian == "<" or endian == "=" and sys.byteorder == "little": + scale = -scale + + file.write("%f\n".encode() % scale) + + image.tofile(file) + + +def readFlow(name): + if name.endswith(".pfm") or name.endswith(".PFM"): + return readPFM(name)[0][:, :, 0:2] + + f = open(name, "rb") + + header = f.read(4) + if header.decode("utf-8") != "PIEH": + raise Exception("Flow file header does not contain PIEH") + + width = np.fromfile(f, np.int32, 1).squeeze() + height = np.fromfile(f, np.int32, 1).squeeze() + + flow = np.fromfile(f, np.float32, width * height * 2).reshape((height, width, 2)) + + return flow.astype(np.float32) + + +def readImage(name): + if name.endswith(".pfm") or name.endswith(".PFM"): + data = readPFM(name)[0] + if len(data.shape) == 3: + return data[:, :, 0:3] + else: + return data + return imread(name) + + +def writeImage(name, data): + if name.endswith(".pfm") or name.endswith(".PFM"): + return writePFM(name, data, 1) + return imwrite(name, data) + + +def writeFlow(name, flow): + f = open(name, "wb") + f.write("PIEH".encode("utf-8")) + np.array([flow.shape[1], flow.shape[0]], dtype=np.int32).tofile(f) + flow = flow.astype(np.float32) + flow.tofile(f) + + +def readFloat(name): + f = open(name, "rb") + + if (f.readline().decode("utf-8")) != "float\n": + raise Exception("float file %s did not contain keyword" % name) + + dim = int(f.readline()) + + dims = [] + count = 1 + for i in range(0, dim): + d = int(f.readline()) + dims.append(d) + count *= d + + dims = list(reversed(dims)) + + data = np.fromfile(f, np.float32, count).reshape(dims) + if dim > 2: + data = np.transpose(data, (2, 1, 0)) + data = np.transpose(data, (1, 0, 2)) + + return data + + +def writeFloat(name, data): + f = open(name, "wb") + + dim = len(data.shape) + if dim > 3: + raise Exception("bad float file dimension: %d" % dim) + + f.write(("float\n").encode("ascii")) + f.write(("%d\n" % dim).encode("ascii")) + + if dim == 1: + f.write(("%d\n" % data.shape[0]).encode("ascii")) + else: + f.write(("%d\n" % data.shape[1]).encode("ascii")) + f.write(("%d\n" % data.shape[0]).encode("ascii")) + for i in range(2, dim): + f.write(("%d\n" % data.shape[i]).encode("ascii")) + + data = data.astype(np.float32) + if dim == 2: + data.tofile(f) + + else: + np.transpose(data, (2, 0, 1)).tofile(f) + + +def check_dim_and_resize(tensor_list): + shape_list = [] + for t in tensor_list: + shape_list.append(t.shape[2:]) + + if len(set(shape_list)) > 1: + desired_shape = shape_list[0] + print(f"Inconsistent size of input video frames. All frames will be resized to {desired_shape}") + + resize_tensor_list = [] + for t in tensor_list: + resize_tensor_list.append(torch.nn.functional.interpolate(t, size=tuple(desired_shape), mode="bilinear")) + + tensor_list = resize_tensor_list + + return tensor_list diff --git a/Helios/eval_moviebench/utils/utils.py b/Helios/eval_moviebench/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5ea395fbfd537174e56a651133d374b834e45ecb --- /dev/null +++ b/Helios/eval_moviebench/utils/utils.py @@ -0,0 +1,451 @@ +import csv +import json +import os +import random +import re + +import cv2 +import numpy as np +import torch +from PIL import Image, ImageSequence +from torchvision import transforms +from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor + +try: + from video_reader import PyVideoReader +except ImportError: + class PyVideoReader: + def __init__(self, video_path, target_height=None, target_width=None, threads=0): + self.video_path = video_path + self.target_height = target_height + self.target_width = target_width + + def _read_frames(self): + cap = cv2.VideoCapture(self.video_path) + frames = [] + while cap.isOpened(): + ok, frame = cap.read() + if not ok: + break + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + if self.target_width is not None and self.target_height is not None: + frame = cv2.resize(frame, (self.target_width, self.target_height), interpolation=cv2.INTER_AREA) + frames.append(frame) + fps = cap.get(cv2.CAP_PROP_FPS) or 0.0 + cap.release() + if not frames: + raise ValueError(f"No frames could be decoded from {self.video_path}") + return np.asarray(frames, dtype=np.uint8), fps + + def decode(self): + frames, _ = self._read_frames() + return frames + + def get_shape(self): + frames, _ = self._read_frames() + t, h, w, _ = frames.shape + return t, h, w + + def get_fps(self): + _, fps = self._read_frames() + return fps if fps > 0 else 24.0 + + def get_batch(self, frame_indices): + frames, _ = self._read_frames() + return frames[frame_indices] + + +try: + from torchvision.transforms import InterpolationMode + + BICUBIC = InterpolationMode.BICUBIC + BILINEAR = InterpolationMode.BILINEAR +except ImportError: + BICUBIC = Image.BICUBIC + BILINEAR = Image.BILINEAR + + +def clip_transform(n_px): + return Compose( + [ + Resize(n_px, interpolation=BICUBIC, antialias=False), + CenterCrop(n_px), + transforms.Lambda(lambda x: x.float().div(255.0)), + Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), + ] + ) + + +def clip_transform_Image(n_px): + return Compose( + [ + Resize(n_px, interpolation=BICUBIC, antialias=False), + CenterCrop(n_px), + ToTensor(), + Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), + ] + ) + + +def get_frame_indices(num_frames, vlen, sample="rand", fix_start=None, input_fps=1, max_num_frames=-1): + if sample in ["rand", "middle"]: # uniform sampling + acc_samples = min(num_frames, vlen) + # split the video into `acc_samples` intervals, and sample from each interval. + intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int) + ranges = [] + for idx, interv in enumerate(intervals[:-1]): + ranges.append((interv, intervals[idx + 1] - 1)) + if sample == "rand": + try: + frame_indices = [random.choice(range(x[0], x[1])) for x in ranges] + except Exception: + frame_indices = np.random.permutation(vlen)[:acc_samples] + frame_indices.sort() + frame_indices = list(frame_indices) + elif fix_start is not None: + frame_indices = [x[0] + fix_start for x in ranges] + elif sample == "middle": + frame_indices = [(x[0] + x[1]) // 2 for x in ranges] + else: + raise NotImplementedError + + if len(frame_indices) < num_frames: # padded with last frame + padded_frame_indices = [frame_indices[-1]] * num_frames + padded_frame_indices[: len(frame_indices)] = frame_indices + frame_indices = padded_frame_indices + elif "fps" in sample: # fps0.5, sequentially sample frames at 0.5 fps + output_fps = float(sample[3:]) + duration = float(vlen) / input_fps + delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents + frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta) + frame_indices = np.around(frame_seconds * input_fps).astype(int) + frame_indices = [e for e in frame_indices if e < vlen] + if max_num_frames > 0 and len(frame_indices) > max_num_frames: + frame_indices = frame_indices[:max_num_frames] + # frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames) + else: + raise ValueError + return frame_indices + + +def align_dimension(value, alignment=2): + return int(round(value / alignment) * alignment) + + +def load_prompt_records(input_csv): + if not os.path.exists(input_csv): + raise FileNotFoundError(f"CSV file not found: {input_csv}") + + with open(input_csv, newline="", encoding="utf-8") as f: + reader = csv.DictReader(f) + rows = list(reader) + + required_columns = {"id", "prompt", "duration"} + missing = required_columns - set(reader.fieldnames or []) + if missing: + raise ValueError(f"CSV must contain columns {sorted(required_columns)}. Missing: {sorted(missing)}") + + prompt_records = {} + for row in rows: + csv_id = int(row["id"]) + prompt_records[csv_id] = { + "id": csv_id, + "prompt": row["prompt"], + "duration": int(row["duration"]), + } + return prompt_records + + +def parse_benchmark_video_path(video_path): + video_name = os.path.basename(video_path) + stem, ext = os.path.splitext(video_name) + if ext.lower() != ".mp4": + raise ValueError(f"Unsupported video extension for benchmark file: {video_path}") + + parts = stem.split("_") + if not parts or not parts[0].isdigit(): + raise ValueError(f"Cannot parse video id from file name: {video_name}") + + version = os.path.basename(os.path.dirname(video_path)) + raw_id = int(parts[0]) + is_official_eval_name = len(parts) >= 3 and parts[1].isdigit() and any(part.startswith("ori") for part in parts[2:]) + csv_id = raw_id if is_official_eval_name else raw_id + 1 + + return { + "video_path": video_path, + "video_name": video_name, + "version": version, + "video_idx": raw_id, + "csv_id": csv_id, + "is_official_eval_name": is_official_eval_name, + } + + +def discover_benchmark_videos(video_dir, input_csv): + prompt_records = load_prompt_records(input_csv) + video_records = [] + + for name in sorted(os.listdir(video_dir)): + path = os.path.join(video_dir, name) + if not os.path.isfile(path) or not name.lower().endswith(".mp4"): + continue + + record = parse_benchmark_video_path(path) + csv_id = record["csv_id"] + if csv_id not in prompt_records: + raise ValueError(f"Video {record['video_name']} maps to csv id {csv_id}, which is missing in {input_csv}") + + prompt_record = prompt_records[csv_id] + record.update( + { + "id": csv_id, + "prompt": prompt_record["prompt"], + "duration": prompt_record["duration"], + } + ) + video_records.append(record) + + video_records.sort(key=lambda item: item["csv_id"]) + return video_records + + +def load_existing_results(output_json_path): + if not os.path.exists(output_json_path): + return {} + + with open(output_json_path, "r", encoding="utf-8") as f: + existing_data = json.load(f) + + existing_results = {} + for item in existing_data.get("per_video_results", []): + key = item.get("id") + if key is not None: + existing_results[int(key)] = item + return existing_results + + +def enrich_result_record(record, **metrics): + enriched = { + "id": record["id"], + "csv_id": record["csv_id"], + "video_idx": record["video_idx"], + "version": record["version"], + "video_name": record["video_name"], + "video_path": record["video_path"], + "prompt": record["prompt"], + "duration": record["duration"], + } + enriched.update(metrics) + return enriched + + +def load_video(video_path, data_transform=None, num_frames=None, return_tensor=True, width=None, height=None): + if video_path.endswith(".gif"): + frame_ls = [] + img = Image.open(video_path) + for frame in ImageSequence.Iterator(img): + frame = frame.convert("RGB") + frame = np.array(frame).astype(np.uint8) + frame_ls.append(frame) + buffer = np.array(frame_ls).astype(np.uint8) + elif video_path.endswith(".png"): + frame = Image.open(video_path) + frame = frame.convert("RGB") + frame = np.array(frame).astype(np.uint8) + frame_ls = [frame] + buffer = np.array(frame_ls) + elif video_path.endswith(".mp4"): + vr = PyVideoReader(video_path, threads=0) + if width is not None and height is not None: + (_, original_height, original_width) = vr.get_shape() + original_aspect_ratio = original_width / original_height + if width > height: + target_width = width + target_height = int(width / original_aspect_ratio) + else: + target_height = height + target_width = int(height * original_aspect_ratio) + target_height = align_dimension(target_height, 2) + target_width = align_dimension(target_width, 2) + vr = PyVideoReader(video_path, target_height=target_height, target_width=target_width, threads=0) + buffer = vr.decode() + vr = None + del vr + else: + raise NotImplementedError + + frames = buffer + if num_frames and not video_path.endswith(".mp4"): + frame_indices = get_frame_indices(num_frames, len(frames), sample="middle") + frames = frames[frame_indices] + + if data_transform: + frames = data_transform(frames) + elif return_tensor: + frames = torch.Tensor(frames) + frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8 + + return frames + + +def read_frames_decord_by_fps( + video_path, + sample_fps=2, + sample="rand", + fix_start=None, + max_num_frames=-1, + trimmed30=False, + num_frames=8, + width=None, + height=None, +): + vr_info = PyVideoReader(video_path, threads=0) + (vlen, original_height, original_width) = vr_info.get_shape() + fps = vr_info.get_fps() + duration = vlen / float(fps) + vr_info = None + del vr_info + + if trimmed30 and duration > 30: + duration = 30 + vlen = int(30 * float(fps)) + + target_width = None + target_height = None + if width is not None and height is not None: + original_aspect_ratio = original_width / original_height + if width > height: + target_width = width + target_height = int(width / original_aspect_ratio) + else: + target_height = height + target_width = int(height * original_aspect_ratio) + target_height = align_dimension(target_height, 2) + target_width = align_dimension(target_width, 2) + + frame_indices = get_frame_indices( + num_frames, vlen, sample=sample, fix_start=fix_start, input_fps=fps, max_num_frames=max_num_frames + ) + + vr = PyVideoReader(video_path, target_height=target_height, target_width=target_width, threads=0) + buffer = vr.decode() + vr = None + del vr + + frames = buffer[frame_indices] + if not isinstance(frames, torch.Tensor): + frames = torch.from_numpy(frames) + + frames = frames.permute(0, 3, 1, 2) # (T, H, W, C) -> (T, C, H, W) + + return frames + + +def load_video_frames(video_path, start_ratio=0.0, end_ratio=1.0, num_frames=8, height=384, width=640): + # First pass: get video shape + vr = PyVideoReader(video_path, threads=0) + (total_frames, original_height, original_width) = vr.get_shape() + + # Calculate target dimensions maintaining aspect ratio + original_aspect_ratio = original_width / original_height + if width > height: + target_width = width + target_height = int(width / original_aspect_ratio) + else: + target_height = height + target_width = int(height * original_aspect_ratio) + + target_height = align_dimension(target_height, 2) + target_width = align_dimension(target_width, 2) + + # Calculate frame range + start_frame = int(total_frames * start_ratio) + end_frame = int(total_frames * end_ratio) + portion_length = end_frame - start_frame + + if portion_length < num_frames: + # Expand the range to accommodate num_frames + needed_frames = num_frames - portion_length + expansion = needed_frames / 2 + + # Try to expand symmetrically + new_start = max(0, start_frame - int(np.ceil(expansion))) + new_end = min(total_frames, end_frame + int(np.floor(expansion))) + + # If still not enough, expand further in available direction + if new_end - new_start < num_frames: + if new_start == 0: + new_end = min(total_frames, new_start + num_frames) + elif new_end == total_frames: + new_start = max(0, new_end - num_frames) + + start_frame = new_start + end_frame = new_end + portion_length = end_frame - start_frame + + # Now sample frames + frame_indices = np.linspace(start_frame, end_frame - 1, num_frames, dtype=int) + else: + # Sample uniformly from the portion + step = portion_length / num_frames + frame_indices = [int(start_frame + i * step) for i in range(num_frames)] + + # Ensure indices are within bounds + frame_indices = [min(idx, total_frames - 1) for idx in frame_indices] + + # Second pass: decode only needed frames with target dimensions + vr = PyVideoReader(video_path, target_height=target_height, target_width=target_width, threads=0) + frames = vr.get_batch(frame_indices) # Only decode needed frames (num_frames, H, W, C) + + # Convert to tensor if needed and permute to (T, C, H, W) + if not isinstance(frames, torch.Tensor): + frames = torch.from_numpy(frames) + frames = frames.permute(0, 3, 1, 2) # (T, C, H, W) + + # Clean up + vr = None + del vr + + return frames + + +def extract_video_segment(input_path, output_path, start_ratio, end_ratio): + """ + 尽可能保持原视频编码参数 + """ + import ffmpeg + + # 获取原视频信息 + probe = ffmpeg.probe(input_path) + video_stream = next(s for s in probe["streams"] if s["codec_type"] == "video") + + duration = float(probe["format"]["duration"]) + start_time = duration * start_ratio + segment_duration = duration * (end_ratio - start_ratio) + + # 检测原视频编码参数 + orig_codec = video_stream.get("codec_name", "h264") + orig_pix_fmt = video_stream.get("pix_fmt", "yuv420p") + + # 如果原视频是 h264/h265,使用相同编码器 + if orig_codec in ["h264", "hevc"]: + codec_name = "libx264" if orig_codec == "h264" else "libx265" + else: + codec_name = "libx264" # fallback + + ( + ffmpeg.input(input_path, ss=start_time) + .output( + output_path, + t=segment_duration, + vcodec=codec_name, + crf=0, + preset="medium", + pix_fmt=orig_pix_fmt, + acodec="copy", + vsync="cfr", + map_metadata=0, + ) + .overwrite_output() + .run(quiet=True) + ) diff --git a/Helios/example/toy_data/toy_filter.json b/Helios/example/toy_data/toy_filter.json new file mode 100644 index 0000000000000000000000000000000000000000..610c8a1edecae7502af491cacedd7aaeeca39319 --- /dev/null +++ b/Helios/example/toy_data/toy_filter.json @@ -0,0 +1,46 @@ +[ + { + "cut": [ + 0, + 81 + ], + "crop": [ + 0, + 832, + 0, + 480 + ], + "fps": 24.0, + "num_frames": 81, + "resolution": { + "height": 480, + "width": 832 + }, + "cap": [ + "A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity." + ], + "path": "videos/2_240_ori81.mp4" + }, + { + "cut": [ + 0, + 129 + ], + "crop": [ + 0, + 832, + 0, + 480 + ], + "fps": 24.0, + "num_frames": 129, + "resolution": { + "height": 480, + "width": 832 + }, + "cap": [ + "An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man." + ], + "path": "videos/239_120_ori129.mp4" + } +] \ No newline at end of file diff --git a/Helios/helios/__pycache__/__init__.cpython-311.pyc b/Helios/helios/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4ee5b95a91618ffb419923e1a14bc91f6b95192 Binary files /dev/null and b/Helios/helios/__pycache__/__init__.cpython-311.pyc differ diff --git a/Helios/helios/__pycache__/__init__.cpython-312.pyc b/Helios/helios/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ceaea09c21ee5e884f677884f14c922c1e287cbb Binary files /dev/null and b/Helios/helios/__pycache__/__init__.cpython-312.pyc differ diff --git a/Helios/helios/dataset/__init__.py b/Helios/helios/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/helios/dataset/dataloader_dmd.py b/Helios/helios/dataset/dataloader_dmd.py new file mode 100644 index 0000000000000000000000000000000000000000..bf66562003089c5a676f49e019ca0188be12ebff --- /dev/null +++ b/Helios/helios/dataset/dataloader_dmd.py @@ -0,0 +1,531 @@ +import os +import pickle +import random +from collections import defaultdict + +import torch +from einops import rearrange +from torch.utils.data import Dataset, Sampler + + +class BucketedFeatureDataset(Dataset): + def __init__( + self, + gan_folders=None, + ode_folders=None, + text_folders=None, + is_use_gt_history=False, + return_secondary=False, + force_rebuild=False, + single_res=True, + single_length=True, + single_num_frame=81, + single_height=384, + single_width=640, + seed=42, + ): + self.is_use_gt_history = is_use_gt_history + self.return_secondary = return_secondary + self.force_rebuild = force_rebuild + self.base_seed = seed + self._epoch = 0 + + self.single_res = single_res + self.single_length = single_length + self.single_num_frame = single_num_frame + self.single_height = single_height + self.single_width = single_width + + self.gan_samples = self._init_samples(gan_folders, "gan") + self.ode_samples = self._init_samples(ode_folders, "ode") + self.text_samples = self._init_samples(text_folders, "text") + + self._align_sample_counts() + + def _init_samples(self, folders, data_type): + if folders is None: + return [] + + folders = [folders] if isinstance(folders, str) else folders + samples = [] + + for folder in folders: + cache_file = os.path.join(folder, f"{data_type}_dataset_cache.pkl") + folder_samples = self._process_folder(folder, cache_file, data_type) + samples.extend(folder_samples) + + return samples + + def _align_sample_counts(self, is_log=True): + lengths = {"gan": len(self.gan_samples), "ode": len(self.ode_samples), "text": len(self.text_samples)} + + non_empty_lengths = {k: v for k, v in lengths.items() if v > 0} + if not non_empty_lengths: + return + max_length = max(non_empty_lengths.values()) + + if is_log: + print(f"\nAligning sample counts to max: {max_length}") + print(f"Original counts - GAN: {lengths['gan']}, ODE: {lengths['ode']}, TEXT: {lengths['text']}") + + random.seed(self.base_seed) + + if self.gan_samples and len(self.gan_samples) < max_length: + self.gan_samples = self._expand_samples(self.gan_samples, max_length, "GAN") + + if self.ode_samples and len(self.ode_samples) < max_length: + self.ode_samples = self._expand_samples(self.ode_samples, max_length, "ODE") + + if self.text_samples and len(self.text_samples) < max_length: + self.text_samples = self._expand_samples(self.text_samples, max_length, "TEXT") + + if is_log: + print( + f"Aligned counts - GAN: {len(self.gan_samples)}, ODE: {len(self.ode_samples)}, TEXT: {len(self.text_samples)}\n" + ) + + def _expand_samples(self, samples, target_length, data_type): + original_length = len(samples) + expanded_samples = samples.copy() + + while len(expanded_samples) < target_length: + random_sample = random.choice(samples) + expanded_samples.append(random_sample) + + print(f"{data_type}: Expanded from {original_length} to {len(expanded_samples)} samples") + return expanded_samples + + def _process_folder(self, folder, cache_file, data_type): + if self.force_rebuild or not os.path.exists(cache_file): + # if os.path.exists(cache_file): + # os.remove(cache_file) + print(f"{data_type.upper()}: Building metadata cache for folder: {folder}") + folder_samples = self._build_folder_metadata(folder, data_type) + + if not self.force_rebuild: + print(f"{data_type.upper()}: Saving metadata cache for folder: {folder}") + with open(cache_file, "wb") as f: + pickle.dump({"samples": folder_samples}, f) + + print(f"{data_type.upper()}: Cached {len(folder_samples)} samples from {folder}") + else: + print(f"{data_type.upper()}: Loading cached metadata from: {folder}") + with open(cache_file, "rb") as f: + folder_samples = pickle.load(f)["samples"] + print(f"{data_type.upper()}: Loaded {len(folder_samples)} samples from cache: {folder}") + + return folder_samples + + def _build_folder_metadata(self, folder, data_type): + feature_files = [f for f in os.listdir(folder) if f.endswith(".pt")] + samples = [] + + print(f"{data_type.upper()}: Processing {len(feature_files)} files in {folder}...") + for i, feature_file in enumerate(feature_files): + if i % 10000 == 0: + print(f" {data_type.upper()}: Processed {i}/{len(feature_files)} files") + + feature_path = os.path.join(folder, feature_file) + + # TODO hard code here now + if data_type == "gan": + parts = feature_file.split("_") + num_frame = int(parts[-3]) + height = int(parts[-2]) + width = int(parts[-1].replace(".pt", "")) + + if self.is_use_gt_history: + if (height, width) not in [(self.single_height, self.single_width)]: + continue + else: + if (num_frame, height, width) not in [ + (self.single_num_frame, self.single_height, self.single_width) + ]: + continue + + samples.append( + { + "uttid": os.path.splitext(os.path.basename(feature_file))[0], + "dataset_name": folder.rstrip("/"), + "file_path": feature_path, + } + ) + + return samples + + def prepare_stage1_latent(self, vae_latent, idx, base_vae_latent=None, return_secondary=False): + self.is_keep_x0 = (True,) + self.history_sizes = [16, 2, 1] + self.num_rollout_sections = 9 + + source_latent = base_vae_latent if base_vae_latent is not None else vae_latent + + x0_latent = None + if self.is_keep_x0: + x0_latent = source_latent[0, :, :1, :, :].clone() + total_sections = source_latent.shape[0] + latent_window_size = source_latent.shape[2] + history_window_size = sum(self.history_sizes) + section_size = history_window_size + latent_window_size + + temp_source_latent = rearrange(source_latent, "b c t h w -> c (b t) h w") + zero_padding_source = torch.zeros( + temp_source_latent.shape[0], + history_window_size, + temp_source_latent.shape[2], + temp_source_latent.shape[3], + device=temp_source_latent.device, + dtype=temp_source_latent.dtype, + ) + continue_source_latent = torch.cat([zero_padding_source, temp_source_latent], dim=1) + + temp_vae_latent = rearrange(vae_latent, "b c t h w -> c (b t) h w") + zero_padding_vae = torch.zeros( + temp_vae_latent.shape[0], + history_window_size, + temp_vae_latent.shape[2], + temp_vae_latent.shape[3], + device=temp_vae_latent.device, + dtype=temp_vae_latent.dtype, + ) + continue_vae_latent = torch.cat([zero_padding_vae, temp_vae_latent], dim=1) + + sample_seed = self.base_seed + self._epoch * 1000000 + idx + choice_idx = torch.randint( + 0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed) + ).item() + if choice_idx == 0 and x0_latent is not None: + x0_latent = torch.zeros_like(x0_latent) + + start_indice = choice_idx * latent_window_size + end_indice = start_indice + section_size + + history_latent = continue_source_latent[:, start_indice : start_indice + history_window_size, :, :] + target_latent = continue_vae_latent[:, start_indice + history_window_size : end_indice, :, :] + + x0_latent_2 = None + history_latent_2 = None + target_latent_2 = None + if return_secondary: + sample_seed_2 = self.base_seed + self._epoch * 1000000 + idx + 999999 + choice_idx_2 = torch.randint( + 0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed_2) + ).item() + + x0_latent_2 = None + if self.is_keep_x0: + x0_latent_2 = source_latent[0, :, :1, :, :].clone() + if choice_idx_2 == 0: + x0_latent_2 = torch.zeros_like(x0_latent_2) + + start_indice_2 = choice_idx_2 * latent_window_size + end_indice_2 = start_indice_2 + section_size + + history_latent_2 = continue_source_latent[:, start_indice_2 : start_indice_2 + history_window_size, :, :] + target_latent_2 = continue_vae_latent[:, start_indice_2 + history_window_size : end_indice_2, :, :] + + return (x0_latent, history_latent, target_latent), (x0_latent_2, history_latent_2, target_latent_2) + + def set_epoch(self, epoch): + self._epoch = epoch + random.seed(self.base_seed + epoch) + self._align_sample_counts(is_log=False) + + def __len__(self): + return max(len(self.gan_samples), len(self.ode_samples), len(self.text_samples)) + + def __getitem__(self, idx): + while True: + try: + output_dict = {} + + if self.gan_samples: + gan_sample = self.gan_samples[idx] + gan_feature = torch.load(gan_sample["file_path"], map_location="cpu", weights_only=False) + if self.is_use_gt_history: + ( + (x0_latent, history_latent, target_latent), + (x0_latent_2, history_latent_2, target_latent_2), + ) = self.prepare_stage1_latent( + gan_feature["vae_latent"], + idx, + return_secondary=self.return_secondary, + ) + output_dict.update( + { + "gan_uttid": gan_sample["uttid"], + "gan_dataset_name": gan_sample["dataset_name"], + "gan_vae_latents": target_latent, + "gan_x0_latents": x0_latent, + "gan_history_latents": history_latent, + "gan_vae_latents_2": target_latent_2, + "gan_x0_latents_2": x0_latent_2, + "gan_history_latents_2": history_latent_2, + "gan_prompt_raws": gan_feature["prompt_raw"], + "gan_prompt_embeds": gan_feature["prompt_embed"], + } + ) + else: + output_dict.update( + { + "gan_uttid": gan_sample["uttid"], + "gan_dataset_name": gan_sample["dataset_name"], + "gan_vae_latents": gan_feature["vae_latent"], + "gan_prompt_raws": gan_feature["prompt_raw"], + "gan_prompt_embeds": gan_feature["prompt_embed"], + } + ) + gan_sample = None + gan_feature = None + del gan_sample + del gan_feature + + if self.ode_samples: + ode_sample = self.ode_samples[idx] + ode_feature = torch.load(ode_sample["file_path"], map_location="cpu", weights_only=False) + output_dict.update( + { + "ode_uttid": ode_sample["uttid"], + "ode_dataset_name": ode_sample["dataset_name"], + "ode_latent_window_size": ode_feature["latent_window_size"], + "ode_latents": ode_feature["ode_latents"], + "ode_prompt_raws": ode_feature["prompt_raw"], + "ode_prompt_embeds": ode_feature["prompt_embed"][0], + } + ) + ode_sample = None + ode_feature = None + del ode_sample + del ode_feature + + if self.text_samples: + text_sample = self.text_samples[idx] + text_feature = torch.load(text_sample["file_path"], map_location="cpu", weights_only=False) + output_dict.update( + { + "text_uttid": text_sample["uttid"], + "text_dataset_name": text_sample["dataset_name"], + "text_prompt_raws": text_feature["prompt_raw"], + "text_prompt_embeds": text_feature["prompt_embed"], + } + ) + text_sample = None + text_feature = None + del text_sample + del text_feature + + return output_dict + + except Exception as e: + idx = random.randint(0, len(self) - 1) + print(f"Error loading sample at idx {idx}, retrying... Error: {e}") + + +class BucketedSampler(Sampler): + def __init__( + self, + dataset, + batch_size, + dataset_sampling_ratios={}, + drop_last=False, + shuffle=True, + seed=42, + num_sp_groups=1, + sp_world_size=1, + global_rank=0, + ): + self.dataset = dataset + self.batch_size = batch_size + self.drop_last = drop_last + self.shuffle = shuffle + self.seed = seed + self.generator = torch.Generator() + self._epoch = 0 + + # Distributed parameters + self.num_sp_groups = num_sp_groups + self.sp_world_size = sp_world_size + self.global_rank = global_rank + self.ith_sp_group = self.global_rank // self.sp_world_size + + def set_epoch(self, epoch): + self._epoch = epoch + + def _shard_indices_for_sp_group(self, indices): + """ + Shard indices across SP groups. + Each SP group gets a disjoint subset of the data. + """ + if self.num_sp_groups == 1: + return indices + + # Convert to tensor if it's a list + if isinstance(indices, list): + indices_tensor = torch.tensor(indices, dtype=torch.long) + else: + indices_tensor = indices + + # Pad indices if necessary to make it divisible by num_sp_groups + total_size = len(indices_tensor) + if total_size % self.num_sp_groups != 0: + if not self.drop_last: + padding_size = self.num_sp_groups - (total_size % self.num_sp_groups) + indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]]) + else: + # If drop_last, truncate to be divisible + if self.drop_last: + truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups + indices_tensor = indices_tensor[:truncate_size] + + # Shard: each SP group gets every num_sp_groups-th element + sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups] + + return sp_group_indices.tolist() + + def __iter__(self): + # Use epoch-level seed for reproducibility + epoch_seed = self.seed + self._epoch + self.generator.manual_seed(epoch_seed) + + # Get all indices + all_indices = list(range(len(self.dataset))) + + # Global shuffle before sharding (important for distributed consistency) + if self.shuffle: + perm = torch.randperm(len(all_indices), generator=self.generator).tolist() + all_indices = [all_indices[i] for i in perm] + + # Shard indices for this SP group + sp_group_indices = self._shard_indices_for_sp_group(all_indices) + + # Create batches + for i in range(0, len(sp_group_indices), self.batch_size): + batch = sp_group_indices[i : i + self.batch_size] + if len(batch) == self.batch_size or not self.drop_last: + yield batch + + def __len__(self): + # Total samples in dataset + total_samples = len(self.dataset) + + # Account for SP group sharding + sp_group_samples = total_samples // self.num_sp_groups + if not self.drop_last and total_samples % self.num_sp_groups != 0: + sp_group_samples += 1 + + # Calculate number of batches + total_batches = sp_group_samples // self.batch_size + if not self.drop_last and sp_group_samples % self.batch_size != 0: + total_batches += 1 + + return total_batches + + +def collate_fn(batch): + return { + key: torch.stack([d[key] for d in batch]) + if isinstance(batch[0][key], torch.Tensor) + else [d[key] for d in batch] + for key in batch[0] + } + + +if __name__ == "__main__": + from accelerate import Accelerator + from torchdata.stateful_dataloader import StatefulDataLoader + + dataloader_num_workers = 8 + batch_size = 2 + num_train_epochs = 2 + seed = 0 + + gan_folder = [ + "/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_long_960", + "/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_short_960", + ] + ode_folder = [ + "/mnt/hdfs/data/ysh_new/userful_things_wan/ode_pairs/vidprom_filtered_extended", + ] + text_folder = [ + "/mnt/hdfs/data/ysh_new/userful_things_wan/text-embedding/mixkit_filter", + "/mnt/hdfs/data/ysh_new/userful_things_wan/text-embedding/vidprom_filtered_extended", + ] + + accelerator = Accelerator() + print(accelerator.process_index, accelerator.num_processes) + + dataset = BucketedFeatureDataset( + gan_folders=gan_folder, + ode_folders=ode_folder, + text_folders=text_folder, + is_use_gt_history=True, + force_rebuild=True, + seed=seed, + ) + sampler = BucketedSampler( + dataset, + batch_size=batch_size, + drop_last=True, + shuffle=True, + seed=seed, + num_sp_groups=accelerator.num_processes // 1, + sp_world_size=1, + global_rank=accelerator.process_index, + ) + dataloader = StatefulDataLoader( + dataset, + batch_sampler=sampler, + collate_fn=collate_fn, + num_workers=dataloader_num_workers, + prefetch_factor=2 if dataloader_num_workers > 0 else None, + ) + print(len(dataset), len(dataloader)) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + + step = 0 + global_step = 0 + first_epoch = 0 + print("Testing dataloader...") + dataset_counts = defaultdict(int) + for epoch in range(first_epoch, num_train_epochs): + sampler.set_epoch(epoch) + dataset.set_epoch(epoch) + for i, batch in enumerate(dataloader): + # Get metadata + gan_uttid = batch["gan_uttid"] + ode_uttid = batch["ode_uttid"] + text_uttid = batch["text_uttid"] + + # Get feature + # For GAN + gan_vae_latents = batch["gan_vae_latents"] + gan_prompt_raws = batch["gan_prompt_raws"] + gan_prompt_embeds = batch["gan_prompt_embeds"] + print(gan_vae_latents.shape, gan_prompt_embeds.shape, gan_prompt_raws) + + # For ODE + ode_prompt_raws = batch["ode_prompt_raws"] + ode_prompt_embeds = batch["ode_prompt_embeds"] + print(ode_prompt_embeds.shape, ode_prompt_raws) + + # For Text + text_prompt_raws = batch["text_prompt_raws"] + text_prompt_embeds = batch["text_prompt_embeds"] + print(text_prompt_embeds.shape, text_prompt_raws) + + if accelerator.process_index == 0: + # print info + print(f" Step {step}:") + print(f" Batch {i}:") + print(f" Batch size: {len(gan_uttid)}") + print(f" Uttids: {gan_uttid}, {ode_uttid}, {text_uttid}") + print( + f" Data Name: {batch['gan_dataset_name']}, {batch['ode_dataset_name']}, {batch['text_dataset_name']}" + ) + + for dataset_name in batch["gan_dataset_name"]: + dataset_counts[dataset_name] += 1 + + step += 1 + + print("实际采样统计:", dict(dataset_counts)) diff --git a/Helios/helios/dataset/dataloader_history_latents_dist.py b/Helios/helios/dataset/dataloader_history_latents_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..f53ca5ee7a429c899ca48fc9baa0df0f24e0e72c --- /dev/null +++ b/Helios/helios/dataset/dataloader_history_latents_dist.py @@ -0,0 +1,685 @@ +import os +import pickle +import random +from collections import defaultdict + +import torch +from einops import rearrange +from torch.utils.data import Dataset, Sampler + + +class BucketedFeatureDataset(Dataset): + def __init__( + self, + feature_folders, + history_sizes=[16, 2, 1], + is_keep_x0=True, + force_rebuild=False, + return_all_vae_latent=False, + return_prompt_raw=False, + num_rollout_sections=3, + single_res=False, + single_height=384, + single_width=640, + seed=42, + ): + self.history_sizes = history_sizes + self.is_keep_x0 = is_keep_x0 + self.force_rebuild = force_rebuild + self.return_all_vae_latent = return_all_vae_latent + self.return_prompt_raw = return_prompt_raw + self.num_rollout_sections = num_rollout_sections + self.single_res = single_res + self.single_height = single_height + self.single_width = single_width + assert self.is_keep_x0, "is_keep_x0 need to be True now!" + + self.base_seed = seed + self._epoch = 0 + + if isinstance(feature_folders, str): + self.feature_folders = [feature_folders] + else: + self.feature_folders = feature_folders + + self.samples = [] + self.buckets = defaultdict(list) + + for folder in self.feature_folders: + cache_file = os.path.join(folder, "dataset_cache.pkl") + self._process_folder(folder, cache_file) + + def _process_folder(self, folder, cache_file): + if self.force_rebuild or not os.path.exists(cache_file): + print(f"Building metadata cache for folder: {folder}") + folder_samples, folder_buckets = self._build_folder_metadata(folder) + + print(f"Saving metadata cache for folder: {folder}") + cached_data = {"samples": folder_samples, "buckets": folder_buckets} + if not self.force_rebuild: + with open(cache_file, "wb") as f: + pickle.dump(cached_data, f) + print(f"Cached {len(folder_samples)} samples from {folder}\n") + else: + print(f"Loading cached metadata from: {folder}") + with open(cache_file, "rb") as f: + cached_data = pickle.load(f) + folder_samples = cached_data["samples"] + folder_buckets = cached_data["buckets"] + print(f"Loaded {len(folder_samples)} samples from cache: {folder}\n") + + sample_idx_offset = len(self.samples) + self.samples.extend(folder_samples) + + for bucket_key, indices in folder_buckets.items(): + adjusted_indices = [idx + sample_idx_offset for idx in indices] + self.buckets[bucket_key].extend(adjusted_indices) + + def _build_folder_metadata(self, folder): + feature_files = [f for f in os.listdir(folder) if f.endswith(".pt")] + samples = [] + buckets = defaultdict(list) + sample_idx = 0 + + print(f"Processing {len(feature_files)} files in {folder}...") + + for i, feature_file in enumerate(feature_files): + if i % 10000 == 0: + print(f" Processed {i}/{len(feature_files)} files") + + feature_path = os.path.join(folder, feature_file) + + # Parse filename + parts = feature_file.split("_") + uttid = "_".join(parts[:-3]) + num_frame = int(parts[-3]) + height = int(parts[-2]) + width = int(parts[-1].replace(".pt", "")) + + # keep length >= 121 + if num_frame < 121: + continue + + # keep resolution + allowed_resolutions = [ + (self.single_height, self.single_width), + (self.single_height // 2, self.single_width // 2), + (self.single_height // 4, self.single_width // 4), + ] + if self.single_res and (height, width) not in allowed_resolutions: + continue + + bucket_key = (num_frame, height, width) + + sample_info = { + "uttid": uttid, + "dataset_name": folder.rstrip("/"), + "file_path": feature_path, + "bucket_key": bucket_key, + "num_frame": num_frame, + "height": height, + "width": width, + } + + samples.append(sample_info) + buckets[bucket_key].append(sample_idx) + sample_idx += 1 + + return samples, buckets + + def set_epoch(self, epoch): + self._epoch = epoch + + def prepare_stage1_latent(self, vae_latent, idx, base_vae_latent=None): + source_latent = base_vae_latent if base_vae_latent is not None else vae_latent + + x0_latent = None + if self.is_keep_x0: + x0_latent = source_latent[0, :, :1, :, :].clone() + total_sections = source_latent.shape[0] + latent_window_size = source_latent.shape[2] + history_window_size = sum(self.history_sizes) + section_size = history_window_size + latent_window_size + + temp_source_latent = rearrange(source_latent, "b c t h w -> c (b t) h w") + zero_padding_source = torch.zeros( + temp_source_latent.shape[0], + history_window_size, + temp_source_latent.shape[2], + temp_source_latent.shape[3], + device=temp_source_latent.device, + dtype=temp_source_latent.dtype, + ) + continue_source_latent = torch.cat([zero_padding_source, temp_source_latent], dim=1) + + temp_vae_latent = rearrange(vae_latent, "b c t h w -> c (b t) h w") + zero_padding_vae = torch.zeros( + temp_vae_latent.shape[0], + history_window_size, + temp_vae_latent.shape[2], + temp_vae_latent.shape[3], + device=temp_vae_latent.device, + dtype=temp_vae_latent.dtype, + ) + continue_vae_latent = torch.cat([zero_padding_vae, temp_vae_latent], dim=1) + + sample_seed = self.base_seed + self._epoch * 1000000 + idx + choice_idx = torch.randint( + 0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed) + ).item() + if choice_idx == 0 and x0_latent is not None: + x0_latent = torch.zeros_like(x0_latent) + + clean_all_vae_latent = None + if self.return_all_vae_latent: + max_start_idx = total_sections - self.num_rollout_sections + if max_start_idx < 0: + raise ValueError( + f"Not enough sections: total_sections={total_sections}, num_rollout_sections={self.num_rollout_sections}" + ) + start_section_idx = random.randint(0, max_start_idx) + start_indice = start_section_idx * latent_window_size + end_indice = start_indice + history_window_size + self.num_rollout_sections * latent_window_size + clean_all_vae_latent = continue_source_latent[:, start_indice:end_indice, :, :] + + start_indice = choice_idx * latent_window_size + end_indice = start_indice + section_size + + history_latent = continue_source_latent[:, start_indice : start_indice + history_window_size, :, :] + target_latent = continue_vae_latent[:, start_indice + history_window_size : end_indice, :, :] + + return x0_latent, history_latent, target_latent, clean_all_vae_latent + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + anchor_f = self.samples[idx]["num_frame"] + anchor_h = self.samples[idx]["height"] + anchor_w = self.samples[idx]["width"] + while True: + sample_info = self.samples[idx] + + if ( + anchor_f != sample_info["num_frame"] + or anchor_h != sample_info["height"] + or anchor_w != sample_info["width"] + ): + idx = random.randint(0, len(self.samples) - 1) + print("Try to find a same dim sample, retrying...") + continue + + try: + base_vae_latent = None + if (anchor_h, anchor_w) in [ + (self.single_height // 2, self.single_width // 2), + (self.single_height // 4, self.single_width // 4), + ]: + base_file_path = ( + sample_info["file_path"] + .replace("/mid", "") + .replace("/low", "") + .replace( + f"{self.single_height // 2}_{self.single_width // 2}", + f"{self.single_height}_{self.single_width}", + ) + .replace( + f"{self.single_height // 4}_{self.single_width // 4}", + f"{self.single_height}_{self.single_width}", + ) + ) + base_vae_latent = torch.load(base_file_path, map_location="cpu", weights_only=False)["vae_latent"] + + feature_data = torch.load(sample_info["file_path"], map_location="cpu", weights_only=False) + x0_latent, history_latent, target_latent, clean_all_vae_latent = self.prepare_stage1_latent( + feature_data["vae_latent"], idx, base_vae_latent + ) + if self.return_prompt_raw: + prompt_raws = feature_data["prompt_raw"] + break + except Exception: + idx = random.randint(0, len(self.samples) - 1) + print(f"Error loading {sample_info['file_path']}, retrying...") + file_name = os.path.basename(sample_info["file_path"]) + txt_name = f"{file_name}.txt" + with open(txt_name, "w") as f: + f.write(sample_info["file_path"] + "\n") + + output_dict = { + "uttid": sample_info["uttid"], + "bucket_key": sample_info["bucket_key"], + "dataset_name": sample_info["dataset_name"], + "num_frame": sample_info["num_frame"], + "height": sample_info["height"], + "width": sample_info["width"], + "x0_latents": x0_latent, + "history_latents": history_latent, + "target_latents": target_latent, + "clean_all_latents": clean_all_vae_latent, + "prompt_embeds": feature_data["prompt_embed"], + "prompt_attention_masks": feature_data.get("prompt_attention_mask", None), + } + + if self.return_prompt_raw: + output_dict["prompt_raws"] = prompt_raws + + return output_dict + + +class BucketedSampler(Sampler): + def __init__( + self, + dataset, + batch_size, + drop_last=False, + shuffle=True, + seed=42, + dataset_sampling_ratios=None, + num_sp_groups=1, + sp_world_size=1, + global_rank=0, + ): + self.dataset = dataset + self.batch_size = batch_size + self.drop_last = drop_last + self.shuffle = shuffle + self.seed = seed + self.generator = torch.Generator() + self.buckets = dataset.buckets + self._epoch = 0 + + # Distributed parameters + self.num_sp_groups = num_sp_groups + self.sp_world_size = sp_world_size + self.global_rank = global_rank + self.ith_sp_group = self.global_rank // self.sp_world_size + + self.dataset_sampling_ratios = ( + {key.rstrip("/"): value for key, value in dataset_sampling_ratios.items()} + if dataset_sampling_ratios is not None + else {} + ) + self._prepare_dataset_buckets() + + def _prepare_dataset_buckets(self): + self.dataset_buckets = {} + + for bucket_key, sample_indices in self.buckets.items(): + dataset_groups = {} + for idx in sample_indices: + dataset_name = self.dataset.samples[idx]["dataset_name"] + if dataset_name not in dataset_groups: + dataset_groups[dataset_name] = [] + dataset_groups[dataset_name].append(idx) + self.dataset_buckets[bucket_key] = dataset_groups + + def set_epoch(self, epoch): + self._epoch = epoch + + def _shard_indices_for_sp_group(self, indices): + """ + Shard indices across SP groups, similar to DP_SP_BatchSampler. + Each SP group gets a disjoint subset of the data. + """ + if self.num_sp_groups == 1: + return indices + + # Convert to tensor if it's a list + if isinstance(indices, list): + indices_tensor = torch.tensor(indices, dtype=torch.long) + else: + indices_tensor = indices + + # Pad indices if necessary to make it divisible by num_sp_groups + total_size = len(indices_tensor) + if total_size % self.num_sp_groups != 0: + if not self.drop_last: + padding_size = self.num_sp_groups - (total_size % self.num_sp_groups) + indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]]) + else: + # If drop_last, truncate to be divisible + if self.drop_last: + truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups + indices_tensor = indices_tensor[:truncate_size] + + # Shard: each SP group gets every num_sp_groups-th element + sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups] + + return sp_group_indices.tolist() + + def _apply_global_ratio_sampling(self): + if not self.dataset_sampling_ratios: + return + + dataset_sample_map = {} + for bucket_key, dataset_groups in self.dataset_buckets.items(): + for dataset_name, indices in dataset_groups.items(): + if dataset_name not in dataset_sample_map: + dataset_sample_map[dataset_name] = {"indices": [], "buckets": []} + dataset_sample_map[dataset_name]["indices"].extend(indices) + dataset_sample_map[dataset_name]["buckets"].extend([bucket_key] * len(indices)) + + total_samples = sum(len(info["indices"]) for info in dataset_sample_map.values()) + total_ratio = sum(self.dataset_sampling_ratios.values()) + + sampled_dataset_map = {} + for dataset_name, info in dataset_sample_map.items(): + if dataset_name in self.dataset_sampling_ratios: + ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio + target_samples = max(1, int(total_samples * ratio)) + + indices = info["indices"] + buckets = info["buckets"] + + if len(indices) >= target_samples: + selected = torch.randperm(len(indices), generator=self.generator)[:target_samples].tolist() + sampled_indices = [indices[i] for i in selected] + sampled_buckets = [buckets[i] for i in selected] + else: + sampled_indices = [] + sampled_buckets = [] + remaining = target_samples + + while remaining > 0: + repeat_count = min(remaining, len(indices)) + selected = torch.randperm(len(indices), generator=self.generator)[:repeat_count].tolist() + sampled_indices.extend([indices[i] for i in selected]) + sampled_buckets.extend([buckets[i] for i in selected]) + remaining -= repeat_count + + sampled_dataset_map[dataset_name] = {"indices": sampled_indices, "buckets": sampled_buckets} + else: + sampled_dataset_map[dataset_name] = info + + new_dataset_buckets = {} + for bucket_key in self.dataset_buckets.keys(): + new_dataset_buckets[bucket_key] = {} + + for dataset_name, info in sampled_dataset_map.items(): + indices = info["indices"] + buckets = info["buckets"] + + for idx, bucket_key in zip(indices, buckets): + if dataset_name not in new_dataset_buckets[bucket_key]: + new_dataset_buckets[bucket_key][dataset_name] = [] + new_dataset_buckets[bucket_key][dataset_name].append(idx) + + self.dataset_buckets = new_dataset_buckets + + def __iter__(self): + # Use epoch-level seed for reproducibility + epoch_seed = self.seed + self._epoch + self.generator.manual_seed(epoch_seed) + + if self.dataset_sampling_ratios: + self._apply_global_ratio_sampling() + + bucket_iterators = {} + bucket_batches = {} + + for bucket_key, dataset_groups in self.dataset_buckets.items(): + balanced_indices = self._create_balanced_indices(dataset_groups) + + # Global shuffle before sharding (important for distributed consistency) + if self.shuffle: + perm = torch.randperm(len(balanced_indices), generator=self.generator).tolist() + balanced_indices = [balanced_indices[i] for i in perm] + + # Shard indices for this SP group + sp_group_indices = self._shard_indices_for_sp_group(balanced_indices) + + batches = [] + for i in range(0, len(sp_group_indices), self.batch_size): + batch = sp_group_indices[i : i + self.batch_size] + if len(batch) == self.batch_size or not self.drop_last: + batches.append(batch) + + if batches: + bucket_batches[bucket_key] = batches + bucket_iterators[bucket_key] = iter(batches) + + remaining_buckets = list(bucket_iterators.keys()) + + while remaining_buckets: + idx = torch.randint(len(remaining_buckets), (1,), generator=self.generator).item() + bucket_key = remaining_buckets[idx] + bucket_iter = bucket_iterators[bucket_key] + + try: + batch = next(bucket_iter) + yield batch + except StopIteration: + remaining_buckets.remove(bucket_key) + + def _create_balanced_indices(self, dataset_groups): + return sum(dataset_groups.values(), []) + + def _equal_sampling(self, dataset_groups): + all_indices = [] + dataset_names = list(dataset_groups.keys()) + + if len(dataset_names) <= 1: + return sum(dataset_groups.values(), []) + + min_samples = min(len(indices) for indices in dataset_groups.values()) + + for dataset_name, indices in dataset_groups.items(): + if len(indices) > min_samples: + selected = torch.randperm(len(indices), generator=self.generator)[:min_samples].tolist() + sampled_indices = [indices[i] for i in selected] + else: + sampled_indices = indices + all_indices.extend(sampled_indices) + + return all_indices + + def _ratio_sampling(self, dataset_groups): + return sum(dataset_groups.values(), []) + + def __len__(self): + if self.dataset_sampling_ratios: + temp_generator = torch.Generator() + temp_generator.manual_seed(self.seed) + + dataset_sample_map = {} + for bucket_key, dataset_groups in self.dataset_buckets.items(): + for dataset_name, indices in dataset_groups.items(): + if dataset_name not in dataset_sample_map: + dataset_sample_map[dataset_name] = [] + dataset_sample_map[dataset_name].extend(indices) + + total_samples = sum(len(indices) for indices in dataset_sample_map.values()) + total_ratio = sum(self.dataset_sampling_ratios.values()) + + sampled_total = 0 + for dataset_name, indices in dataset_sample_map.items(): + if dataset_name in self.dataset_sampling_ratios: + ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio + target_samples = max(1, int(total_samples * ratio)) + sampled_total += target_samples + else: + sampled_total += len(indices) + + # Account for SP group sharding + sp_group_samples = sampled_total // self.num_sp_groups + if not self.drop_last and sampled_total % self.num_sp_groups != 0: + sp_group_samples += 1 + + total_batches = sp_group_samples // self.batch_size + if not self.drop_last and sp_group_samples % self.batch_size != 0: + total_batches += 1 + return total_batches + else: + total_batches = 0 + for bucket_key, dataset_groups in self.dataset_buckets.items(): + balanced_indices = self._create_balanced_indices(dataset_groups) + + # Account for SP group sharding + sp_group_size = len(balanced_indices) // self.num_sp_groups + if not self.drop_last and len(balanced_indices) % self.num_sp_groups != 0: + sp_group_size += 1 + + num_batches = sp_group_size // self.batch_size + if not self.drop_last and sp_group_size % self.batch_size != 0: + num_batches += 1 + total_batches += num_batches + return total_batches + + +def collate_fn(batch): + return { + key: torch.stack([d[key] for d in batch]) + if isinstance(batch[0][key], torch.Tensor) + else [d[key] for d in batch] + for key in batch[0] + } + + +if __name__ == "__main__": + import torch.distributed.checkpoint as dcp + from accelerate import Accelerator + from torchdata.stateful_dataloader import StatefulDataLoader + + feature_folder = [ + "demo_data/ultravideo-long", + ] + dataloader_num_workers = 0 + batch_size = 2 + num_train_epochs = 2 + seed = 0 + output_dir = "accelerate_checkpoints" + checkpoint_dirs = ( + [ + d + for d in os.listdir(output_dir) + if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d)) + ] + if os.path.exists(output_dir) + else [] + ) + + dataset_ratios = {} + # dataset_ratios = { + # "demo_data/ultravideo-long": 0.9, + # } + + accelerator = Accelerator() + print(accelerator.process_index, accelerator.num_processes) + + dataset = BucketedFeatureDataset( + feature_folder, + force_rebuild=True, + return_all_vae_latent=True, + return_prompt_raw=True, + single_res=True, + single_height=384, + single_width=640, + seed=seed, + ) + sampler = BucketedSampler( + dataset, + batch_size=batch_size, + drop_last=True, + shuffle=True, + dataset_sampling_ratios=dataset_ratios, + seed=seed, + # num_sp_groups=get_world_size() // get_sp_world_size(), + # sp_world_size=get_sp_world_size(), + # global_rank=get_world_rank(), + num_sp_groups=accelerator.num_processes // 1, + sp_world_size=1, + global_rank=accelerator.process_index, + ) + dataloader = StatefulDataLoader( + dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=dataloader_num_workers + ) + + print(len(dataset), len(dataloader)) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + + step = 0 + global_step = 0 + first_epoch = 0 + num_update_steps_per_epoch = len(dataloader) + if checkpoint_dirs: + latest_checkpoint = max(checkpoint_dirs, key=lambda x: int(x.split("-")[1])) + checkpoint_path = os.path.join(output_dir, latest_checkpoint) + print(f"Found checkpoint: {checkpoint_path}") + + accelerator.load_state(checkpoint_path) + global_step = int(latest_checkpoint.split("-")[1]) + first_epoch = global_step // num_update_steps_per_epoch + + states = { + "dataloader": dataloader, + } + dcp_dir = os.path.join(checkpoint_path, "distributed_checkpoint") + dcp.load(states, checkpoint_id=dcp_dir) + + print(f"Resuming from step {global_step}, epoch {first_epoch}") + + print("Testing dataloader...") + step = global_step + dataset_counts = defaultdict(int) + for epoch in range(first_epoch, num_train_epochs): + sampler.set_epoch(epoch) + dataset.set_epoch(epoch) + for i, batch in enumerate(dataloader): + # Get metadata + uttid = batch["uttid"] + num_frame = batch["num_frame"] + height = batch["height"] + width = batch["width"] + bucket_key = batch["bucket_key"] + + # Get feature + x0_latents = batch["x0_latents"] + history_latents = batch["history_latents"] + target_latents = batch["target_latents"] + prompt_embeds = batch["prompt_embeds"] + + if accelerator.process_index == 0: + # print info + print(f" Step {step}:") + print(f" Batch {i}:") + # print(f" Data Name: {batch['dataset_name']}") + print(f" Batch size: {len(uttid)}") + print(f" Uttids: {uttid}") + print(f" Dimensions - frames: {num_frame[0]}, height: {height[0]}, width: {width[0]}") + print(f" Bucket key: {bucket_key[0]}") + print(f" X0 latent shape: {x0_latents.shape}") + print(f" History latent shape: {history_latents.shape}") + print(f" Context latent shape: {target_latents.shape}") + print(f" Prompt embed shape: {prompt_embeds.shape}") + # print(f" Prompt attention mask shape: {prompt_attention_masks.shape}") + + # verify + assert all(nf == num_frame[0] for nf in num_frame), "Frame numbers not consistent in batch" + assert all(h == height[0] for h in height), "Heights not consistent in batch" + assert all(w == width[0] for w in width), "Widths not consistent in batch" + + print(" ✓ Batch dimensions are consistent") + + for dataset_name in batch["dataset_name"]: + dataset_counts[dataset_name] += 1 + + step += 1 + + # if step == 20: + # checkpoint_dir = f"checkpoint-{step}" + # save_path = os.path.join(output_dir, checkpoint_dir) + # os.makedirs(save_path, exist_ok=True) + + # if accelerator.is_main_process: + # print(f"Saving checkpoint at step {step}") + + # accelerator.save_state(save_path) + + # print(accelerator.process_index, accelerator.num_processes) + # states = { + # "dataloader": dataloader, + # } + # dcp_dir = os.path.join(save_path, "distributed_checkpoint") + # dcp.save(states, checkpoint_id=dcp_dir) + + print("实际采样统计:", dict(dataset_counts)) diff --git a/Helios/helios/dataset/dataloader_mp4_dist.py b/Helios/helios/dataset/dataloader_mp4_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc7529d39bdde6e8cdb58adeb427fc54c4f013a --- /dev/null +++ b/Helios/helios/dataset/dataloader_mp4_dist.py @@ -0,0 +1,854 @@ +import json +import os +import pickle +import random +from collections import defaultdict +from typing import Optional + +import pandas as pd +import torch +import torchvision +from torch.utils.data import Dataset, Sampler +from video_reader import PyVideoReader + +from diffusers.training_utils import free_memory +from diffusers.utils import export_to_video + + +resolution_bucket_options = { + 640: [ + (768, 320), + (768, 384), + (640, 384), + (768, 512), + (576, 448), + (512, 512), + (448, 576), + (512, 768), + (384, 640), + (384, 768), + (320, 768), + ], +} + +length_bucket_options = { + 1: [ + 501, + 481, + 461, + 441, + 421, + 401, + 381, + 361, + 341, + 321, + 301, + 281, + 261, + 241, + 221, + 193, + 181, + 161, + 141, + 121, + 101, + 81, + 61, + 41, + 21, + ], + 2: [193, 177, 161, 156, 145, 133, 129, 121, 113, 109, 97, 85, 81, 73, 65, 61, 49, 37, 25], +} + + +def find_nearest_resolution_bucket(h, w, resolution=640): + min_metric = float("inf") + best_bucket = None + for bucket_h, bucket_w in resolution_bucket_options[resolution]: + metric = abs(h * bucket_w - w * bucket_h) + if metric <= min_metric: + min_metric = metric + best_bucket = (bucket_h, bucket_w) + return best_bucket + + +def find_nearest_length_bucket(length, stride=1): + buckets = length_bucket_options[stride] + min_bucket = min(buckets) + if length < min_bucket: + return length + valid_buckets = [bucket for bucket in buckets if bucket <= length] + return max(valid_buckets) + + +def read_cut_crop_and_resize( + video_path, f_prime, h_prime, w_prime, stride=1, start_frame=None, end_frame=None, crop=None +): + frame_indices = list(range(start_frame, end_frame, stride)) + assert len(frame_indices) == f_prime + + vr = PyVideoReader(video_path, threads=0) # 0 means auto (let ffmpeg pick the optimal number) + frames = torch.from_numpy(vr.get_batch(frame_indices)).float() + + frames = (frames / 127.5) - 1 + video = frames.permute(0, 3, 1, 2) + + s_x, e_x, s_y, e_y = crop + video = video[:, :, s_y:e_y, s_x:e_x] + + frames, channels, h, w = video.shape + aspect_ratio_original = h / w + aspect_ratio_target = h_prime / w_prime + + if aspect_ratio_original >= aspect_ratio_target: + new_h = int(w * aspect_ratio_target) + top = (h - new_h) // 2 + bottom = top + new_h + left = 0 + right = w + else: + new_w = int(h / aspect_ratio_target) + left = (w - new_w) // 2 + right = left + new_w + top = 0 + bottom = h + + # Crop the video + cropped_video = video[:, :, top:bottom, left:right] + # Resize the cropped video + resized_video = torchvision.transforms.functional.resize(cropped_video, (h_prime, w_prime)) + return resized_video + + +def save_frames(frame_raw, fps=24, video_path="1.mp4"): + save_list = [] + for frame in frame_raw: + frame = (frame + 1) / 2 * 255 + frame = torchvision.transforms.transforms.ToPILImage()(frame.to(torch.uint8)).convert("RGB") + save_list.append(frame) + frame = None + del frame + export_to_video(save_list, video_path, fps=fps) + + save_list = None + del save_list + free_memory() + + +class BucketedFeatureDataset(Dataset): + def __init__( + self, + json_files, + video_folders, + stride=1, + base_fps=None, + resolution=640, + force_rebuild=True, + single_res=False, + single_length=False, + single_num_frame=81, + single_height=384, + single_width=640, + multi_res=False, + id_token: Optional[str] = None, + ): + self.stride = stride + self.base_fps = base_fps + self.resolution = resolution + self.force_rebuild = force_rebuild + self.single_res = single_res + self.single_height = single_height + self.single_width = single_width + self.single_length = single_length + self.single_num_frame = single_num_frame + self.multi_res = multi_res + self.id_token = id_token or "" + self._epoch = 0 + + if isinstance(json_files, str): + self.json_files = [json_files] + else: + self.json_files = json_files + + if isinstance(video_folders, str): + self.video_folders = [video_folders] + else: + self.video_folders = video_folders + + assert len(self.json_files) == len(self.video_folders), ( + f"json_files ({len(self.json_files)}) and video_folders ({len(self.video_folders)}) must have the same length" + ) + + self.samples = [] + self.buckets = defaultdict(list) + + for json_file, video_folder in zip(self.json_files, self.video_folders): + cache_file = json_file.replace(".json", "_cache.pkl").replace(".csv", "_cache.pkl") + self._process_json_file(json_file, video_folder, cache_file) + + def _process_json_file(self, json_file, video_folder, cache_file): + if self.force_rebuild or not os.path.exists(cache_file): + if os.path.exists(cache_file): + print(f"Remove {cache_file}") + os.remove(cache_file) + print(f"Building metadata cache for file: {json_file}") + print(f" Video folder: {video_folder}") + file_samples, file_buckets = self._build_file_metadata(json_file, video_folder) + + print(f"Saving metadata cache to: {cache_file}") + cached_data = {"samples": file_samples, "buckets": file_buckets} + with open(cache_file, "wb") as f: + pickle.dump(cached_data, f) + print(f"Cached {len(file_samples)} samples from {json_file}\n") + else: + print(f"Loading cached metadata from: {cache_file}") + with open(cache_file, "rb") as f: + cached_data = pickle.load(f) + file_samples = cached_data["samples"] + file_buckets = cached_data["buckets"] + print(f"Loaded {len(file_samples)} samples from cache: {cache_file}\n") + + sample_idx_offset = len(self.samples) + self.samples.extend(file_samples) + + for bucket_key, indices in file_buckets.items(): + adjusted_indices = [idx + sample_idx_offset for idx in indices] + self.buckets[bucket_key].extend(adjusted_indices) + + def _build_file_metadata(self, json_file, video_folder): + with open(json_file, "r") as f: + data = json.load(f) + + print(f"Scanning video folder: {video_folder}") + existing_videos = set() + for root, dirs, files in os.walk(video_folder): + for file in files: + if file.endswith(".mp4"): + rel_path = os.path.relpath(os.path.join(root, file), video_folder) + existing_videos.add(rel_path) + print(f"Found {len(existing_videos)} video files") + + df = pd.DataFrame( + [ + { + "cut": item["cut"], + "crop": item["crop"], + "path": item["path"], + "num_frames": item["num_frames"], + "width": item["resolution"]["width"], + "height": item["resolution"]["height"], + "fps": item["fps"], + "cap": item["cap"], + } + for item in data + ] + ) + + samples = [] + buckets = defaultdict(list) + sample_idx = 0 + + print(f"Processing {len(df)} records from {json_file} with stride={self.stride}...") + for i, row in df.iterrows(): + if i % 10000 == 0: + print(f" Processed {i}/{len(df)} records") + + video_file = ( + row["path"] + .replace("videos_clip_v1_20241111/", "") + .replace("videos_clip_v2_20241111/", "") + .replace("videos_clip_v4_20241111/", "") + ) + if video_file not in existing_videos: + print("bad video!") + continue + video_path = os.path.join(video_folder, video_file) + + cut_start_frame = row["cut"][0] + cut_end_frame = row["cut"][1] + num_frame = cut_end_frame - cut_start_frame + + if self.single_length: + if num_frame < self.single_num_frame: + continue + else: + if num_frame < 121: + continue + + uttid = os.path.basename(video_file).replace(".mp4", "") + f"_{cut_start_frame}-{cut_end_frame}" + fps = row["fps"] + + crop = row["crop"] + width = crop[1] - crop[0] + height = crop[3] - crop[2] + + prompt = row["cap"][0] + + # TODO need to be checked + effective_num_frame = (num_frame + self.stride - 1) // self.stride + bucket_num_frame = find_nearest_length_bucket(effective_num_frame, stride=self.stride) + bucket_height, bucket_width = find_nearest_resolution_bucket(height, width, resolution=self.resolution) + + if self.single_res or self.multi_res: + allowed_resolutions = [(self.single_height, self.single_width)] + if self.multi_res: + allowed_resolutions.extend( + [ + (self.single_height // 2, self.single_width // 2), + (self.single_height // 4, self.single_width // 4), + ] + ) + if (bucket_height, bucket_width) not in allowed_resolutions: + print("continue res") + continue + bucket_height, bucket_width = random.choice(allowed_resolutions) + + if self.single_length: + bucket_num_frame = self.single_num_frame + + if self.base_fps is not None: + stride = max(int(fps / self.base_fps), 1) + required_frames = bucket_num_frame * stride + if required_frames >= num_frame: + print("continue frame") + continue + else: + stride = self.stride + + bucket_key = (bucket_num_frame, bucket_height, bucket_width) + + sample_info = { + "uttid": uttid, + "dataset_name": json_file.rstrip("/"), + "video_folder": video_folder, + "video_path": video_path, + "bucket_key": bucket_key, + "prompt": self.id_token + prompt, + "fps": fps, + "stride": stride, + "effective_num_frame": effective_num_frame, + "num_frame": num_frame, + "height": height, + "width": width, + "bucket_num_frame": bucket_num_frame, + "bucket_height": bucket_height, + "bucket_width": bucket_width, + "cut_start_frame": cut_start_frame, + "cut_end_frame": cut_end_frame, + "crop": crop, + } + + samples.append(sample_info) + buckets[bucket_key].append(sample_idx) + sample_idx += 1 + + return samples, buckets + + def set_epoch(self, epoch): + self._epoch = epoch + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + anchor_h = self.samples[idx]["bucket_height"] + anchor_w = self.samples[idx]["bucket_width"] + anchor_f = self.samples[idx]["bucket_num_frame"] + + max_retries = 1000 + retry_count = 0 + + while retry_count < max_retries: + sample_info = self.samples[idx] + + if ( + anchor_h != sample_info["bucket_height"] + or anchor_w != sample_info["bucket_width"] + or anchor_f != sample_info["bucket_num_frame"] + ): + idx = random.randint(0, len(self.samples) - 1) + retry_count += 1 + continue + + try: + stride = sample_info["stride"] + cut_start_frame = sample_info["cut_start_frame"] + cut_end_frame = sample_info["cut_end_frame"] + bucket_num_frame = sample_info["bucket_num_frame"] + + max_start_frame = cut_end_frame - bucket_num_frame * stride + if max_start_frame < cut_start_frame: + start_frame = cut_start_frame + else: + start_frame = random.randint(cut_start_frame, max_start_frame) + end_frame = start_frame + bucket_num_frame * stride + + video_data = read_cut_crop_and_resize( + video_path=sample_info["video_path"], + f_prime=sample_info["bucket_num_frame"], + h_prime=sample_info["bucket_height"], + w_prime=sample_info["bucket_width"], + stride=stride, + start_frame=start_frame, + end_frame=end_frame, + crop=sample_info["crop"], + ) + + return { + "uttid": sample_info["uttid"], + "bucket_key": sample_info["bucket_key"], + "dataset_name": sample_info["dataset_name"], + "video_metadata": { + "num_frames": sample_info["bucket_num_frame"], + "height": sample_info["bucket_height"], + "width": sample_info["bucket_width"], + "fps": sample_info["fps"], + "stride": stride, + "effective_num_frame": sample_info["effective_num_frame"], + }, + "videos": video_data, + "prompts": sample_info["prompt"], + "first_frames_images": (video_data[0] + 1) / 2 * 255, + } + except Exception as e: + print(f"Error loading {sample_info['video_path']}: {e}") + idx = random.randint(0, len(self.samples) - 1) + retry_count += 1 + + print(f"Failed to load sample after {max_retries} retries, returning None") + return None + + +class BucketedSampler(Sampler): + def __init__( + self, + dataset, + batch_size, + drop_last=False, + shuffle=True, + seed=42, + dataset_sampling_ratios=None, + num_sp_groups=1, + sp_world_size=1, + global_rank=0, + ): + self.dataset = dataset + self.batch_size = batch_size + self.drop_last = drop_last + self.shuffle = shuffle + self.seed = seed + self.generator = torch.Generator() + self.buckets = dataset.buckets + self._epoch = 0 + + # Distributed parameters + self.num_sp_groups = num_sp_groups + self.sp_world_size = sp_world_size + self.global_rank = global_rank + self.ith_sp_group = self.global_rank // self.sp_world_size + + self.dataset_sampling_ratios = ( + {key.rstrip("/"): value for key, value in dataset_sampling_ratios.items()} + if dataset_sampling_ratios is not None + else {} + ) + self._prepare_dataset_buckets() + + def _prepare_dataset_buckets(self): + self.dataset_buckets = {} + + for bucket_key, sample_indices in self.buckets.items(): + dataset_groups = {} + for idx in sample_indices: + dataset_name = self.dataset.samples[idx]["dataset_name"] + if dataset_name not in dataset_groups: + dataset_groups[dataset_name] = [] + dataset_groups[dataset_name].append(idx) + self.dataset_buckets[bucket_key] = dataset_groups + + def set_epoch(self, epoch): + self._epoch = epoch + + def _shard_indices_for_sp_group(self, indices): + """ + Shard indices across SP groups, similar to DP_SP_BatchSampler. + Each SP group gets a disjoint subset of the data. + """ + if self.num_sp_groups == 1: + return indices + + # Convert to tensor if it's a list + if isinstance(indices, list): + indices_tensor = torch.tensor(indices, dtype=torch.long) + else: + indices_tensor = indices + + # Pad indices if necessary to make it divisible by num_sp_groups + total_size = len(indices_tensor) + if total_size % self.num_sp_groups != 0: + if not self.drop_last: + padding_size = self.num_sp_groups - (total_size % self.num_sp_groups) + indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]]) + else: + # If drop_last, truncate to be divisible + if self.drop_last: + truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups + indices_tensor = indices_tensor[:truncate_size] + + # Shard: each SP group gets every num_sp_groups-th element + sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups] + + return sp_group_indices.tolist() + + def _apply_global_ratio_sampling(self): + if not self.dataset_sampling_ratios: + return + + dataset_sample_map = {} + for bucket_key, dataset_groups in self.dataset_buckets.items(): + for dataset_name, indices in dataset_groups.items(): + if dataset_name not in dataset_sample_map: + dataset_sample_map[dataset_name] = {"indices": [], "buckets": []} + dataset_sample_map[dataset_name]["indices"].extend(indices) + dataset_sample_map[dataset_name]["buckets"].extend([bucket_key] * len(indices)) + + total_samples = sum(len(info["indices"]) for info in dataset_sample_map.values()) + total_ratio = sum(self.dataset_sampling_ratios.values()) + + sampled_dataset_map = {} + for dataset_name, info in dataset_sample_map.items(): + if dataset_name in self.dataset_sampling_ratios: + ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio + target_samples = max(1, int(total_samples * ratio)) + + indices = info["indices"] + buckets = info["buckets"] + + if len(indices) >= target_samples: + selected = torch.randperm(len(indices), generator=self.generator)[:target_samples].tolist() + sampled_indices = [indices[i] for i in selected] + sampled_buckets = [buckets[i] for i in selected] + else: + sampled_indices = [] + sampled_buckets = [] + remaining = target_samples + + while remaining > 0: + repeat_count = min(remaining, len(indices)) + selected = torch.randperm(len(indices), generator=self.generator)[:repeat_count].tolist() + sampled_indices.extend([indices[i] for i in selected]) + sampled_buckets.extend([buckets[i] for i in selected]) + remaining -= repeat_count + + sampled_dataset_map[dataset_name] = {"indices": sampled_indices, "buckets": sampled_buckets} + else: + sampled_dataset_map[dataset_name] = info + + new_dataset_buckets = {} + for bucket_key in self.dataset_buckets.keys(): + new_dataset_buckets[bucket_key] = {} + + for dataset_name, info in sampled_dataset_map.items(): + indices = info["indices"] + buckets = info["buckets"] + + for idx, bucket_key in zip(indices, buckets): + if dataset_name not in new_dataset_buckets[bucket_key]: + new_dataset_buckets[bucket_key][dataset_name] = [] + new_dataset_buckets[bucket_key][dataset_name].append(idx) + + self.dataset_buckets = new_dataset_buckets + + def __iter__(self): + # Use epoch-level seed for reproducibility + epoch_seed = self.seed + self._epoch + self.generator.manual_seed(epoch_seed) + + if self.dataset_sampling_ratios: + self._apply_global_ratio_sampling() + + bucket_iterators = {} + bucket_batches = {} + + for bucket_key, dataset_groups in self.dataset_buckets.items(): + balanced_indices = self._create_balanced_indices(dataset_groups) + + # Global shuffle before sharding (important for distributed consistency) + if self.shuffle: + perm = torch.randperm(len(balanced_indices), generator=self.generator).tolist() + balanced_indices = [balanced_indices[i] for i in perm] + + # Shard indices for this SP group + sp_group_indices = self._shard_indices_for_sp_group(balanced_indices) + + batches = [] + for i in range(0, len(sp_group_indices), self.batch_size): + batch = sp_group_indices[i : i + self.batch_size] + if len(batch) == self.batch_size or not self.drop_last: + batches.append(batch) + + if batches: + bucket_batches[bucket_key] = batches + bucket_iterators[bucket_key] = iter(batches) + + remaining_buckets = list(bucket_iterators.keys()) + + while remaining_buckets: + idx = torch.randint(len(remaining_buckets), (1,), generator=self.generator).item() + bucket_key = remaining_buckets[idx] + bucket_iter = bucket_iterators[bucket_key] + + try: + batch = next(bucket_iter) + yield batch + except StopIteration: + remaining_buckets.remove(bucket_key) + + def _create_balanced_indices(self, dataset_groups): + return sum(dataset_groups.values(), []) + + def _equal_sampling(self, dataset_groups): + all_indices = [] + dataset_names = list(dataset_groups.keys()) + + if len(dataset_names) <= 1: + return sum(dataset_groups.values(), []) + + min_samples = min(len(indices) for indices in dataset_groups.values()) + + for dataset_name, indices in dataset_groups.items(): + if len(indices) > min_samples: + selected = torch.randperm(len(indices), generator=self.generator)[:min_samples].tolist() + sampled_indices = [indices[i] for i in selected] + else: + sampled_indices = indices + all_indices.extend(sampled_indices) + + return all_indices + + def _ratio_sampling(self, dataset_groups): + return sum(dataset_groups.values(), []) + + def __len__(self): + if self.dataset_sampling_ratios: + temp_generator = torch.Generator() + temp_generator.manual_seed(self.seed) + + dataset_sample_map = {} + for bucket_key, dataset_groups in self.dataset_buckets.items(): + for dataset_name, indices in dataset_groups.items(): + if dataset_name not in dataset_sample_map: + dataset_sample_map[dataset_name] = [] + dataset_sample_map[dataset_name].extend(indices) + + total_samples = sum(len(indices) for indices in dataset_sample_map.values()) + total_ratio = sum(self.dataset_sampling_ratios.values()) + + sampled_total = 0 + for dataset_name, indices in dataset_sample_map.items(): + if dataset_name in self.dataset_sampling_ratios: + ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio + target_samples = max(1, int(total_samples * ratio)) + sampled_total += target_samples + else: + sampled_total += len(indices) + + # Account for SP group sharding + sp_group_samples = sampled_total // self.num_sp_groups + if not self.drop_last and sampled_total % self.num_sp_groups != 0: + sp_group_samples += 1 + + total_batches = sp_group_samples // self.batch_size + if not self.drop_last and sp_group_samples % self.batch_size != 0: + total_batches += 1 + return total_batches + else: + total_batches = 0 + for bucket_key, dataset_groups in self.dataset_buckets.items(): + balanced_indices = self._create_balanced_indices(dataset_groups) + + # Account for SP group sharding + sp_group_size = len(balanced_indices) // self.num_sp_groups + if not self.drop_last and len(balanced_indices) % self.num_sp_groups != 0: + sp_group_size += 1 + + num_batches = sp_group_size // self.batch_size + if not self.drop_last and sp_group_size % self.batch_size != 0: + num_batches += 1 + total_batches += num_batches + return total_batches + + +def collate_fn(batch): + batch = [item for item in batch if item is not None] + + if len(batch) == 0: + return None + + def collate_dict(data_list): + if isinstance(data_list[0], dict): + return {key: collate_dict([d[key] for d in data_list]) for key in data_list[0]} + elif isinstance(data_list[0], torch.Tensor): + return torch.stack(data_list) + else: + return data_list + + return {key: collate_dict([d[key] for d in batch]) for key in batch[0]} + + +if __name__ == "__main__": + import torch.distributed.checkpoint as dcp + from accelerate import Accelerator + from torchdata.stateful_dataloader import StatefulDataLoader + + json_file = [ + "opensoraplan/jsons/video_mixkit_513f_1997.json", + ] + video_folder = [ + "opensoraplan/videos", + ] + stride = 1 + batch_size = 2 + num_train_epochs = 1 + seed = 0 + num_workers = 8 + output_dir = "accelerate_checkpoints" + checkpoint_dirs = ( + [ + d + for d in os.listdir(output_dir) + if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d)) + ] + if os.path.exists(output_dir) + else [] + ) + + dataset_ratios = {} + # dataset_ratios = { + # "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v4/latents": 0.9, + # "/mnt/hdfs/data/ysh_new/userful_things_wan/sekai/sekai-real-walking-hq-193/latents_stride1": 0.1 + # } + + accelerator = Accelerator() + print(accelerator.process_index, accelerator.num_processes) + + dataset = BucketedFeatureDataset( + json_files=json_file, + video_folders=video_folder, + stride=stride, + force_rebuild=False, + resolution=640, + single_res=True, + single_height=384, + single_width=640, + single_length=True, + single_num_frame=81, + multi_res=True, + ) + sampler = BucketedSampler( + dataset, + batch_size=batch_size, + drop_last=True, + shuffle=False, + dataset_sampling_ratios=dataset_ratios, + seed=seed, + # num_sp_groups=get_world_size() // get_sp_world_size(), + # sp_world_size=get_sp_world_size(), + # global_rank=get_world_rank(), + num_sp_groups=accelerator.num_processes // 1, + sp_world_size=1, + global_rank=accelerator.process_index, + ) + dataloader = StatefulDataLoader(dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=num_workers) + + print(len(dataset), len(dataloader)) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + + step = 0 + global_step = 0 + first_epoch = 0 + num_update_steps_per_epoch = len(dataloader) + if checkpoint_dirs: + latest_checkpoint = max(checkpoint_dirs, key=lambda x: int(x.split("-")[1])) + checkpoint_path = os.path.join(output_dir, latest_checkpoint) + print(f"Found checkpoint: {checkpoint_path}") + + accelerator.load_state(checkpoint_path) + global_step = int(latest_checkpoint.split("-")[1]) + first_epoch = global_step // num_update_steps_per_epoch + + states = { + "dataloader": dataloader, + } + dcp_dir = os.path.join(checkpoint_path, "distributed_checkpoint") + dcp.load(states, checkpoint_id=dcp_dir) + + print(f"Resuming from step {global_step}, epoch {first_epoch}") + + print("Testing dataloader...") + step = global_step + dataset_counts = defaultdict(int) + for epoch in range(first_epoch, num_train_epochs): + sampler.set_epoch(epoch) + dataset.set_epoch(epoch) + for i, batch in enumerate(dataloader): + # Get metadata + uttid = batch["uttid"] + bucket_key = batch["bucket_key"] + num_frame = batch["video_metadata"]["num_frames"] + height = batch["video_metadata"]["height"] + width = batch["video_metadata"]["width"] + + # Get feature + video_data = batch["videos"] + prompt = batch["prompts"] + first_frames_images = batch["first_frames_images"] + first_frames_images = [torchvision.transforms.ToPILImage()(x.to(torch.uint8)) for x in first_frames_images] + + # save_frames(video_data[0].squeeze(0), video_path="1.mp4") + # import pdb;pdb.set_trace() + + if accelerator.process_index == 0: + # print info + print(f" Step {step}:") + print(f" Batch {i}:") + # print(f" Data Name: {batch['dataset_name']}") + print(f" Batch size: {len(uttid)}") + print(f" Uttids: {uttid}") + print(f" Dimensions - frames: {num_frame[0]}, height: {height[0]}, width: {width[0]}") + print(f" Bucket key: {bucket_key[0]}") + print(f" Videos shape: {video_data.shape}") + print(f" Cpation: {prompt}") + + # verify + assert all(nf == num_frame[0] for nf in num_frame), "Frame numbers not consistent in batch" + assert all(h == height[0] for h in height), "Heights not consistent in batch" + assert all(w == width[0] for w in width), "Widths not consistent in batch" + + print(" ✓ Batch dimensions are consistent") + + for dataset_name in batch["dataset_name"]: + dataset_counts[dataset_name] += 1 + + step += 1 + + # if step == 20: + # checkpoint_dir = f"checkpoint-{step}" + # save_path = os.path.join(output_dir, checkpoint_dir) + # os.makedirs(save_path, exist_ok=True) + + # if accelerator.is_main_process: + # print(f"Saving checkpoint at step {step}") + + # accelerator.save_state(save_path) + + # print(accelerator.process_index, accelerator.num_processes) + # states = { + # "dataloader": dataloader, + # } + # dcp_dir = os.path.join(save_path, "distributed_checkpoint") + # dcp.save(states, checkpoint_id=dcp_dir) + + print("实际采样统计:", dict(dataset_counts)) diff --git a/Helios/helios/diffusers_version/__init__.py b/Helios/helios/diffusers_version/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/helios/diffusers_version/__pycache__/__init__.cpython-311.pyc b/Helios/helios/diffusers_version/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe3374c84148b1905ed1e5116ca65119e5ebe056 Binary files /dev/null and b/Helios/helios/diffusers_version/__pycache__/__init__.cpython-311.pyc differ diff --git a/Helios/helios/diffusers_version/__pycache__/__init__.cpython-312.pyc b/Helios/helios/diffusers_version/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79ce7a871a461464cca86462bd7aaca409507705 Binary files /dev/null and b/Helios/helios/diffusers_version/__pycache__/__init__.cpython-312.pyc differ diff --git a/Helios/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-311.pyc b/Helios/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7eababf10848acbf2a62d24003750d64de29d793 Binary files /dev/null and b/Helios/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-311.pyc differ diff --git a/Helios/helios/diffusers_version/pipeline_helios_diffusers.py b/Helios/helios/diffusers_version/pipeline_helios_diffusers.py new file mode 100644 index 0000000000000000000000000000000000000000..4115291297ec1f505317186b07a75823bc6dd49a --- /dev/null +++ b/Helios/helios/diffusers_version/pipeline_helios_diffusers.py @@ -0,0 +1,1359 @@ +# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import html +import math +from itertools import accumulate +from typing import Any, Callable + +import numpy as np +import regex as re +import torch +import torch.nn.functional as F +from transformers import AutoTokenizer, UMT5EncoderModel + +from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback +from diffusers.image_processor import PipelineImageInput +from diffusers.loaders import HeliosLoraLoaderMixin +from diffusers.models import AutoencoderKLWan, HeliosTransformer3DModel +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.schedulers import HeliosScheduler +from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring +from diffusers.utils.torch_utils import randn_tensor +from diffusers.video_processor import VideoProcessor + +from ..pipelines.pipeline_output import HeliosPipelineOutput + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + XLA_AVAILABLE = True +else: + XLA_AVAILABLE = False + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + +if is_ftfy_available(): + import ftfy + + +EXAMPLE_DOC_STRING = """ + Examples: + ```python + >>> import torch + >>> from diffusers.utils import export_to_video + >>> from diffusers import AutoencoderKLWan, HeliosPipeline + + >>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled + >>> model_id = "BestWishYsh/Helios-Base" + >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) + >>> pipe = HeliosPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16) + >>> pipe.to("cuda") + + >>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window." + >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" + + >>> output = pipe( + ... prompt=prompt, + ... negative_prompt=negative_prompt, + ... height=384, + ... width=640, + ... num_frames=132, + ... guidance_scale=5.0, + ... ).frames[0] + >>> export_to_video(output, "output.mp4", fps=24) + ``` +""" + + +def optimized_scale(positive_flat, negative_flat): + positive_flat = positive_flat.float() + negative_flat = negative_flat.float() + # Calculate dot production + dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True) + # Squared norm of uncondition + squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8 + # st_star = v_cond^T * v_uncond / ||v_uncond||^2 + st_star = dot_product / squared_norm + return st_star + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r"\s+", " ", text) + text = text.strip() + return text + + +def prompt_clean(text): + text = whitespace_clean(basic_clean(text)) + return text + + +# Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift +def calculate_shift( + image_seq_len, + base_seq_len: int = 256, + max_seq_len: int = 4096, + base_shift: float = 0.5, + max_shift: float = 1.15, +): + m = (max_shift - base_shift) / (max_seq_len - base_seq_len) + b = base_shift - m * base_seq_len + mu = image_seq_len * m + b + return mu + + +class HeliosPipeline(DiffusionPipeline, HeliosLoraLoaderMixin): + r""" + Pipeline for text-to-video / image-to-video / video-to-video generation using Helios. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods + implemented for all pipelines (downloading, saving, running on a particular device, etc.). + + Args: + tokenizer ([`T5Tokenizer`]): + Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer), + specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant. + text_encoder ([`T5EncoderModel`]): + [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically + the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant. + transformer ([`HeliosTransformer3DModel`]): + Conditional Transformer to denoise the input latents. + scheduler ([`HeliosScheduler`]): + A scheduler to be used in combination with `transformer` to denoise the encoded image latents. + vae ([`AutoencoderKLWan`]): + Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations. + """ + + model_cpu_offload_seq = "text_encoder->transformer->vae" + _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"] + _optional_components = ["transformer"] + + def __init__( + self, + tokenizer: AutoTokenizer, + text_encoder: UMT5EncoderModel, + vae: AutoencoderKLWan, + scheduler: HeliosScheduler, + transformer: HeliosTransformer3DModel, + is_cfg_zero_star: bool = False, + is_distilled: bool = False, + ): + super().__init__() + + self.register_modules( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + transformer=transformer, + scheduler=scheduler, + ) + self.register_to_config(is_cfg_zero_star=is_cfg_zero_star) + self.register_to_config(is_distilled=is_distilled) + self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4 + self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8 + self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial) + + def _get_t5_prompt_embeds( + self, + prompt: str | list[str] = None, + num_videos_per_prompt: int = 1, + max_sequence_length: int = 226, + device: torch.device | None = None, + dtype: torch.dtype | None = None, + ): + device = device or self._execution_device + dtype = dtype or self.text_encoder.dtype + + prompt = [prompt] if isinstance(prompt, str) else prompt + prompt = [prompt_clean(u) for u in prompt] + batch_size = len(prompt) + + text_inputs = self.tokenizer( + prompt, + padding="max_length", + max_length=max_sequence_length, + truncation=True, + add_special_tokens=True, + return_attention_mask=True, + return_tensors="pt", + ) + text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask + seq_lens = mask.gt(0).sum(dim=1).long() + + prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state + prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) + prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)] + prompt_embeds = torch.stack( + [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0 + ) + + # duplicate text embeddings for each generation per prompt, using mps friendly method + _, seq_len, _ = prompt_embeds.shape + prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1) + prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1) + + return prompt_embeds, text_inputs.attention_mask.bool() + + def encode_prompt( + self, + prompt: str | list[str], + negative_prompt: str | list[str] | None = None, + do_classifier_free_guidance: bool = True, + num_videos_per_prompt: int = 1, + prompt_embeds: torch.Tensor | None = None, + negative_prompt_embeds: torch.Tensor | None = None, + max_sequence_length: int = 226, + device: torch.device | None = None, + dtype: torch.dtype | None = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `list[str]`, *optional*): + prompt to be encoded + negative_prompt (`str` or `list[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + do_classifier_free_guidance (`bool`, *optional*, defaults to `True`): + Whether to use classifier free guidance or not. + num_videos_per_prompt (`int`, *optional*, defaults to 1): + Number of videos that should be generated per prompt. torch device to place the resulting embeddings on + prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + device: (`torch.device`, *optional*): + torch device + dtype: (`torch.dtype`, *optional*): + torch dtype + """ + device = device or self._execution_device + + prompt = [prompt] if isinstance(prompt, str) else prompt + if prompt is not None: + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + if prompt_embeds is None: + prompt_embeds, _ = self._get_t5_prompt_embeds( + prompt=prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + device=device, + dtype=dtype, + ) + + if do_classifier_free_guidance and negative_prompt_embeds is None: + negative_prompt = negative_prompt or "" + negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt + + if prompt is not None and type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + + negative_prompt_embeds, _ = self._get_t5_prompt_embeds( + prompt=negative_prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + device=device, + dtype=dtype, + ) + + return prompt_embeds, negative_prompt_embeds + + def check_inputs( + self, + prompt, + negative_prompt, + height, + width, + prompt_embeds=None, + negative_prompt_embeds=None, + callback_on_step_end_tensor_inputs=None, + image=None, + video=None, + use_interpolate_prompt=False, + num_videos_per_prompt=None, + interpolate_time_list=None, + interpolation_steps=None, + guidance_scale=None, + ): + if height % 16 != 0 or width % 16 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.") + + if callback_on_step_end_tensor_inputs is not None and not all( + k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs + ): + raise ValueError( + f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" + ) + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + elif negative_prompt is not None and ( + not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list) + ): + raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}") + + if image is not None and video is not None: + raise ValueError("image and video cannot be provided simultaneously") + + if use_interpolate_prompt: + assert num_videos_per_prompt == 1, f"num_videos_per_prompt must be 1, got {num_videos_per_prompt}" + assert isinstance(prompt, list), "prompt must be a list" + assert len(prompt) == len(interpolate_time_list), ( + f"Length mismatch: {len(prompt)} vs {len(interpolate_time_list)}" + ) + assert min(interpolate_time_list) > interpolation_steps, ( + f"Minimum value {min(interpolate_time_list)} must be greater than {interpolation_steps}" + ) + + if guidance_scale > 1.0 and self.config.is_distilled: + logger.warning(f"Guidance scale {guidance_scale} is ignored for step-wise distilled models.") + + def prepare_latents( + self, + batch_size: int, + num_channels_latents: int = 16, + height: int = 384, + width: int = 640, + num_frames: int = 33, + dtype: torch.dtype | None = None, + device: torch.device | None = None, + generator: torch.Generator | list[torch.Generator] | None = None, + latents: torch.Tensor | None = None, + ) -> torch.Tensor: + if latents is not None: + return latents.to(device=device, dtype=dtype) + + num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1 + shape = ( + batch_size, + num_channels_latents, + num_latent_frames, + int(height) // self.vae_scale_factor_spatial, + int(width) // self.vae_scale_factor_spatial, + ) + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + return latents + + def prepare_image_latents( + self, + image: torch.Tensor, + latents_mean: torch.Tensor, + latents_std: torch.Tensor, + num_latent_frames_per_chunk: int, + dtype: torch.dtype | None = None, + device: torch.device | None = None, + generator: torch.Generator | list[torch.Generator] | None = None, + latents: torch.Tensor | None = None, + fake_latents: torch.Tensor | None = None, + ) -> torch.Tensor: + device = device or self._execution_device + if latents is None: + image = image.unsqueeze(2).to(device=device, dtype=self.vae.dtype) + latents = self.vae.encode(image).latent_dist.sample(generator=generator) + latents = (latents - latents_mean) * latents_std + if fake_latents is None: + min_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1 + fake_video = image.repeat(1, 1, min_frames, 1, 1).to(device=device, dtype=self.vae.dtype) + fake_latents_full = self.vae.encode(fake_video).latent_dist.sample(generator=generator) + fake_latents_full = (fake_latents_full - latents_mean) * latents_std + fake_latents = fake_latents_full[:, :, -1:, :, :] + return latents.to(device=device, dtype=dtype), fake_latents.to(device=device, dtype=dtype) + + def prepare_video_latents( + self, + video: torch.Tensor, + latents_mean: torch.Tensor, + latents_std: torch.Tensor, + num_latent_frames_per_chunk: int, + dtype: torch.dtype | None = None, + device: torch.device | None = None, + generator: torch.Generator | list[torch.Generator] | None = None, + latents: torch.Tensor | None = None, + ) -> torch.Tensor: + device = device or self._execution_device + video = video.to(device=device, dtype=self.vae.dtype) + if latents is None: + num_frames = video.shape[2] + min_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1 + num_chunks = num_frames // min_frames + if num_chunks == 0: + raise ValueError( + f"Video must have at least {min_frames} frames " + f"(got {num_frames} frames). " + f"Required: (num_latent_frames_per_chunk - 1) * {self.vae_scale_factor_temporal} + 1 = ({num_latent_frames_per_chunk} - 1) * {self.vae_scale_factor_temporal} + 1 = {min_frames}" + ) + total_valid_frames = num_chunks * min_frames + start_frame = num_frames - total_valid_frames + + first_frame = video[:, :, 0:1, :, :] + first_frame_latent = self.vae.encode(first_frame).latent_dist.sample(generator=generator) + first_frame_latent = (first_frame_latent - latents_mean) * latents_std + + latents_chunks = [] + for i in range(num_chunks): + chunk_start = start_frame + i * min_frames + chunk_end = chunk_start + min_frames + video_chunk = video[:, :, chunk_start:chunk_end, :, :] + chunk_latents = self.vae.encode(video_chunk).latent_dist.sample(generator=generator) + chunk_latents = (chunk_latents - latents_mean) * latents_std + latents_chunks.append(chunk_latents) + latents = torch.cat(latents_chunks, dim=2) + return first_frame_latent.to(device=device, dtype=dtype), latents.to(device=device, dtype=dtype) + + def interpolate_prompt_embeds( + self, + prompt_embeds_1: torch.Tensor, + prompt_embeds_2: torch.Tensor, + interpolation_steps: int = 3, + ): + x = torch.lerp( + prompt_embeds_1, + prompt_embeds_2, + torch.linspace(0, 1, steps=interpolation_steps).unsqueeze(1).unsqueeze(2).to(prompt_embeds_1), + ) + interpolated_prompt_embeds = list(x.chunk(interpolation_steps, dim=0)) + return interpolated_prompt_embeds + + def sample_block_noise( + self, + batch_size, + channel, + num_frames, + height, + width, + patch_size: tuple[int, ...] = (1, 2, 2), + device: torch.device | None = None, + generator: torch.Generator | None = None, + ): + # NOTE: A generator must be provided to ensure correct and reproducible results. + # Creating a default generator here is a fallback only — without a fixed seed, + # the output will be non-deterministic and may produce incorrect results in CP context. + if generator is None: + generator = torch.Generator(device=device) + elif isinstance(generator, list): + generator = generator[0] + + gamma = self.scheduler.config.gamma + _, ph, pw = patch_size + block_size = ph * pw + + cov = ( + torch.eye(block_size, device=device) * (1 + gamma) + - torch.ones(block_size, block_size, device=device) * gamma + ) + cov += torch.eye(block_size, device=device) * 1e-8 + cov = cov.float() # Upcast to fp32 for numerical stability — cholesky is unreliable in fp16/bf16. + + L = torch.linalg.cholesky(cov) + block_number = batch_size * channel * num_frames * (height // ph) * (width // pw) + z = torch.randn(block_number, block_size, generator=generator, device=generator.device).to(device=device) + noise = z @ L.T + + noise = noise.view(batch_size, channel, num_frames, height // ph, width // pw, ph, pw) + noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(batch_size, channel, num_frames, height, width) + + return noise + + def stage1_sample( + self, + latents: torch.Tensor = None, + prompt_embeds: torch.Tensor = None, + negative_prompt_embeds: torch.Tensor = None, + timesteps: torch.Tensor = None, + guidance_scale: float | None = 5.0, + indices_hidden_states: torch.Tensor = None, + indices_latents_history_short: torch.Tensor = None, + indices_latents_history_mid: torch.Tensor = None, + indices_latents_history_long: torch.Tensor = None, + latents_history_short: torch.Tensor = None, + latents_history_mid: torch.Tensor = None, + latents_history_long: torch.Tensor = None, + attention_kwargs: dict | None = None, + device: torch.device | None = None, + transformer_dtype: torch.dtype = None, + generator: torch.Generator | None = None, + num_warmup_steps: int | None = None, + # ------------ CFG Zero ------------ + use_zero_init: bool | None = True, + zero_steps: int | None = 1, + # ------------ Callback ------------ + callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None, + callback_on_step_end_tensor_inputs: list[str] = ["latents"], + progress_bar=None, + ): + batch_size = latents.shape[0] + + for i, t in enumerate(timesteps): + if self.interrupt: + continue + + self._current_timestep = t + timestep = t.expand(latents.shape[0]) + + latent_model_input = latents.to(transformer_dtype) + with self.transformer.cache_context("cond"): + noise_pred = self.transformer( + hidden_states=latent_model_input, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + attention_kwargs=attention_kwargs, + return_dict=False, + )[0] + + if self.do_classifier_free_guidance: + with self.transformer.cache_context("uncond"): + noise_uncond = self.transformer( + hidden_states=latent_model_input, + timestep=timestep, + encoder_hidden_states=negative_prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + attention_kwargs=attention_kwargs, + return_dict=False, + )[0] + + if self.config.is_cfg_zero_star: + noise_pred_text = noise_pred + positive_flat = noise_pred_text.view(batch_size, -1) + negative_flat = noise_uncond.view(batch_size, -1) + + alpha = optimized_scale(positive_flat, negative_flat) + alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1))) + alpha = alpha.to(noise_pred_text.dtype) + + if (i <= zero_steps) and use_zero_init: + noise_pred = noise_pred_text * 0.0 + else: + noise_pred = noise_uncond * alpha + guidance_scale * (noise_pred_text - noise_uncond * alpha) + else: + noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond) + + latents = self.scheduler.step( + noise_pred, + t, + latents, + return_dict=False, + )[0] + + if callback_on_step_end is not None: + callback_kwargs = {} + for k in callback_on_step_end_tensor_inputs: + callback_kwargs[k] = locals()[k] + callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) + + latents = callback_outputs.pop("latents", latents) + prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) + negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) + + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + + if XLA_AVAILABLE: + xm.mark_step() + + return latents + + def stage2_sample( + self, + latents: torch.Tensor = None, + pyramid_num_stages: int = None, + pyramid_num_inference_steps_list: list[int] = None, + prompt_embeds: torch.Tensor = None, + negative_prompt_embeds: torch.Tensor = None, + guidance_scale: float | None = 5.0, + indices_hidden_states: torch.Tensor = None, + indices_latents_history_short: torch.Tensor = None, + indices_latents_history_mid: torch.Tensor = None, + indices_latents_history_long: torch.Tensor = None, + latents_history_short: torch.Tensor = None, + latents_history_mid: torch.Tensor = None, + latents_history_long: torch.Tensor = None, + attention_kwargs: dict | None = None, + device: torch.device | None = None, + transformer_dtype: torch.dtype = None, + generator: torch.Generator | None = None, + # ------------ CFG Zero ------------ + use_zero_init: bool | None = True, + zero_steps: int | None = 1, + # -------------- DMD -------------- + is_amplify_first_chunk: bool = False, + # ------------ Callback ------------ + callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None, + callback_on_step_end_tensor_inputs: list[str] = ["latents"], + progress_bar=None, + ): + batch_size, num_channel, num_frames, height, width = latents.shape + latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, num_channel, height, width) + for _ in range(pyramid_num_stages - 1): + height //= 2 + width //= 2 + latents = ( + F.interpolate( + latents, + size=(height, width), + mode="bilinear", + ) + * 2 + ) + latents = latents.reshape(batch_size, num_frames, num_channel, height, width).permute(0, 2, 1, 3, 4) + + batch_size = latents.shape[0] + start_point_list = None + if self.config.is_distilled: + start_point_list = [latents] + + i = 0 + for i_s in range(pyramid_num_stages): + patch_size = self.transformer.config.patch_size + image_seq_len = (latents.shape[-1] * latents.shape[-2] * latents.shape[-3]) // ( + patch_size[0] * patch_size[1] * patch_size[2] + ) + mu = calculate_shift( + image_seq_len, + self.scheduler.config.get("base_image_seq_len", 256), + self.scheduler.config.get("max_image_seq_len", 4096), + self.scheduler.config.get("base_shift", 0.5), + self.scheduler.config.get("max_shift", 1.15), + ) + self.scheduler.set_timesteps( + pyramid_num_inference_steps_list[i_s], + i_s, + device=device, + mu=mu, + is_amplify_first_chunk=is_amplify_first_chunk, + ) + timesteps = self.scheduler.timesteps + + if i_s > 0: + height *= 2 + width *= 2 + num_frames = latents.shape[2] + latents = latents.permute(0, 2, 1, 3, 4).reshape( + batch_size * num_frames, num_channel, height // 2, width // 2 + ) + latents = F.interpolate(latents, size=(height, width), mode="nearest") + latents = latents.reshape(batch_size, num_frames, num_channel, height, width).permute(0, 2, 1, 3, 4) + # Fix the stage + ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal + gamma = self.scheduler.config.gamma + alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma) + beta = alpha * (1 - ori_sigma) / math.sqrt(gamma) + + batch_size, channel, num_frames, height, width = latents.shape + noise = self.sample_block_noise( + batch_size, channel, num_frames, height, width, patch_size, device, generator + ) + noise = noise.to(device=device, dtype=transformer_dtype) + latents = alpha * latents + beta * noise # To fix the block artifact + + if self.config.is_distilled: + start_point_list.append(latents) + + for idx, t in enumerate(timesteps): + timestep = t.expand(latents.shape[0]).to(torch.int64) + + with self.transformer.cache_context("cond"): + noise_pred = self.transformer( + hidden_states=latents.to(transformer_dtype), + timestep=timestep, + encoder_hidden_states=prompt_embeds, + attention_kwargs=attention_kwargs, + return_dict=False, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + )[0] + + if self.do_classifier_free_guidance: + with self.transformer.cache_context("uncond"): + noise_uncond = self.transformer( + hidden_states=latents.to(transformer_dtype), + timestep=timestep, + encoder_hidden_states=negative_prompt_embeds, + attention_kwargs=attention_kwargs, + return_dict=False, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + )[0] + + if self.config.is_cfg_zero_star: + noise_pred_text = noise_pred + positive_flat = noise_pred_text.view(batch_size, -1) + negative_flat = noise_uncond.view(batch_size, -1) + + alpha = optimized_scale(positive_flat, negative_flat) + alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1))) + alpha = alpha.to(noise_pred_text.dtype) + + if (i_s == 0 and idx <= zero_steps) and use_zero_init: + noise_pred = noise_pred_text * 0.0 + else: + noise_pred = noise_uncond * alpha + guidance_scale * ( + noise_pred_text - noise_uncond * alpha + ) + else: + noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond) + + latents = self.scheduler.step( + noise_pred, + t, + latents, + generator=generator, + return_dict=False, + cur_sampling_step=idx, + dmd_noisy_tensor=start_point_list[i_s] if start_point_list is not None else None, + dmd_sigmas=self.scheduler.sigmas, + dmd_timesteps=self.scheduler.timesteps, + all_timesteps=timesteps, + )[0] + + if callback_on_step_end is not None: + callback_kwargs = {} + for k in callback_on_step_end_tensor_inputs: + callback_kwargs[k] = locals()[k] + callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) + + latents = callback_outputs.pop("latents", latents) + prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) + negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) + + progress_bar.update() + + if XLA_AVAILABLE: + xm.mark_step() + + i += 1 + + return latents + + @property + def guidance_scale(self): + return self._guidance_scale + + @property + def do_classifier_free_guidance(self): + return self._guidance_scale > 1.0 + + @property + def num_timesteps(self): + return self._num_timesteps + + @property + def current_timestep(self): + return self._current_timestep + + @property + def interrupt(self): + return self._interrupt + + @property + def attention_kwargs(self): + return self._attention_kwargs + + @torch.no_grad() + @replace_example_docstring(EXAMPLE_DOC_STRING) + def __call__( + self, + prompt: str | list[str] = None, + negative_prompt: str | list[str] = None, + height: int = 384, + width: int = 640, + num_frames: int = 132, + num_inference_steps: int = 50, + sigmas: list[float] = None, + guidance_scale: float = 5.0, + num_videos_per_prompt: int | None = 1, + generator: torch.Generator | list[torch.Generator] | None = None, + latents: torch.Tensor | None = None, + prompt_embeds: torch.Tensor | None = None, + negative_prompt_embeds: torch.Tensor | None = None, + output_type: str | None = "np", + return_dict: bool = True, + attention_kwargs: dict[str, Any] | None = None, + callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None, + callback_on_step_end_tensor_inputs: list[str] = ["latents"], + max_sequence_length: int = 512, + # ------------ I2V ------------ + image: PipelineImageInput | None = None, + image_latents: torch.Tensor | None = None, + fake_image_latents: torch.Tensor | None = None, + add_noise_to_image_latents: bool = True, + image_noise_sigma_min: float = 0.111, + image_noise_sigma_max: float = 0.135, + # ------------ V2V ------------ + video: PipelineImageInput | None = None, + video_latents: torch.Tensor | None = None, + add_noise_to_video_latents: bool = True, + video_noise_sigma_min: float = 0.111, + video_noise_sigma_max: float = 0.135, + # ------------ Interactive ------------ + use_interpolate_prompt: bool = False, + interpolate_time_list: list = [7, 7, 7], + interpolation_steps: int = 3, + # ------------ Stage 1 ------------ + history_sizes: list = [16, 2, 1], + num_latent_frames_per_chunk: int = 9, + keep_first_frame: bool = True, + is_skip_first_chunk: bool = False, + # ------------ Stage 2 ------------ + is_enable_stage2: bool = False, + pyramid_num_stages: int = 3, + pyramid_num_inference_steps_list: list = [10, 10, 10], + # ------------ CFG Zero ------------ + use_zero_init: bool | None = True, + zero_steps: int | None = 1, + # ------------ DMD ------------ + is_amplify_first_chunk: bool = False, + ): + r""" + The call function to the pipeline for generation. + + Args: + prompt (`str` or `list[str]`, *optional*): + The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead. + negative_prompt (`str` or `list[str]`, *optional*): + The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds` + instead. Ignored when not using guidance (`guidance_scale` < `1`). + height (`int`, defaults to `384`): + The height in pixels of the generated image. + width (`int`, defaults to `640`): + The width in pixels of the generated image. + num_frames (`int`, defaults to `132`): + The number of frames in the generated video. + num_inference_steps (`int`, defaults to `50`): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, defaults to `5.0`): + Guidance scale as defined in [Classifier-Free Diffusion + Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2. + of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting + `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to + the text `prompt`, usually at the expense of lower image quality. + num_videos_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + generator (`torch.Generator` or `list[torch.Generator]`, *optional*): + A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make + generation deterministic. + latents (`torch.Tensor`, *optional*): + Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor is generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not + provided, text embeddings are generated from the `prompt` input argument. + output_type (`str`, *optional*, defaults to `"np"`): + The output format of the generated image. Choose between `PIL.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`HeliosPipelineOutput`] instead of a plain tuple. + attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*): + A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of + each denoising step during the inference. with the following arguments: `callback_on_step_end(self: + DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a + list of all tensors as specified by `callback_on_step_end_tensor_inputs`. + callback_on_step_end_tensor_inputs (`list`, *optional*): + The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list + will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the + `._callback_tensor_inputs` attribute of your pipeline class. + max_sequence_length (`int`, defaults to `512`): + The maximum sequence length of the text encoder. If the prompt is longer than this, it will be + truncated. If the prompt is shorter, it will be padded to this length. + + Examples: + + Returns: + [`~HeliosPipelineOutput`] or `tuple`: + If `return_dict` is `True`, [`HeliosPipelineOutput`] is returned, otherwise a `tuple` is returned where + the first element is a list with the generated images and the second element is a list of `bool`s + indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content. + """ + + if image is not None and video is not None: + raise ValueError("image and video cannot be provided simultaneously") + + history_sizes = sorted(history_sizes, reverse=True) # From big to small + + if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)): + callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs + + # 1. Check inputs. Raise error if not correct + self.check_inputs( + prompt, + negative_prompt, + height, + width, + prompt_embeds, + negative_prompt_embeds, + callback_on_step_end_tensor_inputs, + image, + video, + use_interpolate_prompt, + num_videos_per_prompt, + interpolate_time_list, + interpolation_steps, + guidance_scale, + ) + + num_frames = max(num_frames, 1) + + self._guidance_scale = guidance_scale + self._attention_kwargs = attention_kwargs + self._current_timestep = None + self._interrupt = False + + device = self._execution_device + vae_dtype = self.vae.dtype + + latents_mean = ( + torch.tensor(self.vae.config.latents_mean) + .view(1, self.vae.config.z_dim, 1, 1, 1) + .to(device, self.vae.dtype) + ) + latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to( + device, self.vae.dtype + ) + + # 2. Define call parameters + if use_interpolate_prompt or (prompt is not None and isinstance(prompt, str)): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + # 3. Encode input prompt + if use_interpolate_prompt: + interpolate_interval_idx = None + interpolate_embeds = None + interpolate_cumulative_list = list(accumulate(interpolate_time_list)) + + all_prompt_embeds, negative_prompt_embeds = self.encode_prompt( + prompt=prompt, + negative_prompt=negative_prompt, + do_classifier_free_guidance=self.do_classifier_free_guidance, + num_videos_per_prompt=num_videos_per_prompt, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + max_sequence_length=max_sequence_length, + device=device, + ) + + transformer_dtype = self.transformer.dtype + all_prompt_embeds = all_prompt_embeds.to(transformer_dtype) + if negative_prompt_embeds is not None: + if use_interpolate_prompt: + negative_prompt_embeds = negative_prompt_embeds[0].unsqueeze(0) + negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype) + + # 4. Prepare image or video + if image is not None: + image = self.video_processor.preprocess(image, height=height, width=width) + image_latents, fake_image_latents = self.prepare_image_latents( + image, + latents_mean=latents_mean, + latents_std=latents_std, + num_latent_frames_per_chunk=num_latent_frames_per_chunk, + dtype=torch.float32, + device=device, + generator=generator, + latents=image_latents, + fake_latents=fake_image_latents, + ) + + if image_latents is not None and add_noise_to_image_latents: + image_noise_sigma = ( + torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min) + + image_noise_sigma_min + ) + image_latents = ( + image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device) + + (1 - image_noise_sigma) * image_latents + ) + fake_image_noise_sigma = ( + torch.rand(1, device=device, generator=generator) * (video_noise_sigma_max - video_noise_sigma_min) + + video_noise_sigma_min + ) + fake_image_latents = ( + fake_image_noise_sigma * randn_tensor(fake_image_latents.shape, generator=generator, device=device) + + (1 - fake_image_noise_sigma) * fake_image_latents + ) + + if video is not None: + video = self.video_processor.preprocess_video(video, height=height, width=width) + image_latents, video_latents = self.prepare_video_latents( + video, + latents_mean=latents_mean, + latents_std=latents_std, + num_latent_frames_per_chunk=num_latent_frames_per_chunk, + dtype=torch.float32, + device=device, + generator=generator, + latents=video_latents, + ) + + if video_latents is not None and add_noise_to_video_latents: + image_noise_sigma = ( + torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min) + + image_noise_sigma_min + ) + image_latents = ( + image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device) + + (1 - image_noise_sigma) * image_latents + ) + + noisy_latents_chunks = [] + num_latent_chunks = video_latents.shape[2] // num_latent_frames_per_chunk + for i in range(num_latent_chunks): + chunk_start = i * num_latent_frames_per_chunk + chunk_end = chunk_start + num_latent_frames_per_chunk + latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :] + + chunk_frames = latent_chunk.shape[2] + frame_sigmas = ( + torch.rand(chunk_frames, device=device, generator=generator) + * (video_noise_sigma_max - video_noise_sigma_min) + + video_noise_sigma_min + ) + frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1) + + noisy_chunk = ( + frame_sigmas * randn_tensor(latent_chunk.shape, generator=generator, device=device) + + (1 - frame_sigmas) * latent_chunk + ) + noisy_latents_chunks.append(noisy_chunk) + video_latents = torch.cat(noisy_latents_chunks, dim=2) + + # 5. Prepare latent variables + num_channels_latents = self.transformer.config.in_channels + window_num_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1 + num_latent_chunk = max(1, (num_frames + window_num_frames - 1) // window_num_frames) + num_history_latent_frames = sum(history_sizes) + history_video = None + total_generated_latent_frames = 0 + + if not keep_first_frame: + history_sizes[-1] = history_sizes[-1] + 1 + history_latents = torch.zeros( + batch_size, + num_channels_latents, + num_history_latent_frames, + height // self.vae_scale_factor_spatial, + width // self.vae_scale_factor_spatial, + device=device, + dtype=torch.float32, + ) + if fake_image_latents is not None: + history_latents = torch.cat([history_latents[:, :, :-1, :, :], fake_image_latents], dim=2) + total_generated_latent_frames += 1 + if video_latents is not None: + history_frames = history_latents.shape[2] + video_frames = video_latents.shape[2] + if video_frames < history_frames: + keep_frames = history_frames - video_frames + history_latents = torch.cat([history_latents[:, :, :keep_frames, :, :], video_latents], dim=2) + else: + history_latents = video_latents + total_generated_latent_frames += video_latents.shape[2] + + if keep_first_frame: + indices = torch.arange(0, sum([1, *history_sizes, num_latent_frames_per_chunk])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, num_latent_frames_per_chunk], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + else: + indices = torch.arange(0, sum([*history_sizes, num_latent_frames_per_chunk])) + ( + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_short, + indices_hidden_states, + ) = indices.split([*history_sizes, num_latent_frames_per_chunk], dim=0) + indices_hidden_states = indices_hidden_states.unsqueeze(0) + indices_latents_history_short = indices_latents_history_short.unsqueeze(0) + indices_latents_history_mid = indices_latents_history_mid.unsqueeze(0) + indices_latents_history_long = indices_latents_history_long.unsqueeze(0) + + # 6. Denoising loop + if use_interpolate_prompt: + if num_latent_chunk < max(interpolate_cumulative_list): + num_latent_chunk = sum(interpolate_cumulative_list) + print(f"Update num_latent_chunk to: {num_latent_chunk}") + + if not is_enable_stage2: + patch_size = self.transformer.config.patch_size + image_seq_len = ( + num_latent_frames_per_chunk + * (height // self.vae_scale_factor_spatial) + * (width // self.vae_scale_factor_spatial) + // (patch_size[0] * patch_size[1] * patch_size[2]) + ) + sigmas = np.linspace(0.999, 0.0, num_inference_steps + 1)[:-1] if sigmas is None else sigmas + mu = calculate_shift( + image_seq_len, + self.scheduler.config.get("base_image_seq_len", 256), + self.scheduler.config.get("max_image_seq_len", 4096), + self.scheduler.config.get("base_shift", 0.5), + self.scheduler.config.get("max_shift", 1.15), + ) + + for k in range(num_latent_chunk): + if use_interpolate_prompt: + assert num_latent_chunk >= max(interpolate_cumulative_list) + + current_interval_idx = 0 + for idx, cumulative_val in enumerate(interpolate_cumulative_list): + if k < cumulative_val: + current_interval_idx = idx + break + + if current_interval_idx == 0: + prompt_embeds = all_prompt_embeds[0].unsqueeze(0) + else: + interval_start = interpolate_cumulative_list[current_interval_idx - 1] + position_in_interval = k - interval_start + + if position_in_interval < interpolation_steps: + if interpolate_embeds is None or interpolate_interval_idx != current_interval_idx: + interpolate_embeds = self.interpolate_prompt_embeds( + prompt_embeds_1=all_prompt_embeds[current_interval_idx - 1].unsqueeze(0), + prompt_embeds_2=all_prompt_embeds[current_interval_idx].unsqueeze(0), + interpolation_steps=interpolation_steps, + ) + interpolate_interval_idx = current_interval_idx + + prompt_embeds = interpolate_embeds[position_in_interval] + else: + prompt_embeds = all_prompt_embeds[current_interval_idx].unsqueeze(0) + else: + prompt_embeds = all_prompt_embeds + + is_first_chunk = k == 0 + is_second_chunk = k == 1 + if keep_first_frame: + latents_history_long, latents_history_mid, latents_history_1x = history_latents[ + :, :, -num_history_latent_frames: + ].split(history_sizes, dim=2) + if image_latents is None and is_first_chunk: + latents_prefix = torch.zeros( + ( + batch_size, + num_channels_latents, + 1, + latents_history_1x.shape[-2], + latents_history_1x.shape[-1], + ), + device=device, + dtype=latents_history_1x.dtype, + ) + else: + latents_prefix = image_latents + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + latents_history_long, latents_history_mid, latents_history_short = history_latents[ + :, :, -num_history_latent_frames: + ].split(history_sizes, dim=2) + + latents = self.prepare_latents( + batch_size, + num_channels_latents, + height, + width, + window_num_frames, + dtype=torch.float32, + device=device, + generator=generator, + latents=None, + ) + + if not is_enable_stage2: + self.scheduler.set_timesteps(num_inference_steps, device=device, sigmas=sigmas, mu=mu) + timesteps = self.scheduler.timesteps + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + self._num_timesteps = len(timesteps) + else: + num_inference_steps = ( + sum(pyramid_num_inference_steps_list) * 2 + if is_amplify_first_chunk and self.config.is_distilled and is_first_chunk + else sum(pyramid_num_inference_steps_list) + ) + + with self.progress_bar(total=num_inference_steps) as progress_bar: + if is_enable_stage2: + latents = self.stage2_sample( + latents=latents, + pyramid_num_stages=pyramid_num_stages, + pyramid_num_inference_steps_list=pyramid_num_inference_steps_list, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + guidance_scale=guidance_scale, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + attention_kwargs=attention_kwargs, + device=device, + transformer_dtype=transformer_dtype, + # ------------ CFG Zero ------------ + use_zero_init=use_zero_init, + zero_steps=zero_steps, + # -------------- DMD -------------- + is_amplify_first_chunk=is_amplify_first_chunk and is_first_chunk, + # ------------ Callback ------------ + callback_on_step_end=callback_on_step_end, + callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, + progress_bar=progress_bar, + ) + else: + latents = self.stage1_sample( + latents=latents, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + timesteps=timesteps, + guidance_scale=guidance_scale, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + attention_kwargs=attention_kwargs, + device=device, + transformer_dtype=transformer_dtype, + generator=generator, + num_warmup_steps=num_warmup_steps, + # ------------ CFG Zero ------------ + use_zero_init=use_zero_init, + zero_steps=zero_steps, + # ------------ Callback ------------ + callback_on_step_end=callback_on_step_end, + callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, + progress_bar=progress_bar, + ) + + if keep_first_frame and ( + (is_first_chunk and image_latents is None) or (is_skip_first_chunk and is_second_chunk) + ): + image_latents = latents[:, :, 0:1, :, :] + + total_generated_latent_frames += latents.shape[2] + history_latents = torch.cat([history_latents, latents], dim=2) + real_history_latents = history_latents[:, :, -total_generated_latent_frames:] + current_latents = ( + real_history_latents[:, :, -num_latent_frames_per_chunk:].to(vae_dtype) / latents_std + + latents_mean + ) + current_video = self.vae.decode(current_latents, return_dict=False)[0] + + if history_video is None: + history_video = current_video + else: + history_video = torch.cat([history_video, current_video], dim=2) + + self._current_timestep = None + + if output_type != "latent": + generated_frames = history_video.size(2) + generated_frames = ( + generated_frames - 1 + ) // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1 + history_video = history_video[:, :, :generated_frames] + video = self.video_processor.postprocess_video(history_video, output_type=output_type) + else: + video = real_history_latents + + # Offload all models + self.maybe_free_model_hooks() + + if not return_dict: + return (video,) + + return HeliosPipelineOutput(frames=video) diff --git a/Helios/helios/diffusers_version/scheduling_helios_diffusers.py b/Helios/helios/diffusers_version/scheduling_helios_diffusers.py new file mode 100644 index 0000000000000000000000000000000000000000..e6c1ad2279a242e31f3781461cf9f31935e6b43b --- /dev/null +++ b/Helios/helios/diffusers_version/scheduling_helios_diffusers.py @@ -0,0 +1,947 @@ +# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from dataclasses import dataclass +from typing import Literal + +import numpy as np +import torch + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.schedulers.scheduling_utils import SchedulerMixin +from diffusers.utils import BaseOutput, deprecate + + +@dataclass +class HeliosSchedulerOutput(BaseOutput): + prev_sample: torch.FloatTensor + model_outputs: torch.FloatTensor | None = None + last_sample: torch.FloatTensor | None = None + this_order: int | None = None + + +class HeliosScheduler(SchedulerMixin, ConfigMixin): + _compatibles = [] + order = 1 + + @register_to_config + def __init__( + self, + num_train_timesteps: int = 1000, + shift: float = 1.0, # Following Stable diffusion 3, + stages: int = 3, + stage_range: list = [0, 1 / 3, 2 / 3, 1], + gamma: float = 1 / 3, + # For UniPC + thresholding: bool = False, + prediction_type: str = "flow_prediction", + solver_order: int = 2, + predict_x0: bool = True, + solver_type: str = "bh2", + lower_order_final: bool = True, + disable_corrector: list[int] = [], + solver_p: SchedulerMixin = None, + use_flow_sigmas: bool = True, + scheduler_type: str = "unipc", # ["euler", "unipc", "dmd"] + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + ): + self.timestep_ratios = {} # The timestep ratio for each stage + self.timesteps_per_stage = {} # The detailed timesteps per stage (fix max and min per stage) + self.sigmas_per_stage = {} # always uniform [1000, 0] + self.start_sigmas = {} # for start point / upsample renoise + self.end_sigmas = {} # for end point + self.ori_start_sigmas = {} + + # self.init_sigmas() + self.init_sigmas_for_each_stage() + self.sigma_min = self.sigmas[-1].item() + self.sigma_max = self.sigmas[0].item() + self.gamma = gamma + + if solver_type not in ["bh1", "bh2"]: + if solver_type in ["midpoint", "heun", "logrho"]: + self.register_to_config(solver_type="bh2") + else: + raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}") + + self.predict_x0 = predict_x0 + self.model_outputs = [None] * solver_order + self.timestep_list = [None] * solver_order + self.lower_order_nums = 0 + self.disable_corrector = disable_corrector + self.solver_p = solver_p + self.last_sample = None + self._step_index = None + self._begin_index = None + + def init_sigmas(self): + """ + initialize the global timesteps and sigmas + """ + num_train_timesteps = self.config.num_train_timesteps + shift = self.config.shift + + alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps + 1) + sigmas = 1.0 - alphas + sigmas = np.flip(shift * sigmas / (1 + (shift - 1) * sigmas))[:-1].copy() + sigmas = torch.from_numpy(sigmas) + timesteps = (sigmas * num_train_timesteps).clone() + + self._step_index = None + self._begin_index = None + self.timesteps = timesteps + self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication + + def init_sigmas_for_each_stage(self): + """ + Init the timesteps for each stage + """ + self.init_sigmas() + + stage_distance = [] + stages = self.config.stages + training_steps = self.config.num_train_timesteps + stage_range = self.config.stage_range + + # Init the start and end point of each stage + for i_s in range(stages): + # To decide the start and ends point + start_indice = int(stage_range[i_s] * training_steps) + start_indice = max(start_indice, 0) + end_indice = int(stage_range[i_s + 1] * training_steps) + end_indice = min(end_indice, training_steps) + start_sigma = self.sigmas[start_indice].item() + end_sigma = self.sigmas[end_indice].item() if end_indice < training_steps else 0.0 + self.ori_start_sigmas[i_s] = start_sigma + + if i_s != 0: + ori_sigma = 1 - start_sigma + gamma = self.config.gamma + corrected_sigma = (1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)) * ori_sigma + # corrected_sigma = 1 / (2 - ori_sigma) * ori_sigma + start_sigma = 1 - corrected_sigma + + stage_distance.append(start_sigma - end_sigma) + self.start_sigmas[i_s] = start_sigma + self.end_sigmas[i_s] = end_sigma + + # Determine the ratio of each stage according to flow length + tot_distance = sum(stage_distance) + for i_s in range(stages): + if i_s == 0: + start_ratio = 0.0 + else: + start_ratio = sum(stage_distance[:i_s]) / tot_distance + if i_s == stages - 1: + end_ratio = 0.9999999999999999 + else: + end_ratio = sum(stage_distance[: i_s + 1]) / tot_distance + + self.timestep_ratios[i_s] = (start_ratio, end_ratio) + + # Determine the timesteps and sigmas for each stage + for i_s in range(stages): + timestep_ratio = self.timestep_ratios[i_s] + # timestep_max = self.timesteps[int(timestep_ratio[0] * training_steps)] + timestep_max = min(self.timesteps[int(timestep_ratio[0] * training_steps)], 999) + timestep_min = self.timesteps[min(int(timestep_ratio[1] * training_steps), training_steps - 1)] + timesteps = np.linspace(timestep_max, timestep_min, training_steps + 1) + self.timesteps_per_stage[i_s] = ( + timesteps[:-1] if isinstance(timesteps, torch.Tensor) else torch.from_numpy(timesteps[:-1]) + ) + stage_sigmas = np.linspace(0.999, 0, training_steps + 1) + self.sigmas_per_stage[i_s] = torch.from_numpy(stage_sigmas[:-1]) + + @property + def step_index(self): + """ + The index counter for current timestep. It will increase 1 after each scheduler step. + """ + return self._step_index + + @property + def begin_index(self): + """ + The index for the first timestep. It should be set from pipeline with `set_begin_index` method. + """ + return self._begin_index + + def set_begin_index(self, begin_index: int = 0): + """ + Sets the begin index for the scheduler. This function should be run from pipeline before the inference. + + Args: + begin_index (`int`): + The begin index for the scheduler. + """ + self._begin_index = begin_index + + def _sigma_to_t(self, sigma): + return sigma * self.config.num_train_timesteps + + def set_timesteps( + self, + num_inference_steps: int, + stage_index: int | None = None, + device: str | torch.device = None, + sigmas: bool | None = None, + mu: bool | None = None, + is_amplify_first_chunk: bool = False, + ): + """ + Setting the timesteps and sigmas for each stage + """ + if self.config.scheduler_type == "dmd": + if is_amplify_first_chunk: + num_inference_steps = num_inference_steps * 2 + 1 + else: + num_inference_steps = num_inference_steps + 1 + + self.num_inference_steps = num_inference_steps + self.init_sigmas() + + if self.config.stages == 1: + if sigmas is None: + sigmas = np.linspace(1, 1 / self.config.num_train_timesteps, num_inference_steps + 1)[:-1].astype( + np.float32 + ) + if self.config.shift != 1.0: + assert not self.config.use_dynamic_shifting + sigmas = self.time_shift(self.config.shift, 1.0, sigmas) + timesteps = (sigmas * self.config.num_train_timesteps).copy() + sigmas = torch.from_numpy(sigmas) + else: + stage_timesteps = self.timesteps_per_stage[stage_index] + timesteps = np.linspace( + stage_timesteps[0].item(), + stage_timesteps[-1].item(), + num_inference_steps, + ) + + stage_sigmas = self.sigmas_per_stage[stage_index] + ratios = np.linspace(stage_sigmas[0].item(), stage_sigmas[-1].item(), num_inference_steps) + sigmas = torch.from_numpy(ratios) + + self.timesteps = torch.from_numpy(timesteps).to(device=device) + self.sigmas = torch.cat([sigmas, torch.zeros(1)]).to(device=device) + + self._step_index = None + self.reset_scheduler_history() + + if self.config.scheduler_type == "dmd": + self.timesteps = self.timesteps[:-1] + self.sigmas = torch.cat([self.sigmas[:-2], self.sigmas[-1:]]) + + if self.config.use_dynamic_shifting: + assert self.config.shift == 1.0 + self.sigmas = self.time_shift(mu, 1.0, self.sigmas) + if self.config.stages == 1: + self.timesteps = self.sigmas[:-1] * self.config.num_train_timesteps + else: + self.timesteps = self.timesteps_per_stage[stage_index].min() + self.sigmas[:-1] * ( + self.timesteps_per_stage[stage_index].max() - self.timesteps_per_stage[stage_index].min() + ) + + # Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler.time_shift + def time_shift(self, mu: float, sigma: float, t: torch.Tensor): + """ + Apply time shifting to the sigmas. + + Args: + mu (`float`): + The mu parameter for the time shift. + sigma (`float`): + The sigma parameter for the time shift. + t (`torch.Tensor`): + The input timesteps. + + Returns: + `torch.Tensor`: + The time-shifted timesteps. + """ + if self.config.time_shift_type == "exponential": + return self._time_shift_exponential(mu, sigma, t) + elif self.config.time_shift_type == "linear": + return self._time_shift_linear(mu, sigma, t) + + # Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._time_shift_exponential + def _time_shift_exponential(self, mu, sigma, t): + return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma) + + # Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._time_shift_linear + def _time_shift_linear(self, mu, sigma, t): + return mu / (mu + (1 / t - 1) ** sigma) + + # ---------------------------------- Euler ---------------------------------- + def index_for_timestep(self, timestep, schedule_timesteps=None): + if schedule_timesteps is None: + schedule_timesteps = self.timesteps + + indices = (schedule_timesteps == timestep).nonzero() + + # The sigma index that is taken for the **very** first `step` + # is always the second index (or the last index if there is only 1) + # This way we can ensure we don't accidentally skip a sigma in + # case we start in the middle of the denoising schedule (e.g. for image-to-image) + pos = 1 if len(indices) > 1 else 0 + + return indices[pos].item() + + def _init_step_index(self, timestep): + if self.begin_index is None: + if isinstance(timestep, torch.Tensor): + timestep = timestep.to(self.timesteps.device) + self._step_index = self.index_for_timestep(timestep) + else: + self._step_index = self._begin_index + + def step_euler( + self, + model_output: torch.FloatTensor, + timestep: float | torch.FloatTensor = None, + sample: torch.FloatTensor = None, + generator: torch.Generator | None = None, + sigma: torch.FloatTensor | None = None, + sigma_next: torch.FloatTensor | None = None, + return_dict: bool = True, + ) -> HeliosSchedulerOutput | tuple: + assert (sigma is None) == (sigma_next is None), "sigma and sigma_next must both be None or both be not None" + + if sigma is None and sigma_next is None: + if ( + isinstance(timestep, int) + or isinstance(timestep, torch.IntTensor) + or isinstance(timestep, torch.LongTensor) + ): + raise ValueError( + ( + "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to" + " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass" + " one of the `scheduler.timesteps` as a timestep." + ), + ) + + if self.step_index is None: + self._step_index = 0 + + # Upcast to avoid precision issues when computing prev_sample + sample = sample.to(torch.float32) + + if sigma is None and sigma_next is None: + sigma = self.sigmas[self.step_index] + sigma_next = self.sigmas[self.step_index + 1] + + prev_sample = sample + (sigma_next - sigma) * model_output + + # Cast sample back to model compatible dtype + prev_sample = prev_sample.to(model_output.dtype) + + # upon completion increase step index by one + self._step_index += 1 + + if not return_dict: + return (prev_sample,) + + return HeliosSchedulerOutput(prev_sample=prev_sample) + + # ---------------------------------- UniPC ---------------------------------- + def _sigma_to_alpha_sigma_t(self, sigma): + if self.config.use_flow_sigmas: + alpha_t = 1 - sigma + sigma_t = torch.clamp(sigma, min=1e-8) + else: + alpha_t = 1 / ((sigma**2 + 1) ** 0.5) + sigma_t = sigma * alpha_t + + return alpha_t, sigma_t + + def convert_model_output( + self, + model_output: torch.Tensor, + *args, + sample: torch.Tensor = None, + sigma: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + r""" + Convert the model output to the corresponding type the UniPC algorithm needs. + + Args: + model_output (`torch.Tensor`): + The direct output from the learned diffusion model. + timestep (`int`): + The current discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + + Returns: + `torch.Tensor`: + The converted model output. + """ + timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError("missing `sample` as a required keyword argument") + if timestep is not None: + deprecate( + "timesteps", + "1.0.0", + "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + flag = False + if sigma is None: + flag = True + sigma = self.sigmas[self.step_index] + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) + + if self.predict_x0: + if self.config.prediction_type == "epsilon": + x0_pred = (sample - sigma_t * model_output) / alpha_t + elif self.config.prediction_type == "sample": + x0_pred = model_output + elif self.config.prediction_type == "v_prediction": + x0_pred = alpha_t * sample - sigma_t * model_output + elif self.config.prediction_type == "flow_prediction": + if flag: + sigma_t = self.sigmas[self.step_index] + else: + sigma_t = sigma + x0_pred = sample - sigma_t * model_output + else: + raise ValueError( + f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, " + "`v_prediction`, or `flow_prediction` for the UniPCMultistepScheduler." + ) + + if self.config.thresholding: + x0_pred = self._threshold_sample(x0_pred) + + return x0_pred + else: + if self.config.prediction_type == "epsilon": + return model_output + elif self.config.prediction_type == "sample": + epsilon = (sample - alpha_t * model_output) / sigma_t + return epsilon + elif self.config.prediction_type == "v_prediction": + epsilon = alpha_t * model_output + sigma_t * sample + return epsilon + else: + raise ValueError( + f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" + " `v_prediction` for the UniPCMultistepScheduler." + ) + + def multistep_uni_p_bh_update( + self, + model_output: torch.Tensor, + *args, + sample: torch.Tensor = None, + order: int = None, + sigma: torch.Tensor = None, + sigma_next: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + """ + One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified. + + Args: + model_output (`torch.Tensor`): + The direct output from the learned diffusion model at the current timestep. + prev_timestep (`int`): + The previous discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + order (`int`): + The order of UniP at this timestep (corresponds to the *p* in UniPC-p). + + Returns: + `torch.Tensor`: + The sample tensor at the previous timestep. + """ + prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError("missing `sample` as a required keyword argument") + if order is None: + if len(args) > 2: + order = args[2] + else: + raise ValueError("missing `order` as a required keyword argument") + if prev_timestep is not None: + deprecate( + "prev_timestep", + "1.0.0", + "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + model_output_list = self.model_outputs + + s0 = self.timestep_list[-1] + m0 = model_output_list[-1] + x = sample + + if self.solver_p: + x_t = self.solver_p.step(model_output, s0, x).prev_sample + return x_t + + if sigma_next is None and sigma is None: + sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index] + else: + sigma_t, sigma_s0 = sigma_next, sigma + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = sample.device + + rks = [] + D1s = [] + for i in range(1, order): + si = self.step_index - i + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + D1s.append((mi - m0) / rk) + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + R = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.config.solver_type == "bh1": + B_h = hh + elif self.config.solver_type == "bh2": + B_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + R.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / B_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + R = torch.stack(R) + b = torch.tensor(b, device=device) + + if len(D1s) > 0: + D1s = torch.stack(D1s, dim=1) # (B, K) + # for order 2, we use a simplified version + if order == 2: + rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]).to(device).to(x.dtype) + else: + D1s = None + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if D1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) + else: + pred_res = 0 + x_t = x_t_ - alpha_t * B_h * pred_res + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if D1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) + else: + pred_res = 0 + x_t = x_t_ - sigma_t * B_h * pred_res + + x_t = x_t.to(x.dtype) + return x_t + + def multistep_uni_c_bh_update( + self, + this_model_output: torch.Tensor, + *args, + last_sample: torch.Tensor = None, + this_sample: torch.Tensor = None, + order: int = None, + sigma_before: torch.Tensor = None, + sigma: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + """ + One step for the UniC (B(h) version). + + Args: + this_model_output (`torch.Tensor`): + The model outputs at `x_t`. + this_timestep (`int`): + The current timestep `t`. + last_sample (`torch.Tensor`): + The generated sample before the last predictor `x_{t-1}`. + this_sample (`torch.Tensor`): + The generated sample after the last predictor `x_{t}`. + order (`int`): + The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`. + + Returns: + `torch.Tensor`: + The corrected sample tensor at the current timestep. + """ + this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None) + if last_sample is None: + if len(args) > 1: + last_sample = args[1] + else: + raise ValueError("missing `last_sample` as a required keyword argument") + if this_sample is None: + if len(args) > 2: + this_sample = args[2] + else: + raise ValueError("missing `this_sample` as a required keyword argument") + if order is None: + if len(args) > 3: + order = args[3] + else: + raise ValueError("missing `order` as a required keyword argument") + if this_timestep is not None: + deprecate( + "this_timestep", + "1.0.0", + "Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + model_output_list = self.model_outputs + + m0 = model_output_list[-1] + x = last_sample + x_t = this_sample + model_t = this_model_output + + if sigma_before is None and sigma is None: + sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1] + else: + sigma_t, sigma_s0 = sigma, sigma_before + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = this_sample.device + + rks = [] + D1s = [] + for i in range(1, order): + si = self.step_index - (i + 1) + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + D1s.append((mi - m0) / rk) + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + R = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.config.solver_type == "bh1": + B_h = hh + elif self.config.solver_type == "bh2": + B_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + R.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / B_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + R = torch.stack(R) + b = torch.tensor(b, device=device) + + if len(D1s) > 0: + D1s = torch.stack(D1s, dim=1) + else: + D1s = None + + # for order 1, we use a simplified version + if order == 1: + rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype) + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if D1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s) + else: + corr_res = 0 + D1_t = model_t - m0 + x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t) + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if D1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s) + else: + corr_res = 0 + D1_t = model_t - m0 + x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t) + x_t = x_t.to(x.dtype) + return x_t + + def step_unipc( + self, + model_output: torch.Tensor, + timestep: int | torch.Tensor = None, + sample: torch.Tensor = None, + return_dict: bool = True, + model_outputs: list = None, + timestep_list: list = None, + sigma_before: torch.Tensor = None, + sigma: torch.Tensor = None, + sigma_next: torch.Tensor = None, + cus_step_index: int = None, + cus_lower_order_num: int = None, + cus_this_order: int = None, + cus_last_sample: torch.Tensor = None, + ) -> HeliosSchedulerOutput | tuple: + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + if cus_step_index is None: + if self.step_index is None: + self._step_index = 0 + else: + self._step_index = cus_step_index + + if cus_lower_order_num is not None: + self.lower_order_nums = cus_lower_order_num + + if cus_this_order is not None: + self.this_order = cus_this_order + + if cus_last_sample is not None: + self.last_sample = cus_last_sample + + use_corrector = ( + self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None + ) + + # Convert model output using the proper conversion method + model_output_convert = self.convert_model_output(model_output, sample=sample, sigma=sigma) + + if model_outputs is not None and timestep_list is not None: + self.model_outputs = model_outputs[:-1] + self.timestep_list = timestep_list[:-1] + + if use_corrector: + sample = self.multistep_uni_c_bh_update( + this_model_output=model_output_convert, + last_sample=self.last_sample, + this_sample=sample, + order=self.this_order, + sigma_before=sigma_before, + sigma=sigma, + ) + + if model_outputs is not None and timestep_list is not None: + model_outputs[-1] = model_output_convert + self.model_outputs = model_outputs[1:] + self.timestep_list = timestep_list[1:] + else: + for i in range(self.config.solver_order - 1): + self.model_outputs[i] = self.model_outputs[i + 1] + self.timestep_list[i] = self.timestep_list[i + 1] + self.model_outputs[-1] = model_output_convert + self.timestep_list[-1] = timestep + + if self.config.lower_order_final: + this_order = min(self.config.solver_order, len(self.timesteps) - self.step_index) + else: + this_order = self.config.solver_order + self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep + assert self.this_order > 0 + + self.last_sample = sample + prev_sample = self.multistep_uni_p_bh_update( + model_output=model_output, # pass the original non-converted model output, in case solver-p is used + sample=sample, + order=self.this_order, + sigma=sigma, + sigma_next=sigma_next, + ) + + if cus_lower_order_num is None: + if self.lower_order_nums < self.config.solver_order: + self.lower_order_nums += 1 + + # upon completion increase step index by one + if cus_step_index is None: + self._step_index += 1 + + if not return_dict: + return (prev_sample, model_outputs, self.last_sample, self.this_order) + + return HeliosSchedulerOutput( + prev_sample=prev_sample, + model_outputs=model_outputs, + last_sample=self.last_sample, + this_order=self.this_order, + ) + + # ---------------------------------- For DMD ---------------------------------- + def add_noise(self, original_samples, noise, timestep, sigmas, timesteps): + sigmas = sigmas.to(noise.device) + timesteps = timesteps.to(noise.device) + timestep_id = torch.argmin((timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1) + sigma = sigmas[timestep_id].reshape(-1, 1, 1, 1, 1) + sample = (1 - sigma) * original_samples + sigma * noise + return sample.type_as(noise) + + def convert_flow_pred_to_x0(self, flow_pred, xt, timestep, sigmas, timesteps): + # use higher precision for calculations + original_dtype = flow_pred.dtype + device = flow_pred.device + flow_pred, xt, sigmas, timesteps = (x.double().to(device) for x in (flow_pred, xt, sigmas, timesteps)) + + timestep_id = torch.argmin((timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1) + sigma_t = sigmas[timestep_id].reshape(-1, 1, 1, 1, 1) + x0_pred = xt - sigma_t * flow_pred + return x0_pred.to(original_dtype) + + def step_dmd( + self, + model_output: torch.FloatTensor, + timestep: float | torch.FloatTensor = None, + sample: torch.FloatTensor = None, + generator: torch.Generator | None = None, + return_dict: bool = True, + cur_sampling_step: int = 0, + dmd_noisy_tensor: torch.FloatTensor | None = None, + dmd_sigmas: torch.FloatTensor | None = None, + dmd_timesteps: torch.FloatTensor | None = None, + all_timesteps: torch.FloatTensor | None = None, + ): + pred_image_or_video = self.convert_flow_pred_to_x0( + flow_pred=model_output, + xt=sample, + timestep=torch.full((model_output.shape[0],), timestep, dtype=torch.long, device=model_output.device), + sigmas=dmd_sigmas, + timesteps=dmd_timesteps, + ) + if cur_sampling_step < len(all_timesteps) - 1: + prev_sample = self.add_noise( + pred_image_or_video, + dmd_noisy_tensor, + torch.full( + (model_output.shape[0],), + all_timesteps[cur_sampling_step + 1], + dtype=torch.long, + device=model_output.device, + ), + sigmas=dmd_sigmas, + timesteps=dmd_timesteps, + ) + else: + prev_sample = pred_image_or_video + + if not return_dict: + return (prev_sample,) + + return HeliosSchedulerOutput(prev_sample=prev_sample) + + # ---------------------------------- Merge ---------------------------------- + def step( + self, + model_output: torch.FloatTensor, + timestep: float | torch.FloatTensor = None, + sample: torch.FloatTensor = None, + generator: torch.Generator | None = None, + return_dict: bool = True, + # For DMD + cur_sampling_step: int = 0, + dmd_noisy_tensor: torch.FloatTensor | None = None, + dmd_sigmas: torch.FloatTensor | None = None, + dmd_timesteps: torch.FloatTensor | None = None, + all_timesteps: torch.FloatTensor | None = None, + ) -> HeliosSchedulerOutput | tuple: + if self.config.scheduler_type == "euler": + return self.step_euler( + model_output=model_output, + timestep=timestep, + sample=sample, + generator=generator, + return_dict=return_dict, + ) + elif self.config.scheduler_type == "unipc": + return self.step_unipc( + model_output=model_output, + timestep=timestep, + sample=sample, + return_dict=return_dict, + ) + elif self.config.scheduler_type == "dmd": + return self.step_dmd( + model_output=model_output, + timestep=timestep, + sample=sample, + generator=generator, + return_dict=return_dict, + cur_sampling_step=cur_sampling_step, + dmd_noisy_tensor=dmd_noisy_tensor, + dmd_sigmas=dmd_sigmas, + dmd_timesteps=dmd_timesteps, + all_timesteps=all_timesteps, + ) + else: + raise NotImplementedError + + def reset_scheduler_history(self): + self.model_outputs = [None] * self.config.solver_order + self.timestep_list = [None] * self.config.solver_order + self.lower_order_nums = 0 + self.disable_corrector = self.config.disable_corrector + self.solver_p = self.config.solver_p + self.last_sample = None + self._step_index = None + self._begin_index = None + + def __len__(self): + return self.config.num_train_timesteps diff --git a/Helios/helios/diffusers_version/transformer_helios_diffusers.py b/Helios/helios/diffusers_version/transformer_helios_diffusers.py new file mode 100644 index 0000000000000000000000000000000000000000..aec1d755e2a3d2407d6807fce7aab66626a6aef8 --- /dev/null +++ b/Helios/helios/diffusers_version/transformer_helios_diffusers.py @@ -0,0 +1,825 @@ +# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from functools import lru_cache +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin +from diffusers.models._modeling_parallel import ContextParallelInput, ContextParallelOutput +from diffusers.models.attention import AttentionMixin, AttentionModuleMixin, FeedForward +from diffusers.models.attention_dispatch import dispatch_attention_fn +from diffusers.models.cache_utils import CacheMixin +from diffusers.models.embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps +from diffusers.models.modeling_outputs import Transformer2DModelOutput +from diffusers.models.modeling_utils import ModelMixin +from diffusers.models.normalization import FP32LayerNorm +from diffusers.utils import apply_lora_scale, logging +from diffusers.utils.torch_utils import maybe_allow_in_graph + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def pad_for_3d_conv(x, kernel_size): + b, c, t, h, w = x.shape + pt, ph, pw = kernel_size + pad_t = (pt - (t % pt)) % pt + pad_h = (ph - (h % ph)) % ph + pad_w = (pw - (w % pw)) % pw + return torch.nn.functional.pad(x, (0, pad_w, 0, pad_h, 0, pad_t), mode="replicate") + + +def center_down_sample_3d(x, kernel_size): + return torch.nn.functional.avg_pool3d(x, kernel_size, stride=kernel_size) + + +def apply_rotary_emb_transposed( + hidden_states: torch.Tensor, + freqs_cis: torch.Tensor, +): + x_1, x_2 = hidden_states.unflatten(-1, (-1, 2)).unbind(-1) + cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1) + out = torch.empty_like(hidden_states) + out[..., 0::2] = x_1 * cos[..., 0::2] - x_2 * sin[..., 1::2] + out[..., 1::2] = x_1 * sin[..., 1::2] + x_2 * cos[..., 0::2] + return out.type_as(hidden_states) + + +def _get_qkv_projections(attn: "HeliosAttention", hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor): + # encoder_hidden_states is only passed for cross-attention + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + + if attn.fused_projections: + if not attn.is_cross_attention: + # In self-attention layers, we can fuse the entire QKV projection into a single linear + query, key, value = attn.to_qkv(hidden_states).chunk(3, dim=-1) + else: + # In cross-attention layers, we can only fuse the KV projections into a single linear + query = attn.to_q(hidden_states) + key, value = attn.to_kv(encoder_hidden_states).chunk(2, dim=-1) + else: + query = attn.to_q(hidden_states) + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + return query, key, value + + +class HeliosOutputNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine: bool = False): + super().__init__() + self.scale_shift_table = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5) + self.norm = FP32LayerNorm(dim, eps, elementwise_affine=False) + + def forward(self, hidden_states: torch.Tensor, temb: torch.Tensor, original_context_length: int): + temb = temb[:, -original_context_length:, :] + shift, scale = (self.scale_shift_table.unsqueeze(0).to(temb.device) + temb.unsqueeze(2)).chunk(2, dim=2) + shift, scale = shift.squeeze(2).to(hidden_states.device), scale.squeeze(2).to(hidden_states.device) + hidden_states = hidden_states[:, -original_context_length:, :] + hidden_states = (self.norm(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states) + return hidden_states + + +class HeliosAttnProcessor: + _attention_backend = None + _parallel_config = None + + def __init__(self): + if not hasattr(F, "scaled_dot_product_attention"): + raise ImportError( + "HeliosAttnProcessor requires PyTorch 2.0. To use it, please upgrade PyTorch to version 2.0 or higher." + ) + + def __call__( + self, + attn: "HeliosAttention", + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, + original_context_length: int = None, + ) -> torch.Tensor: + query, key, value = _get_qkv_projections(attn, hidden_states, encoder_hidden_states) + + query = attn.norm_q(query) + key = attn.norm_k(key) + + query = query.unflatten(2, (attn.heads, -1)) + key = key.unflatten(2, (attn.heads, -1)) + value = value.unflatten(2, (attn.heads, -1)) + + if rotary_emb is not None: + query = apply_rotary_emb_transposed(query, rotary_emb) + key = apply_rotary_emb_transposed(key, rotary_emb) + + if not attn.is_cross_attention and attn.is_amplify_history: + history_seq_len = hidden_states.shape[1] - original_context_length + + if history_seq_len > 0: + scale_key = 1.0 + torch.sigmoid(attn.history_key_scale) * (attn.max_scale - 1.0) + if attn.history_scale_mode == "per_head": + scale_key = scale_key.view(1, 1, -1, 1) + key = torch.cat([key[:, :history_seq_len] * scale_key, key[:, history_seq_len:]], dim=1) + + hidden_states = dispatch_attention_fn( + query, + key, + value, + attn_mask=attention_mask, + dropout_p=0.0, + is_causal=False, + backend=self._attention_backend, + # Reference: https://github.com/huggingface/diffusers/pull/12909 + parallel_config=(self._parallel_config if encoder_hidden_states is None else None), + ) + hidden_states = hidden_states.flatten(2, 3) + hidden_states = hidden_states.type_as(query) + + hidden_states = attn.to_out[0](hidden_states) + hidden_states = attn.to_out[1](hidden_states) + return hidden_states + + +class HeliosAttention(torch.nn.Module, AttentionModuleMixin): + _default_processor_cls = HeliosAttnProcessor + _available_processors = [HeliosAttnProcessor] + + def __init__( + self, + dim: int, + heads: int = 8, + dim_head: int = 64, + eps: float = 1e-5, + dropout: float = 0.0, + added_kv_proj_dim: int | None = None, + cross_attention_dim_head: int | None = None, + processor=None, + is_cross_attention=None, + is_amplify_history=False, + history_scale_mode="per_head", # [scalar, per_head] + ): + super().__init__() + + self.inner_dim = dim_head * heads + self.heads = heads + self.added_kv_proj_dim = added_kv_proj_dim + self.cross_attention_dim_head = cross_attention_dim_head + self.kv_inner_dim = self.inner_dim if cross_attention_dim_head is None else cross_attention_dim_head * heads + + self.to_q = torch.nn.Linear(dim, self.inner_dim, bias=True) + self.to_k = torch.nn.Linear(dim, self.kv_inner_dim, bias=True) + self.to_v = torch.nn.Linear(dim, self.kv_inner_dim, bias=True) + self.to_out = torch.nn.ModuleList( + [ + torch.nn.Linear(self.inner_dim, dim, bias=True), + torch.nn.Dropout(dropout), + ] + ) + self.norm_q = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True) + self.norm_k = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True) + + self.add_k_proj = self.add_v_proj = None + if added_kv_proj_dim is not None: + self.add_k_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True) + self.add_v_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True) + self.norm_added_k = torch.nn.RMSNorm(dim_head * heads, eps=eps) + + if is_cross_attention is not None: + self.is_cross_attention = is_cross_attention + else: + self.is_cross_attention = cross_attention_dim_head is not None + + self.set_processor(processor) + + self.is_amplify_history = is_amplify_history + if is_amplify_history: + if history_scale_mode == "scalar": + self.history_key_scale = nn.Parameter(torch.ones(1)) + elif history_scale_mode == "per_head": + self.history_key_scale = nn.Parameter(torch.ones(heads)) + else: + raise ValueError(f"Unknown history_scale_mode: {history_scale_mode}") + self.history_scale_mode = history_scale_mode + self.max_scale = 10.0 + + def fuse_projections(self): + if getattr(self, "fused_projections", False): + return + + if not self.is_cross_attention: + concatenated_weights = torch.cat([self.to_q.weight.data, self.to_k.weight.data, self.to_v.weight.data]) + concatenated_bias = torch.cat([self.to_q.bias.data, self.to_k.bias.data, self.to_v.bias.data]) + out_features, in_features = concatenated_weights.shape + with torch.device("meta"): + self.to_qkv = nn.Linear(in_features, out_features, bias=True) + self.to_qkv.load_state_dict( + {"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True + ) + else: + concatenated_weights = torch.cat([self.to_k.weight.data, self.to_v.weight.data]) + concatenated_bias = torch.cat([self.to_k.bias.data, self.to_v.bias.data]) + out_features, in_features = concatenated_weights.shape + with torch.device("meta"): + self.to_kv = nn.Linear(in_features, out_features, bias=True) + self.to_kv.load_state_dict( + {"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True + ) + + if self.added_kv_proj_dim is not None: + concatenated_weights = torch.cat([self.add_k_proj.weight.data, self.add_v_proj.weight.data]) + concatenated_bias = torch.cat([self.add_k_proj.bias.data, self.add_v_proj.bias.data]) + out_features, in_features = concatenated_weights.shape + with torch.device("meta"): + self.to_added_kv = nn.Linear(in_features, out_features, bias=True) + self.to_added_kv.load_state_dict( + {"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True + ) + + self.fused_projections = True + + @torch.no_grad() + def unfuse_projections(self): + if not getattr(self, "fused_projections", False): + return + + if hasattr(self, "to_qkv"): + delattr(self, "to_qkv") + if hasattr(self, "to_kv"): + delattr(self, "to_kv") + if hasattr(self, "to_added_kv"): + delattr(self, "to_added_kv") + + self.fused_projections = False + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, + original_context_length: int = None, + **kwargs, + ) -> torch.Tensor: + return self.processor( + self, + hidden_states, + encoder_hidden_states, + attention_mask, + rotary_emb, + original_context_length, + **kwargs, + ) + + +class HeliosTimeTextEmbedding(nn.Module): + def __init__( + self, + dim: int, + time_freq_dim: int, + time_proj_dim: int, + text_embed_dim: int, + ): + super().__init__() + + self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0) + self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim) + self.act_fn = nn.SiLU() + self.time_proj = nn.Linear(dim, time_proj_dim) + self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh") + + def forward( + self, + timestep: torch.Tensor, + encoder_hidden_states: torch.Tensor | None = None, + is_return_encoder_hidden_states: bool = True, + ): + timestep = self.timesteps_proj(timestep) + + time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype + if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8: + timestep = timestep.to(time_embedder_dtype) + temb = self.time_embedder(timestep).type_as(encoder_hidden_states) + timestep_proj = self.time_proj(self.act_fn(temb)) + + if encoder_hidden_states is not None and is_return_encoder_hidden_states: + encoder_hidden_states = self.text_embedder(encoder_hidden_states) + + return temb, timestep_proj, encoder_hidden_states + + +class HeliosRotaryPosEmbed(nn.Module): + def __init__(self, rope_dim, theta): + super().__init__() + self.DT, self.DY, self.DX = rope_dim + self.theta = theta + self.register_buffer("freqs_base_t", self._get_freqs_base(self.DT), persistent=False) + self.register_buffer("freqs_base_y", self._get_freqs_base(self.DY), persistent=False) + self.register_buffer("freqs_base_x", self._get_freqs_base(self.DX), persistent=False) + + def _get_freqs_base(self, dim): + return 1.0 / (self.theta ** (torch.arange(0, dim, 2, dtype=torch.float32)[: (dim // 2)] / dim)) + + @torch.no_grad() + def get_frequency_batched(self, freqs_base, pos): + freqs = torch.einsum("d,bthw->dbthw", freqs_base, pos) + freqs = freqs.repeat_interleave(2, dim=0) + return freqs.cos(), freqs.sin() + + @torch.no_grad() + @lru_cache(maxsize=32) + def _get_spatial_meshgrid(self, height, width, device_str): + device = torch.device(device_str) + grid_y_coords = torch.arange(height, device=device, dtype=torch.float32) + grid_x_coords = torch.arange(width, device=device, dtype=torch.float32) + grid_y, grid_x = torch.meshgrid(grid_y_coords, grid_x_coords, indexing="ij") + return grid_y, grid_x + + @torch.no_grad() + def forward(self, frame_indices, height, width, device): + batch_size = frame_indices.shape[0] + num_frames = frame_indices.shape[1] + + frame_indices = frame_indices.to(device=device, dtype=torch.float32) + grid_y, grid_x = self._get_spatial_meshgrid(height, width, str(device)) + + grid_t = frame_indices[:, :, None, None].expand(batch_size, num_frames, height, width) + grid_y_batch = grid_y[None, None, :, :].expand(batch_size, num_frames, -1, -1) + grid_x_batch = grid_x[None, None, :, :].expand(batch_size, num_frames, -1, -1) + + freqs_cos_t, freqs_sin_t = self.get_frequency_batched(self.freqs_base_t, grid_t) + freqs_cos_y, freqs_sin_y = self.get_frequency_batched(self.freqs_base_y, grid_y_batch) + freqs_cos_x, freqs_sin_x = self.get_frequency_batched(self.freqs_base_x, grid_x_batch) + + result = torch.cat([freqs_cos_t, freqs_cos_y, freqs_cos_x, freqs_sin_t, freqs_sin_y, freqs_sin_x], dim=0) + + return result.permute(1, 0, 2, 3, 4) + + +@maybe_allow_in_graph +class HeliosTransformerBlock(nn.Module): + def __init__( + self, + dim: int, + ffn_dim: int, + num_heads: int, + qk_norm: str = "rms_norm_across_heads", + cross_attn_norm: bool = False, + eps: float = 1e-6, + added_kv_proj_dim: int | None = None, + guidance_cross_attn: bool = False, + is_amplify_history: bool = False, + history_scale_mode: str = "per_head", # [scalar, per_head] + ): + super().__init__() + + # 1. Self-attention + self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False) + self.attn1 = HeliosAttention( + dim=dim, + heads=num_heads, + dim_head=dim // num_heads, + eps=eps, + cross_attention_dim_head=None, + processor=HeliosAttnProcessor(), + is_amplify_history=is_amplify_history, + history_scale_mode=history_scale_mode, + ) + + # 2. Cross-attention + self.attn2 = HeliosAttention( + dim=dim, + heads=num_heads, + dim_head=dim // num_heads, + eps=eps, + added_kv_proj_dim=added_kv_proj_dim, + cross_attention_dim_head=dim // num_heads, + processor=HeliosAttnProcessor(), + ) + self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity() + + # 3. Feed-forward + self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate") + self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False) + + self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5) + + # 4. Guidance cross-attention + self.guidance_cross_attn = guidance_cross_attn + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor, + temb: torch.Tensor, + rotary_emb: torch.Tensor, + original_context_length: int = None, + ) -> torch.Tensor: + if temb.ndim == 4: + shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = ( + self.scale_shift_table.unsqueeze(0) + temb.float() + ).chunk(6, dim=2) + # batch_size, seq_len, 1, inner_dim + shift_msa = shift_msa.squeeze(2) + scale_msa = scale_msa.squeeze(2) + gate_msa = gate_msa.squeeze(2) + c_shift_msa = c_shift_msa.squeeze(2) + c_scale_msa = c_scale_msa.squeeze(2) + c_gate_msa = c_gate_msa.squeeze(2) + else: + shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = ( + self.scale_shift_table + temb.float() + ).chunk(6, dim=1) + + # 1. Self-attention + norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states) + attn_output = self.attn1( + norm_hidden_states, + None, + None, + rotary_emb, + original_context_length, + ) + hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states) + + # 2. Cross-attention + if self.guidance_cross_attn: + history_seq_len = hidden_states.shape[1] - original_context_length + + history_hidden_states, hidden_states = torch.split( + hidden_states, [history_seq_len, original_context_length], dim=1 + ) + norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states) + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states, + None, + None, + original_context_length, + ) + hidden_states = hidden_states + attn_output + hidden_states = torch.cat([history_hidden_states, hidden_states], dim=1) + else: + norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states) + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states, + None, + None, + original_context_length, + ) + hidden_states = hidden_states + attn_output + + # 3. Feed-forward + norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as( + hidden_states + ) + ff_output = self.ffn(norm_hidden_states) + hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states) + + return hidden_states + + +class HeliosTransformer3DModel( + ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin, AttentionMixin +): + r""" + A Transformer model for video-like data used in the Helios model. + + Args: + patch_size (`tuple[int]`, defaults to `(1, 2, 2)`): + 3D patch dimensions for video embedding (t_patch, h_patch, w_patch). + num_attention_heads (`int`, defaults to `40`): + Fixed length for text embeddings. + attention_head_dim (`int`, defaults to `128`): + The number of channels in each head. + in_channels (`int`, defaults to `16`): + The number of channels in the input. + out_channels (`int`, defaults to `16`): + The number of channels in the output. + text_dim (`int`, defaults to `512`): + Input dimension for text embeddings. + freq_dim (`int`, defaults to `256`): + Dimension for sinusoidal time embeddings. + ffn_dim (`int`, defaults to `13824`): + Intermediate dimension in feed-forward network. + num_layers (`int`, defaults to `40`): + The number of layers of transformer blocks to use. + window_size (`tuple[int]`, defaults to `(-1, -1)`): + Window size for local attention (-1 indicates global attention). + cross_attn_norm (`bool`, defaults to `True`): + Enable cross-attention normalization. + qk_norm (`bool`, defaults to `True`): + Enable query/key normalization. + eps (`float`, defaults to `1e-6`): + Epsilon value for normalization layers. + add_img_emb (`bool`, defaults to `False`): + Whether to use img_emb. + added_kv_proj_dim (`int`, *optional*, defaults to `None`): + The number of channels to use for the added key and value projections. If `None`, no projection is used. + """ + + _supports_gradient_checkpointing = True + _skip_layerwise_casting_patterns = [ + "patch_embedding", + "patch_short", + "patch_mid", + "patch_long", + "condition_embedder", + "norm", + ] + _no_split_modules = ["HeliosTransformerBlock", "HeliosOutputNorm"] + _keep_in_fp32_modules = [ + "time_embedder", + "scale_shift_table", + "norm1", + "norm2", + "norm3", + "history_key_scale", + ] + _keys_to_ignore_on_load_unexpected = ["norm_added_q"] + _repeated_blocks = ["HeliosTransformerBlock"] + _cp_plan = { + # Input split at attn level and ffn level. + "blocks.*.attn1": { + "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), + "rotary_emb": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), + }, + "blocks.*.attn2": { + "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), + }, + "blocks.*.ffn": { + "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), + }, + # Output gather at attn level and ffn level. + **{f"blocks.{i}.attn1": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)}, + **{f"blocks.{i}.attn2": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)}, + **{f"blocks.{i}.ffn": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)}, + } + + @register_to_config + def __init__( + self, + patch_size: tuple[int, ...] = (1, 2, 2), + num_attention_heads: int = 40, + attention_head_dim: int = 128, + in_channels: int = 16, + out_channels: int = 16, + text_dim: int = 4096, + freq_dim: int = 256, + ffn_dim: int = 13824, + num_layers: int = 40, + cross_attn_norm: bool = True, + qk_norm: str | None = "rms_norm_across_heads", + eps: float = 1e-6, + added_kv_proj_dim: int | None = None, + rope_dim: tuple[int, ...] = (44, 42, 42), + rope_theta: float = 10000.0, + guidance_cross_attn: bool = True, + zero_history_timestep: bool = True, + has_multi_term_memory_patch: bool = True, + is_amplify_history: bool = False, + history_scale_mode: str = "per_head", # [scalar, per_head] + ) -> None: + super().__init__() + + inner_dim = num_attention_heads * attention_head_dim + out_channels = out_channels or in_channels + + # 1. Patch & position embedding + self.rope = HeliosRotaryPosEmbed(rope_dim=rope_dim, theta=rope_theta) + self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size) + + # 2. Initial Multi Term Memory Patch + self.zero_history_timestep = zero_history_timestep + self.inner_dim = inner_dim + if has_multi_term_memory_patch: + self.patch_short = nn.Conv3d(in_channels, self.inner_dim, kernel_size=patch_size, stride=patch_size) + self.patch_mid = nn.Conv3d( + in_channels, + self.inner_dim, + kernel_size=tuple(2 * p for p in patch_size), + stride=tuple(2 * p for p in patch_size), + ) + self.patch_long = nn.Conv3d( + in_channels, + self.inner_dim, + kernel_size=tuple(4 * p for p in patch_size), + stride=tuple(4 * p for p in patch_size), + ) + + # 3. Condition embeddings + self.condition_embedder = HeliosTimeTextEmbedding( + dim=inner_dim, + time_freq_dim=freq_dim, + time_proj_dim=inner_dim * 6, + text_embed_dim=text_dim, + ) + + # 4. Transformer blocks + self.blocks = nn.ModuleList( + [ + HeliosTransformerBlock( + inner_dim, + ffn_dim, + num_attention_heads, + qk_norm, + cross_attn_norm, + eps, + added_kv_proj_dim, + guidance_cross_attn=guidance_cross_attn, + is_amplify_history=is_amplify_history, + history_scale_mode=history_scale_mode, + ) + for _ in range(num_layers) + ] + ) + + # 5. Output norm & projection + self.norm_out = HeliosOutputNorm(inner_dim, eps, elementwise_affine=False) + self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size)) + + self.gradient_checkpointing = False + + @apply_lora_scale("attention_kwargs") + def forward( + self, + hidden_states: torch.Tensor, + timestep: torch.LongTensor, + encoder_hidden_states: torch.Tensor, + # ------------ Stage 1 ------------ + indices_hidden_states=None, + indices_latents_history_short=None, + indices_latents_history_mid=None, + indices_latents_history_long=None, + latents_history_short=None, + latents_history_mid=None, + latents_history_long=None, + return_dict: bool = True, + attention_kwargs: dict[str, Any] | None = None, + ) -> torch.Tensor | dict[str, torch.Tensor]: + # 1. Input + batch_size = hidden_states.shape[0] + p_t, p_h, p_w = self.config.patch_size + + # 2. Process noisy latents + hidden_states = self.patch_embedding(hidden_states) + _, _, post_patch_num_frames, post_patch_height, post_patch_width = hidden_states.shape + + if indices_hidden_states is None: + indices_hidden_states = torch.arange(0, post_patch_num_frames).unsqueeze(0).expand(batch_size, -1) + + hidden_states = hidden_states.flatten(2).transpose(1, 2) + rotary_emb = self.rope( + frame_indices=indices_hidden_states, + height=post_patch_height, + width=post_patch_width, + device=hidden_states.device, + ) + rotary_emb = rotary_emb.flatten(2).transpose(1, 2) + original_context_length = hidden_states.shape[1] + + # 3. Process short history latents + if latents_history_short is not None and indices_latents_history_short is not None: + latents_history_short = latents_history_short.to(hidden_states) + latents_history_short = self.patch_short(latents_history_short) + _, _, _, H1, W1 = latents_history_short.shape + latents_history_short = latents_history_short.flatten(2).transpose(1, 2) + + rotary_emb_history_short = self.rope( + frame_indices=indices_latents_history_short, + height=H1, + width=W1, + device=latents_history_short.device, + ) + rotary_emb_history_short = rotary_emb_history_short.flatten(2).transpose(1, 2) + + hidden_states = torch.cat([latents_history_short, hidden_states], dim=1) + rotary_emb = torch.cat([rotary_emb_history_short, rotary_emb], dim=1) + + # 4. Process mid history latents + if latents_history_mid is not None and indices_latents_history_mid is not None: + latents_history_mid = latents_history_mid.to(hidden_states) + latents_history_mid = pad_for_3d_conv(latents_history_mid, (2, 4, 4)) + latents_history_mid = self.patch_mid(latents_history_mid) + latents_history_mid = latents_history_mid.flatten(2).transpose(1, 2) + + rotary_emb_history_mid = self.rope( + frame_indices=indices_latents_history_mid, + height=H1, + width=W1, + device=latents_history_mid.device, + ) + rotary_emb_history_mid = pad_for_3d_conv(rotary_emb_history_mid, (2, 2, 2)) + rotary_emb_history_mid = center_down_sample_3d(rotary_emb_history_mid, (2, 2, 2)) + rotary_emb_history_mid = rotary_emb_history_mid.flatten(2).transpose(1, 2) + + hidden_states = torch.cat([latents_history_mid, hidden_states], dim=1) + rotary_emb = torch.cat([rotary_emb_history_mid, rotary_emb], dim=1) + + # 5. Process long history latents + if latents_history_long is not None and indices_latents_history_long is not None: + latents_history_long = latents_history_long.to(hidden_states) + latents_history_long = pad_for_3d_conv(latents_history_long, (4, 8, 8)) + latents_history_long = self.patch_long(latents_history_long) + latents_history_long = latents_history_long.flatten(2).transpose(1, 2) + + rotary_emb_history_long = self.rope( + frame_indices=indices_latents_history_long, + height=H1, + width=W1, + device=latents_history_long.device, + ) + rotary_emb_history_long = pad_for_3d_conv(rotary_emb_history_long, (4, 4, 4)) + rotary_emb_history_long = center_down_sample_3d(rotary_emb_history_long, (4, 4, 4)) + rotary_emb_history_long = rotary_emb_history_long.flatten(2).transpose(1, 2) + + hidden_states = torch.cat([latents_history_long, hidden_states], dim=1) + rotary_emb = torch.cat([rotary_emb_history_long, rotary_emb], dim=1) + + history_context_length = hidden_states.shape[1] - original_context_length + + if indices_hidden_states is not None and self.zero_history_timestep: + timestep_t0 = torch.zeros((1), dtype=timestep.dtype, device=timestep.device) + temb_t0, timestep_proj_t0, _ = self.condition_embedder( + timestep_t0, encoder_hidden_states, is_return_encoder_hidden_states=False + ) + temb_t0 = temb_t0.unsqueeze(1).expand(batch_size, history_context_length, -1) + timestep_proj_t0 = ( + timestep_proj_t0.unflatten(-1, (6, -1)) + .view(1, 6, 1, -1) + .expand(batch_size, -1, history_context_length, -1) + ) + + temb, timestep_proj, encoder_hidden_states = self.condition_embedder(timestep, encoder_hidden_states) + timestep_proj = timestep_proj.unflatten(-1, (6, -1)) + + if indices_hidden_states is not None and not self.zero_history_timestep: + main_repeat_size = hidden_states.shape[1] + else: + main_repeat_size = original_context_length + temb = temb.view(batch_size, 1, -1).expand(batch_size, main_repeat_size, -1) + timestep_proj = timestep_proj.view(batch_size, 6, 1, -1).expand(batch_size, 6, main_repeat_size, -1) + + if indices_hidden_states is not None and self.zero_history_timestep: + temb = torch.cat([temb_t0, temb], dim=1) + timestep_proj = torch.cat([timestep_proj_t0, timestep_proj], dim=2) + + if timestep_proj.ndim == 4: + timestep_proj = timestep_proj.permute(0, 2, 1, 3) + + # 6. Transformer blocks + hidden_states = hidden_states.contiguous() + encoder_hidden_states = encoder_hidden_states.contiguous() + rotary_emb = rotary_emb.contiguous() + if torch.is_grad_enabled() and self.gradient_checkpointing: + for block in self.blocks: + hidden_states = self._gradient_checkpointing_func( + block, + hidden_states, + encoder_hidden_states, + timestep_proj, + rotary_emb, + original_context_length, + ) + else: + for block in self.blocks: + hidden_states = block( + hidden_states, + encoder_hidden_states, + timestep_proj, + rotary_emb, + original_context_length, + ) + + # 7. Normalization + hidden_states = self.norm_out(hidden_states, temb, original_context_length) + hidden_states = self.proj_out(hidden_states) + + # 8. Unpatchify + hidden_states = hidden_states.reshape( + batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1 + ) + hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6) + output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3) + + if not return_dict: + return (output,) + + return Transformer2DModelOutput(sample=output) diff --git a/Helios/helios/modules/__init__.py b/Helios/helios/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/helios/modules/transformer_helios.py b/Helios/helios/modules/transformer_helios.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1c654962059958e0380ed93f93a9bc28e0385c --- /dev/null +++ b/Helios/helios/modules/transformer_helios.py @@ -0,0 +1,1913 @@ +# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import glob +import json +import math +import os +from functools import lru_cache +from typing import Any, Dict, List, Optional, Tuple, Union + +import einops +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin +from diffusers.models._modeling_parallel import ContextParallelInput, ContextParallelOutput +from diffusers.models.attention import AttentionMixin, AttentionModuleMixin, FeedForward +from diffusers.models.cache_utils import CacheMixin +from diffusers.models.embeddings import ( + PixArtAlphaTextProjection, + TimestepEmbedding, + Timesteps, +) +from diffusers.models.modeling_outputs import Transformer2DModelOutput +from diffusers.models.modeling_utils import ModelMixin +from diffusers.models.normalization import FP32LayerNorm +from diffusers.utils import apply_lora_scale, deprecate, logging +from diffusers.utils.torch_utils import maybe_allow_in_graph + +from .helios_kernels import attn_varlen_func, create_navit_attention_masks + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def pad_for_3d_conv(x, kernel_size): + b, c, t, h, w = x.shape + pt, ph, pw = kernel_size + pad_t = (pt - (t % pt)) % pt + pad_h = (ph - (h % ph)) % ph + pad_w = (pw - (w % pw)) % pw + return torch.nn.functional.pad(x, (0, pad_w, 0, pad_h, 0, pad_t), mode="replicate") + + +def center_down_sample_3d(x, kernel_size): + return torch.nn.functional.avg_pool3d(x, kernel_size, stride=kernel_size) + + +def apply_rotary_emb_transposed( + hidden_states: torch.Tensor, + freqs_cis: torch.Tensor, +): + x_1, x_2 = hidden_states.unflatten(-1, (-1, 2)).unbind(-1) + cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1) + out = torch.empty_like(hidden_states) + out[..., 0::2] = x_1 * cos[..., 0::2] - x_2 * sin[..., 1::2] + out[..., 1::2] = x_1 * sin[..., 1::2] + x_2 * cos[..., 0::2] + return out.type_as(hidden_states) + + +def _get_qkv_projections(attn: "HeliosAttention", hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor): + # encoder_hidden_states is only passed for cross-attention + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + + if attn.fused_projections: + if not attn.is_cross_attention: + # In self-attention layers, we can fuse the entire QKV projection into a single linear + query, key, value = attn.to_qkv(hidden_states).chunk(3, dim=-1) + else: + # In cross-attention layers, we can only fuse the KV projections into a single linear + query = attn.to_q(hidden_states) + key, value = attn.to_kv(encoder_hidden_states).chunk(2, dim=-1) + else: + query = attn.to_q(hidden_states) + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + return query, key, value + + +class Discriminator3DHead(nn.Module): + def __init__(self, input_channel, cond_map_dim=768): + super().__init__() + + self.head3d = nn.Sequential( + nn.Conv3d(input_channel, cond_map_dim, 3, stride=(1, 1, 1), padding=(1, 1, 1)), # [31, 8, 8] + nn.GroupNorm(32, cond_map_dim), + nn.SiLU(False), + nn.Conv3d(cond_map_dim, cond_map_dim, 4, stride=[2, 2, 2], padding=(1, 1, 1)), # [15, 4, 4] + nn.GroupNorm(32, cond_map_dim), + nn.SiLU(False), + nn.Conv3d(cond_map_dim, cond_map_dim, 4, stride=[2, 2, 2], padding=(1, 1, 1)), # [7, 2, 2] + nn.GroupNorm(32, cond_map_dim), + nn.SiLU(False), + nn.Conv3d(cond_map_dim, cond_map_dim, 3, stride=[2, 1, 1], padding=(1, 1, 1)), # [3, 2, 2] + nn.GroupNorm(32, cond_map_dim), + nn.SiLU(False), + nn.Conv3d(cond_map_dim, cond_map_dim, 3, stride=[2, 1, 1], padding=(1, 1, 1)), # [1, 2, 2] + nn.GroupNorm(32, cond_map_dim), + nn.SiLU(False), + nn.Conv3d( + cond_map_dim, cond_map_dim, kernel_size=[1, 3, 3], stride=[1, 1, 1], padding=(0, 1, 1) + ), # [b, 768, 1, 1, 2] + nn.GroupNorm(32, cond_map_dim), + nn.SiLU(False), + nn.AdaptiveAvgPool3d((1, 1, 1)), + nn.Flatten(), + nn.Linear(cond_map_dim, 1), + ) + + def forward(self, x): + return self.head3d(x) + + +class LoRALinearLayer(nn.Module): + def __init__( + self, + in_features: int, + out_features: int, + rank: int = 128, + device="cuda", + dtype: Optional[torch.dtype] = torch.float32, + ): + super().__init__() + self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype) + self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype) + self.rank = rank + self.out_features = out_features + self.in_features = in_features + + nn.init.normal_(self.down.weight, std=1 / rank) + nn.init.zeros_(self.up.weight) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + orig_dtype = hidden_states.dtype + dtype = self.down.weight.dtype + + down_hidden_states = self.down(hidden_states.to(dtype)) + up_hidden_states = self.up(down_hidden_states) + return up_hidden_states.to(orig_dtype) + + +class HeliosOutputNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine: bool = False): + super().__init__() + self.scale_shift_table = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5) + self.norm = FP32LayerNorm(dim, eps, elementwise_affine=False) + + def forward(self, hidden_states: torch.Tensor, temb: torch.Tensor, original_context_length: int): + temb = temb[:, -original_context_length:, :] + shift, scale = (self.scale_shift_table.unsqueeze(0).to(temb.device) + temb.unsqueeze(2)).chunk(2, dim=2) + shift, scale = shift.squeeze(2).to(hidden_states.device), scale.squeeze(2).to(hidden_states.device) + hidden_states = hidden_states[:, -original_context_length:, :] + hidden_states = (self.norm(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states) + return hidden_states + + +class HeliosAttnProcessor: + _attention_backend = None + _parallel_config = None + + def __init__(self): + if not hasattr(F, "scaled_dot_product_attention"): + raise ImportError( + "HeliosAttnProcessor requires PyTorch 2.0. To use it, please upgrade PyTorch to version 2.0 or higher." + ) + + self.kv_cache = None + self.cache_enabled = False + + def enable_cache(self): + self.cache_enabled = True + self.kv_cache = None + + def disable_cache(self): + self.cache_enabled = False + self.kv_cache = None + + def clear_cache(self): + self.kv_cache = None + + def __call__( + self, + attn: "HeliosAttention", + hidden_states: torch.Tensor, + encoder_hidden_states: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, + original_context_length: int = None, + original_context_length_list: list = None, + enable_navit: bool = False, + is_first_denoising_step: bool = False, + ) -> torch.Tensor: + use_cache = False + history_seq_len = None + enable_cross = attn.is_cross_attention + + if not enable_cross: + history_seq_len = (hidden_states.shape[1] - original_context_length) // len(original_context_length_list) + + if attn.restrict_self_attn: + use_cache = self.cache_enabled and not is_first_denoising_step and self.kv_cache is not None + assert not (use_cache and enable_navit), "Cache and NAViT are incompatible" + + if use_cache: + key_history = self.kv_cache["key_history"] + value_history = self.kv_cache["value_history"] + history_hidden_states = self.kv_cache["history_hidden_states"] + + hidden_states = hidden_states[:, history_seq_len:] + rotary_emb = rotary_emb[:, history_seq_len:] if rotary_emb is not None else None + + query, key, value = _get_qkv_projections(attn, hidden_states, encoder_hidden_states) + + query = attn.norm_q(query) + key = attn.norm_k(key) + + if attn.restrict_self_attn and not use_cache: + if enable_navit: + seq_start = 0 + num_seqs = len(original_context_length_list) + query_list = [None] * num_seqs + key_list = [None] * num_seqs + value_list = [None] * num_seqs + query_history_list = [None] * num_seqs + key_history_list = [None] * num_seqs + value_history_list = [None] * num_seqs + + if attn.restrict_lora: + history_hidden_states_list = [None] * num_seqs + + if rotary_emb is not None: + rotary_emb_list = [None] * num_seqs + history_rotary_emb_list = [None] * num_seqs + + for idx, cur_seq_len in enumerate(original_context_length_list[::-1]): + seq_end = seq_start + cur_seq_len + history_seq_len + + slice_qkv = slice(seq_start, seq_end) + cur_query = query[:, slice_qkv, :] + cur_key = key[:, slice_qkv, :] + cur_value = value[:, slice_qkv, :] + + query_history_list[idx] = cur_query[:, :history_seq_len] + query_list[idx] = cur_query[:, history_seq_len:] + + key_history_list[idx] = cur_key[:, :history_seq_len] + key_list[idx] = cur_key[:, history_seq_len:] + + value_history_list[idx] = cur_value[:, :history_seq_len] + value_list[idx] = cur_value[:, history_seq_len:] + + if attn.restrict_lora: + cur_hidden = hidden_states[:, slice_qkv, :] + history_hidden_states_list[idx] = cur_hidden[:, :history_seq_len] + + if rotary_emb is not None: + cur_rotary_emb = rotary_emb[:, slice_qkv, :] + history_rotary_emb_list[idx] = cur_rotary_emb[:, :history_seq_len] + rotary_emb_list[idx] = cur_rotary_emb[:, history_seq_len:] + + seq_start = seq_end + + query = torch.cat(query_list, dim=1) + key = torch.cat(key_list, dim=1) + value = torch.cat(value_list, dim=1) + query_history = torch.cat(query_history_list, dim=1) + key_history = torch.cat(key_history_list, dim=1) + value_history = torch.cat(value_history_list, dim=1) + + if attn.restrict_lora: + history_hidden_states = torch.cat(history_hidden_states_list, dim=1) + query_history = query_history + attn.q_loras(history_hidden_states) + key_history = key_history + attn.k_loras(history_hidden_states) + value_history = value_history + attn.v_loras(history_hidden_states) + + query_history = query_history.unflatten(2, (attn.heads, -1)) + key_history = key_history.unflatten(2, (attn.heads, -1)) + value_history = value_history.unflatten(2, (attn.heads, -1)) + + if rotary_emb is not None: + rotary_emb = torch.cat(rotary_emb_list, dim=1) + history_rotary_emb = torch.cat(history_rotary_emb_list, dim=1) + query_history = apply_rotary_emb_transposed(query_history, history_rotary_emb) + key_history = apply_rotary_emb_transposed(key_history, history_rotary_emb) + else: + history_hidden_states = hidden_states[:, :history_seq_len] + query_history, query = query[:, :history_seq_len], query[:, history_seq_len:] + key_history, key = key[:, :history_seq_len], key[:, history_seq_len:] + value_history, value = value[:, :history_seq_len], value[:, history_seq_len:] + + if attn.restrict_lora: + query_history = query_history + attn.q_loras(history_hidden_states) + key_history = key_history + attn.k_loras(history_hidden_states) + value_history = value_history + attn.v_loras(history_hidden_states) + + query_history = query_history.unflatten(2, (attn.heads, -1)) + key_history = key_history.unflatten(2, (attn.heads, -1)) + value_history = value_history.unflatten(2, (attn.heads, -1)) + + if rotary_emb is not None: + history_rotary_emb, rotary_emb = (rotary_emb[:, :history_seq_len], rotary_emb[:, history_seq_len:]) + query_history = apply_rotary_emb_transposed(query_history, history_rotary_emb) + key_history = apply_rotary_emb_transposed(key_history, history_rotary_emb) + + query = query.unflatten(2, (attn.heads, -1)) + key = key.unflatten(2, (attn.heads, -1)) + value = value.unflatten(2, (attn.heads, -1)) + + if rotary_emb is not None: + query = apply_rotary_emb_transposed(query, rotary_emb) + key = apply_rotary_emb_transposed(key, rotary_emb) + + if attn.restrict_self_attn: + if use_cache: + key = torch.cat([key_history, key], dim=1) + value = torch.cat([value_history, value], dim=1) + else: + if enable_navit: + num_seqs = len(original_context_length_list) + + key_list = [None] * num_seqs + value_list = [None] * num_seqs + + seq_start = 0 + seq_start_history = 0 + + for idx, cur_seq_len in enumerate(original_context_length_list[::-1]): + key_list[idx] = torch.cat( + [ + key_history[:, seq_start_history : seq_start_history + history_seq_len, :], + key[:, seq_start : seq_start + cur_seq_len, :], + ], + dim=1, + ) + + value_list[idx] = torch.cat( + [ + value_history[:, seq_start_history : seq_start_history + history_seq_len, :], + value[:, seq_start : seq_start + cur_seq_len, :], + ], + dim=1, + ) + + seq_start += cur_seq_len + seq_start_history += history_seq_len + + key = torch.cat(key_list, dim=1) + value = torch.cat(value_list, dim=1) + + history_hidden_states = attn_varlen_func( + query_history, + key_history, + value_history, + attention_mask=attention_mask[1], + ) + else: + key = torch.cat([key_history, key], dim=1) + value = torch.cat([value_history, value], dim=1) + + history_hidden_states = attn_varlen_func( + query_history, + key_history, + value_history, + ) + history_hidden_states = history_hidden_states.flatten(2, 3) + history_hidden_states = history_hidden_states.type_as(query) + + if self.cache_enabled and is_first_denoising_step and not enable_navit: + self.kv_cache = { + "key_history": key_history, + "value_history": value_history, + "history_hidden_states": history_hidden_states, + } + + if enable_cross and enable_navit: + key = key.repeat(1, len(original_context_length_list), 1, 1) + value = value.repeat(1, len(original_context_length_list), 1, 1) + + if not enable_cross and history_seq_len > 0 and attn.is_amplify_history: + scale_key = attn.get_scale_key() + if attn.history_scale_mode == "per_head": + scale_key = scale_key.view(1, 1, -1, 1) + + if enable_navit: + key_new = key.clone() + seq_start = 0 + for cur_seq_len in original_context_length_list[::-1]: + hist_slice = slice(seq_start, seq_start + history_seq_len) + key_new[:, hist_slice] = key[:, hist_slice] * scale_key + seq_start += history_seq_len + cur_seq_len + key = key_new + else: + key = torch.cat([key[:, :history_seq_len] * scale_key, key[:, history_seq_len:]], dim=1) + + hidden_states = attn_varlen_func( + query, + key, + value, + attention_mask=attention_mask[0] if isinstance(attention_mask, list) else attention_mask, + ) + hidden_states = hidden_states.flatten(2, 3) + hidden_states = hidden_states.type_as(query) + + if attn.restrict_self_attn: + if enable_navit: + num_seqs = len(original_context_length_list) + hidden_states_list = [None] * num_seqs + + seq_start = 0 + seq_start_history = 0 + + for idx, cur_seq_len in enumerate(original_context_length_list[::-1]): + hidden_states_list[idx] = torch.cat( + [ + history_hidden_states[:, seq_start_history : seq_start_history + history_seq_len, :], + hidden_states[:, seq_start : seq_start + cur_seq_len, :], + ], + dim=1, + ) + + seq_start += cur_seq_len + seq_start_history += history_seq_len + + hidden_states = torch.cat(hidden_states_list, dim=1) + else: + hidden_states = torch.cat([history_hidden_states, hidden_states], dim=1) + + hidden_states = attn.to_out[0](hidden_states) + hidden_states = attn.to_out[1](hidden_states) + return hidden_states + + +class HeliosAttnProcessor2_0: + def __new__(cls, *args, **kwargs): + deprecation_message = ( + "The HeliosAttnProcessor2_0 class is deprecated and will be removed in a future version. " + "Please use HeliosAttnProcessor instead. " + ) + deprecate("HeliosAttnProcessor2_0", "1.0.0", deprecation_message, standard_warn=False) + return HeliosAttnProcessor(*args, **kwargs) + + +class HeliosAttention(torch.nn.Module, AttentionModuleMixin): + _default_processor_cls = HeliosAttnProcessor + _available_processors = [HeliosAttnProcessor] + + def __init__( + self, + dim: int, + heads: int = 8, + dim_head: int = 64, + eps: float = 1e-5, + dropout: float = 0.0, + added_kv_proj_dim: Optional[int] = None, + cross_attention_dim_head: Optional[int] = None, + processor=None, + is_cross_attention=None, + restrict_self_attn=False, + is_train_restrict_lora=False, + restrict_lora=False, + restrict_lora_rank=128, + is_amplify_history=False, + history_scale_mode="per_head", # [scalar, per_head] + ): + super().__init__() + + self.inner_dim = dim_head * heads + self.heads = heads + self.added_kv_proj_dim = added_kv_proj_dim + self.cross_attention_dim_head = cross_attention_dim_head + self.kv_inner_dim = self.inner_dim if cross_attention_dim_head is None else cross_attention_dim_head * heads + + self.to_q = torch.nn.Linear(dim, self.inner_dim, bias=True) + self.to_k = torch.nn.Linear(dim, self.kv_inner_dim, bias=True) + self.to_v = torch.nn.Linear(dim, self.kv_inner_dim, bias=True) + self.to_out = torch.nn.ModuleList( + [ + torch.nn.Linear(self.inner_dim, dim, bias=True), + torch.nn.Dropout(dropout), + ] + ) + self.norm_q = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True) + self.norm_k = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True) + + self.add_k_proj = self.add_v_proj = None + if added_kv_proj_dim is not None: + self.add_k_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True) + self.add_v_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True) + self.norm_added_k = torch.nn.RMSNorm(dim_head * heads, eps=eps) + + if is_cross_attention is not None: + self.is_cross_attention = is_cross_attention + else: + self.is_cross_attention = cross_attention_dim_head is not None + + self.set_processor(processor) + + self.restrict_self_attn = restrict_self_attn + self.restrict_lora = restrict_lora + if restrict_lora: + self.init_lora(is_train=is_train_restrict_lora, lora_rank=restrict_lora_rank) + + self.is_amplify_history = is_amplify_history + if is_amplify_history: + if history_scale_mode == "scalar": + self.history_key_scale = nn.Parameter(torch.ones(1)) + elif history_scale_mode == "per_head": + self.history_key_scale = nn.Parameter(torch.ones(heads)) + else: + raise ValueError(f"Unknown history_scale_mode: {history_scale_mode}") + self.history_scale_mode = history_scale_mode + self.max_scale = 10.0 + self.register_buffer("_scale_cache", None) + + def get_scale_key(self): + if self.history_key_scale.requires_grad: + scale = 1.0 + torch.sigmoid(self.history_key_scale) * (self.max_scale - 1.0) + else: + if self._scale_cache is None: + self._scale_cache = 1.0 + torch.sigmoid(self.history_key_scale) * (self.max_scale - 1.0) + scale = self._scale_cache + return scale + + def init_lora(self, is_train=False, lora_rank=128): + dim = self.inner_dim + self.q_loras = LoRALinearLayer(dim, dim, rank=lora_rank) + self.k_loras = LoRALinearLayer(dim, dim, rank=lora_rank) + self.v_loras = LoRALinearLayer(dim, dim, rank=lora_rank) + + requires_grad = is_train + for lora in [self.q_loras, self.k_loras, self.v_loras]: + for param in lora.parameters(): + param.requires_grad = requires_grad + + def fuse_projections(self): + if getattr(self, "fused_projections", False): + return + + if not self.is_cross_attention: + concatenated_weights = torch.cat([self.to_q.weight.data, self.to_k.weight.data, self.to_v.weight.data]) + concatenated_bias = torch.cat([self.to_q.bias.data, self.to_k.bias.data, self.to_v.bias.data]) + out_features, in_features = concatenated_weights.shape + with torch.device("meta"): + self.to_qkv = nn.Linear(in_features, out_features, bias=True) + self.to_qkv.load_state_dict( + {"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True + ) + else: + concatenated_weights = torch.cat([self.to_k.weight.data, self.to_v.weight.data]) + concatenated_bias = torch.cat([self.to_k.bias.data, self.to_v.bias.data]) + out_features, in_features = concatenated_weights.shape + with torch.device("meta"): + self.to_kv = nn.Linear(in_features, out_features, bias=True) + self.to_kv.load_state_dict( + {"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True + ) + + if self.added_kv_proj_dim is not None: + concatenated_weights = torch.cat([self.add_k_proj.weight.data, self.add_v_proj.weight.data]) + concatenated_bias = torch.cat([self.add_k_proj.bias.data, self.add_v_proj.bias.data]) + out_features, in_features = concatenated_weights.shape + with torch.device("meta"): + self.to_added_kv = nn.Linear(in_features, out_features, bias=True) + self.to_added_kv.load_state_dict( + {"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True + ) + + self.fused_projections = True + + @torch.no_grad() + def unfuse_projections(self): + if not getattr(self, "fused_projections", False): + return + + if hasattr(self, "to_qkv"): + delattr(self, "to_qkv") + if hasattr(self, "to_kv"): + delattr(self, "to_kv") + if hasattr(self, "to_added_kv"): + delattr(self, "to_added_kv") + + self.fused_projections = False + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, + original_context_length: int = None, + original_context_length_list: list = None, + enable_navit: bool = False, + **kwargs, + ) -> torch.Tensor: + return self.processor( + self, + hidden_states, + encoder_hidden_states, + attention_mask, + rotary_emb, + original_context_length, + original_context_length_list, + enable_navit, + **kwargs, + ) + + +class HeliosTimeTextEmbedding(nn.Module): + def __init__( + self, + dim: int, + time_freq_dim: int, + time_proj_dim: int, + text_embed_dim: int, + ): + super().__init__() + + self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0) + self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim) + self.act_fn = nn.SiLU() + self.time_proj = nn.Linear(dim, time_proj_dim) + self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh") + + def forward( + self, + timestep: torch.Tensor, + encoder_hidden_states: Optional[torch.Tensor] = None, + is_return_encoder_hidden_states: bool = True, + ): + B = None + F = None + if timestep.ndim == 2: + B, F = timestep.shape + timestep = timestep.flatten() + + timestep = self.timesteps_proj(timestep) # torch.Size([2]) -> torch.Size([2, 256]) + + time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype + if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8: + timestep = timestep.to(time_embedder_dtype) + temb = self.time_embedder(timestep).type_as(encoder_hidden_states) # torch.Size([2, 1536]) + timestep_proj = self.time_proj(self.act_fn(temb)) # torch.Size([2, 9216] + + if B is not None and F is not None: + temb = temb.reshape(B, F, -1) + timestep_proj = timestep_proj.reshape(B, F, -1) + + if encoder_hidden_states is not None and is_return_encoder_hidden_states: + encoder_hidden_states = self.text_embedder(encoder_hidden_states) # torch.Size([2, 512, 1536]) + + return temb, timestep_proj, encoder_hidden_states + + +class HeliosRotaryPosEmbed(nn.Module): + def __init__(self, rope_dim, theta): + super().__init__() + self.DT, self.DY, self.DX = rope_dim + self.theta = theta + self.register_buffer("freqs_base_t", self._get_freqs_base(self.DT), persistent=False) + self.register_buffer("freqs_base_y", self._get_freqs_base(self.DY), persistent=False) + self.register_buffer("freqs_base_x", self._get_freqs_base(self.DX), persistent=False) + + def _get_freqs_base(self, dim): + return 1.0 / (self.theta ** (torch.arange(0, dim, 2, dtype=torch.float32)[: (dim // 2)] / dim)) + + @torch.no_grad() + def get_frequency_batched(self, freqs_base, pos): + freqs = torch.einsum("d,bthw->dbthw", freqs_base, pos) + freqs = freqs.repeat_interleave(2, dim=0) + return freqs.cos(), freqs.sin() + + @torch.no_grad() + @lru_cache(maxsize=32) + def _get_spatial_meshgrid(self, height, width, device_str): + device = torch.device(device_str) + gy = torch.arange(height, device=device, dtype=torch.float32) + gx = torch.arange(width, device=device, dtype=torch.float32) + GY, GX = torch.meshgrid(gy, gx, indexing="ij") + return GY, GX + + @torch.no_grad() + def forward(self, frame_indices, height, width, device): + B = frame_indices.shape[0] + T = frame_indices.shape[1] + + frame_indices = frame_indices.to(device=device, dtype=torch.float32) + GY, GX = self._get_spatial_meshgrid(height, width, str(device)) + + GT = frame_indices[:, :, None, None].expand(B, T, height, width) + GY_batch = GY[None, None, :, :].expand(B, T, -1, -1) + GX_batch = GX[None, None, :, :].expand(B, T, -1, -1) + + FCT, FST = self.get_frequency_batched(self.freqs_base_t, GT) + FCY, FSY = self.get_frequency_batched(self.freqs_base_y, GY_batch) + FCX, FSX = self.get_frequency_batched(self.freqs_base_x, GX_batch) + + result = torch.cat([FCT, FCY, FCX, FST, FSY, FSX], dim=0) + + return result.permute(1, 0, 2, 3, 4) + + +@maybe_allow_in_graph +class HeliosTransformerBlock(nn.Module): + def __init__( + self, + dim: int, + ffn_dim: int, + num_heads: int, + qk_norm: str = "rms_norm_across_heads", + cross_attn_norm: bool = False, + eps: float = 1e-6, + added_kv_proj_dim: Optional[int] = None, + restrict_self_attn: bool = False, + guidance_cross_attn: bool = False, + is_train_restrict_lora: bool = False, + restrict_lora: bool = False, + restrict_lora_rank: int = 128, + is_amplify_history: bool = False, + history_scale_mode: str = "per_head", # [scalar, per_head], + ): + super().__init__() + + # 1. Self-attention + self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False) + self.attn1 = HeliosAttention( + dim=dim, + heads=num_heads, + dim_head=dim // num_heads, + eps=eps, + cross_attention_dim_head=None, + processor=HeliosAttnProcessor(), + restrict_self_attn=restrict_self_attn, + is_train_restrict_lora=is_train_restrict_lora, + restrict_lora=restrict_lora, + restrict_lora_rank=restrict_lora_rank, + is_amplify_history=is_amplify_history, + history_scale_mode=history_scale_mode, + ) + + # 2. Cross-attention + self.attn2 = HeliosAttention( + dim=dim, + heads=num_heads, + dim_head=dim // num_heads, + eps=eps, + added_kv_proj_dim=added_kv_proj_dim, + cross_attention_dim_head=dim // num_heads, + processor=HeliosAttnProcessor(), + ) + self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity() + + # 3. Feed-forward + self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate") + self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False) + + self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5) + + # 4. Guidance cross-attention + self.guidance_cross_attn = guidance_cross_attn + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor, + temb: torch.Tensor, + rotary_emb: torch.Tensor, + navit_hidden_attention_mask: Optional[torch.Tensor] = None, + navit_encoder_attention_mask: Optional[torch.Tensor] = None, + original_context_length: int = None, + original_context_length_list: list = None, + is_first_denoising_step: bool = False, + ) -> torch.Tensor: + enable_navit = False + if len(original_context_length_list) > 1: + enable_navit = True + + if temb.ndim == 4: + shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = ( + self.scale_shift_table.unsqueeze(0) + temb.float() + ).chunk(6, dim=2) + # batch_size, seq_len, 1, inner_dim + shift_msa = shift_msa.squeeze(2) + scale_msa = scale_msa.squeeze(2) + gate_msa = gate_msa.squeeze(2) + c_shift_msa = c_shift_msa.squeeze(2) + c_scale_msa = c_scale_msa.squeeze(2) + c_gate_msa = c_gate_msa.squeeze(2) + else: + shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = ( + self.scale_shift_table + temb.float() + ).chunk(6, dim=1) + + # 1. Self-attention + norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states) + attn_output = self.attn1( + norm_hidden_states, + None, + navit_hidden_attention_mask, + rotary_emb, + original_context_length, + original_context_length_list, + enable_navit, + is_first_denoising_step=is_first_denoising_step, + ) + hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states) + + # 2. Cross-attention + if self.guidance_cross_attn: + history_seq_len = (hidden_states.shape[1] - original_context_length) // len(original_context_length_list) + + if enable_navit: + num_seqs = len(original_context_length_list) + + hidden_states_list = [None] * num_seqs + history_hidden_states_list = [None] * num_seqs + + seq_start = 0 + for idx, cur_seq_len in enumerate(original_context_length_list[::-1]): + seq_end = seq_start + cur_seq_len + history_seq_len + cur_hidden_states = hidden_states[:, seq_start:seq_end, :] + + history_hidden_states_list[idx] = cur_hidden_states[:, :history_seq_len] + hidden_states_list[idx] = cur_hidden_states[:, history_seq_len:] + + seq_start += cur_seq_len + history_seq_len + + hidden_states = torch.cat(hidden_states_list, dim=1) + + norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states) + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states, + navit_encoder_attention_mask, + None, + original_context_length, + original_context_length_list, + enable_navit, + ) + hidden_states = hidden_states + attn_output + + seq_start = 0 + for idx, cur_seq_len in enumerate(original_context_length_list[::-1]): + cur_hidden_states = hidden_states[:, seq_start : seq_start + cur_seq_len, :] + + hidden_states_list[idx] = torch.cat([history_hidden_states_list[idx], cur_hidden_states], dim=1) + + seq_start += cur_seq_len + + hidden_states = torch.cat(hidden_states_list, dim=1) + else: + history_hidden_states, hidden_states = ( + hidden_states[:, :history_seq_len], + hidden_states[:, history_seq_len:], + ) + norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states) + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states, + navit_encoder_attention_mask, + None, + original_context_length, + original_context_length_list, + enable_navit, + ) + hidden_states = hidden_states + attn_output + hidden_states = torch.cat([history_hidden_states, hidden_states], dim=1) + else: + norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states) + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states, + navit_encoder_attention_mask, + None, + original_context_length, + original_context_length_list, + enable_navit, + ) + hidden_states = hidden_states + attn_output + + # 3. Feed-forward + norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as( + hidden_states + ) + ff_output = self.ffn(norm_hidden_states) + hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states) + + return hidden_states + + +class HeliosTransformer3DModel( + ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin, AttentionMixin +): + r""" + A Transformer model for video-like data used in the Helios model. + + Args: + patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`): + 3D patch dimensions for video embedding (t_patch, h_patch, w_patch). + num_attention_heads (`int`, defaults to `40`): + Fixed length for text embeddings. + attention_head_dim (`int`, defaults to `128`): + The number of channels in each head. + in_channels (`int`, defaults to `16`): + The number of channels in the input. + out_channels (`int`, defaults to `16`): + The number of channels in the output. + text_dim (`int`, defaults to `512`): + Input dimension for text embeddings. + freq_dim (`int`, defaults to `256`): + Dimension for sinusoidal time embeddings. + ffn_dim (`int`, defaults to `13824`): + Intermediate dimension in feed-forward network. + num_layers (`int`, defaults to `40`): + The number of layers of transformer blocks to use. + window_size (`Tuple[int]`, defaults to `(-1, -1)`): + Window size for local attention (-1 indicates global attention). + cross_attn_norm (`bool`, defaults to `True`): + Enable cross-attention normalization. + qk_norm (`bool`, defaults to `True`): + Enable query/key normalization. + eps (`float`, defaults to `1e-6`): + Epsilon value for normalization layers. + add_img_emb (`bool`, defaults to `False`): + Whether to use img_emb. + added_kv_proj_dim (`int`, *optional*, defaults to `None`): + The number of channels to use for the added key and value projections. If `None`, no projection is used. + """ + + _supports_gradient_checkpointing = True + _skip_layerwise_casting_patterns = [ + "patch_embedding", + "patch_short", + "patch_mid", + "patch_long", + "condition_embedder", + "norm", + ] + _no_split_modules = ["HeliosTransformerBlock", "HeliosOutputNorm"] + _keep_in_fp32_modules = [ + "time_embedder", + "scale_shift_table", + "norm1", + "norm2", + "norm3", + "history_key_scale", + ] + _keys_to_ignore_on_load_unexpected = ["norm_added_q"] + _repeated_blocks = ["HeliosTransformerBlock"] + _cp_plan = { + # Input split at attn level and ffn level. + "blocks.*.attn1": { + "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), + "rotary_emb": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), + }, + "blocks.*.attn2": { + "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), + }, + "blocks.*.ffn": { + "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), + }, + # Output gather at attn level and ffn level. + **{f"blocks.{i}.attn1": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)}, + **{f"blocks.{i}.attn2": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)}, + **{f"blocks.{i}.ffn": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)}, + } + + @register_to_config + def __init__( + self, + patch_size: tuple[int, ...] = (1, 2, 2), + num_attention_heads: int = 40, + attention_head_dim: int = 128, + in_channels: int = 16, + out_channels: int = 16, + text_dim: int = 4096, + freq_dim: int = 256, + ffn_dim: int = 13824, + num_layers: int = 40, + cross_attn_norm: bool = True, + qk_norm: str | None = "rms_norm_across_heads", + eps: float = 1e-6, + image_dim: int | None = None, + added_kv_proj_dim: int | None = None, + rope_dim: tuple[int, ...] = (44, 42, 42), + rope_theta: float = 10000.0, + restrict_self_attn: bool = False, + guidance_cross_attn: bool = False, + is_train_restrict_lora: bool = False, + restrict_lora: bool = False, + restrict_lora_rank: int = 128, + zero_history_timestep: bool = False, + has_multi_term_memory_patch: bool = False, + is_amplify_history: bool = False, + history_scale_mode: str = "per_head", # [scalar, per_head] + is_use_gan: bool = False, + is_use_gan_hooks: bool = False, + is_use_gan_final: bool = False, + gan_cond_map_dim: int = 768, + gan_hooks: List[int] = [5, 15, 25, 35], + ) -> None: + super().__init__() + + inner_dim = num_attention_heads * attention_head_dim + out_channels = out_channels or in_channels + + # 1. Patch & position embedding + self.rope = HeliosRotaryPosEmbed(rope_dim=rope_dim, theta=rope_theta) + self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size) + + # 2. Condition embeddings + self.condition_embedder = HeliosTimeTextEmbedding( + dim=inner_dim, + time_freq_dim=freq_dim, + time_proj_dim=inner_dim * 6, + text_embed_dim=text_dim, + ) + + # 3. Transformer blocks + self.blocks = nn.ModuleList( + [ + HeliosTransformerBlock( + inner_dim, + ffn_dim, + num_attention_heads, + qk_norm, + cross_attn_norm, + eps, + added_kv_proj_dim, + restrict_self_attn=restrict_self_attn, + guidance_cross_attn=guidance_cross_attn, + is_train_restrict_lora=is_train_restrict_lora, + restrict_lora=restrict_lora, + restrict_lora_rank=restrict_lora_rank, + is_amplify_history=is_amplify_history, + history_scale_mode=history_scale_mode, + ) + for _ in range(num_layers) + ] + ) + + # 4. Output norm & projection + self.norm_out = HeliosOutputNorm(inner_dim, eps, elementwise_affine=False) + self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size)) + + self.init_weights() + + # 5. Initial Stage1 + self.zero_history_timestep = zero_history_timestep + self.inner_dim = inner_dim + if has_multi_term_memory_patch: + self.patch_short = nn.Conv3d(in_channels, self.inner_dim, kernel_size=(1, 2, 2), stride=(1, 2, 2)) + self.patch_mid = nn.Conv3d(in_channels, self.inner_dim, kernel_size=(2, 4, 4), stride=(2, 4, 4)) + self.patch_long = nn.Conv3d(in_channels, self.inner_dim, kernel_size=(4, 8, 8), stride=(4, 8, 8)) + self.initialize_weight_from_another_conv3d(self.patch_embedding) + + # 6. Initial Gan + self.is_use_gan = is_use_gan + if is_use_gan: + self.is_use_gan_hooks = is_use_gan_hooks + self.is_use_gan_final = is_use_gan_final + if is_use_gan_hooks: + gan_heads = [] + self.gan_hooks = gan_hooks + for hook in self.gan_hooks: + gan_heads.append((str(hook), Discriminator3DHead(inner_dim, gan_cond_map_dim))) + self.gan_heads = nn.ModuleDict(gan_heads) + if is_use_gan_final: + self.gan_final_head = Discriminator3DHead(out_channels, gan_cond_map_dim) + + self.gradient_checkpointing = False + + @torch.no_grad() + def initialize_weight_from_another_conv3d(self, another_layer): + weight = another_layer.weight.detach().clone() + bias = another_layer.bias.detach().clone() + + weight = weight[:, :16, :, :, :] + + sd = { + "patch_short.weight": weight.clone(), + "patch_short.bias": bias.clone(), + "patch_mid.weight": einops.repeat(weight, "b c t h w -> b c (t tk) (h hk) (w wk)", tk=2, hk=2, wk=2) / 8.0, + "patch_mid.bias": bias.clone(), + "patch_long.weight": einops.repeat(weight, "b c t h w -> b c (t tk) (h hk) (w wk)", tk=4, hk=4, wk=4) + / 64.0, + "patch_long.bias": bias.clone(), + } + + sd = {k: v.clone() for k, v in sd.items()} + + self.load_state_dict(sd, strict=False) + + def gradient_checkpointing_method(self, block, *args): + if torch.is_grad_enabled() and self.gradient_checkpointing: + result = self._gradient_checkpointing_func(block, *args) + else: + result = block(*args) + return result + + def enable_kv_cache(self): + for block in self.blocks: + if hasattr(block.attn1, "processor") and hasattr(block.attn1.processor, "enable_cache"): + block.attn1.processor.enable_cache() + + def disable_kv_cache(self): + for block in self.blocks: + if hasattr(block.attn1, "processor") and hasattr(block.attn1.processor, "disable_cache"): + block.attn1.processor.disable_cache() + + def clear_kv_cache(self): + for block in self.blocks: + if hasattr(block.attn1, "processor") and hasattr(block.attn1.processor, "clear_cache"): + block.attn1.processor.clear_cache() + + def process_input_hidden_states( + self, + latents, + indices_hidden_states=None, + indices_latents_history_short=None, + indices_latents_history_mid=None, + indices_latents_history_long=None, + latents_history_short=None, + latents_history_mid=None, + latents_history_long=None, + ): + height_list = [] + width_list = [] + temporal_list = [] + seq_list = [] + if isinstance(latents, list): + hidden_states = None + rope_freqs = None + for idx, cur_hidden_states in enumerate(latents): + cur_hidden_states = self.gradient_checkpointing_method( + self.patch_embedding, cur_hidden_states.to(self.device, dtype=self.dtype) + ) + B, C, T, H, W = cur_hidden_states.shape + + cur_hidden_states = cur_hidden_states.flatten(2).transpose(1, 2) + + if indices_hidden_states is None: + indices_hidden_states = torch.arange(0, T).unsqueeze(0).expand(B, -1) + + cur_indices_latents = indices_hidden_states + cur_rope_freqs = self.rope( + frame_indices=cur_indices_latents, height=H, width=W, device=cur_hidden_states.device + ) + cur_rope_freqs = cur_rope_freqs.flatten(2).transpose(1, 2) + + height_list.append(H) + width_list.append(W) + temporal_list.append(T) + seq_list.append(cur_hidden_states.shape[1]) + + if hidden_states is None: + hidden_states = cur_hidden_states + rope_freqs = cur_rope_freqs + else: + hidden_states = torch.cat([cur_hidden_states, hidden_states], dim=1) + rope_freqs = torch.cat([cur_rope_freqs, rope_freqs], dim=1) + else: + hidden_states = self.gradient_checkpointing_method(self.patch_embedding, latents) + B, C, T, H, W = hidden_states.shape + + if indices_hidden_states is None: + indices_hidden_states = torch.arange(0, T).unsqueeze(0).expand(B, -1) + + hidden_states = hidden_states.flatten(2).transpose( + 1, 2 + ) # torch.Size([1, 3072, 9, 44, 34]) -> torch.Size([1, 13464, 3072]) + + rope_freqs = self.rope( + frame_indices=indices_hidden_states, + height=H, + width=W, + device=hidden_states.device, + ) # torch.Size([1, 9]) -> torch.Size([1, 256, 9, 44, 34]) + rope_freqs = rope_freqs.flatten(2).transpose(1, 2) # torch.Size([1, 13464, 256]) + + height_list.append(H) + width_list.append(W) + temporal_list.append(T) + seq_list.append(hidden_states.shape[1]) + + # Process short history latents + if latents_history_short is not None and indices_latents_history_short is not None: + latents_history_short = latents_history_short.to(hidden_states) + latents_history_short = self.gradient_checkpointing_method(self.patch_short, latents_history_short) + _, _, _, H1, W1 = latents_history_short.shape + latents_history_short = latents_history_short.flatten(2).transpose(1, 2) + + rope_freqs_history_short = self.rope( + frame_indices=indices_latents_history_short, + height=H1, + width=W1, + device=latents_history_short.device, + ) + rope_freqs_history_short = rope_freqs_history_short.flatten(2).transpose(1, 2) + + hidden_states = torch.cat([latents_history_short, hidden_states], dim=1) + rope_freqs = torch.cat([rope_freqs_history_short, rope_freqs], dim=1) + + # Process mid history latents + if latents_history_mid is not None and indices_latents_history_mid is not None: + latents_history_mid = latents_history_mid.to(hidden_states) + latents_history_mid = pad_for_3d_conv(latents_history_mid, (2, 4, 4)) + latents_history_mid = self.gradient_checkpointing_method(self.patch_mid, latents_history_mid) + latents_history_mid = latents_history_mid.flatten(2).transpose(1, 2) + + rope_freqs_history_mid = self.rope( + frame_indices=indices_latents_history_mid, + height=H1, + width=W1, + device=latents_history_mid.device, + ) + rope_freqs_history_mid = pad_for_3d_conv(rope_freqs_history_mid, (2, 2, 2)) + rope_freqs_history_mid = center_down_sample_3d(rope_freqs_history_mid, (2, 2, 2)) + rope_freqs_history_mid = rope_freqs_history_mid.flatten(2).transpose(1, 2) + + hidden_states = torch.cat([latents_history_mid, hidden_states], dim=1) + rope_freqs = torch.cat([rope_freqs_history_mid, rope_freqs], dim=1) + + # Process long history latents + if latents_history_long is not None and indices_latents_history_long is not None: + latents_history_long = latents_history_long.to(hidden_states) + latents_history_long = pad_for_3d_conv(latents_history_long, (4, 8, 8)) + latents_history_long = self.gradient_checkpointing_method(self.patch_long, latents_history_long) + latents_history_long = latents_history_long.flatten(2).transpose(1, 2) + + rope_freqs_history_long = self.rope( + frame_indices=indices_latents_history_long, + height=H1, + width=W1, + device=latents_history_long.device, + ) + rope_freqs_history_long = pad_for_3d_conv(rope_freqs_history_long, (4, 4, 4)) + rope_freqs_history_long = center_down_sample_3d(rope_freqs_history_long, (4, 4, 4)) + rope_freqs_history_long = rope_freqs_history_long.flatten(2).transpose(1, 2) + + hidden_states = torch.cat([latents_history_long, hidden_states], dim=1) + rope_freqs = torch.cat([rope_freqs_history_long, rope_freqs], dim=1) + + return ( + hidden_states, + rope_freqs, + height_list, + width_list, + temporal_list, + seq_list, + ) + + @apply_lora_scale("attention_kwargs") + def forward( + self, + hidden_states: torch.Tensor, + timestep: torch.LongTensor, + encoder_hidden_states: torch.Tensor, + # ------------ Stage 1 ------------ + indices_hidden_states=None, + indices_latents_history_short=None, + indices_latents_history_mid=None, + indices_latents_history_long=None, + latents_history_short=None, + latents_history_mid=None, + latents_history_long=None, + is_first_denoising_step: bool = False, + # ------------ GAN ------------ + gan_mode: bool = False, + return_dict: bool = True, + attention_kwargs: dict[str, Any] | None = None, + ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + assert ( + len( + { + x is None + for x in [ + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + ] + } + ) + == 1 + ), "All history latents and indices must either all exist or all be None" + + if indices_hidden_states is not None and indices_hidden_states.ndim == 1: + indices_hidden_states = indices_hidden_states.unsqueeze(0) + if indices_latents_history_short is not None and indices_latents_history_short.ndim == 1: + indices_latents_history_short = indices_latents_history_short.unsqueeze(0) + if indices_latents_history_mid is not None and indices_latents_history_mid.ndim == 1: + indices_latents_history_mid = indices_latents_history_mid.unsqueeze(0) + if indices_latents_history_long is not None and indices_latents_history_long.ndim == 1: + indices_latents_history_long = indices_latents_history_long.unsqueeze(0) + + if gan_mode: + assert self.is_use_gan + + if isinstance(hidden_states, list): + assert gan_mode is False and self.is_use_gan is False + enable_navit = True + navit_len = len(hidden_states) + batch_size = hidden_states[0].shape[0] + else: + enable_navit = False + batch_size = hidden_states.shape[0] + p_t, p_h, p_w = self.config.patch_size + + ( + hidden_states, + rotary_emb, + post_patch_height_list, + post_patch_width_list, + post_patch_num_frames_list, + original_context_length_list, + ) = self.process_input_hidden_states( + latents=hidden_states, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + ) # hidden: [high, mid, low] -> [low, mid, high] + post_patch_num_frames = sum(post_patch_num_frames_list) + post_patch_height = sum(post_patch_height_list) + post_patch_width = sum(post_patch_width_list) + original_context_length = sum(original_context_length_list) + history_context_length = hidden_states.shape[1] - original_context_length + + if indices_hidden_states is not None and self.zero_history_timestep: + if isinstance(timestep, list): + timestep_t0 = torch.zeros((1), dtype=timestep[0].dtype, device=timestep[0].device) + else: + timestep_t0 = torch.zeros((1), dtype=timestep.dtype, device=timestep.device) + temb_t0, timestep_proj_t0, _ = self.condition_embedder( + timestep_t0, encoder_hidden_states, is_return_encoder_hidden_states=False + ) + temb_t0 = temb_t0.unsqueeze(1).expand(batch_size, history_context_length, -1) + timestep_proj_t0 = ( + timestep_proj_t0.unflatten(-1, (6, -1)) + .view(1, 6, 1, -1) + .expand(batch_size, -1, history_context_length, -1) + ) + + navit_hidden_attention_mask = None + navit_encoder_attention_mask = None + if enable_navit: + assert navit_len == len(original_context_length_list) + navit_hidden_attention_mask, navit_encoder_attention_mask, navit_history_hidden_attention_mask = ( + create_navit_attention_masks( + batch_size=batch_size, + original_context_length_list=original_context_length_list[::-1], + history_context_length=history_context_length, + encoder_hidden_states_seq_len=encoder_hidden_states.shape[1], + device=hidden_states.device, + restrict_self_attn=self.config.restrict_self_attn, + guidance_cross_attn=self.config.guidance_cross_attn, + ) + ) + navit_hidden_attention_mask = [navit_hidden_attention_mask, navit_history_hidden_attention_mask] + + history_hidden_states, hidden_states = ( + hidden_states[:, :history_context_length], + hidden_states[:, history_context_length:], + ) + history_rotary_emb, rotary_emb = ( + rotary_emb[:, :history_context_length], + rotary_emb[:, history_context_length:], + ) + timestep = timestep[::-1] + + hidden_states_list = [None] * navit_len + rotary_emb_list = [None] * navit_len + temb_list = [None] * navit_len + timestep_proj_list = [None] * navit_len + + seq_start = 0 + for idx, cur_seq_len in zip(range(navit_len), original_context_length_list[::-1]): + cur_hidden_states = hidden_states[:, seq_start : seq_start + cur_seq_len, :] + cur_rotary_emb = rotary_emb[:, seq_start : seq_start + cur_seq_len, :] + + hidden_states_list[idx] = torch.cat([history_hidden_states, cur_hidden_states], dim=1) + rotary_emb_list[idx] = torch.cat([history_rotary_emb, cur_rotary_emb], dim=1) + + seq_start += cur_seq_len + + if idx == 0: + cur_temb, cur_timestep_proj, encoder_hidden_states = self.condition_embedder( + timestep[idx], encoder_hidden_states + ) + else: + cur_temb, cur_timestep_proj, _ = self.condition_embedder( + timestep[idx], encoder_hidden_states, is_return_encoder_hidden_states=False + ) + + cur_temb = cur_temb.view(batch_size, 1, -1).expand(-1, cur_seq_len, -1) + cur_timestep_proj = cur_timestep_proj.view(batch_size, 6, 1, -1).expand(-1, -1, cur_seq_len, -1) + + if self.zero_history_timestep: + temb_list[idx] = torch.cat([temb_t0, cur_temb], dim=1) + timestep_proj_list[idx] = torch.cat([timestep_proj_t0, cur_timestep_proj], dim=2) + else: + temb_list[idx] = cur_temb + timestep_proj_list[idx] = cur_timestep_proj + + hidden_states = torch.cat(hidden_states_list, dim=1) + rotary_emb = torch.cat(rotary_emb_list, dim=1) + temb = torch.cat(temb_list, dim=1) + timestep_proj = torch.cat(timestep_proj_list, dim=2) + else: + temb, timestep_proj, encoder_hidden_states = self.condition_embedder(timestep, encoder_hidden_states) + timestep_proj = timestep_proj.unflatten(-1, (6, -1)) + + if indices_hidden_states is not None and not self.zero_history_timestep: + main_repeat_size = hidden_states.shape[1] + else: + main_repeat_size = original_context_length + temb = temb.view(batch_size, 1, -1).expand(batch_size, main_repeat_size, -1) + timestep_proj = timestep_proj.view(batch_size, 6, 1, -1).expand(batch_size, 6, main_repeat_size, -1) + + if indices_hidden_states is not None and self.zero_history_timestep: + temb = torch.cat([temb_t0, temb], dim=1) + timestep_proj = torch.cat([timestep_proj_t0, timestep_proj], dim=2) + + if timestep_proj.ndim == 4: + timestep_proj = timestep_proj.permute(0, 2, 1, 3) + + # 4. Transformer blocks + logits_hidden = [] + hidden_states = hidden_states.contiguous() + encoder_hidden_states = encoder_hidden_states.contiguous() + rotary_emb = rotary_emb.contiguous() + if torch.is_grad_enabled() and self.gradient_checkpointing: + for iidx, block in enumerate(self.blocks): + hidden_states = self._gradient_checkpointing_func( + block, + hidden_states, + encoder_hidden_states, + timestep_proj, + rotary_emb, + navit_hidden_attention_mask, + navit_encoder_attention_mask, + original_context_length, + original_context_length_list, + is_first_denoising_step, + ) + if gan_mode and self.is_use_gan and self.is_use_gan_hooks and iidx in self.gan_hooks: + logits_hidden.append(hidden_states[:, -original_context_length:, :]) + else: + for iidx, block in enumerate(self.blocks): + hidden_states = block( + hidden_states, + encoder_hidden_states, + timestep_proj, + rotary_emb, + navit_hidden_attention_mask, + navit_encoder_attention_mask, + original_context_length, + original_context_length_list, + is_first_denoising_step, + ) + if gan_mode and self.is_use_gan and self.is_use_gan_hooks and iidx in self.gan_hooks: + logits_hidden.append(hidden_states[:, -original_context_length:, :]) + + # 5. Output norm, projection & unpatchify + if temb.ndim == 3: + if not enable_navit: + temb = temb[:, -original_context_length:, :] + shift, scale = (self.norm_out.scale_shift_table.unsqueeze(0).to(temb.device) + temb.unsqueeze(2)).chunk( + 2, dim=2 + ) + shift = shift.squeeze(2) + scale = scale.squeeze(2) + else: + # batch_size, inner_dim + shift, scale = (self.norm_out.scale_shift_table.to(temb.device) + temb.unsqueeze(1)).chunk(2, dim=1) + + # Move the shift and scale tensors to the same device as hidden_states. + # When using multi-GPU inference via accelerate these will be on the + # first device rather than the last device, which hidden_states ends up + # on. + shift = shift.to(hidden_states.device) + scale = scale.to(hidden_states.device) + + if enable_navit: + hidden_states = (self.norm_out.norm(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states) + + output = [] + seq_start = 0 + for ( + cur_original_context_length, + cur_post_patch_num_frames, + cur_post_patch_height, + cur_post_patch_width, + ) in zip( + reversed(original_context_length_list), + reversed(post_patch_num_frames_list), + reversed(post_patch_height_list), + reversed(post_patch_width_list), + ): + cur_hidden_states = hidden_states[ + :, seq_start : seq_start + cur_original_context_length + history_context_length, : + ] # (B, T*H*W, C) + cur_hidden_states = cur_hidden_states[:, history_context_length:, :] + cur_hidden_states = self.proj_out(cur_hidden_states) + seq_start += cur_original_context_length + history_context_length + + cur_hidden_states = cur_hidden_states.reshape( + batch_size, + cur_post_patch_num_frames, + cur_post_patch_height, + cur_post_patch_width, + p_t, + p_h, + p_w, + -1, + ) + cur_hidden_states = cur_hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6) + cur_hidden_states = cur_hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3) + + output.append(cur_hidden_states) + + output = output[::-1] + else: + hidden_states = hidden_states[:, -original_context_length:, :] + hidden_states = (self.norm_out.norm(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states) + hidden_states = self.proj_out(hidden_states) + hidden_states = hidden_states.reshape( + batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1 + ) + hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6) + output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3) + + logits = [] + if gan_mode and self.is_use_gan: + if self.is_use_gan_final: + logits.append(self.gradient_checkpointing_method(self.gan_final_head, output)) + if self.is_use_gan_hooks: + for idx, (_, gan_head) in enumerate(self.gan_heads.items()): + activation = rearrange( + logits_hidden[idx], + "b (f h w) c -> b c f h w", + f=post_patch_num_frames, + h=post_patch_height, + w=post_patch_width, + ) + logits.append(self.gradient_checkpointing_method(gan_head, activation.contiguous())) + logits = torch.cat(logits, dim=1) if len(logits) > 1 else logits[0] + logits_hidden = None + del logits_hidden + + if not return_dict: + return (output, logits) + + return Transformer2DModelOutput(sample=output, logits=logits) + + def init_weights(self): + r""" + Initialize model parameters using Xavier initialization. + """ + + # basic init + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.zeros_(m.bias) + + # init embeddings + nn.init.xavier_uniform_(self.patch_embedding.weight.flatten(1)) + for m in self.condition_embedder.modules(): + if isinstance(m, nn.Linear): + nn.init.normal_(m.weight, std=0.02) + + # init output layer + nn.init.zeros_(self.proj_out.weight) + + @classmethod + def from_pretrained( + cls, + pretrained_model_path, + subfolder=None, + transformer_additional_kwargs={}, + low_cpu_mem_usage=False, + torch_dtype=torch.float32, + device_map="cpu", + max_workers=8, + use_default_loader=False, + ): + if use_default_loader: + return super().from_pretrained( + pretrained_model_path, subfolder=subfolder, device_map=device_map, torch_dtype=torch_dtype + ) + + import os + from concurrent.futures import ThreadPoolExecutor, as_completed + + from huggingface_hub import snapshot_download + + from diffusers.utils import WEIGHTS_NAME + + if os.path.exists(pretrained_model_path): + if subfolder is not None: + pretrained_model_path = os.path.join(pretrained_model_path, subfolder) + else: + print(f"Downloading from Hugging Face Hub: {pretrained_model_path}") + cache_dir = snapshot_download( + repo_id=pretrained_model_path, + # allow_patterns=["*.json", "*.safetensors", "*.bin"], + ) + pretrained_model_path = cache_dir + if subfolder is not None: + pretrained_model_path = os.path.join(cache_dir, subfolder) + + print(f"loaded 3D transformer's pretrained weights from {pretrained_model_path} ...") + + config_file = os.path.join(pretrained_model_path, "config.json") + if not os.path.isfile(config_file): + raise RuntimeError(f"{config_file} does not exist") + with open(config_file, "r") as f: + config = json.load(f) + + model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME) + model_file_safetensors = model_file.replace(".bin", ".safetensors") + + if "dict_mapping" in transformer_additional_kwargs.keys(): + for key in transformer_additional_kwargs["dict_mapping"]: + transformer_additional_kwargs[transformer_additional_kwargs["dict_mapping"][key]] = config[key] + + def remap_state_dict_keys(state_dict): + """Remap old key names to new key names for compatibility.""" + remapped = {} + for key, value in state_dict.items(): + new_key = key + # Only remap top-level scale_shift_table, not blocks.*.scale_shift_table + if key == "scale_shift_table": + new_key = "norm_out.scale_shift_table" + print(f"Remapping key: {key} -> {new_key}") + remapped[new_key] = value + return remapped + + if low_cpu_mem_usage: + try: + import re + + from diffusers import __version__ as diffusers_version + from diffusers.models.model_loading_utils import load_model_dict_into_meta + from diffusers.utils import is_accelerate_available + + if is_accelerate_available(): + import accelerate + + # Instantiate model with empty weights + with accelerate.init_empty_weights(): + model = cls.from_config(config, **transformer_additional_kwargs) + + param_device = "cpu" + if os.path.exists(model_file): + state_dict = torch.load(model_file, map_location="cpu") + elif os.path.exists(model_file_safetensors): + from safetensors.torch import load_file + + state_dict = load_file(model_file_safetensors) + else: + from safetensors.torch import load_file + + model_files_safetensors = glob.glob(os.path.join(pretrained_model_path, "*.safetensors")) + state_dict = {} + print(f"Loading {len(model_files_safetensors)} safetensors files with {max_workers} workers...") + with ThreadPoolExecutor(max_workers=max_workers) as executor: + future_to_file = {executor.submit(load_file, f): f for f in model_files_safetensors} + for future in as_completed(future_to_file): + _state_dict = future.result() + state_dict.update(_state_dict) + + # Remap keys before loading into meta model + state_dict = remap_state_dict_keys(state_dict) + + if diffusers_version >= "0.33.0": + # Diffusers has refactored `load_model_dict_into_meta` since version 0.33.0 in this commit: + # https://github.com/huggingface/diffusers/commit/f5929e03060d56063ff34b25a8308833bec7c785. + load_model_dict_into_meta( + model, + state_dict, + dtype=torch_dtype, + model_name_or_path=pretrained_model_path, + keep_in_fp32_modules=cls._keep_in_fp32_modules, + ) + else: + model._convert_deprecated_attention_blocks(state_dict) + # move the params from meta device to cpu + missing_keys = set(model.state_dict().keys()) - set(state_dict.keys()) + if len(missing_keys) > 0: + raise ValueError( + f"Cannot load {cls} from {pretrained_model_path} because the following keys are" + f" missing: \n {', '.join(missing_keys)}. \n Please make sure to pass" + " `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize" + " those weights or else make sure your checkpoint file is correct." + ) + + unexpected_keys = load_model_dict_into_meta( + model, + state_dict, + device=param_device, + dtype=torch_dtype, + model_name_or_path=pretrained_model_path, + ) + + if cls._keys_to_ignore_on_load_unexpected is not None: + for pat in cls._keys_to_ignore_on_load_unexpected: + unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None] + + if len(unexpected_keys) > 0: + print( + f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}" + ) + + return model + except Exception as e: + print(f"The low_cpu_mem_usage mode is not work because {e}. Use low_cpu_mem_usage=False instead.") + + model = cls.from_config(config, **transformer_additional_kwargs) + if os.path.exists(model_file): + state_dict = torch.load(model_file, map_location="cpu") + elif os.path.exists(model_file_safetensors): + from safetensors.torch import load_file + + state_dict = load_file(model_file_safetensors) + else: + from safetensors.torch import load_file + + model_files_safetensors = glob.glob(os.path.join(pretrained_model_path, "*.safetensors")) + state_dict = {} + print(f"Loading {len(model_files_safetensors)} safetensors files with {max_workers} workers...") + with ThreadPoolExecutor(max_workers=max_workers) as executor: + future_to_file = {executor.submit(load_file, f): f for f in model_files_safetensors} + for future in as_completed(future_to_file): + _state_dict = future.result() + state_dict.update(_state_dict) + + # Remap keys before size check and loading + state_dict = remap_state_dict_keys(state_dict) + + tmp_state_dict = {} + for key in state_dict: + if key in model.state_dict().keys() and model.state_dict()[key].size() == state_dict[key].size(): + tmp_state_dict[key] = state_dict[key] + else: + print(key, "Size don't match, skip") + + state_dict = tmp_state_dict + + m, u = model.load_state_dict(state_dict, strict=False) + print(f"### missing keys: {len(m)}; \n### unexpected keys: {len(u)};") + print(m) + + for name, param in model.named_parameters(): + should_keep_fp32 = any(pattern in name for pattern in cls._keep_in_fp32_modules) + if should_keep_fp32: + param.data = param.data.to(torch.float32) + # print(f"Keeping parameter {name} in fp32") + else: + param.data = param.data.to(torch_dtype) + model = model.to(device_map) + + params = [p.numel() if "." in n else 0 for n, p in model.named_parameters()] + print(f"### All Parameters: {sum(params) / 1e6} M") + + params = [p.numel() if "attn1." in n else 0 for n, p in model.named_parameters()] + print(f"### attn1 Parameters: {sum(params) / 1e6} M") + + params = [p.numel() if "attn2." in n else 0 for n, p in model.named_parameters()] + print(f"### attn2 Parameters: {sum(params) / 1e6} M") + + return model + + +if __name__ == "__main__": + import os + + os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes" + os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes" + # export DIFFUSERS_ENABLE_HUB_KERNELS=yes + + # def compare_models(model1, model2): + # for (name1, param1), (name2, param2) in zip(model1.named_parameters(), model2.named_parameters()): + # if name1 != name2: + # print(f"参数名不同: {name1} vs {name2}") + # return False + # if not torch.equal(param1, param2): + # print(f"参数 {name1} 的值不同") + # print(f"最大差异: {torch.max(torch.abs(param1 - param2))}") + # return False + # print("所有参数完全相同!") + # return True + # compare_models(transformer, transformer1) + + gan_mode = False + is_use_gan_hooks = False + transformer_additional_kwargs = { + "has_multi_term_memory_patch": True, + "zero_history_timestep": True, + "guidance_cross_attn": True, + "restrict_self_attn": False, + "restrict_lora": False, + "is_train_restrict_lora": False, + "is_amplify_history": False, + "history_scale_mode": "per_head", # [scalar, per_head] + "is_use_gan": gan_mode, + "is_use_gan_hooks": is_use_gan_hooks, + "gan_hooks": [13, 21, 29], + "gan_cond_map_dim": 768, + # "gan_hooks": [10, 20, 30], + # "gan_cond_map_dim": 512, + } + # transformer_additional_kwargs={} + + device = "cuda" + weight_dtype = torch.bfloat16 + transformer = HeliosTransformer3DModel.from_pretrained( + "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", + subfolder="transformer", + torch_dtype=torch.bfloat16, + transformer_additional_kwargs=transformer_additional_kwargs, + ) + transformer.requires_grad_(False) + transformer.eval() + transformer = transformer.to(device, dtype=weight_dtype) + + # import sys + # from argparse import Namespace + # sys.path.append("../../") + # from helios.utils.utils_helios_base import save_extra_components, load_extra_components + # args = Namespace() + # args.training_config = Namespace() + # args.training_config.is_enable_stage1 = True + # args.training_config.is_train_restrict_lora = True + # save_extra_components(args, transformer, "./temp") + # load_extra_components(args, transformer, "./temp/transformer_partial.pth") + + is_navit = False + batch_size = 4 + max_length = 512 + if is_navit: + noisy_model_input = [ + torch.randn(batch_size, 16, 9, 12, 20), + torch.randn(batch_size, 16, 9, 24, 40), + torch.randn(batch_size, 16, 9, 48, 80), + ] + timesteps = [ + torch.randint(0, 1000, (batch_size,)).to(device), + torch.randint(0, 1000, (batch_size,)).to(device), + torch.randint(0, 1000, (batch_size,)).to(device), + ] + else: + noisy_model_input = torch.randn(batch_size, 16, 9, 48, 80).to(device, dtype=weight_dtype) + timesteps = torch.randint(0, 1000, (batch_size,)).to(device) + + prompt_embeds = torch.randn(batch_size, max_length, 4096).to(device, dtype=weight_dtype) + indices_hidden_states = torch.randint(0, 10, (batch_size, 9)).to(device) + indices_latents_history_short = torch.randint(0, 3, (batch_size, 2)).to(device) + indices_latents_history_mid = torch.randint(0, 3, (batch_size, 2)).to(device) + indices_latents_history_long = torch.randint(0, 17, (batch_size, 16)).to(device) + latents_history_short = torch.randn(batch_size, 16, 2, 48, 80).to(device, dtype=weight_dtype) + latents_history_mid = torch.randn(batch_size, 16, 2, 48, 80).to(device, dtype=weight_dtype) + latents_history_long = torch.randn(batch_size, 16, 16, 48, 80).to(device, dtype=weight_dtype) + + # 16 2 2: 2400 + # 16 2 3: 3360 + # 16 4 2: 2640 + # 16 4 3: 3600 + # 8 2 2: 2280 + # 8 2 3: 3240 + + # noisy_model_input_1 = torch.randn(batch_size, 16, 9, 12, 20).to(device, dtype=weight_dtype) + # timesteps_1 = torch.randint(0, 1000, (batch_size,)).to(device) + # noisy_model_input = [noisy_model_input_1, noisy_model_input_1, noisy_model_input_1] + # timesteps = [timesteps_1, timesteps_1, torch.randint(0, 1000, (batch_size,)).to(device)] + + model_pred = transformer( + hidden_states=noisy_model_input, + timestep=timesteps, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(weight_dtype), + latents_history_mid=latents_history_mid.to(weight_dtype), + latents_history_long=latents_history_long.to(weight_dtype), + gan_mode=gan_mode, + return_dict=False, + )[0] diff --git a/Helios/helios/pipelines/__init__.py b/Helios/helios/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/helios/pipelines/pipeline_helios.py b/Helios/helios/pipelines/pipeline_helios.py new file mode 100644 index 0000000000000000000000000000000000000000..3f011352d659acce0ac3a88b4ad8ce5228469ce5 --- /dev/null +++ b/Helios/helios/pipelines/pipeline_helios.py @@ -0,0 +1,1535 @@ +# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import html +import math +from enum import Enum +from itertools import accumulate +from typing import Any, Callable, Dict, List, Literal, Optional, Union + +import regex as re +import torch +import torch.nn.functional as F +from einops import rearrange +from transformers import AutoTokenizer, UMT5EncoderModel + +from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback +from diffusers.image_processor import PipelineImageInput +from diffusers.loaders import WanLoraLoaderMixin +from diffusers.models import AutoencoderKLWan +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.schedulers import UniPCMultistepScheduler +from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring +from diffusers.utils.torch_utils import randn_tensor +from diffusers.video_processor import VideoProcessor + +from ..modules.transformer_helios import HeliosTransformer3DModel +from ..scheduler.scheduling_helios import HeliosScheduler +from ..utils.utils_base import AdaptiveAntiDrifting, apply_schedule_shift +from ..utils.utils_helios_post import add_noise, convert_flow_pred_to_x0 +from .pipeline_output import HeliosPipelineOutput + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + XLA_AVAILABLE = True +else: + XLA_AVAILABLE = False + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + +if is_ftfy_available(): + import ftfy + + +EXAMPLE_DOC_STRING = """ + Examples: + ```python + >>> import torch + >>> from diffusers.utils import export_to_video + >>> from diffusers import AutoencoderKLWan, HeliosPipeline + + >>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled + >>> model_id = "BestWishYsh/Helios-Base" + >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) + >>> pipe = HeliosPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16) + >>> pipe.to("cuda") + + >>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window." + >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" + + >>> output = pipe( + ... prompt=prompt, + ... negative_prompt=negative_prompt, + ... height=384, + ... width=640, + ... num_frames=132, + ... guidance_scale=5.0, + ... ).frames[0] + >>> export_to_video(output, "output.mp4", fps=24) + ``` +""" + + +@torch.amp.autocast("cuda", dtype=torch.float32) +def optimized_scale(positive_flat, negative_flat): + # Calculate dot production + dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True) + + # Squared norm of uncondition + squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8 + + # st_star = v_cond^T * v_uncond / ||v_uncond||^2 + st_star = dot_product / squared_norm + + return st_star + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r"\s+", " ", text) + text = text.strip() + return text + + +def prompt_clean(text): + text = whitespace_clean(basic_clean(text)) + return text + + +class VAEDecodeType(str, Enum): + DEFAULT = "default" + DEFAULT_BATCH = "default_batch" + + +class HeliosPipeline(DiffusionPipeline, WanLoraLoaderMixin): + r""" + Pipeline for text-to-video / image-to-video / video-to-video generation using Helios. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods + implemented for all pipelines (downloading, saving, running on a particular device, etc.). + + Args: + tokenizer ([`T5Tokenizer`]): + Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer), + specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant. + text_encoder ([`T5EncoderModel`]): + [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically + the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant. + transformer ([`HeliosTransformer3DModel`]): + Conditional Transformer to denoise the input latents. + scheduler ([`UniPCMultistepScheduler`]): + A scheduler to be used in combination with `transformer` to denoise the encoded image latents. + vae ([`AutoencoderKLWan`]): + Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations. + """ + + model_cpu_offload_seq = "text_encoder->transformer->vae" + _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"] + _optional_components = ["transformer"] + + def __init__( + self, + tokenizer: AutoTokenizer, + text_encoder: UMT5EncoderModel, + vae: AutoencoderKLWan, + scheduler: UniPCMultistepScheduler | HeliosScheduler, + transformer: HeliosTransformer3DModel, + ): + super().__init__() + + self.register_modules( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + transformer=transformer, + scheduler=scheduler, + ) + self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4 + self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8 + self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial) + + def _get_t5_prompt_embeds( + self, + prompt: Union[str, List[str]] = None, + num_videos_per_prompt: int = 1, + max_sequence_length: int = 226, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ): + device = device or self._execution_device + dtype = dtype or self.text_encoder.dtype + + prompt = [prompt] if isinstance(prompt, str) else prompt + prompt = [prompt_clean(u) for u in prompt] + batch_size = len(prompt) + + text_inputs = self.tokenizer( + prompt, + padding="max_length", + max_length=max_sequence_length, + truncation=True, + add_special_tokens=True, + return_attention_mask=True, + return_tensors="pt", + ) + text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask + seq_lens = mask.gt(0).sum(dim=1).long() + + prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state + prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) + prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)] + prompt_embeds = torch.stack( + [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0 + ) + + # duplicate text embeddings for each generation per prompt, using mps friendly method + _, seq_len, _ = prompt_embeds.shape + prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1) + prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1) + + return prompt_embeds, text_inputs.attention_mask.bool() + + def encode_prompt( + self, + prompt: Union[str, List[str]], + negative_prompt: Optional[Union[str, List[str]]] = None, + do_classifier_free_guidance: bool = True, + num_videos_per_prompt: int = 1, + prompt_embeds: Optional[torch.Tensor] = None, + negative_prompt_embeds: Optional[torch.Tensor] = None, + max_sequence_length: int = 226, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + do_classifier_free_guidance (`bool`, *optional*, defaults to `True`): + Whether to use classifier free guidance or not. + num_videos_per_prompt (`int`, *optional*, defaults to 1): + Number of videos that should be generated per prompt. torch device to place the resulting embeddings on + prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + device: (`torch.device`, *optional*): + torch device + dtype: (`torch.dtype`, *optional*): + torch dtype + """ + device = device or self._execution_device + + prompt = [prompt] if isinstance(prompt, str) else prompt + if prompt is not None: + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + if prompt_embeds is None: + prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds( + prompt=prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + device=device, + dtype=dtype, + ) + + negative_prompt_attention_mask = None + if do_classifier_free_guidance and negative_prompt_embeds is None: + negative_prompt = negative_prompt or "" + negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt + + if prompt is not None and type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + + negative_prompt_embeds, negative_prompt_attention_mask = self._get_t5_prompt_embeds( + prompt=negative_prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + device=device, + dtype=dtype, + ) + + return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask + + def check_inputs( + self, + prompt, + negative_prompt, + height, + width, + prompt_embeds=None, + negative_prompt_embeds=None, + callback_on_step_end_tensor_inputs=None, + ): + if height % 16 != 0 or width % 16 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.") + + if callback_on_step_end_tensor_inputs is not None and not all( + k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs + ): + raise ValueError( + f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" + ) + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + elif negative_prompt is not None and ( + not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list) + ): + raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}") + + def prepare_latents( + self, + batch_size: int, + num_channels_latents: int = 16, + height: int = 480, + width: int = 832, + num_frames: int = 81, + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + if latents is not None: + return latents.to(device=device, dtype=dtype) + + num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1 + shape = ( + batch_size, + num_channels_latents, + num_latent_frames, + int(height) // self.vae_scale_factor_spatial, + int(width) // self.vae_scale_factor_spatial, + ) + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + return latents + + def prepare_image_latents( + self, + image: torch.Tensor, + latents_mean: torch.Tensor, + latents_std: torch.Tensor, + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.Tensor] = None, + fake_latents: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + device = device or self._execution_device + if latents is None: + image = image.unsqueeze(2).to(device=device, dtype=self.vae.dtype) + latents = self.vae.encode(image).latent_dist.sample(generator=generator) + latents = (latents - latents_mean) * latents_std + if fake_latents is None: + fake_video = image.repeat(1, 1, 33, 1, 1).to(device=device, dtype=self.vae.dtype) + fake_latents_full = self.vae.encode(fake_video).latent_dist.sample(generator=generator) + fake_latents_full = (fake_latents_full - latents_mean) * latents_std + fake_latents = fake_latents_full[:, :, -1:, :, :] + return latents.to(device=device, dtype=dtype), fake_latents.to(device=device, dtype=dtype) + + def prepare_video_latents( + self, + video: torch.Tensor, + latents_mean: torch.Tensor, + latents_std: torch.Tensor, + latent_window_size: int, + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + device = device or self._execution_device + video = video.to(device=device, dtype=self.vae.dtype) + if latents is None: + num_frames = video.shape[2] + min_frames = (latent_window_size - 1) * 4 + 1 + num_chunks = num_frames // min_frames + if num_chunks == 0: + raise ValueError( + f"Video must have at least {min_frames} frames " + f"(got {num_frames} frames). " + f"Required: (latent_window_size - 1) * 4 + 1 = ({latent_window_size} - 1) * 4 + 1 = {min_frames}" + ) + total_valid_frames = num_chunks * min_frames + start_frame = num_frames - total_valid_frames + + first_frame = video[:, :, 0:1, :, :] + first_frame_latent = self.vae.encode(first_frame).latent_dist.sample(generator=generator) + first_frame_latent = (first_frame_latent - latents_mean) * latents_std + + latents_chunks = [] + for i in range(num_chunks - 1, -1, -1): + chunk_start = start_frame + i * min_frames + chunk_end = chunk_start + min_frames + video_chunk = video[:, :, chunk_start:chunk_end, :, :] + chunk_latents = self.vae.encode(video_chunk).latent_dist.sample(generator=generator) + chunk_latents = (chunk_latents - latents_mean) * latents_std + latents_chunks.insert(0, chunk_latents) + latents = torch.cat(latents_chunks, dim=2) + return first_frame_latent.to(device=device, dtype=dtype), latents.to(device=device, dtype=dtype) + + def interpolate_prompt_embeds( + self, + prompt_embeds_1: torch.Tensor, + prompt_embeds_2: torch.Tensor, + interpolation_steps: int = 4, + ): + x = torch.lerp( + prompt_embeds_1, + prompt_embeds_2, + torch.linspace(0, 1, steps=interpolation_steps).unsqueeze(1).unsqueeze(2).to(prompt_embeds_1), + ) + interpolated_prompt_embeds = list(x.chunk(interpolation_steps, dim=0)) + return interpolated_prompt_embeds + + def sample_block_noise( + self, + batch_size, + channel, + num_frames, + height, + width, + patch_size: tuple[int, ...] = (1, 2, 2), + device: torch.device | None = None, + generator: torch.Generator | None = None, + ): + # NOTE: A generator must be provided to ensure correct and reproducible results. + # Creating a default generator here is a fallback only — without a fixed seed, + # the output will be non-deterministic and may produce incorrect results in CP context. + if generator is None: + generator = torch.Generator(device=device) + elif isinstance(generator, list): + generator = generator[0] + + gamma = self.scheduler.config.gamma + _, ph, pw = patch_size + block_size = ph * pw + + cov = ( + torch.eye(block_size, device=device) * (1 + gamma) + - torch.ones(block_size, block_size, device=device) * gamma + ) + cov += torch.eye(block_size, device=device) * 1e-8 + cov = cov.float() # Upcast to fp32 for numerical stability — cholesky is unreliable in fp16/bf16. + + L = torch.linalg.cholesky(cov) + block_number = batch_size * channel * num_frames * (height // ph) * (width // pw) + z = torch.randn(block_number, block_size, generator=generator, device=generator.device).to(device=device) + noise = z @ L.T + + noise = noise.view(batch_size, channel, num_frames, height // ph, width // pw, ph, pw) + noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(batch_size, channel, num_frames, height, width) + + return noise + + def stage1_sample( + self, + latents: torch.Tensor = None, + prompt_embeds: torch.Tensor = None, + negative_prompt_embeds: torch.Tensor = None, + timesteps: torch.Tensor = None, + guidance_scale: Optional[float] = 5.0, + indices_hidden_states: torch.Tensor = None, + indices_latents_history_short: torch.Tensor = None, + indices_latents_history_mid: torch.Tensor = None, + indices_latents_history_long: torch.Tensor = None, + latents_history_short: torch.Tensor = None, + latents_history_mid: torch.Tensor = None, + latents_history_long: torch.Tensor = None, + attention_kwargs: Optional[dict] = None, + device: Optional[torch.device] = None, + transformer_dtype: torch.dtype = None, + generator: Optional[torch.Generator] = None, + # ------------ CFG Zero ------------ + use_cfg_zero_star: Optional[bool] = False, + use_zero_init: Optional[bool] = True, + zero_steps: Optional[int] = 1, + # -------------- DMD -------------- + use_dmd: bool = False, + dmd_sigmas: torch.Tensor = None, + dmd_timesteps: torch.Tensor = None, + is_amplify_first_chunk: bool = False, + # ------------ Callback ------------ + callback_on_step_end: Optional[callable] = None, + callback_on_step_end_tensor_inputs: list = None, + progress_bar=None, + ): + batch_size = latents.shape[0] + + for i, t in enumerate(timesteps): + is_first_step = i == 0 + + if self.interrupt: + continue + + self._current_timestep = t + timestep = t.expand(latents.shape[0]) + + latent_model_input = latents.to(transformer_dtype) + with self.transformer.cache_context("cond"): + noise_pred = self.transformer( + hidden_states=latent_model_input, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + is_first_denoising_step=is_first_step, + attention_kwargs=attention_kwargs, + return_dict=False, + )[0] + + if self.do_classifier_free_guidance and not use_dmd: + with self.transformer.cache_context("uncond"): + noise_uncond = self.transformer( + hidden_states=latent_model_input, + timestep=timestep, + encoder_hidden_states=negative_prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + is_first_denoising_step=is_first_step, + attention_kwargs=attention_kwargs, + return_dict=False, + )[0] + + if use_cfg_zero_star: + noise_pred_text = noise_pred + positive_flat = noise_pred_text.view(batch_size, -1) + negative_flat = noise_uncond.view(batch_size, -1) + + alpha = optimized_scale(positive_flat, negative_flat) + alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1))) + alpha = alpha.to(noise_pred_text.dtype) + + if (i <= zero_steps) and use_zero_init: + noise_pred = noise_pred_text * 0.0 + else: + noise_pred = noise_uncond * alpha + guidance_scale * (noise_pred_text - noise_uncond * alpha) + else: + noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond) + + if use_dmd: + pred_image_or_video = convert_flow_pred_to_x0( + flow_pred=noise_pred, + xt=latent_model_input, + timestep=t * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device), + sigmas=dmd_sigmas, + timesteps=dmd_timesteps, + ) + if i < len(timesteps) - 1: + latents = add_noise( + pred_image_or_video, + randn_tensor(pred_image_or_video.shape, generator=generator, device=device), + timesteps[i + 1] * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device), + sigmas=dmd_sigmas, + timesteps=dmd_timesteps, + ) + else: + latents = pred_image_or_video + else: + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0] + + if callback_on_step_end is not None: + callback_kwargs = {} + for k in callback_on_step_end_tensor_inputs: + callback_kwargs[k] = locals()[k] + callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) + + latents = callback_outputs.pop("latents", latents) + prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) + negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) + + progress_bar.update() + + if XLA_AVAILABLE: + xm.mark_step() + + return latents + + def stage2_sample( + self, + latents: torch.Tensor = None, + stage2_num_stages: int = None, + stage2_num_inference_steps_list: List[int] = None, + prompt_embeds: torch.Tensor = None, + negative_prompt_embeds: torch.Tensor = None, + guidance_scale: Optional[float] = 5.0, + indices_hidden_states: torch.Tensor = None, + indices_latents_history_short: torch.Tensor = None, + indices_latents_history_mid: torch.Tensor = None, + indices_latents_history_long: torch.Tensor = None, + latents_history_short: torch.Tensor = None, + latents_history_mid: torch.Tensor = None, + latents_history_long: torch.Tensor = None, + attention_kwargs: Optional[dict] = None, + device: Optional[torch.device] = None, + transformer_dtype: torch.dtype = None, + scheduler_type: str = "unipc", # unipc, euler + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + generator: torch.Generator | list[torch.Generator] | None = None, + # ------------ CFG Zero ------------ + use_cfg_zero_star: Optional[bool] = False, + use_zero_init: Optional[bool] = True, + zero_steps: Optional[int] = 1, + # -------------- DMD -------------- + use_dmd: bool = False, + is_amplify_first_chunk: bool = False, + # ------------ Callback ------------ + callback_on_step_end: Optional[callable] = None, + callback_on_step_end_tensor_inputs: list = None, + progress_bar=None, + ): + num_frames, height, width = ( + latents.shape[-3], + latents.shape[-2], + latents.shape[-1], + ) + latents = rearrange(latents, "b c t h w -> (b t) c h w") + for _ in range(stage2_num_stages - 1): + height //= 2 + width //= 2 + latents = ( + F.interpolate( + latents, + size=(height, width), + mode="bilinear", + ) + * 2 + ) + latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames) + + batch_size = latents.shape[0] + if use_dmd: + start_point_list = [latents] + + i = 0 + for i_s in range(stage2_num_stages): + if use_dmd: + if is_amplify_first_chunk: + self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s] * 2 + 1, i_s, device=device) + else: + self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s] + 1, i_s, device=device) + self.scheduler.timesteps = self.scheduler.timesteps[:-1] + self.scheduler.sigmas = torch.cat([self.scheduler.sigmas[:-2], self.scheduler.sigmas[-1:]]) + else: + self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s, device=device) + + if i_s > 0: + height *= 2 + width *= 2 + num_frames = latents.shape[2] + latents = rearrange(latents, "b c t h w -> (b t) c h w") + latents = F.interpolate(latents, size=(height, width), mode="nearest") + latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames) + # Fix the stage + ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal + gamma = self.scheduler.config.gamma + alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma) + beta = alpha * (1 - ori_sigma) / math.sqrt(gamma) + + batch_size, channel, num_frames, height, width = latents.shape + noise = self.sample_block_noise( + batch_size, + channel, + num_frames, + height, + width, + self.transformer.config.patch_size, + device, + generator, + ) + noise = noise.to(device=device, dtype=transformer_dtype) + latents = alpha * latents + beta * noise # To fix the block artifact + + if use_dmd: + start_point_list.append(latents) + + if use_dynamic_shifting: + temp_sigmas = apply_schedule_shift( + self.scheduler.sigmas, + latents, + base_seq_len=self.scheduler.config.get("base_image_seq_len", 256), + max_seq_len=self.scheduler.config.get("max_image_seq_len", 4096), + base_shift=self.scheduler.config.get("base_shift", 0.5), + max_shift=self.scheduler.config.get("max_shift", 1.15), + time_shift_type=time_shift_type, + ) + temp_timesteps = self.scheduler.timesteps_per_stage[i_s].min() + temp_sigmas[:-1] * ( + self.scheduler.timesteps_per_stage[i_s].max() - self.scheduler.timesteps_per_stage[i_s].min() + ) + + self.scheduler.sigmas = temp_sigmas + self.scheduler.timesteps = temp_timesteps + + timesteps = self.scheduler.timesteps + + for idx, t in enumerate(timesteps): + is_first_step = i_s == 0 and idx == 0 + + timestep = t.expand(latents.shape[0]).to(torch.int64) + + with self.transformer.cache_context("cond"): + noise_pred = self.transformer( + hidden_states=latents.to(transformer_dtype), + timestep=timestep, + encoder_hidden_states=prompt_embeds, + attention_kwargs=attention_kwargs, + return_dict=False, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + is_first_denoising_step=is_first_step, + )[0] + + if self.do_classifier_free_guidance: + with self.transformer.cache_context("cond_uncond"): + noise_uncond = self.transformer( + hidden_states=latents.to(transformer_dtype), + timestep=timestep, + encoder_hidden_states=negative_prompt_embeds, + attention_kwargs=attention_kwargs, + return_dict=False, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + is_first_denoising_step=is_first_step, + )[0] + + if use_cfg_zero_star: + noise_pred_text = noise_pred + positive_flat = noise_pred_text.view(batch_size, -1) + negative_flat = noise_uncond.view(batch_size, -1) + + alpha = optimized_scale(positive_flat, negative_flat) + alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1))) + alpha = alpha.to(noise_pred_text.dtype) + + if (i_s == 0 and idx <= zero_steps) and use_zero_init: + noise_pred = noise_pred_text * 0.0 + else: + noise_pred = noise_uncond * alpha + guidance_scale * ( + noise_pred_text - noise_uncond * alpha + ) + else: + noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond) + + if use_dmd: + pred_image_or_video = convert_flow_pred_to_x0( + flow_pred=noise_pred, + xt=latents, + timestep=timestep, + sigmas=self.scheduler.sigmas, + timesteps=self.scheduler.timesteps, + ) + if idx < len(timesteps) - 1: + latents = add_noise( + pred_image_or_video, + start_point_list[i_s], + timesteps[idx + 1] * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device), + sigmas=self.scheduler.sigmas, + timesteps=self.scheduler.timesteps, + ) + else: + latents = pred_image_or_video + else: + if scheduler_type == "unipc": + latents = self.scheduler.step_unipc(noise_pred.float(), t, latents, return_dict=False)[0] + else: + latents = self.scheduler.step(noise_pred.float(), t, latents, return_dict=False)[0] + + if callback_on_step_end is not None: + callback_kwargs = {} + for k in callback_on_step_end_tensor_inputs: + callback_kwargs[k] = locals()[k] + callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) + + latents = callback_outputs.pop("latents", latents) + prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) + negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) + + progress_bar.update() + + if XLA_AVAILABLE: + xm.mark_step() + + i += 1 + + return latents + + @property + def guidance_scale(self): + return self._guidance_scale + + @property + def do_classifier_free_guidance(self): + return self._guidance_scale > 1.0 + + @property + def num_timesteps(self): + return self._num_timesteps + + @property + def current_timestep(self): + return self._current_timestep + + @property + def interrupt(self): + return self._interrupt + + @property + def attention_kwargs(self): + return self._attention_kwargs + + @torch.no_grad() + @replace_example_docstring(EXAMPLE_DOC_STRING) + def __call__( + self, + prompt: Union[str, List[str]] = None, + negative_prompt: Union[str, List[str]] = None, + height: int = 384, + width: int = 640, + num_frames: int = 73, + num_inference_steps: int = 50, + guidance_scale: float = 5.0, + num_videos_per_prompt: Optional[int] = 1, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.Tensor] = None, + prompt_embeds: Optional[torch.Tensor] = None, + negative_prompt_embeds: Optional[torch.Tensor] = None, + output_type: Optional[str] = "np", + return_dict: bool = True, + attention_kwargs: Optional[Dict[str, Any]] = None, + callback_on_step_end: Optional[ + Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks] + ] = None, + callback_on_step_end_tensor_inputs: List[str] = ["latents"], + max_sequence_length: int = 512, + # ------------ I2V ------------ + image: Optional[PipelineImageInput] = None, + image_latents: Optional[torch.Tensor] = None, + fake_image_latents: Optional[torch.Tensor] = None, + add_noise_to_image_latents: bool = True, + image_noise_sigma_min: float = 0.111, + image_noise_sigma_max: float = 0.135, + # ------------ V2V ------------ + video: Optional[PipelineImageInput] = None, + video_latents: Optional[torch.Tensor] = None, + add_noise_to_video_latents: bool = True, + video_noise_sigma_min: float = 0.111, + video_noise_sigma_max: float = 0.135, + # ------------ Interactive ------------ + use_interpolate_prompt: bool = False, + interpolate_time_list: list = [7, 7, 7], + interpolation_steps: int = 3, + # ------------ Stage 1 ------------ + history_sizes: list = [16, 2, 1], + latent_window_size: int = 9, + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + is_keep_x0: bool = True, + # ------------ Stage 2 ------------ + is_enable_stage2: bool = False, + stage2_num_stages: int = 3, + stage2_num_inference_steps_list: list = [10, 10, 10], + scheduler_type: str = "unipc", # unipc, euler + # ------------ CFG Zero ------------ + use_cfg_zero_star: Optional[bool] = False, + use_zero_init: Optional[bool] = True, + zero_steps: Optional[int] = 1, + # ------------ DMD ------------ + use_dmd: bool = False, + is_skip_first_section: bool = False, + is_amplify_first_chunk: bool = False, + # ------------ Adaptive Anti-Drifting ------------ + use_adaptive_anti_drifting: bool = False, + anti_drift_rho_mu: float = 0.9, + anti_drift_rho_sigma: float = 0.9, + anti_drift_delta_mu: float = 0.15, + anti_drift_delta_sigma: float = 0.15, + anti_drift_corruption_strength: float = 0.1, + # ------------ other ------------ + use_kv_cache: bool = False, + vae_decode_type: VAEDecodeType = "default", # "default", "default_batch" + ): + r""" + The call function to the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds` + instead. Ignored when not using guidance (`guidance_scale` < `1`). + height (`int`, defaults to `480`): + The height in pixels of the generated image. + width (`int`, defaults to `832`): + The width in pixels of the generated image. + num_frames (`int`, defaults to `81`): + The number of frames in the generated video. + num_inference_steps (`int`, defaults to `50`): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, defaults to `5.0`): + Guidance scale as defined in [Classifier-Free Diffusion + Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2. + of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting + `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to + the text `prompt`, usually at the expense of lower image quality. + num_videos_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make + generation deterministic. + latents (`torch.Tensor`, *optional*): + Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor is generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not + provided, text embeddings are generated from the `prompt` input argument. + output_type (`str`, *optional*, defaults to `"np"`): + The output format of the generated image. Choose between `PIL.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`HeliosPipelineOutput`] instead of a plain tuple. + attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*): + A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of + each denoising step during the inference. with the following arguments: `callback_on_step_end(self: + DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a + list of all tensors as specified by `callback_on_step_end_tensor_inputs`. + callback_on_step_end_tensor_inputs (`List`, *optional*): + The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list + will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the + `._callback_tensor_inputs` attribute of your pipeline class. + max_sequence_length (`int`, defaults to `512`): + The maximum sequence length of the text encoder. If the prompt is longer than this, it will be + truncated. If the prompt is shorter, it will be padded to this length. + + Examples: + + Returns: + [`~HeliosPipelineOutput`] or `tuple`: + If `return_dict` is `True`, [`HeliosPipelineOutput`] is returned, otherwise a `tuple` is returned where + the first element is a list with the generated images and the second element is a list of `bool`s + indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content. + """ + + if image is not None and video is not None: + raise ValueError("image and video cannot be provided simultaneously") + + if use_kv_cache: + self.transformer.enable_kv_cache() + + if use_interpolate_prompt: + assert num_videos_per_prompt == 1, f"num_videos_per_prompt must be 1, got {num_videos_per_prompt}" + assert isinstance(prompt, list), "prompt must be a list" + assert len(prompt) == len(interpolate_time_list), ( + f"Length mismatch: {len(prompt)} vs {len(interpolate_time_list)}" + ) + assert min(interpolate_time_list) > interpolation_steps, ( + f"Minimum value {min(interpolate_time_list)} must be greater than {interpolation_steps}" + ) + interpolate_interval_idx = None + interpolate_embeds = None + interpolate_cumulative_list = list(accumulate(interpolate_time_list)) + + anti_drifting_helper = None + if use_adaptive_anti_drifting: + anti_drifting_helper = AdaptiveAntiDrifting( + rho_mu=anti_drift_rho_mu, + rho_sigma=anti_drift_rho_sigma, + delta_mu=anti_drift_delta_mu, + delta_sigma=anti_drift_delta_sigma, + device=self._execution_device, + dtype=torch.float32, + ) + + history_sizes = sorted(history_sizes, reverse=True) # From big to small + + latents_mean = ( + torch.tensor(self.vae.config.latents_mean) + .view(1, self.vae.config.z_dim, 1, 1, 1) + .to(self.vae.device, self.vae.dtype) + ) + latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to( + self.vae.device, self.vae.dtype + ) + + if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)): + callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs + + # 1. Check inputs. Raise error if not correct + self.check_inputs( + prompt, + negative_prompt, + height, + width, + prompt_embeds, + negative_prompt_embeds, + callback_on_step_end_tensor_inputs, + ) + + num_frames = max(num_frames, 1) + + self._guidance_scale = guidance_scale + self._attention_kwargs = attention_kwargs + self._current_timestep = None + self._interrupt = False + + device = self._execution_device + vae_dtype = self.vae.dtype + + # 2. Define call parameters + if use_interpolate_prompt or (prompt is not None and isinstance(prompt, str)): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + # 3. Encode input prompt + all_prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask = ( + self.encode_prompt( + prompt=prompt, + negative_prompt=negative_prompt, + do_classifier_free_guidance=self.do_classifier_free_guidance, + num_videos_per_prompt=num_videos_per_prompt, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + max_sequence_length=max_sequence_length, + device=device, + ) + ) + + transformer_dtype = self.transformer.dtype + all_prompt_embeds = all_prompt_embeds.to(transformer_dtype) + if negative_prompt_embeds is not None: + if use_interpolate_prompt: + negative_prompt_embeds = negative_prompt_embeds[0].unsqueeze(0) + negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype) + + # 4. Prepare image + if image is not None: + image = self.video_processor.preprocess(image, height=height, width=width) + image_latents, fake_image_latents = self.prepare_image_latents( + image, + latents_mean=latents_mean, + latents_std=latents_std, + dtype=torch.float32, + device=device, + generator=generator, + latents=image_latents, + fake_latents=fake_image_latents, + ) + + if image_latents is not None and add_noise_to_image_latents: + image_noise_sigma = ( + torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min) + + image_noise_sigma_min + ) + image_latents = ( + image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device) + + (1 - image_noise_sigma) * image_latents + ) + fake_image_noise_sigma = ( + torch.rand(1, device=device, generator=generator) * (video_noise_sigma_max - video_noise_sigma_min) + + video_noise_sigma_min + ) + fake_image_latents = ( + fake_image_noise_sigma * randn_tensor(fake_image_latents.shape, generator=generator, device=device) + + (1 - fake_image_noise_sigma) * fake_image_latents + ) + + if video is not None: + video = self.video_processor.preprocess_video(video, height=height, width=width) + image_latents, video_latents = self.prepare_video_latents( + video, + latents_mean=latents_mean, + latents_std=latents_std, + latent_window_size=latent_window_size, + dtype=torch.float32, + device=device, + generator=generator, + latents=video_latents, + ) + + if video_latents is not None and add_noise_to_video_latents: + image_noise_sigma = ( + torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min) + + image_noise_sigma_min + ) + image_latents = ( + image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device) + + (1 - image_noise_sigma) * image_latents + ) + + noisy_latents_chunks = [] + num_latent_chunks = video_latents.shape[2] // latent_window_size + for i in range(num_latent_chunks): + chunk_start = i * latent_window_size + chunk_end = chunk_start + latent_window_size + latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :] + + chunk_frames = latent_chunk.shape[2] + frame_sigmas = ( + torch.rand(chunk_frames, device=device, generator=generator) + * (video_noise_sigma_max - video_noise_sigma_min) + + video_noise_sigma_min + ) + frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1) + + noisy_chunk = ( + frame_sigmas * randn_tensor(latent_chunk.shape, generator=generator, device=device) + + (1 - frame_sigmas) * latent_chunk + ) + noisy_latents_chunks.append(noisy_chunk) + video_latents = torch.cat(noisy_latents_chunks, dim=2) + + # 5. Prepare latent variables + num_channels_latents = self.transformer.config.in_channels + window_num_frames = (latent_window_size - 1) * self.vae_scale_factor_temporal + 1 + num_latent_sections = max(1, (num_frames + window_num_frames - 1) // window_num_frames) + history_video = None + total_generated_latent_frames = 0 + + if not is_keep_x0: + history_sizes[-1] = history_sizes[-1] + 1 + history_latents = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes), + height // self.vae_scale_factor_spatial, + width // self.vae_scale_factor_spatial, + device=device, + dtype=torch.float32, + ) + if fake_image_latents is not None: + history_latents = torch.cat([history_latents, fake_image_latents], dim=2) + total_generated_latent_frames += 1 + if video_latents is not None: + history_frames = history_latents.shape[2] + video_frames = video_latents.shape[2] + if video_frames < history_frames: + keep_frames = history_frames - video_frames + history_latents = torch.cat([history_latents[:, :, :keep_frames, :, :], video_latents], dim=2) + else: + history_latents = video_latents + total_generated_latent_frames += video_latents.shape[2] + + # 6. Denoising loop + if use_interpolate_prompt: + if num_latent_sections < max(interpolate_cumulative_list): + num_latent_sections = sum(interpolate_cumulative_list) + print(f"Update num_latent_sections to: {num_latent_sections}") + + for k in range(num_latent_sections): + if use_interpolate_prompt: + assert num_latent_sections >= max(interpolate_cumulative_list) + + current_interval_idx = 0 + for idx, cumulative_val in enumerate(interpolate_cumulative_list): + if k < cumulative_val: + current_interval_idx = idx + break + + if current_interval_idx == 0: + prompt_embeds = all_prompt_embeds[0].unsqueeze(0) + else: + interval_start = interpolate_cumulative_list[current_interval_idx - 1] + position_in_interval = k - interval_start + + if position_in_interval < interpolation_steps: + if interpolate_embeds is None or interpolate_interval_idx != current_interval_idx: + interpolate_embeds = self.interpolate_prompt_embeds( + prompt_embeds_1=all_prompt_embeds[current_interval_idx - 1].unsqueeze(0), + prompt_embeds_2=all_prompt_embeds[current_interval_idx].unsqueeze(0), + interpolation_steps=interpolation_steps, + ) + interpolate_interval_idx = current_interval_idx + + prompt_embeds = interpolate_embeds[position_in_interval] + else: + prompt_embeds = all_prompt_embeds[current_interval_idx].unsqueeze(0) + else: + prompt_embeds = all_prompt_embeds + + is_first_section = k == 0 + is_second_section = k == 1 + if is_keep_x0: + if is_first_section: + history_sizes_first_section = [1] + history_sizes.copy() + history_latents_first_section = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes_first_section), + height // self.vae_scale_factor_spatial, + width // self.vae_scale_factor_spatial, + device=device, + dtype=torch.float32, + ) + if fake_image_latents is not None: + history_latents_first_section = torch.cat( + [history_latents_first_section, fake_image_latents], dim=2 + ) + if video_latents is not None: + history_frames = history_latents_first_section.shape[2] + video_frames = video_latents.shape[2] + if video_frames < history_frames: + keep_frames = history_frames - video_frames + history_latents_first_section = torch.cat( + [history_latents_first_section[:, :, :keep_frames, :, :], video_latents], dim=2 + ) + else: + history_latents_first_section = video_latents + + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix, latents_history_long, latents_history_mid, latents_history_1x = ( + history_latents_first_section[:, :, -sum(history_sizes_first_section) :].split( + history_sizes_first_section, dim=2 + ) + ) + if image_latents is not None: + latents_prefix = image_latents + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix = image_latents + latents_history_long, latents_history_mid, latents_history_1x = history_latents[ + :, :, -sum(history_sizes) : + ].split(history_sizes, dim=2) + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + indices = torch.arange(0, sum([*history_sizes, latent_window_size])) + ( + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_short, + indices_hidden_states, + ) = indices.split([*history_sizes, latent_window_size], dim=0) + latents_history_long, latents_history_mid, latents_history_short = history_latents[ + :, :, -sum(history_sizes) : + ].split(history_sizes, dim=2) + + latents = self.prepare_latents( + batch_size, + num_channels_latents, + height, + width, + window_num_frames, + dtype=torch.float32, + device=device, + generator=generator, + latents=None, + ) + + if not is_enable_stage2: + self.scheduler.set_timesteps(num_inference_steps, mu=1, device=device) + + if use_dynamic_shifting: + sigmas = torch.linspace( + 0.999, 0.0, steps=num_inference_steps + 1, dtype=torch.float32, device=device + )[:-1] + sigmas = apply_schedule_shift( + sigmas=sigmas, + noise=latents, + base_seq_len=self.scheduler.config.get("base_image_seq_len", 256), + max_seq_len=self.scheduler.config.get("max_image_seq_len", 4096), + base_shift=self.scheduler.config.get("base_shift", 0.5), + max_shift=self.scheduler.config.get("max_shift", 1.15), + time_shift_type=time_shift_type, + ) + timesteps = sigmas * 1000.0 # rescale to [0, 1000.0) + timesteps = timesteps.to(device) + sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)]) + self.scheduler.timesteps = timesteps + self.scheduler.sigmas = sigmas + + timesteps = self.scheduler.timesteps + + dmd_sigmas = None + dmd_timesteps = None + if use_dmd: + dmd_sigmas = self.scheduler.sigmas.to(self.transformer.device) + dmd_timesteps = self.scheduler.timesteps.to(self.transformer.device) + + self._num_timesteps = len(timesteps) + else: + num_inference_steps = ( + sum(stage2_num_inference_steps_list) * 2 + if is_amplify_first_chunk and use_dmd and is_first_section + else sum(stage2_num_inference_steps_list) + ) + + with self.progress_bar(total=num_inference_steps) as progress_bar: + if is_enable_stage2: + latents = self.stage2_sample( + latents=latents, + stage2_num_stages=stage2_num_stages, + stage2_num_inference_steps_list=stage2_num_inference_steps_list, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + guidance_scale=guidance_scale, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + attention_kwargs=attention_kwargs, + device=device, + transformer_dtype=transformer_dtype, + scheduler_type=scheduler_type, + use_dynamic_shifting=use_dynamic_shifting, + time_shift_type=time_shift_type, + generator=generator, + # ------------ CFG Zero ------------ + use_cfg_zero_star=use_cfg_zero_star, + use_zero_init=use_zero_init, + zero_steps=zero_steps, + # -------------- DMD -------------- + use_dmd=use_dmd, + is_amplify_first_chunk=is_amplify_first_chunk and is_first_section, + # ------------ Callback ------------ + callback_on_step_end=callback_on_step_end, + callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, + progress_bar=progress_bar, + ) + else: + latents = self.stage1_sample( + latents=latents, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + timesteps=timesteps, + guidance_scale=guidance_scale, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + attention_kwargs=attention_kwargs, + device=device, + transformer_dtype=transformer_dtype, + generator=generator, + # ------------ CFG Zero ------------ + use_cfg_zero_star=use_cfg_zero_star, + use_zero_init=use_zero_init, + zero_steps=zero_steps, + # -------------- DMD -------------- + use_dmd=use_dmd, + dmd_sigmas=dmd_sigmas, + dmd_timesteps=dmd_timesteps, + is_amplify_first_chunk=is_amplify_first_chunk and is_first_section, + # ------------ Callback ------------ + callback_on_step_end=callback_on_step_end, + callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, + progress_bar=progress_bar, + ) + + if use_kv_cache: + self.transformer.clear_kv_cache() + + if use_adaptive_anti_drifting: + current_mean, current_var = anti_drifting_helper.compute_latent_statistics(latents) + anti_drifting_helper.update_global_statistics(current_mean, current_var) + has_drift = anti_drifting_helper.detect_drift(current_mean, current_var) + + if has_drift and k < num_latent_sections - 1: + print( + f"Drift detected at chunk {k + 1}/{num_latent_sections}. Applying Frame-Aware Corruption." + ) + latents = anti_drifting_helper.apply_frame_aware_corruption( + latents, + corruption_strength=anti_drift_corruption_strength, + generator=generator, + ) + + if is_keep_x0 and ( + (is_first_section and image_latents is None) or (is_skip_first_section and is_second_section) + ): + image_latents = latents[:, :, 0:1, :, :] + + total_generated_latent_frames += latents.shape[2] + history_latents = torch.cat([history_latents, latents], dim=2) + real_history_latents = history_latents[:, :, -total_generated_latent_frames:] + index_slice = ( + slice(None), + slice(None), + slice(-latent_window_size, None), + ) + + if vae_decode_type == "default": + current_latents = real_history_latents[index_slice].to(vae_dtype) / latents_std + latents_mean + current_video = self.vae.decode(current_latents, return_dict=False)[0] + + if history_video is None: + history_video = current_video + else: + history_video = torch.cat([history_video, current_video], dim=2) + + self._current_timestep = None + + if output_type != "latent": + if vae_decode_type == "default_batch": + total_latent_frames = real_history_latents.shape[2] + batch_size = real_history_latents.shape[0] + num_chunks = total_latent_frames // latent_window_size + + chunks = ( + real_history_latents.reshape( + batch_size, + -1, + num_chunks, + latent_window_size, + real_history_latents.shape[-2], + real_history_latents.shape[-1], + ) + .permute(0, 2, 1, 3, 4, 5) + .reshape( + batch_size * num_chunks, + -1, + latent_window_size, + real_history_latents.shape[-2], + real_history_latents.shape[-1], + ) + ) + + chunks = chunks.to(vae_dtype) / latents_std + latents_mean + batch_video = self.vae.decode(chunks, return_dict=False)[0] + + video_frames_per_chunk = batch_video.shape[2] + history_video = ( + batch_video.reshape( + batch_size, + num_chunks, + -1, + video_frames_per_chunk, + batch_video.shape[-2], + batch_video.shape[-1], + ) + .permute(0, 2, 1, 3, 4, 5) + .reshape( + batch_size, + -1, + num_chunks * video_frames_per_chunk, + batch_video.shape[-2], + batch_video.shape[-1], + ) + ) + + generated_frames = history_video.size(2) + generated_frames = ( + generated_frames - 1 + ) // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1 + history_video = history_video[:, :, :generated_frames] + video = self.video_processor.postprocess_video(history_video, output_type=output_type) + else: + video = real_history_latents + + # Offload all models + self.maybe_free_model_hooks() + + if not return_dict: + return (video,) + + return HeliosPipelineOutput(frames=video) diff --git a/Helios/helios/pipelines/pipeline_helios_ode.py b/Helios/helios/pipelines/pipeline_helios_ode.py new file mode 100644 index 0000000000000000000000000000000000000000..2af787661753475ef4484a589fa9b23c992b7517 --- /dev/null +++ b/Helios/helios/pipelines/pipeline_helios_ode.py @@ -0,0 +1,1510 @@ +# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import html +import math +from enum import Enum +from itertools import accumulate +from typing import Any, Callable, Dict, List, Literal, Optional, Union + +import regex as re +import torch +import torch.nn.functional as F +from einops import rearrange +from transformers import AutoTokenizer, UMT5EncoderModel + +from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback +from diffusers.image_processor import PipelineImageInput +from diffusers.loaders import WanLoraLoaderMixin +from diffusers.models import AutoencoderKLWan +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.schedulers import UniPCMultistepScheduler +from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring +from diffusers.utils.torch_utils import randn_tensor +from diffusers.video_processor import VideoProcessor + +from ..modules.transformer_helios import HeliosTransformer3DModel +from ..scheduler.scheduling_helios import HeliosScheduler +from ..utils.utils_base import AdaptiveAntiDrifting, apply_schedule_shift +from ..utils.utils_helios_post import add_noise, convert_flow_pred_to_x0 + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + XLA_AVAILABLE = True +else: + XLA_AVAILABLE = False + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + +if is_ftfy_available(): + import ftfy + + +EXAMPLE_DOC_STRING = """ + Examples: + ```python + >>> import torch + >>> from diffusers.utils import export_to_video + >>> from diffusers import AutoencoderKLWan, HeliosPipeline + + >>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled + >>> model_id = "BestWishYsh/Helios-Base" + >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) + >>> pipe = HeliosPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16) + >>> pipe.to("cuda") + + >>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window." + >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" + + >>> output = pipe( + ... prompt=prompt, + ... negative_prompt=negative_prompt, + ... height=384, + ... width=640, + ... num_frames=132, + ... guidance_scale=5.0, + ... ).frames[0] + >>> export_to_video(output, "output.mp4", fps=24) + ``` +""" + + +@torch.amp.autocast("cuda", dtype=torch.float32) +def optimized_scale(positive_flat, negative_flat): + # Calculate dot production + dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True) + + # Squared norm of uncondition + squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8 + + # st_star = v_cond^T * v_uncond / ||v_uncond||^2 + st_star = dot_product / squared_norm + + return st_star + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r"\s+", " ", text) + text = text.strip() + return text + + +def prompt_clean(text): + text = whitespace_clean(basic_clean(text)) + return text + + +class VAEDecodeType(str, Enum): + DEFAULT = "default" + DEFAULT_BATCH = "default_batch" + + +class HeliosPipeline(DiffusionPipeline, WanLoraLoaderMixin): + r""" + Pipeline for text-to-video / image-to-video / video-to-video generation using Helios. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods + implemented for all pipelines (downloading, saving, running on a particular device, etc.). + + Args: + tokenizer ([`T5Tokenizer`]): + Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer), + specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant. + text_encoder ([`T5EncoderModel`]): + [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically + the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant. + transformer ([`HeliosTransformer3DModel`]): + Conditional Transformer to denoise the input latents. + scheduler ([`UniPCMultistepScheduler`]): + A scheduler to be used in combination with `transformer` to denoise the encoded image latents. + vae ([`AutoencoderKLWan`]): + Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations. + """ + + model_cpu_offload_seq = "text_encoder->transformer->vae" + _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"] + _optional_components = ["transformer"] + + def __init__( + self, + tokenizer: AutoTokenizer, + text_encoder: UMT5EncoderModel, + vae: AutoencoderKLWan, + scheduler: UniPCMultistepScheduler | HeliosScheduler, + transformer: HeliosTransformer3DModel, + ): + super().__init__() + + self.register_modules( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + transformer=transformer, + scheduler=scheduler, + ) + self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4 + self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8 + self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial) + + def _get_t5_prompt_embeds( + self, + prompt: Union[str, List[str]] = None, + num_videos_per_prompt: int = 1, + max_sequence_length: int = 226, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ): + device = device or self._execution_device + dtype = dtype or self.text_encoder.dtype + + prompt = [prompt] if isinstance(prompt, str) else prompt + prompt = [prompt_clean(u) for u in prompt] + batch_size = len(prompt) + + text_inputs = self.tokenizer( + prompt, + padding="max_length", + max_length=max_sequence_length, + truncation=True, + add_special_tokens=True, + return_attention_mask=True, + return_tensors="pt", + ) + text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask + seq_lens = mask.gt(0).sum(dim=1).long() + + prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state + prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) + prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)] + prompt_embeds = torch.stack( + [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0 + ) + + # duplicate text embeddings for each generation per prompt, using mps friendly method + _, seq_len, _ = prompt_embeds.shape + prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1) + prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1) + + return prompt_embeds, text_inputs.attention_mask.bool() + + def encode_prompt( + self, + prompt: Union[str, List[str]], + negative_prompt: Optional[Union[str, List[str]]] = None, + do_classifier_free_guidance: bool = True, + num_videos_per_prompt: int = 1, + prompt_embeds: Optional[torch.Tensor] = None, + negative_prompt_embeds: Optional[torch.Tensor] = None, + max_sequence_length: int = 226, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + do_classifier_free_guidance (`bool`, *optional*, defaults to `True`): + Whether to use classifier free guidance or not. + num_videos_per_prompt (`int`, *optional*, defaults to 1): + Number of videos that should be generated per prompt. torch device to place the resulting embeddings on + prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + device: (`torch.device`, *optional*): + torch device + dtype: (`torch.dtype`, *optional*): + torch dtype + """ + device = device or self._execution_device + + prompt = [prompt] if isinstance(prompt, str) else prompt + if prompt is not None: + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + if prompt_embeds is None: + prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds( + prompt=prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + device=device, + dtype=dtype, + ) + + negative_prompt_attention_mask = None + if do_classifier_free_guidance and negative_prompt_embeds is None: + negative_prompt = negative_prompt or "" + negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt + + if prompt is not None and type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + + negative_prompt_embeds, negative_prompt_attention_mask = self._get_t5_prompt_embeds( + prompt=negative_prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + device=device, + dtype=dtype, + ) + + return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask + + def check_inputs( + self, + prompt, + negative_prompt, + height, + width, + prompt_embeds=None, + negative_prompt_embeds=None, + callback_on_step_end_tensor_inputs=None, + ): + if height % 16 != 0 or width % 16 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.") + + if callback_on_step_end_tensor_inputs is not None and not all( + k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs + ): + raise ValueError( + f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" + ) + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + elif negative_prompt is not None and ( + not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list) + ): + raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}") + + def prepare_latents( + self, + batch_size: int, + num_channels_latents: int = 16, + height: int = 480, + width: int = 832, + num_frames: int = 81, + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + if latents is not None: + return latents.to(device=device, dtype=dtype) + + num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1 + shape = ( + batch_size, + num_channels_latents, + num_latent_frames, + int(height) // self.vae_scale_factor_spatial, + int(width) // self.vae_scale_factor_spatial, + ) + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + return latents + + def prepare_image_latents( + self, + image: torch.Tensor, + latents_mean: torch.Tensor, + latents_std: torch.Tensor, + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.Tensor] = None, + fake_latents: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + device = device or self._execution_device + if latents is None: + image = image.unsqueeze(2).to(device=device, dtype=self.vae.dtype) + latents = self.vae.encode(image).latent_dist.sample(generator=generator) + latents = (latents - latents_mean) * latents_std + if fake_latents is None: + fake_video = image.repeat(1, 1, 33, 1, 1).to(device=device, dtype=self.vae.dtype) + fake_latents_full = self.vae.encode(fake_video).latent_dist.sample(generator=generator) + fake_latents_full = (fake_latents_full - latents_mean) * latents_std + fake_latents = fake_latents_full[:, :, -1:, :, :] + return latents.to(device=device, dtype=dtype), fake_latents.to(device=device, dtype=dtype) + + def prepare_video_latents( + self, + video: torch.Tensor, + latents_mean: torch.Tensor, + latents_std: torch.Tensor, + latent_window_size: int, + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + device = device or self._execution_device + video = video.to(device=device, dtype=self.vae.dtype) + if latents is None: + num_frames = video.shape[2] + min_frames = (latent_window_size - 1) * 4 + 1 + num_chunks = num_frames // min_frames + if num_chunks == 0: + raise ValueError( + f"Video must have at least {min_frames} frames " + f"(got {num_frames} frames). " + f"Required: (latent_window_size - 1) * 4 + 1 = ({latent_window_size} - 1) * 4 + 1 = {min_frames}" + ) + total_valid_frames = num_chunks * min_frames + start_frame = num_frames - total_valid_frames + + first_frame = video[:, :, 0:1, :, :] + first_frame_latent = self.vae.encode(first_frame).latent_dist.sample(generator=generator) + first_frame_latent = (first_frame_latent - latents_mean) * latents_std + + latents_chunks = [] + for i in range(num_chunks - 1, -1, -1): + chunk_start = start_frame + i * min_frames + chunk_end = chunk_start + min_frames + video_chunk = video[:, :, chunk_start:chunk_end, :, :] + chunk_latents = self.vae.encode(video_chunk).latent_dist.sample(generator=generator) + chunk_latents = (chunk_latents - latents_mean) * latents_std + latents_chunks.insert(0, chunk_latents) + latents = torch.cat(latents_chunks, dim=2) + return first_frame_latent.to(device=device, dtype=dtype), latents.to(device=device, dtype=dtype) + + def interpolate_prompt_embeds( + self, + prompt_embeds_1: torch.Tensor, + prompt_embeds_2: torch.Tensor, + interpolation_steps: int = 4, + ): + x = torch.lerp( + prompt_embeds_1, + prompt_embeds_2, + torch.linspace(0, 1, steps=interpolation_steps).unsqueeze(1).unsqueeze(2).to(prompt_embeds_1), + ) + interpolated_prompt_embeds = list(x.chunk(interpolation_steps, dim=0)) + return interpolated_prompt_embeds + + def sample_block_noise( + self, + batch_size, + channel, + num_frames, + height, + width, + patch_size: tuple[int, ...] = (1, 2, 2), + device: torch.device | None = None, + generator: torch.Generator | None = None, + ): + # NOTE: A generator must be provided to ensure correct and reproducible results. + # Creating a default generator here is a fallback only — without a fixed seed, + # the output will be non-deterministic and may produce incorrect results in CP context. + if generator is None: + generator = torch.Generator(device=device) + elif isinstance(generator, list): + generator = generator[0] + + gamma = self.scheduler.config.gamma + _, ph, pw = patch_size + block_size = ph * pw + + cov = ( + torch.eye(block_size, device=device) * (1 + gamma) + - torch.ones(block_size, block_size, device=device) * gamma + ) + cov += torch.eye(block_size, device=device) * 1e-8 + cov = cov.float() # Upcast to fp32 for numerical stability — cholesky is unreliable in fp16/bf16. + + L = torch.linalg.cholesky(cov) + block_number = batch_size * channel * num_frames * (height // ph) * (width // pw) + z = torch.randn(block_number, block_size, generator=generator, device=generator.device).to(device=device) + noise = z @ L.T + + noise = noise.view(batch_size, channel, num_frames, height // ph, width // pw, ph, pw) + noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(batch_size, channel, num_frames, height, width) + + return noise + + def stage1_sample( + self, + latents: torch.Tensor = None, + prompt_embeds: torch.Tensor = None, + negative_prompt_embeds: torch.Tensor = None, + timesteps: torch.Tensor = None, + guidance_scale: Optional[float] = 5.0, + indices_hidden_states: torch.Tensor = None, + indices_latents_history_short: torch.Tensor = None, + indices_latents_history_mid: torch.Tensor = None, + indices_latents_history_long: torch.Tensor = None, + latents_history_short: torch.Tensor = None, + latents_history_mid: torch.Tensor = None, + latents_history_long: torch.Tensor = None, + attention_kwargs: Optional[dict] = None, + device: Optional[torch.device] = None, + transformer_dtype: torch.dtype = None, + generator: Optional[torch.Generator] = None, + # ------------ CFG Zero ------------ + use_cfg_zero_star: Optional[bool] = False, + use_zero_init: Optional[bool] = True, + zero_steps: Optional[int] = 1, + # -------------- DMD -------------- + use_dmd: bool = False, + dmd_sigmas: torch.Tensor = None, + dmd_timesteps: torch.Tensor = None, + # ------------ Callback ------------ + callback_on_step_end: Optional[callable] = None, + callback_on_step_end_tensor_inputs: list = None, + progress_bar=None, + ): + batch_size = latents.shape[0] + + for i, t in enumerate(timesteps): + is_first_step = i == 0 + + if self.interrupt: + continue + + self._current_timestep = t + timestep = t.expand(latents.shape[0]) + + latent_model_input = latents.to(transformer_dtype) + with self.transformer.cache_context("cond"): + noise_pred = self.transformer( + hidden_states=latent_model_input, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + is_first_denoising_step=is_first_step, + attention_kwargs=attention_kwargs, + return_dict=False, + )[0] + + if self.do_classifier_free_guidance and not use_dmd: + with self.transformer.cache_context("uncond"): + noise_uncond = self.transformer( + hidden_states=latent_model_input, + timestep=timestep, + encoder_hidden_states=negative_prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + is_first_denoising_step=is_first_step, + attention_kwargs=attention_kwargs, + return_dict=False, + )[0] + + if use_cfg_zero_star: + noise_pred_text = noise_pred + positive_flat = noise_pred_text.view(batch_size, -1) + negative_flat = noise_uncond.view(batch_size, -1) + + alpha = optimized_scale(positive_flat, negative_flat) + alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1))) + alpha = alpha.to(noise_pred_text.dtype) + + if (i <= zero_steps) and use_zero_init: + noise_pred = noise_pred_text * 0.0 + else: + noise_pred = noise_uncond * alpha + guidance_scale * (noise_pred_text - noise_uncond * alpha) + else: + noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond) + + if use_dmd: + pred_image_or_video = convert_flow_pred_to_x0( + flow_pred=noise_pred, + xt=latent_model_input, + timestep=t * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device), + sigmas=dmd_sigmas, + timesteps=dmd_timesteps, + ) + if i < len(timesteps) - 1: + latents = add_noise( + pred_image_or_video, + randn_tensor(pred_image_or_video.shape, generator=generator, device=device), + timesteps[i + 1] * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device), + sigmas=dmd_sigmas, + timesteps=dmd_timesteps, + ) + else: + latents = pred_image_or_video + else: + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0] + + if callback_on_step_end is not None: + callback_kwargs = {} + for k in callback_on_step_end_tensor_inputs: + callback_kwargs[k] = locals()[k] + callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) + + latents = callback_outputs.pop("latents", latents) + prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) + negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) + + progress_bar.update() + + if XLA_AVAILABLE: + xm.mark_step() + + return latents + + def stage2_sample( + self, + is_first_section, + latents: torch.Tensor = None, + stage2_num_stages: int = None, + stage2_num_inference_steps_list: List[int] = None, + prompt_embeds: torch.Tensor = None, + negative_prompt_embeds: torch.Tensor = None, + guidance_scale: Optional[float] = 5.0, + indices_hidden_states: torch.Tensor = None, + indices_latents_history_short: torch.Tensor = None, + indices_latents_history_mid: torch.Tensor = None, + indices_latents_history_long: torch.Tensor = None, + latents_history_short: torch.Tensor = None, + latents_history_mid: torch.Tensor = None, + latents_history_long: torch.Tensor = None, + attention_kwargs: Optional[dict] = None, + device: Optional[torch.device] = None, + transformer_dtype: torch.dtype = None, + scheduler_type: str = "unipc", # unipc, euler + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + generator: torch.Generator | list[torch.Generator] | None = None, + # ------------ CFG Zero ------------ + use_cfg_zero_star: Optional[bool] = False, + use_zero_init: Optional[bool] = True, + zero_steps: Optional[int] = 1, + # -------------- DMD -------------- + use_dmd: bool = False, + # ------------ Callback ------------ + callback_on_step_end: Optional[callable] = None, + callback_on_step_end_tensor_inputs: list = None, + progress_bar=None, + ): + num_frames, height, width = ( + latents.shape[-3], + latents.shape[-2], + latents.shape[-1], + ) + latents = rearrange(latents, "b c t h w -> (b t) c h w") + for _ in range(stage2_num_stages - 1): + height //= 2 + width //= 2 + latents = ( + F.interpolate( + latents, + size=(height, width), + mode="bilinear", + ) + * 2 + ) + latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames) + + batch_size = latents.shape[0] + if use_dmd: + start_point_list = [latents] + + ode_stages_tensor = [] + + for i_s in range(stage2_num_stages): + num_steps = stage2_num_inference_steps_list[i_s] + ode_stages_tensor.append( + { + "latents": None, + "timesteps": None, + "noise_pred": None, + } + ) + + i = 0 + for i_s in range(stage2_num_stages): + if use_dmd: + self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s] + 1, i_s, device=device) + self.scheduler.timesteps = self.scheduler.timesteps[:-1] + self.scheduler.sigmas = torch.cat([self.scheduler.sigmas[:-2], self.scheduler.sigmas[-1:]]) + else: + self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s, device=device) + + if i_s > 0: + height *= 2 + width *= 2 + num_frames = latents.shape[2] + latents = rearrange(latents, "b c t h w -> (b t) c h w") + latents = F.interpolate(latents, size=(height, width), mode="nearest") + latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames) + # Fix the stage + ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal + gamma = self.scheduler.config.gamma + alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma) + beta = alpha * (1 - ori_sigma) / math.sqrt(gamma) + + batch_size, channel, num_frames, height, width = latents.shape + noise = self.sample_block_noise( + batch_size, + channel, + num_frames, + height, + width, + self.transformer.config.patch_size, + device, + generator, + ) + noise = noise.to(device=device, dtype=transformer_dtype) + latents = alpha * latents + beta * noise # To fix the block artifact + + if use_dmd: + start_point_list.append(latents) + + if is_first_section: + if i_s == 0: + target_timesteps = [999.0000, 935.1279, 871.2559, 807.3838] + elif i_s == 1: + target_timesteps = [743.2560, 653.9349, 564.6138, 475.2927] + elif i_s == 2: + target_timesteps = [385.6140, 289.5564, 193.4988, 97.4412] + else: + if i_s == 0: + target_timesteps = [999.0000, 871.2559] + elif i_s == 1: + target_timesteps = [743.2560, 564.6138] + elif i_s == 2: + target_timesteps = [385.6140, 193.4988] + + current_timesteps = self.scheduler.timesteps + target_tensor = torch.tensor(target_timesteps, device=device, dtype=current_timesteps.dtype) + + mask = torch.all(torch.abs(current_timesteps.unsqueeze(0) - target_tensor.unsqueeze(1)) >= 1e-4, dim=1) + new_timesteps = target_tensor[mask] + if len(new_timesteps) > 0: + timestep_id = torch.argmin( + ( + new_timesteps.unsqueeze(1) + - self.scheduler.timesteps_per_stage[i_s].unsqueeze(0).to(new_timesteps.device) + ).abs(), + dim=1, + ) + new_sigmas = self.scheduler.sigmas_per_stage[i_s].to(new_timesteps.device)[timestep_id] + + merged_timesteps = torch.cat([current_timesteps, new_timesteps]) + merged_sigmas = torch.cat([self.scheduler.sigmas[:-1], new_sigmas]) + + sorted_indices = torch.argsort(merged_timesteps, descending=True) + self.scheduler.timesteps = merged_timesteps[sorted_indices] + self.scheduler.sigmas = torch.cat([merged_sigmas[sorted_indices], self.scheduler.sigmas[-1:]]) + + if use_dynamic_shifting: + temp_sigmas = apply_schedule_shift( + self.scheduler.sigmas, + latents, + base_seq_len=self.scheduler.config.get("base_image_seq_len", 256), + max_seq_len=self.scheduler.config.get("max_image_seq_len", 4096), + base_shift=self.scheduler.config.get("base_shift", 0.5), + max_shift=self.scheduler.config.get("max_shift", 1.15), + time_shift_type=time_shift_type, + ) + temp_timesteps = self.scheduler.timesteps_per_stage[i_s].min() + temp_sigmas[:-1] * ( + self.scheduler.timesteps_per_stage[i_s].max() - self.scheduler.timesteps_per_stage[i_s].min() + ) + + self.scheduler.sigmas = temp_sigmas + self.scheduler.timesteps = temp_timesteps + + timesteps = self.scheduler.timesteps + + num_steps = len(timesteps) + ode_stages_tensor[i_s]["timesteps"] = torch.zeros(num_steps, dtype=torch.float32, device="cpu") + + for idx, t in enumerate(timesteps): + if idx == 0: + batch_size, c, t_dim, h, w = latents.shape + num_steps = len(timesteps) + + ode_stages_tensor[i_s]["latents"] = torch.zeros( + num_steps + 1, batch_size, c, t_dim, h, w, dtype=torch.float32, device="cpu" + ) + ode_stages_tensor[i_s]["noise_pred"] = torch.zeros( + num_steps, batch_size, c, t_dim, h, w, dtype=torch.float32, device="cpu" + ) + + is_first_step = i_s == 0 and idx == 0 + + timestep = t.expand(latents.shape[0]).to(torch.int64) + + ode_stages_tensor[i_s]["latents"][idx] = latents.detach().cpu() + ode_stages_tensor[i_s]["timesteps"][idx] = t.item() + + with self.transformer.cache_context("cond"): + noise_pred = self.transformer( + hidden_states=latents.to(transformer_dtype), + timestep=timestep, + encoder_hidden_states=prompt_embeds, + attention_kwargs=attention_kwargs, + return_dict=False, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + is_first_denoising_step=is_first_step, + )[0] + + if self.do_classifier_free_guidance: + with self.transformer.cache_context("cond_uncond"): + noise_uncond = self.transformer( + hidden_states=latents.to(transformer_dtype), + timestep=timestep, + encoder_hidden_states=negative_prompt_embeds, + attention_kwargs=attention_kwargs, + return_dict=False, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(transformer_dtype), + latents_history_mid=latents_history_mid.to(transformer_dtype), + latents_history_long=latents_history_long.to(transformer_dtype), + is_first_denoising_step=is_first_step, + )[0] + + if use_cfg_zero_star: + noise_pred_text = noise_pred + positive_flat = noise_pred_text.view(batch_size, -1) + negative_flat = noise_uncond.view(batch_size, -1) + + alpha = optimized_scale(positive_flat, negative_flat) + alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1))) + alpha = alpha.to(noise_pred_text.dtype) + + if (i_s == 0 and idx <= zero_steps) and use_zero_init: + noise_pred = noise_pred_text * 0.0 + else: + noise_pred = noise_uncond * alpha + guidance_scale * ( + noise_pred_text - noise_uncond * alpha + ) + else: + noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond) + + if use_dmd: + pred_image_or_video = convert_flow_pred_to_x0( + flow_pred=noise_pred, + xt=latents, + timestep=timestep, + sigmas=self.scheduler.sigmas, + timesteps=self.scheduler.timesteps, + ) + if idx < len(timesteps) - 1: + latents = add_noise( + pred_image_or_video, + start_point_list[i_s], + timesteps[idx + 1] * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device), + sigmas=self.scheduler.sigmas, + timesteps=self.scheduler.timesteps, + ) + else: + latents = pred_image_or_video + else: + if scheduler_type == "unipc": + latents = self.scheduler.step_unipc(noise_pred.float(), t, latents, return_dict=False)[0] + else: + latents = self.scheduler.step(noise_pred.float(), t, latents, return_dict=False)[0] + + ode_stages_tensor[i_s]["noise_pred"][idx] = noise_pred.detach().cpu() + + if callback_on_step_end is not None: + callback_kwargs = {} + for k in callback_on_step_end_tensor_inputs: + callback_kwargs[k] = locals()[k] + callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) + + latents = callback_outputs.pop("latents", latents) + prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) + negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) + + progress_bar.update() + + if XLA_AVAILABLE: + xm.mark_step() + + i += 1 + + ode_stages_tensor[i_s]["latents"][num_steps] = latents.detach().cpu() + + return latents, ode_stages_tensor + + @property + def guidance_scale(self): + return self._guidance_scale + + @property + def do_classifier_free_guidance(self): + return self._guidance_scale > 1.0 + + @property + def num_timesteps(self): + return self._num_timesteps + + @property + def current_timestep(self): + return self._current_timestep + + @property + def interrupt(self): + return self._interrupt + + @property + def attention_kwargs(self): + return self._attention_kwargs + + @torch.no_grad() + @replace_example_docstring(EXAMPLE_DOC_STRING) + def __call__( + self, + prompt: Union[str, List[str]] = None, + negative_prompt: Union[str, List[str]] = None, + height: int = 384, + width: int = 640, + num_frames: int = 73, + num_inference_steps: int = 50, + guidance_scale: float = 5.0, + num_videos_per_prompt: Optional[int] = 1, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.Tensor] = None, + prompt_embeds: Optional[torch.Tensor] = None, + negative_prompt_embeds: Optional[torch.Tensor] = None, + output_type: Optional[str] = "np", + return_dict: bool = True, + attention_kwargs: Optional[Dict[str, Any]] = None, + callback_on_step_end: Optional[ + Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks] + ] = None, + callback_on_step_end_tensor_inputs: List[str] = ["latents"], + max_sequence_length: int = 512, + # ------------ I2V ------------ + image: Optional[PipelineImageInput] = None, + image_latents: Optional[torch.Tensor] = None, + fake_image_latents: Optional[torch.Tensor] = None, + add_noise_to_image_latents: bool = True, + image_noise_sigma_min: float = 0.111, + image_noise_sigma_max: float = 0.135, + # ------------ V2V ------------ + video: Optional[PipelineImageInput] = None, + video_latents: Optional[torch.Tensor] = None, + add_noise_to_video_latents: bool = True, + video_noise_sigma_min: float = 0.111, + video_noise_sigma_max: float = 0.135, + # ------------ Interactive ------------ + use_interpolate_prompt: bool = False, + interpolate_time_list: list = [7, 7, 7], + interpolation_steps: int = 3, + # ------------ Stage 1 ------------ + history_sizes: list = [16, 2, 1], + latent_window_size: int = 9, + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + is_keep_x0: bool = True, + # ------------ Stage 2 ------------ + is_enable_stage2: bool = False, + stage2_num_stages: int = 3, + stage2_num_inference_steps_list: list = [10, 10, 10], + scheduler_type: str = "unipc", # unipc, euler + # ------------ CFG Zero ------------ + use_cfg_zero_star: Optional[bool] = False, + use_zero_init: Optional[bool] = True, + zero_steps: Optional[int] = 1, + # ------------ DMD ------------ + use_dmd: bool = False, + is_skip_first_section: bool = False, + # ------------ Adaptive Anti-Drifting ------------ + use_adaptive_anti_drifting: bool = False, + anti_drift_rho_mu: float = 0.9, + anti_drift_rho_sigma: float = 0.9, + anti_drift_delta_mu: float = 0.15, + anti_drift_delta_sigma: float = 0.15, + anti_drift_corruption_strength: float = 0.1, + # ------------ other ------------ + use_kv_cache: bool = False, + vae_decode_type: VAEDecodeType = "default", # "default", "default_batch" + ): + r""" + The call function to the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds` + instead. Ignored when not using guidance (`guidance_scale` < `1`). + height (`int`, defaults to `480`): + The height in pixels of the generated image. + width (`int`, defaults to `832`): + The width in pixels of the generated image. + num_frames (`int`, defaults to `81`): + The number of frames in the generated video. + num_inference_steps (`int`, defaults to `50`): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, defaults to `5.0`): + Guidance scale as defined in [Classifier-Free Diffusion + Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2. + of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting + `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to + the text `prompt`, usually at the expense of lower image quality. + num_videos_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make + generation deterministic. + latents (`torch.Tensor`, *optional*): + Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor is generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not + provided, text embeddings are generated from the `prompt` input argument. + output_type (`str`, *optional*, defaults to `"np"`): + The output format of the generated image. Choose between `PIL.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`HeliosPipelineOutput`] instead of a plain tuple. + attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*): + A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of + each denoising step during the inference. with the following arguments: `callback_on_step_end(self: + DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a + list of all tensors as specified by `callback_on_step_end_tensor_inputs`. + callback_on_step_end_tensor_inputs (`List`, *optional*): + The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list + will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the + `._callback_tensor_inputs` attribute of your pipeline class. + max_sequence_length (`int`, defaults to `512`): + The maximum sequence length of the text encoder. If the prompt is longer than this, it will be + truncated. If the prompt is shorter, it will be padded to this length. + + Examples: + + Returns: + [`~HeliosPipelineOutput`] or `tuple`: + If `return_dict` is `True`, [`HeliosPipelineOutput`] is returned, otherwise a `tuple` is returned where + the first element is a list with the generated images and the second element is a list of `bool`s + indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content. + """ + + if image is not None and video is not None: + raise ValueError("image and video cannot be provided simultaneously") + + if use_kv_cache: + self.transformer.enable_kv_cache() + + if use_interpolate_prompt: + assert num_videos_per_prompt == 1, f"num_videos_per_prompt must be 1, got {num_videos_per_prompt}" + assert isinstance(prompt, list), "prompt must be a list" + assert len(prompt) == len(interpolate_time_list), ( + f"Length mismatch: {len(prompt)} vs {len(interpolate_time_list)}" + ) + assert min(interpolate_time_list) > interpolation_steps, ( + f"Minimum value {min(interpolate_time_list)} must be greater than {interpolation_steps}" + ) + interpolate_interval_idx = None + interpolate_embeds = None + interpolate_cumulative_list = list(accumulate(interpolate_time_list)) + + anti_drifting_helper = None + if use_adaptive_anti_drifting: + anti_drifting_helper = AdaptiveAntiDrifting( + rho_mu=anti_drift_rho_mu, + rho_sigma=anti_drift_rho_sigma, + delta_mu=anti_drift_delta_mu, + delta_sigma=anti_drift_delta_sigma, + device=self._execution_device, + dtype=torch.float32, + ) + + history_sizes = sorted(history_sizes, reverse=True) # From big to small + + latents_mean = ( + torch.tensor(self.vae.config.latents_mean) + .view(1, self.vae.config.z_dim, 1, 1, 1) + .to(self.vae.device, self.vae.dtype) + ) + latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to( + self.vae.device, self.vae.dtype + ) + + if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)): + callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs + + # 1. Check inputs. Raise error if not correct + self.check_inputs( + prompt, + negative_prompt, + height, + width, + prompt_embeds, + negative_prompt_embeds, + callback_on_step_end_tensor_inputs, + ) + + num_frames = max(num_frames, 1) + + self._guidance_scale = guidance_scale + self._attention_kwargs = attention_kwargs + self._current_timestep = None + self._interrupt = False + + device = self._execution_device + + # 2. Define call parameters + if use_interpolate_prompt or (prompt is not None and isinstance(prompt, str)): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + # 3. Encode input prompt + all_prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask = ( + self.encode_prompt( + prompt=prompt, + negative_prompt=negative_prompt, + do_classifier_free_guidance=self.do_classifier_free_guidance, + num_videos_per_prompt=num_videos_per_prompt, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + max_sequence_length=max_sequence_length, + device=device, + ) + ) + + transformer_dtype = self.transformer.dtype + all_prompt_embeds = all_prompt_embeds.to(transformer_dtype) + if negative_prompt_embeds is not None: + if use_interpolate_prompt: + negative_prompt_embeds = negative_prompt_embeds[0].unsqueeze(0) + negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype) + + # 4. Prepare image + if image is not None: + image = self.video_processor.preprocess(image, height=height, width=width) + image_latents, fake_image_latents = self.prepare_image_latents( + image, + latents_mean=latents_mean, + latents_std=latents_std, + dtype=torch.float32, + device=device, + generator=generator, + latents=image_latents, + fake_latents=fake_image_latents, + ) + + if image_latents is not None and add_noise_to_image_latents: + image_noise_sigma = ( + torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min) + + image_noise_sigma_min + ) + image_latents = ( + image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device) + + (1 - image_noise_sigma) * image_latents + ) + fake_image_noise_sigma = ( + torch.rand(1, device=device, generator=generator) * (video_noise_sigma_max - video_noise_sigma_min) + + video_noise_sigma_min + ) + fake_image_latents = ( + fake_image_noise_sigma * randn_tensor(fake_image_latents.shape, generator=generator, device=device) + + (1 - fake_image_noise_sigma) * fake_image_latents + ) + + if video is not None: + video = self.video_processor.preprocess_video(video, height=height, width=width) + image_latents, video_latents = self.prepare_video_latents( + video, + latents_mean=latents_mean, + latents_std=latents_std, + latent_window_size=latent_window_size, + dtype=torch.float32, + device=device, + generator=generator, + latents=video_latents, + ) + + if video_latents is not None and add_noise_to_video_latents: + image_noise_sigma = ( + torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min) + + image_noise_sigma_min + ) + image_latents = ( + image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device) + + (1 - image_noise_sigma) * image_latents + ) + + noisy_latents_chunks = [] + num_latent_chunks = video_latents.shape[2] // latent_window_size + for i in range(num_latent_chunks): + chunk_start = i * latent_window_size + chunk_end = chunk_start + latent_window_size + latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :] + + chunk_frames = latent_chunk.shape[2] + frame_sigmas = ( + torch.rand(chunk_frames, device=device, generator=generator) + * (video_noise_sigma_max - video_noise_sigma_min) + + video_noise_sigma_min + ) + frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1) + + noisy_chunk = ( + frame_sigmas * randn_tensor(latent_chunk.shape, generator=generator, device=device) + + (1 - frame_sigmas) * latent_chunk + ) + noisy_latents_chunks.append(noisy_chunk) + video_latents = torch.cat(noisy_latents_chunks, dim=2) + + # 5. Prepare latent variables + num_channels_latents = self.transformer.config.in_channels + window_num_frames = (latent_window_size - 1) * self.vae_scale_factor_temporal + 1 + num_latent_sections = max(1, (num_frames + window_num_frames - 1) // window_num_frames) + total_generated_latent_frames = 0 + + if not is_keep_x0: + history_sizes[-1] = history_sizes[-1] + 1 + history_latents = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes), + height // self.vae_scale_factor_spatial, + width // self.vae_scale_factor_spatial, + device=device, + dtype=torch.float32, + ) + if fake_image_latents is not None: + history_latents = torch.cat([history_latents, fake_image_latents], dim=2) + total_generated_latent_frames += 1 + if video_latents is not None: + history_frames = history_latents.shape[2] + video_frames = video_latents.shape[2] + if video_frames < history_frames: + keep_frames = history_frames - video_frames + history_latents = torch.cat([history_latents[:, :, :keep_frames, :, :], video_latents], dim=2) + else: + history_latents = video_latents + total_generated_latent_frames += video_latents.shape[2] + + # 6. Denoising loop + all_sections_ode = [] + for k in range(num_latent_sections): + if use_interpolate_prompt: + assert num_latent_sections >= max(interpolate_cumulative_list) + + current_interval_idx = 0 + for idx, cumulative_val in enumerate(interpolate_cumulative_list): + if k < cumulative_val: + current_interval_idx = idx + break + + if current_interval_idx == 0: + prompt_embeds = all_prompt_embeds[0].unsqueeze(0) + else: + interval_start = interpolate_cumulative_list[current_interval_idx - 1] + position_in_interval = k - interval_start + + if position_in_interval < interpolation_steps: + if interpolate_embeds is None or interpolate_interval_idx != current_interval_idx: + interpolate_embeds = self.interpolate_prompt_embeds( + prompt_embeds_1=all_prompt_embeds[current_interval_idx - 1].unsqueeze(0), + prompt_embeds_2=all_prompt_embeds[current_interval_idx].unsqueeze(0), + interpolation_steps=interpolation_steps, + ) + interpolate_interval_idx = current_interval_idx + + prompt_embeds = interpolate_embeds[position_in_interval] + else: + prompt_embeds = all_prompt_embeds[current_interval_idx].unsqueeze(0) + else: + prompt_embeds = all_prompt_embeds + + is_first_section = k == 0 + is_second_section = k == 1 + if is_keep_x0: + if is_first_section: + history_sizes_first_section = [1] + history_sizes.copy() + history_latents_first_section = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes_first_section), + height // self.vae_scale_factor_spatial, + width // self.vae_scale_factor_spatial, + device=device, + dtype=torch.float32, + ) + if fake_image_latents is not None: + history_latents_first_section = torch.cat( + [history_latents_first_section, fake_image_latents], dim=2 + ) + if video_latents is not None: + history_frames = history_latents_first_section.shape[2] + video_frames = video_latents.shape[2] + if video_frames < history_frames: + keep_frames = history_frames - video_frames + history_latents_first_section = torch.cat( + [history_latents_first_section[:, :, :keep_frames, :, :], video_latents], dim=2 + ) + else: + history_latents_first_section = video_latents + + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix, latents_history_long, latents_history_mid, latents_history_1x = ( + history_latents_first_section[:, :, -sum(history_sizes_first_section) :].split( + history_sizes_first_section, dim=2 + ) + ) + if image_latents is not None: + latents_prefix = image_latents + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix = image_latents + latents_history_long, latents_history_mid, latents_history_1x = history_latents[ + :, :, -sum(history_sizes) : + ].split(history_sizes, dim=2) + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + indices = torch.arange(0, sum([*history_sizes, latent_window_size])) + ( + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_short, + indices_hidden_states, + ) = indices.split([*history_sizes, latent_window_size], dim=0) + latents_history_long, latents_history_mid, latents_history_short = history_latents[ + :, :, -sum(history_sizes) : + ].split(history_sizes, dim=2) + + latents = self.prepare_latents( + batch_size, + num_channels_latents, + height, + width, + window_num_frames, + dtype=torch.float32, + device=device, + generator=generator, + latents=None, + ) + + if not is_enable_stage2: + self.scheduler.set_timesteps(num_inference_steps, device=device) + + if use_dynamic_shifting: + sigmas = torch.linspace( + 0.999, 0.0, steps=num_inference_steps + 1, dtype=torch.float32, device=device + )[:-1] + sigmas = apply_schedule_shift( + sigmas=sigmas, + noise=latents, + base_seq_len=self.scheduler.config.get("base_image_seq_len", 256), + max_seq_len=self.scheduler.config.get("max_image_seq_len", 4096), + base_shift=self.scheduler.config.get("base_shift", 0.5), + max_shift=self.scheduler.config.get("max_shift", 1.15), + time_shift_type=time_shift_type, + ) + timesteps = sigmas * 1000.0 # rescale to [0, 1000.0) + timesteps = timesteps.to(device) + sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)]) + self.scheduler.timesteps = timesteps + self.scheduler.sigmas = sigmas + + timesteps = self.scheduler.timesteps + + dmd_sigmas = None + dmd_timesteps = None + if use_dmd: + dmd_sigmas = self.scheduler.sigmas.to(self.transformer.device) + dmd_timesteps = self.scheduler.timesteps.to(self.transformer.device) + + self._num_timesteps = len(timesteps) + else: + num_inference_steps = sum(stage2_num_inference_steps_list) + + with self.progress_bar(total=num_inference_steps) as progress_bar: + if is_enable_stage2: + latents, ode_stages_tensor = self.stage2_sample( + is_first_section=is_first_section, + latents=latents, + stage2_num_stages=stage2_num_stages, + stage2_num_inference_steps_list=stage2_num_inference_steps_list, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + guidance_scale=guidance_scale, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + attention_kwargs=attention_kwargs, + device=device, + transformer_dtype=transformer_dtype, + scheduler_type=scheduler_type, + use_dynamic_shifting=use_dynamic_shifting, + time_shift_type=time_shift_type, + generator=generator, + # ------------ CFG Zero ------------ + use_cfg_zero_star=use_cfg_zero_star, + use_zero_init=use_zero_init, + zero_steps=zero_steps, + # -------------- DMD -------------- + use_dmd=use_dmd, + # ------------ Callback ------------ + callback_on_step_end=callback_on_step_end, + callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, + progress_bar=progress_bar, + ) + + all_sections_ode.append(ode_stages_tensor) + else: + latents = self.stage1_sample( + latents=latents, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + timesteps=timesteps, + guidance_scale=guidance_scale, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + attention_kwargs=attention_kwargs, + device=device, + transformer_dtype=transformer_dtype, + generator=generator, + # ------------ CFG Zero ------------ + use_cfg_zero_star=use_cfg_zero_star, + use_zero_init=use_zero_init, + zero_steps=zero_steps, + # -------------- DMD -------------- + use_dmd=use_dmd, + dmd_sigmas=dmd_sigmas, + dmd_timesteps=dmd_timesteps, + # ------------ Callback ------------ + callback_on_step_end=callback_on_step_end, + callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, + progress_bar=progress_bar, + ) + + if use_kv_cache: + self.transformer.clear_kv_cache() + + if use_adaptive_anti_drifting: + current_mean, current_var = anti_drifting_helper.compute_latent_statistics(latents) + anti_drifting_helper.update_global_statistics(current_mean, current_var) + has_drift = anti_drifting_helper.detect_drift(current_mean, current_var) + + if has_drift and k < num_latent_sections - 1: + print( + f"Drift detected at chunk {k + 1}/{num_latent_sections}. Applying Frame-Aware Corruption." + ) + latents = anti_drifting_helper.apply_frame_aware_corruption( + latents, + corruption_strength=anti_drift_corruption_strength, + generator=generator, + ) + + if is_keep_x0 and ( + (is_first_section and image_latents is None) or (is_skip_first_section and is_second_section) + ): + image_latents = latents[:, :, 0:1, :, :] + + total_generated_latent_frames += latents.shape[2] + history_latents = torch.cat([history_latents, latents], dim=2) + + return all_sections_ode diff --git a/Helios/helios/pipelines/pipeline_output.py b/Helios/helios/pipelines/pipeline_output.py new file mode 100644 index 0000000000000000000000000000000000000000..08546289ef4c0739916c3106b8d9e6a93120d64a --- /dev/null +++ b/Helios/helios/pipelines/pipeline_output.py @@ -0,0 +1,20 @@ +from dataclasses import dataclass + +import torch + +from diffusers.utils import BaseOutput + + +@dataclass +class HeliosPipelineOutput(BaseOutput): + r""" + Output class for Helios pipelines. + + Args: + frames (`torch.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]): + List of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing + denoised PIL image sequences of length `num_frames.` It can also be a NumPy array or Torch tensor of shape + `(batch_size, num_frames, channels, height, width)`. + """ + + frames: torch.Tensor diff --git a/Helios/helios/scheduler/__init__.py b/Helios/helios/scheduler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/helios/scheduler/scheduling_helios.py b/Helios/helios/scheduler/scheduling_helios.py new file mode 100644 index 0000000000000000000000000000000000000000..b4831b9e9405e9d41d7fdae73eb1640d04d0a373 --- /dev/null +++ b/Helios/helios/scheduler/scheduling_helios.py @@ -0,0 +1,1056 @@ +import math +from dataclasses import dataclass +from typing import List, Optional, Tuple, Union + +import numpy as np +import torch + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.schedulers.scheduling_utils import SchedulerMixin +from diffusers.utils import BaseOutput, deprecate + + +@dataclass +class HeliosSchedulerOutput(BaseOutput): + """ + Output class for the scheduler's `step` function output. + + Args: + prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): + Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the + denoising loop. + """ + + prev_sample: torch.FloatTensor + model_outputs: torch.FloatTensor + last_sample: torch.FloatTensor + this_order: int + + +class HeliosScheduler(SchedulerMixin, ConfigMixin): + """ + Euler scheduler. + + This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic + methods the library implements for all schedulers such as loading and saving. + + Args: + num_train_timesteps (`int`, defaults to 1000): + The number of diffusion steps to train the model. + timestep_spacing (`str`, defaults to `"linspace"`): + The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and + Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information. + shift (`float`, defaults to 1.0): + The shift value for the timestep schedule. + """ + + _compatibles = [] + order = 1 + + @register_to_config + def __init__( + self, + num_train_timesteps: int = 1000, + shift: float = 1.0, # Following Stable diffusion 3, + stages: int = 3, + stage_range: List = [0, 1 / 3, 2 / 3, 1], + gamma: float = 1 / 3, + # For UniPC + thresholding: bool = False, + prediction_type: str = "flow_prediction", + solver_order: int = 2, + predict_x0: bool = True, + solver_type: str = "bh2", + lower_order_final: bool = True, + disable_corrector: List[int] = [], + solver_p: SchedulerMixin = None, + use_flow_sigmas: bool = True, + version: str = "v1", + ): + self.version = version + self.timestep_ratios = {} # The timestep ratio for each stage + self.timesteps_per_stage = {} # The detailed timesteps per stage (fix max and min per stage) + self.sigmas_per_stage = {} # always uniform [1000, 0] + self.start_sigmas = {} # for start point / upsample renoise + self.end_sigmas = {} # for end point + self.ori_start_sigmas = {} + + # self.init_sigmas() + self.init_sigmas_for_each_stage() + self.sigma_min = self.sigmas[-1].item() + self.sigma_max = self.sigmas[0].item() + self.gamma = gamma + + if solver_type not in ["bh1", "bh2"]: + if solver_type in ["midpoint", "heun", "logrho"]: + self.register_to_config(solver_type="bh2") + else: + raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}") + + self.predict_x0 = predict_x0 + self.model_outputs = [None] * solver_order + self.timestep_list = [None] * solver_order + self.lower_order_nums = 0 + self.disable_corrector = disable_corrector + self.solver_p = solver_p + self.last_sample = None + self._step_index = None + self._begin_index = None + + def init_sigmas(self): + """ + initialize the global timesteps and sigmas + """ + num_train_timesteps = self.config.num_train_timesteps + shift = self.config.shift + + alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps + 1) + sigmas = 1.0 - alphas + sigmas = np.flip(shift * sigmas / (1 + (shift - 1) * sigmas))[:-1].copy() + sigmas = torch.from_numpy(sigmas) + timesteps = (sigmas * num_train_timesteps).clone() + + self._step_index = None + self._begin_index = None + self.timesteps = timesteps + self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication + + def init_sigmas_for_each_stage(self): + """ + Init the timesteps for each stage + """ + self.init_sigmas() + + stage_distance = [] + stages = self.config.stages + training_steps = self.config.num_train_timesteps + stage_range = self.config.stage_range + + # Init the start and end point of each stage + for i_s in range(stages): + # To decide the start and ends point + start_indice = int(stage_range[i_s] * training_steps) + start_indice = max(start_indice, 0) + end_indice = int(stage_range[i_s + 1] * training_steps) + end_indice = min(end_indice, training_steps) + start_sigma = self.sigmas[start_indice].item() + end_sigma = self.sigmas[end_indice].item() if end_indice < training_steps else 0.0 + self.ori_start_sigmas[i_s] = start_sigma + + if i_s != 0: + ori_sigma = 1 - start_sigma + gamma = self.config.gamma + corrected_sigma = (1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)) * ori_sigma + # corrected_sigma = 1 / (2 - ori_sigma) * ori_sigma + start_sigma = 1 - corrected_sigma + + stage_distance.append(start_sigma - end_sigma) + self.start_sigmas[i_s] = start_sigma + self.end_sigmas[i_s] = end_sigma + + if self.version == "v2": + new_start_indice = ( + len(self.sigmas) - torch.searchsorted(self.sigmas.flip(0), start_sigma, right=True) + ).item() + self.sigmas_per_stage[i_s] = self.sigmas[new_start_indice:end_indice] + self.timesteps_per_stage[i_s] = self.timesteps[new_start_indice:end_indice] + + if self.version == "v2": + return + + # Determine the ratio of each stage according to flow length + tot_distance = sum(stage_distance) + for i_s in range(stages): + if i_s == 0: + start_ratio = 0.0 + else: + start_ratio = sum(stage_distance[:i_s]) / tot_distance + if i_s == stages - 1: + end_ratio = 0.9999999999999999 + else: + end_ratio = sum(stage_distance[: i_s + 1]) / tot_distance + + self.timestep_ratios[i_s] = (start_ratio, end_ratio) + + # Determine the timesteps and sigmas for each stage + for i_s in range(stages): + timestep_ratio = self.timestep_ratios[i_s] + # timestep_max = self.timesteps[int(timestep_ratio[0] * training_steps)] + timestep_max = min(self.timesteps[int(timestep_ratio[0] * training_steps)], 999) + timestep_min = self.timesteps[min(int(timestep_ratio[1] * training_steps), training_steps - 1)] + timesteps = np.linspace(timestep_max, timestep_min, training_steps + 1) + self.timesteps_per_stage[i_s] = ( + timesteps[:-1] if isinstance(timesteps, torch.Tensor) else torch.from_numpy(timesteps[:-1]) + ) + stage_sigmas = np.linspace(0.999, 0, training_steps + 1) + self.sigmas_per_stage[i_s] = torch.from_numpy(stage_sigmas[:-1]) + + @property + def step_index(self): + """ + The index counter for current timestep. It will increase 1 after each scheduler step. + """ + return self._step_index + + @property + def begin_index(self): + """ + The index for the first timestep. It should be set from pipeline with `set_begin_index` method. + """ + return self._begin_index + + # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index + def set_begin_index(self, begin_index: int = 0): + """ + Sets the begin index for the scheduler. This function should be run from pipeline before the inference. + + Args: + begin_index (`int`): + The begin index for the scheduler. + """ + self._begin_index = begin_index + + def _sigma_to_t(self, sigma): + return sigma * self.config.num_train_timesteps + + def set_timesteps( + self, + num_inference_steps: int, + stage_index: int, + device: Union[str, torch.device] = None, + ): + """ + Setting the timesteps and sigmas for each stage + """ + self.num_inference_steps = num_inference_steps + self.init_sigmas() + + if self.version == "v1": + stage_timesteps = self.timesteps_per_stage[stage_index] + timestep_max = stage_timesteps[0].item() + timestep_min = stage_timesteps[-1].item() + + timesteps = np.linspace( + timestep_max, + timestep_min, + num_inference_steps, + ) + self.timesteps = torch.from_numpy(timesteps).to(device=device) + + stage_sigmas = self.sigmas_per_stage[stage_index] + sigma_max = stage_sigmas[0].item() + sigma_min = stage_sigmas[-1].item() + + ratios = np.linspace(sigma_max, sigma_min, num_inference_steps) + sigmas = torch.from_numpy(ratios).to(device=device) + self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)]) + else: + total_steps = len(self.timesteps_per_stage[stage_index]) + indices = np.linspace(0, total_steps - 1, num_inference_steps, dtype=int) + + self.timesteps = self.timesteps_per_stage[stage_index][indices].to(device=device) + + if stage_index == (self.config.stages - 1): + sigmas = self.sigmas_per_stage[stage_index][indices].to(device=device) + self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)]) + else: + sigmas = self.sigmas_per_stage[stage_index][indices].to(device=device) + self.sigmas = torch.cat( + [sigmas, torch.tensor([self.ori_start_sigmas[stage_index + 1]], device=sigmas.device)] + ) + + self._step_index = None + self.reset_scheduler_history() + + def index_for_timestep(self, timestep, schedule_timesteps=None): + if schedule_timesteps is None: + schedule_timesteps = self.timesteps + + indices = (schedule_timesteps == timestep).nonzero() + + # The sigma index that is taken for the **very** first `step` + # is always the second index (or the last index if there is only 1) + # This way we can ensure we don't accidentally skip a sigma in + # case we start in the middle of the denoising schedule (e.g. for image-to-image) + pos = 1 if len(indices) > 1 else 0 + + return indices[pos].item() + + def _init_step_index(self, timestep): + if self.begin_index is None: + if isinstance(timestep, torch.Tensor): + timestep = timestep.to(self.timesteps.device) + self._step_index = self.index_for_timestep(timestep) + else: + self._step_index = self._begin_index + + def step( + self, + model_output: torch.FloatTensor, + timestep: Union[float, torch.FloatTensor] = None, + sample: torch.FloatTensor = None, + generator: Optional[torch.Generator] = None, + sigma: Optional[torch.FloatTensor] = None, + sigma_next: Optional[torch.FloatTensor] = None, + return_dict: bool = True, + ) -> Union[HeliosSchedulerOutput, Tuple]: + """ + Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion + process from the learned model outputs (most often the predicted noise). + + Args: + model_output (`torch.FloatTensor`): + The direct output from learned diffusion model. + timestep (`float`): + The current discrete timestep in the diffusion chain. + sample (`torch.FloatTensor`): + A current instance of a sample created by the diffusion process. + generator (`torch.Generator`, *optional*): + A random number generator. + return_dict (`bool`): + Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or + tuple. + + Returns: + [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`: + If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is + returned, otherwise a tuple is returned where the first element is the sample tensor. + """ + + assert (sigma is None) == (sigma_next is None), "sigma and sigma_next must both be None or both be not None" + + if sigma is None and sigma_next is None: + if ( + isinstance(timestep, int) + or isinstance(timestep, torch.IntTensor) + or isinstance(timestep, torch.LongTensor) + ): + raise ValueError( + ( + "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to" + " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass" + " one of the `scheduler.timesteps` as a timestep." + ), + ) + + if self.step_index is None: + self._step_index = 0 + + # Upcast to avoid precision issues when computing prev_sample + sample = sample.to(torch.float32) + + if sigma is None and sigma_next is None: + sigma = self.sigmas[self.step_index] + sigma_next = self.sigmas[self.step_index + 1] + + prev_sample = sample + (sigma_next - sigma) * model_output + + # Cast sample back to model compatible dtype + prev_sample = prev_sample.to(model_output.dtype) + + # upon completion increase step index by one + self._step_index += 1 + + if not return_dict: + return (prev_sample,) + + return HeliosSchedulerOutput(prev_sample=prev_sample) + + # ---------------------------------- UniPC ---------------------------------- + # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._sigma_to_alpha_sigma_t + def _sigma_to_alpha_sigma_t(self, sigma): + if self.config.use_flow_sigmas: + alpha_t = 1 - sigma + sigma_t = torch.clamp(sigma, min=1e-8) + else: + alpha_t = 1 / ((sigma**2 + 1) ** 0.5) + sigma_t = sigma * alpha_t + + return alpha_t, sigma_t + + def convert_model_output( + self, + model_output: torch.Tensor, + *args, + sample: torch.Tensor = None, + sigma: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + r""" + Convert the model output to the corresponding type the UniPC algorithm needs. + + Args: + model_output (`torch.Tensor`): + The direct output from the learned diffusion model. + timestep (`int`): + The current discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + + Returns: + `torch.Tensor`: + The converted model output. + """ + timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError("missing `sample` as a required keyword argument") + if timestep is not None: + deprecate( + "timesteps", + "1.0.0", + "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + flag = False + if sigma is None: + flag = True + sigma = self.sigmas[self.step_index] + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) + + if self.predict_x0: + if self.config.prediction_type == "epsilon": + x0_pred = (sample - sigma_t * model_output) / alpha_t + elif self.config.prediction_type == "sample": + x0_pred = model_output + elif self.config.prediction_type == "v_prediction": + x0_pred = alpha_t * sample - sigma_t * model_output + elif self.config.prediction_type == "flow_prediction": + if flag: + sigma_t = self.sigmas[self.step_index] + else: + sigma_t = sigma + x0_pred = sample - sigma_t * model_output + else: + raise ValueError( + f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, " + "`v_prediction`, or `flow_prediction` for the UniPCMultistepScheduler." + ) + + if self.config.thresholding: + x0_pred = self._threshold_sample(x0_pred) + + return x0_pred + else: + if self.config.prediction_type == "epsilon": + return model_output + elif self.config.prediction_type == "sample": + epsilon = (sample - alpha_t * model_output) / sigma_t + return epsilon + elif self.config.prediction_type == "v_prediction": + epsilon = alpha_t * model_output + sigma_t * sample + return epsilon + else: + raise ValueError( + f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" + " `v_prediction` for the UniPCMultistepScheduler." + ) + + def multistep_uni_p_bh_update( + self, + model_output: torch.Tensor, + *args, + sample: torch.Tensor = None, + order: int = None, + sigma: torch.Tensor = None, + sigma_next: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + """ + One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified. + + Args: + model_output (`torch.Tensor`): + The direct output from the learned diffusion model at the current timestep. + prev_timestep (`int`): + The previous discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + order (`int`): + The order of UniP at this timestep (corresponds to the *p* in UniPC-p). + + Returns: + `torch.Tensor`: + The sample tensor at the previous timestep. + """ + prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError("missing `sample` as a required keyword argument") + if order is None: + if len(args) > 2: + order = args[2] + else: + raise ValueError("missing `order` as a required keyword argument") + if prev_timestep is not None: + deprecate( + "prev_timestep", + "1.0.0", + "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + model_output_list = self.model_outputs + + s0 = self.timestep_list[-1] + m0 = model_output_list[-1] + x = sample + + if self.solver_p: + x_t = self.solver_p.step(model_output, s0, x).prev_sample + return x_t + + if sigma_next is None and sigma is None: + sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index] + else: + sigma_t, sigma_s0 = sigma_next, sigma + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = sample.device + + rks = [] + D1s = [] + for i in range(1, order): + si = self.step_index - i + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + D1s.append((mi - m0) / rk) + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + R = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.config.solver_type == "bh1": + B_h = hh + elif self.config.solver_type == "bh2": + B_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + R.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / B_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + R = torch.stack(R) + b = torch.tensor(b, device=device) + + if len(D1s) > 0: + D1s = torch.stack(D1s, dim=1) # (B, K) + # for order 2, we use a simplified version + if order == 2: + rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]).to(device).to(x.dtype) + else: + D1s = None + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if D1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) + else: + pred_res = 0 + x_t = x_t_ - alpha_t * B_h * pred_res + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if D1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) + else: + pred_res = 0 + x_t = x_t_ - sigma_t * B_h * pred_res + + x_t = x_t.to(x.dtype) + return x_t + + def multistep_uni_c_bh_update( + self, + this_model_output: torch.Tensor, + *args, + last_sample: torch.Tensor = None, + this_sample: torch.Tensor = None, + order: int = None, + sigma_before: torch.Tensor = None, + sigma: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + """ + One step for the UniC (B(h) version). + + Args: + this_model_output (`torch.Tensor`): + The model outputs at `x_t`. + this_timestep (`int`): + The current timestep `t`. + last_sample (`torch.Tensor`): + The generated sample before the last predictor `x_{t-1}`. + this_sample (`torch.Tensor`): + The generated sample after the last predictor `x_{t}`. + order (`int`): + The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`. + + Returns: + `torch.Tensor`: + The corrected sample tensor at the current timestep. + """ + this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None) + if last_sample is None: + if len(args) > 1: + last_sample = args[1] + else: + raise ValueError("missing `last_sample` as a required keyword argument") + if this_sample is None: + if len(args) > 2: + this_sample = args[2] + else: + raise ValueError("missing `this_sample` as a required keyword argument") + if order is None: + if len(args) > 3: + order = args[3] + else: + raise ValueError("missing `order` as a required keyword argument") + if this_timestep is not None: + deprecate( + "this_timestep", + "1.0.0", + "Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + model_output_list = self.model_outputs + + m0 = model_output_list[-1] + x = last_sample + x_t = this_sample + model_t = this_model_output + + if sigma_before is None and sigma is None: + sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1] + else: + sigma_t, sigma_s0 = sigma, sigma_before + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = this_sample.device + + rks = [] + D1s = [] + for i in range(1, order): + si = self.step_index - (i + 1) + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + D1s.append((mi - m0) / rk) + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + R = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.config.solver_type == "bh1": + B_h = hh + elif self.config.solver_type == "bh2": + B_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + R.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / B_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + R = torch.stack(R) + b = torch.tensor(b, device=device) + + if len(D1s) > 0: + D1s = torch.stack(D1s, dim=1) + else: + D1s = None + + # for order 1, we use a simplified version + if order == 1: + rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype) + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if D1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s) + else: + corr_res = 0 + D1_t = model_t - m0 + x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t) + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if D1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s) + else: + corr_res = 0 + D1_t = model_t - m0 + x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t) + x_t = x_t.to(x.dtype) + return x_t + + def step_unipc( + self, + model_output: torch.Tensor, + timestep: Union[int, torch.Tensor] = None, + sample: torch.Tensor = None, + return_dict: bool = True, + model_outputs: list = None, + timestep_list: list = None, + sigma_before: torch.Tensor = None, + sigma: torch.Tensor = None, + sigma_next: torch.Tensor = None, + cus_step_index: int = None, + cus_lower_order_num: int = None, + cus_this_order: int = None, + cus_last_sample: torch.Tensor = None, + ) -> Union[HeliosSchedulerOutput, Tuple]: + """ + Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with + the multistep UniPC. + + Args: + model_output (`torch.Tensor`): + The direct output from learned diffusion model. + timestep (`int`): + The current discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + return_dict (`bool`): + Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`. + + Returns: + [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`: + If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a + tuple is returned where the first element is the sample tensor. + + """ + # don't change + # print(len(self.model_outputs), len(self.timestep_list), self.disable_corrector, self.solver_p, self._begin_index) + + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + if cus_step_index is None: + if self.step_index is None: + self._step_index = 0 + else: + self._step_index = cus_step_index + + if cus_lower_order_num is not None: + self.lower_order_nums = cus_lower_order_num + + if cus_this_order is not None: + self.this_order = cus_this_order + + if cus_last_sample is not None: + self.last_sample = cus_last_sample + + use_corrector = ( + self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None + ) + + # Convert model output using the proper conversion method + model_output_convert = self.convert_model_output(model_output, sample=sample, sigma=sigma) + + if model_outputs is not None and timestep_list is not None: + self.model_outputs = model_outputs[:-1] + self.timestep_list = timestep_list[:-1] + + # print("1", self.step_index, self.timestep_list) + + if use_corrector: + sample = self.multistep_uni_c_bh_update( + this_model_output=model_output_convert, + last_sample=self.last_sample, + this_sample=sample, + order=self.this_order, + sigma_before=sigma_before, + sigma=sigma, + ) + + if model_outputs is not None and timestep_list is not None: + model_outputs[-1] = model_output_convert + self.model_outputs = model_outputs[1:] + self.timestep_list = timestep_list[1:] + else: + for i in range(self.config.solver_order - 1): + self.model_outputs[i] = self.model_outputs[i + 1] + self.timestep_list[i] = self.timestep_list[i + 1] + self.model_outputs[-1] = model_output_convert + self.timestep_list[-1] = timestep + + if self.config.lower_order_final: + this_order = min(self.config.solver_order, len(self.timesteps) - self.step_index) + else: + this_order = self.config.solver_order + self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep + assert self.this_order > 0 + + # change + # print("2", self.step_index, self.timestep_list, self.lower_order_nums, self.this_order, "\n") + # print(self._step_index, self.lower_order_nums, use_corrector, self.this_order, self.lower_order_nums) + # 0 1 False 1 1 + # 1 2 True 2 2 + # 2 2 True 2 2 + # 3 2 True 2 2 + # 4 2 True 2 2 + # 5 2 True 2 2 + # 6 2 True 2 2 + # 7 2 True 2 2 + # 8 2 True 2 2 + # 9 2 True 1 2 + + self.last_sample = sample + prev_sample = self.multistep_uni_p_bh_update( + model_output=model_output, # pass the original non-converted model output, in case solver-p is used + sample=sample, + order=self.this_order, + sigma=sigma, + sigma_next=sigma_next, + ) + + if cus_lower_order_num is None: + if self.lower_order_nums < self.config.solver_order: + self.lower_order_nums += 1 + + # upon completion increase step index by one + if cus_step_index is None: + self._step_index += 1 + + if not return_dict: + return (prev_sample, model_outputs, self.last_sample, self.this_order) + + return HeliosSchedulerOutput( + prev_sample=prev_sample, + model_outputs=model_outputs, + last_sample=self.last_sample, + this_order=self.this_order, + ) + + def reset_scheduler_history(self): + self.model_outputs = [None] * self.config.solver_order + self.timestep_list = [None] * self.config.solver_order + self.lower_order_nums = 0 + self.disable_corrector = self.config.disable_corrector + self.solver_p = self.config.solver_p + self.last_sample = None + self._step_index = None + self._begin_index = None + + def __len__(self): + return self.config.num_train_timesteps + + +if __name__ == "__main__": + device = "cuda" + + # ---------------------- For dynamic shifting ---------------------- + from examples.scheduling_unipc_multistep_latest import UniPCMultistepScheduler + + scheduler_official = UniPCMultistepScheduler.from_pretrained("BestWishYsh/Helios-Base", subfolder="scheduler") + scheduler_official.set_timesteps(num_inference_steps=50) + scheduler_official.timesteps + scheduler_official.sigmas + + # # Official + # from scheduling_flow_match_euler_discrete_official import FlowMatchEulerDiscreteScheduler + # scheduler_official = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=3.0) + # scheduler_official.set_timesteps(num_inference_steps=50, sigmas=None) + # scheduler_official.timesteps + # scheduler_official.sigmas + + # import sys + # sys.path.append("../../") + # from helios.utils.utils_helios_base import apply_schedule_shift + + # sigmas = apply_schedule_shift(scheduler_official.sigmas, torch.ones([2, 16, 21, 48, 80]), mu=3) + # timesteps = sigmas[:-1] * 1000.0 + + # import copy + # from diffusers.training_utils import compute_density_for_timestep_sampling + + # def get_sigmas(timesteps, n_dim=4, device="cpu", dtype=torch.float32): + # sigmas = noise_scheduler_copy.sigmas.to(device=device, dtype=dtype) + # schedule_timesteps = noise_scheduler_copy.timesteps.to(device) + # timesteps = timesteps.to(device) + # step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps] + # sigma = sigmas[step_indices].flatten() + # while len(sigma.shape) < n_dim: + # sigma = sigma.unsqueeze(-1) + # return sigma + + # noise_scheduler_copy = copy.deepcopy(scheduler_official) + + # # Sample noise that we'll add to the latents + # model_input = torch.ones([2, 16, 9, 88, 68]) + # noise = torch.randn_like(model_input) + # bsz = model_input.shape[0] + + # # Sample a random timestep for each image + # # for weighting schemes where we sample timesteps non-uniformly + # u = compute_density_for_timestep_sampling( + # weighting_scheme="logit_normal", batch_size=bsz, logit_mean=0.0, logit_std=1.0, mode_scale=1.29 + # ) + # indices = (u * noise_scheduler_copy.config.num_train_timesteps).long() + # timesteps = noise_scheduler_copy.timesteps[indices].to(device=model_input.device) + + # # Add noise according to flow matching. + # # zt = (1 - texp) * x + texp * z1 + # sigmas = get_sigmas(timesteps, n_dim=model_input.ndim, dtype=model_input.dtype) + + # import sys + # sys.path.append("../../") + # from helios.utils.utils_helios_base import apply_schedule_shift + + # sigmas = apply_schedule_shift(sigmas, noise) # torch.Size([2, 1, 1, 1, 1]) + # timesteps = sigmas * 1000.0 # rescale to [0, 1000.0) + # while timesteps.ndim > 1: + # timesteps = timesteps.squeeze(-1) + # ---------------------- For dynamic shifting ---------------------- + + # ---------------------- For timestep shifting ---------------------- + stages = 3 + timestep_shift = 1.0 + stage_range = [0, 1 / 3, 2 / 3, 1] + scheduler_gamma = 1 / 3 + version = "v1" + scheduler = HeliosScheduler( + shift=timestep_shift, stages=stages, stage_range=stage_range, gamma=scheduler_gamma, version=version + ) + print( + f"The start sigmas and end sigmas of each stage is Start: {scheduler.start_sigmas}, End: {scheduler.end_sigmas}, Ori_start: {scheduler.ori_start_sigmas}" + ) + + i_s = 1 + stage2_num_inference_steps_list = [3, 3, 3] + scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s) + scheduler.timesteps.to(dtype=torch.float32) + scheduler.sigmas.to(dtype=torch.float32) + + # stages = 2 + # timestep_shift = 3.0 + # stage_range = [0, 1 / 2, 1] + # scheduler_gamma = 1 / 3 + # version = "v2" + # scheduler = HeliosScheduler( + # shift=timestep_shift, stages=stages, stage_range=stage_range, gamma=scheduler_gamma, version=version + # ) + # print( + # f"The start sigmas and end sigmas of each stage is Start: {scheduler.start_sigmas}, End: {scheduler.end_sigmas}, Ori_start: {scheduler.ori_start_sigmas}" + # ) + + # i_s = 1 + # stage2_num_inference_steps_list = [10, 10] + # scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s) + # scheduler.timesteps.to(dtype=torch.float32) + # scheduler.sigmas.to(dtype=torch.float32) + + # scheduler.timesteps_per_stage[0] + # scheduler.sigmas_per_stage[0] + # shift1: (999, 743.5120) -> (743.2563, 385.9723) -> (385.6146, 1.3846) + # shift3: (999, 957.3958) -> (957.3542, 828.9170) -> (828.7885, 3.8198) + + # timesteps_1 = np.linspace(1, 1000 - 1, 1000, dtype=np.float32)[::-1].copy() + # timesteps_1 = torch.from_numpy(timesteps_1).to(dtype=torch.float32) + # sigmas_1 = timesteps_1 / 1000 + # sigmas_1 = apply_schedule_shift(sigmas_1, torch.ones([2, 16, 21, 48, 80]), mu=3) + # timesteps_2 = sigmas_1 * 1000 + + # import pdb;pdb.set_trace() + # temp_sigmas = apply_schedule_shift(scheduler.timesteps / 1000, torch.ones([2, 16, 21, 48, 80]), mu=3) + # temp_timesteps = temp_sigmas * 1000 + # while temp_timesteps.ndim > 1: + # temp_timesteps = temp_timesteps.squeeze(-1) + # temp_timesteps = temp_timesteps[:-1] + + # # very important here! + # timesteps = temp_timesteps + # # self.scheduler.sigmas = temp_sigmas + # scheduler.timesteps = temp_timesteps + + # ---------------------- For timestep shifting ---------------------- + + # ---------------------- For dynamic shifting ---------------------- + + # ---------------------- For per step sigmas & timesteps ---------------------- + # scheduler = HeliosScheduler(shift=3.0, stages=stages, stage_range=stage_range, gamma=scheduler_gamma) + # stage2_num_inference_steps_list = [10, 10, 10] + # i_s = 0 + # scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s) + # scheduler.timesteps_per_stage[0] + # scheduler.sigmas_per_stage[0] + # scheduler.timesteps + # scheduler.sigmas + # ---------------------- For per step sigmas & timesteps ---------------------- + + # ---------------------- For Custom step ---------------------- + # timesteps = scheduler.timesteps + # noise_pred = torch.randn([2, 16, 10, 48, 80], device=device) + # latents = torch.randn([2, 16, 10, 48, 80], device=device) + # for i, t in enumerate(timesteps): + # print(i, t) + # # latents = scheduler.step(noise_pred, t, latents, return_dict=False)[0] + # latents = scheduler.step_custom_unipc(noise_pred, t, latents, return_dict=False)[0] + + # def upsample_tensor(tensor, scale_factor=2): + # return torch.nn.functional.interpolate( + # tensor, scale_factor=scale_factor, mode="trilinear", align_corners=False + # ) + + # stage2_num_inference_steps_list = [10, 10, 10] + # noise_pred = torch.randn([2, 16, 10, 12, 20], device=device) + # latents = torch.randn([2, 16, 10, 12, 20], device=device) + # for stage, num_steps in enumerate(stage2_num_inference_steps_list): + # print(f"stage: {stage}, num_steps: {num_steps}") + # if stage > 0: + # latents = upsample_tensor(latents, scale_factor=2) + # noise_pred = upsample_tensor(noise_pred, scale_factor=2) + + # scheduler.set_timesteps(num_steps, stage) + # timesteps = scheduler.timesteps + + # print(f"Timesteps for stage {stage + 1}: {timesteps}") + + # for i, t in enumerate(timesteps): + # # print(i, t, latents.shape) + # # latents = scheduler.step(noise_pred, t, latents, return_dict=False)[0] + # latents = scheduler.step_unipc(noise_pred, t, latents, return_dict=False)[0] + # ---------------------- For Custom step ---------------------- diff --git a/Helios/helios/utils/__init__.py b/Helios/helios/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/helios/utils/create_ema_zero3.py b/Helios/helios/utils/create_ema_zero3.py new file mode 100644 index 0000000000000000000000000000000000000000..7b9b271a5aed1bbfc6060ca34314946e23989120 --- /dev/null +++ b/Helios/helios/utils/create_ema_zero3.py @@ -0,0 +1,401 @@ +import copy +import json +import math +import os +from typing import Any, Dict, Iterable, Optional, Union + +from huggingface_hub import save_torch_state_dict + +from diffusers.utils import ( + deprecate, + is_torchvision_available, + is_transformers_available, +) + + +if is_transformers_available(): + pass + +if is_torchvision_available(): + pass + +import deepspeed +import torch +from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + + +def _z3_params_to_fetch(param_list): + return [p for p in param_list if hasattr(p, "ds_id") and p.ds_status == ZeroParamStatus.NOT_AVAILABLE] + + +# Adapted from diffusers-style ema https://github.com/huggingface/diffusers/blob/main/src/diffusers/training_utils.py#L263 +class EMAModel_Zero3: + """ + Exponential Moving Average of models weights + """ + + def __init__( + self, + model: torch.nn.Module, + decay: float = 0.9999, + min_decay: float = 0.0, + update_after_step: int = 0, + use_ema_warmup: bool = False, + inv_gamma: Union[float, int] = 1.0, + power: Union[float, int] = 2 / 3, + model_cls: Optional[Any] = None, + model_config: Dict[str, Any] = None, + weight_file_prefix: Optional[str] = "", + **kwargs, + ): + """ + Args: + parameters (Iterable[torch.nn.Parameter]): The parameters to track. + decay (float): The decay factor for the exponential moving average. + min_decay (float): The minimum decay factor for the exponential moving average. + update_after_step (int): The number of steps to wait before starting to update the EMA weights. + use_ema_warmup (bool): Whether to use EMA warmup. + inv_gamma (float): + Inverse multiplicative factor of EMA warmup. Default: 1. Only used if `use_ema_warmup` is True. + power (float): Exponential factor of EMA warmup. Default: 2/3. Only used if `use_ema_warmup` is True. + device (Optional[Union[str, torch.device]]): The device to store the EMA weights on. If None, the EMA + weights will be stored on CPU. + + @crowsonkb's notes on EMA Warmup: + If gamma=1 and power=1, implements a simple average. gamma=1, power=2/3 are good values for models you plan + to train for a million or more steps (reaches decay factor 0.999 at 31.6K steps, 0.9999 at 1M steps), + gamma=1, power=3/4 for models you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999 + at 215.4k steps). + """ + + self.model = model + + if kwargs.get("max_value", None) is not None: + deprecation_message = "The `max_value` argument is deprecated. Please use `decay` instead." + deprecate("max_value", "1.0.0", deprecation_message, standard_warn=False) + decay = kwargs["max_value"] + + if kwargs.get("min_value", None) is not None: + deprecation_message = "The `min_value` argument is deprecated. Please use `min_decay` instead." + deprecate("min_value", "1.0.0", deprecation_message, standard_warn=False) + min_decay = kwargs["min_value"] + + if kwargs.get("device", None) is not None: + deprecation_message = "The `device` argument is deprecated. Please use `to` instead." + deprecate("device", "1.0.0", deprecation_message, standard_warn=False) + self.to(device=kwargs["device"]) + + self.temp_stored_params = None + + self.decay = decay + self.min_decay = min_decay + self.update_after_step = update_after_step + self.use_ema_warmup = use_ema_warmup + self.inv_gamma = inv_gamma + self.power = power + self.optimization_step = 0 + self.cur_decay_value = None # set in `step()` + + self.model_cls = model_cls + self.model_config = model_config + + self.weight_file_prefix = weight_file_prefix + + @classmethod + def extract_ema_kwargs(cls, kwargs): + """ + Extracts the EMA kwargs from the kwargs of a class method. + """ + ema_kwargs = {} + for key in [ + "decay", + "min_decay", + "optimization_step", + "update_after_step", + "use_ema_warmup", + "inv_gamma", + "power", + ]: + if kwargs.get(key, None) is not None: + ema_kwargs[key] = kwargs.pop(key) + return ema_kwargs + + @classmethod + def from_pretrained(cls, path, model_cls) -> "EMAModel_Zero3": + config = model_cls.load_config(path) + ema_kwargs = cls.extract_ema_kwargs(config) + model = model_cls.from_pretrained(path) + + ema_model = cls(model, model_cls=model_cls, model_config=config) + + ema_model.load_state_dict(ema_kwargs) + return ema_model + + def save_pretrained(self, path): + if self.model_cls is None: + raise ValueError("`save_pretrained` can only be used if `model_cls` was defined at __init__.") + + if self.model_config is None: + raise ValueError("`save_pretrained` can only be used if `model_config` was defined at __init__.") + + rank = int(os.getenv("RANK", "0")) + state_dict = self.state_dict() + state_dict.pop("model") + + model_to_save = self.model.module if hasattr(self.model, "module") else self.model + model_state_dict = {} + for k, v in model_to_save.named_parameters(): + # only gather z3 params + params_to_fetch = _z3_params_to_fetch([v]) + with deepspeed.zero.GatheredParameters(params_to_fetch, enabled=len(params_to_fetch) > 0): + vv = v.data.cpu() + if rank == 0: + model_state_dict[k] = vv + + if rank == 0: + os.makedirs(path, exist_ok=True) + print(f"state_dict, {state_dict.keys()}") + import time + + t_start = time.perf_counter() + print(f"[{t_start:.4f}] 开始 save_pretrained") + + print(type(self.model_config), self.model_config) + for k, v in state_dict.items(): + if isinstance(self.model_config, dict): + self.model.config[k] = v + else: + setattr(self.model_config, k, v) + t1 = time.perf_counter() + print(f"[{t1:.4f}] after setattr config (耗时 {t1 - t_start:.4f} 秒)") + + if hasattr(self.model_config, "save_pretrained"): + self.model_config.save_pretrained(path) + else: + with open(os.path.join(path, "config.json"), "w") as f: + json.dump(self.model_config, f, indent=2) + if hasattr(self.model, "generation_config"): + print(type(self.model.generation_config), self.model.generation_config) + self.model.generation_config.save_pretrained(path) + # with open(os.path.join(path, "generation_config.json"), "w") as f: + # json.dump(self.model.generation_config, f, indent=2) + t2 = time.perf_counter() + print(f"[{t2:.4f}] self.model.save_config(path) (耗时 {t2 - t1:.4f} 秒)") + + if self.weight_file_prefix != "": + self._save_pretrained_with_prefix(model_state_dict, path, self.weight_file_prefix) + else: + torch.save(model_state_dict, os.path.join(path, "pytorch_model.bin")) + t3 = time.perf_counter() + print(f"[{t3:.4f}] after save_pretrained (耗时 {t3 - t2:.4f} 秒)") + + print(f"[{t3:.4f}] 总耗时 {t3 - t_start:.4f} 秒") + return model_state_dict + + def _save_pretrained_with_prefix(self, state_dict, save_dir, weight_file_prefix): + suffix = "{suffix}" + pattern = f"{weight_file_prefix}{suffix}.safetensors" + save_torch_state_dict( + state_dict=state_dict, + save_directory=save_dir, + filename_pattern=pattern, + max_shard_size="5GB", + safe_serialization=True, + ) + + def get_decay(self, optimization_step: int) -> float: + """ + Compute the decay factor for the exponential moving average. + """ + step = max(0, optimization_step - self.update_after_step - 1) + + if step <= 0: + return 0.0 + + if self.use_ema_warmup: + cur_decay_value = 1 - (1 + step / self.inv_gamma) ** -self.power + else: + cur_decay_value = (1 + step) / (10 + step) + + cur_decay_value = min(cur_decay_value, self.decay) + # make sure decay is not smaller than min_decay + cur_decay_value = max(cur_decay_value, self.min_decay) + return cur_decay_value + + @torch.no_grad() + def step(self, parameters: Iterable[torch.nn.Parameter]): + if isinstance(parameters, torch.nn.Module): + deprecation_message = ( + "Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. " + "Please pass the parameters of the module instead." + ) + deprecate( + "passing a `torch.nn.Module` to `ExponentialMovingAverage.step`", + "1.0.0", + deprecation_message, + standard_warn=False, + ) + parameters = parameters.parameters() + + parameters = list(parameters) + + self.optimization_step += 1 + + # Compute the decay factor for the exponential moving average. + decay = self.get_decay(self.optimization_step) + self.cur_decay_value = decay + one_minus_decay = 1 - decay + # print(f'one_minus_decay {one_minus_decay}') + # https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/runtime/zero/partition_parameters.py#L1543 + for s_param, param in zip(self.model.parameters(), parameters): + s_tensor, tensor = None, None + if hasattr(s_param, "ds_tensor"): # EMA ZeRO-3 + # print('EMA ZeRO-3') + s_tensor = s_param.ds_tensor + if hasattr(param, "ds_tensor"): # DiT ZeRO-3 + tensor = param.ds_tensor + else: # DiT ZeRO-2 + rank, world_size = int(os.getenv("RANK")), int(os.getenv("WORLD_SIZE")) + partition_size = math.ceil(param.numel() / world_size) + start = partition_size * rank + end = start + partition_size + + one_dim_param = param.data.contiguous().view(-1) + if start < param.numel() and end <= param.numel(): + tensor = one_dim_param.narrow(0, start, partition_size) + elif start < param.numel(): + # raise ValueError(f'start {start}, end {end}, param.numel() {param.numel()}, partition_size {partition_size}') + elems_to_copy = param.numel() - start + s_tensor = s_param.ds_tensor.narrow(0, 0, elems_to_copy) + tensor = one_dim_param.narrow(0, start, elems_to_copy) + else: + # raise ValueError(f'start {start}, end {end}, param.numel() {param.numel()}, partition_size {partition_size}') + continue + else: # DiT/EMA ZeRO-2 + s_tensor = s_param.data + tensor = param.data + + assert s_tensor.shape == tensor.shape, ( + f"mismatch shape, s_tensor: {s_tensor.shape}, tensor: {tensor.shape}" + ) + + if param.requires_grad: + s_tensor.sub_(one_minus_decay * (s_tensor - tensor.to(s_tensor.dtype))) + else: + s_tensor.copy_(tensor) + + def copy_to(self, parameters: Iterable[torch.nn.Parameter]) -> None: + """ + Copy current averaged parameters into given collection of parameters. + + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + updated with the stored moving averages. If `None`, the parameters with which this + `ExponentialMovingAverage` was initialized will be used. + """ + parameters = list(parameters) + for s_param, param in zip(self.model.parameters(), parameters): + param.data.copy_(s_param.to(param.device).data) + + def to(self, device=None, dtype=None) -> None: + r"""Move internal buffers of the ExponentialMovingAverage to `device`. + + Args: + device: like `device` argument to `torch.Tensor.to` + """ + # .to() on the tensors handles None correctly + self.model = self.model.to(device=device, dtype=dtype) + + def state_dict(self) -> dict: + r""" + Returns the state of the ExponentialMovingAverage as a dict. This method is used by accelerate during + checkpointing to save the ema state dict. + """ + # Following PyTorch conventions, references to tensors are returned: + # "returns a reference to the state and not its copy!" - + # https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict + return { + "decay": self.decay, + "min_decay": self.min_decay, + "optimization_step": self.optimization_step, + "update_after_step": self.update_after_step, + "use_ema_warmup": self.use_ema_warmup, + "inv_gamma": self.inv_gamma, + "power": self.power, + "weight_file_prefix": self.weight_file_prefix, + "model": self.model.state_dict(), + } + + def store(self, parameters: Iterable[torch.nn.Parameter]) -> None: + r""" + Args: + Save the current parameters for restoring later. + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + temporarily stored. + """ + self.temp_stored_params = [param.detach().cpu().clone() for param in parameters] + + def restore(self, parameters: Iterable[torch.nn.Parameter]) -> None: + r""" + Args: + Restore the parameters stored with the `store` method. Useful to validate the model with EMA parameters without: + affecting the original optimization process. Store the parameters before the `copy_to()` method. After + validation (or model saving), use this to restore the former parameters. + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + updated with the stored parameters. If `None`, the parameters with which this + `ExponentialMovingAverage` was initialized will be used. + """ + if self.temp_stored_params is None: + raise RuntimeError("This ExponentialMovingAverage has no `store()`ed weights to `restore()`") + for c_param, param in zip(self.temp_stored_params, parameters): + param.data.copy_(c_param.data) + + # Better memory-wise. + self.temp_stored_params = None + + def load_state_dict(self, state_dict: dict) -> None: + r""" + Args: + Loads the ExponentialMovingAverage state. This method is used by accelerate during checkpointing to save the + ema state dict. + state_dict (dict): EMA state. Should be an object returned + from a call to :meth:`state_dict`. + """ + # deepcopy, to be consistent with module API + state_dict = copy.deepcopy(state_dict) + + self.decay = state_dict.get("decay", self.decay) + if self.decay < 0.0 or self.decay > 1.0: + raise ValueError("Decay must be between 0 and 1") + + self.min_decay = state_dict.get("min_decay", self.min_decay) + if not isinstance(self.min_decay, float): + raise ValueError("Invalid min_decay") + + self.optimization_step = state_dict.get("optimization_step", self.optimization_step) + if not isinstance(self.optimization_step, int): + raise ValueError("Invalid optimization_step") + + self.update_after_step = state_dict.get("update_after_step", self.update_after_step) + if not isinstance(self.update_after_step, int): + raise ValueError("Invalid update_after_step") + + self.use_ema_warmup = state_dict.get("use_ema_warmup", self.use_ema_warmup) + if not isinstance(self.use_ema_warmup, bool): + raise ValueError("Invalid use_ema_warmup") + + self.inv_gamma = state_dict.get("inv_gamma", self.inv_gamma) + if not isinstance(self.inv_gamma, (float, int)): + raise ValueError("Invalid inv_gamma") + + self.power = state_dict.get("power", self.power) + if not isinstance(self.power, (float, int)): + raise ValueError("Invalid power") + + self.weight_file_prefix = state_dict.get("weight_file_prefix", self.weight_file_prefix) + if not isinstance(self.weight_file_prefix, (str)): + raise ValueError("Invalid weight_file_prefix") + + model_state_dict = state_dict.get("model", None) + if model_state_dict is not None: + self.model.load_state_dict(model_state_dict) diff --git a/Helios/helios/utils/create_ema_zero3_lora.py b/Helios/helios/utils/create_ema_zero3_lora.py new file mode 100644 index 0000000000000000000000000000000000000000..8974336b4aadbfae9cdcc9c824040c9aaf94e53e --- /dev/null +++ b/Helios/helios/utils/create_ema_zero3_lora.py @@ -0,0 +1,336 @@ +import copy +import json +import os +import time + +import deepspeed +import torch +from peft import LoraConfig, set_peft_model_state_dict +from peft.utils import get_peft_model_state_dict + +from diffusers.training_utils import _collate_lora_metadata, free_memory +from diffusers.utils import convert_unet_state_dict_to_peft + +from ..pipelines.pipeline_helios import HeliosPipeline +from ..utils.create_ema_zero3 import EMAModel_Zero3, _z3_params_to_fetch +from ..utils.utils_base import NORM_LAYER_PREFIXES, load_extra_components, save_extra_components + + +GB = 1024 * 1024 * 1024 + + +# Adapted from diffusers-style ema https://github.com/huggingface/diffusers/blob/main/src/diffusers/training_utils.py#L263 +class EMAModel_Zero3_LoRA(EMAModel_Zero3): + """ + Exponential Moving Average of models weights + """ + + def __init__( + self, + *args, + **kwargs, + ): + super().__init__(*args, **kwargs) + + @classmethod + def from_pretrained( + cls, args, path, model_cls, lora_config, transformer_additional_kwargs={} + ) -> "EMAModel_Zero3_LoRA": + model = model_cls.from_pretrained( + args.model_config.transformer_model_name_or_path, + subfolder=args.model_config.subfolder or "transformer", + transformer_additional_kwargs=transformer_additional_kwargs, + ) + model.add_adapter(lora_config) + + # ------------- load lora ------------- + lora_state_dict = HeliosPipeline.lora_state_dict(path) + model_state_dict = { + f"{k.replace('transformer.', '')}": v for k, v in lora_state_dict.items() if k.startswith("transformer.") + } + model_state_dict = convert_unet_state_dict_to_peft(model_state_dict) + incompatible_keys = set_peft_model_state_dict(model, model_state_dict, adapter_name="default") + if incompatible_keys is not None: + # check only for unexpected keys + unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None) + if unexpected_keys: + accelerator.print( + f"Loading adapter weights from state_dict led to unexpected keys not found in the model: " + f" {unexpected_keys}. " + ) + + if args.model_config.train_norm_layers: + model_norm_state_dict = { + k: v + for k, v in lora_state_dict.items() + if k.startswith("transformer.") and any(norm_k in k for norm_k in NORM_LAYER_PREFIXES) + } + model._transformer_norm_layers = HeliosPipeline._load_norm_into_transformer( + model_norm_state_dict, + transformer=model, + discard_original_layers=False, + ) + # ------------- load lora ------------- + + # ------------- load extra components ------------- + load_extra_components(args, model, os.path.join(path, "transformer_partial.pth")) + # ------------- load extra components ------------- + + ema_model = cls(model, model_cls=model_cls, model_config=model.config) + + with open(os.path.join(path, "ema_kwargs.json"), "r") as f: + ema_kwargs = json.load(f) + ema_model.load_state_dict(ema_kwargs) + + return ema_model + + def save_pretrained( + self, args, path, pretrained_name_or_path, lora_config, transformer_additional_kwargs={}, transformer_cpu=None + ): + if self.model_cls is None: + raise ValueError("`save_pretrained` can only be used if `model_cls` was defined at __init__.") + + if self.model_config is None: + raise ValueError("`save_pretrained` can only be used if `model_config` was defined at __init__.") + + rank = int(os.getenv("RANK", "0")) + + model_to_save = self.model.module if hasattr(self.model, "module") else self.model + model_state_dict = {} + for k, v in model_to_save.named_parameters(): + # only gather z3 params + params_to_fetch = _z3_params_to_fetch([v]) + with deepspeed.zero.GatheredParameters(params_to_fetch, enabled=len(params_to_fetch) > 0): + if rank == 0: + model_state_dict[k] = v.data.cpu().clone() + + if rank == 0: + state_dict = self.state_dict() + state_dict.pop("model") + + os.makedirs(path, exist_ok=True) + print(f"state_dict, {state_dict.keys()}") + t_start = time.perf_counter() + print(f"[{t_start:.4f}] self.model_cls.from_pretrained") + + print("self.model_cls", self.model_cls) + if transformer_cpu is None: + model = self.model_cls.from_pretrained( + pretrained_name_or_path, + subfolder=args.model_config.subfolder or "transformer", + transformer_additional_kwargs=transformer_additional_kwargs, + ) + model.add_adapter(lora_config) + else: + model = transformer_cpu + t1 = time.perf_counter() + print(f"[{t1:.4f}] after self.model_cls.from_pretrained (耗时 {t1 - t_start:.4f} 秒)") + + miss, unexp = model.load_state_dict(model_state_dict, strict=False) + assert len(unexp) == 0, f"miss: {miss}; unexp: {unexp}" + + # ------------- only save lora ------------- + config_dict = model.config if hasattr(model, "config") else self.model_config + with open(os.path.join(path, "config.json"), "w") as f: + json.dump(config_dict, f, indent=2) + + modules_to_save = {} + transformer_lora_layers_to_save = get_peft_model_state_dict(model) + if args.model_config.train_norm_layers: + transformer_norm_layers_to_save = { + f"transformer.{name}": param + for name, param in model.named_parameters() + if any(k in name for k in NORM_LAYER_PREFIXES) + } + transformer_lora_layers_to_save = { + **transformer_lora_layers_to_save, + **transformer_norm_layers_to_save, + } + modules_to_save["transformer"] = model + HeliosPipeline.save_lora_weights( + path, + transformer_lora_layers=transformer_lora_layers_to_save, + **_collate_lora_metadata(modules_to_save), + ) + # ------------- only save lora ------------- + + # ------------- only save extra components ------------- + save_extra_components(args, model_state_dict=model_state_dict, output_dir=path) + # ------------- only save extra components ------------- + + t2 = time.perf_counter() + print(f"[{t2:.4f}] after save_pretrained (耗时 {t2 - t1:.4f} 秒)") + + print(f"[{t2:.4f}] 总耗时 {t2 - t_start:.4f} 秒") + + with open(os.path.join(path, "ema_kwargs.json"), "w") as f: + json.dump(state_dict, f, indent=2) + + model = None + transformer_cpu = None + params_to_fetch = None + state_dict = None + model_state_dict = None + transformer_lora_layers_to_save = None + transformer_norm_layers_to_save = None + modules_to_save = None + del model + del transformer_cpu + del params_to_fetch + del state_dict + del model_state_dict + del transformer_lora_layers_to_save + del transformer_norm_layers_to_save + del modules_to_save + free_memory() + + print(f"rank {rank} done saved ema!") + + +def gather_zero3ema(accelerator, ema_model): + model_to_save = ema_model.model.module if hasattr(ema_model.model, "module") else ema_model.model + model_state_dict = {} + for k, v in model_to_save.named_parameters(): + # only gather z3 params + params_to_fetch = _z3_params_to_fetch([v]) + with deepspeed.zero.GatheredParameters(params_to_fetch, enabled=len(params_to_fetch) > 0): + # if accelerator.process_index == 0: + model_state_dict[k] = v.data.cpu().clone() + return model_state_dict + + +def create_ema_model( + accelerator, + args, + transformer, + resume_checkpoint_path, + model_cls, + model_config, + ds_config=None, + lora_config=None, + update_after_step=0, + transformer_additional_kwargs={}, +): + ds_config["train_micro_batch_size_per_gpu"] = args.training_config.train_batch_size + ds_config["fp16"]["enabled"] = False + ds_config["bf16"]["enabled"] = False + ds_config["gradient_accumulation_steps"] = args.training_config.gradient_accumulation_steps + ds_config["train_batch_size"] = ( + args.training_config.train_batch_size + * args.training_config.gradient_accumulation_steps + * accelerator.num_processes + ) + accelerator.print(f"EMA deepspeed config {ds_config}") + + if resume_checkpoint_path: + ema_model = EMAModel_Zero3_LoRA.from_pretrained( + args=args, + path=resume_checkpoint_path, + model_cls=model_cls, + lora_config=lora_config, + transformer_additional_kwargs=transformer_additional_kwargs, + ) + accelerator.print(f"Successully resume EMAModel_Zero3 from {resume_checkpoint_path}") + else: + ema_model = EMAModel_Zero3_LoRA( + copy.deepcopy(transformer), + decay=args.training_config.ema_decay, + model_cls=model_cls, + model_config=model_config, + update_after_step=update_after_step, + ) + accelerator.print(f"EMAModel_Zero3 finish, memory_allocated: {torch.cuda.memory_allocated() / GB:.2f} GB") + accelerator.print("Successully deepcopy EMAModel_Zero3 from model") + ema_model.model, _, _, _ = deepspeed.initialize( + model=ema_model.model, config_params=ds_config, distributed_port=args.training_config.ema_zero3_port + ) + return ema_model + + +def create_ema_final( + accelerator, + args, + transformer_cpu, + model_cls, + ds_config, + transformer_lora_config, + update_after_step=0, + resume_checkpoint_path=None, + transformer_additional_kwargs=None, +): + ema_transformer = create_ema_model( + accelerator, + args=args, + transformer=transformer_cpu, + resume_checkpoint_path=resume_checkpoint_path, + model_cls=model_cls, + model_config=transformer_cpu.config, + ds_config=ds_config, + lora_config=transformer_lora_config, + update_after_step=update_after_step, + transformer_additional_kwargs=transformer_additional_kwargs, + ) + free_memory() + return ema_transformer + + +if __name__ == "__main__": + import json + import sys + from argparse import Namespace + + import deepspeed + from accelerate import Accelerator + + sys.path.append("../../") + from helios.modules.transformer_helios import HeliosTransformer3DModel + + args = Namespace() + args.data_config = Namespace() + args.training_config = Namespace() + args.model_config = Namespace() + args.training_config.train_batch_size = 1 + args.training_config.gradient_accumulation_steps = 1 + args.training_config.ema_decay = 0.999 + args.training_config.ema_zero3_port = 10543 + args.model_config.train_norm_layers = False + args.model_config.transformer_model_name_or_path = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers" + args.training_config.ema_deepspeed_config_file = "../../scripts/accelerate_configs/zero3.json" + resume_checkpoint_path = None + + output_dir = "temp" + accelerator = Accelerator() + + model_cls = HeliosTransformer3DModel + transformer = model_cls.from_pretrained( + args.model_config.transformer_model_name_or_path, subfolder="transformer", torch_dtype=torch.bfloat16 + ) + target_modules = set() + for name, module in transformer.named_modules(): + if isinstance(module, torch.nn.Linear): + target_modules.add(name) + target_modules = list(target_modules) + lora_config = LoraConfig( + r=256, + lora_alpha=256, + # target_modules=["to_k", "to_v", "to_q", "to_out.0"], + target_modules=target_modules, + lora_dropout=0.0, + ) + transformer.add_adapter(lora_config) + + transformer_cpu = copy.deepcopy(transformer) + transformer.to(device=accelerator.device, dtype=torch.bfloat16) + accelerator.print(f"Load model finish, memory_allocated: {torch.cuda.memory_allocated() / GB:.2f} GB") + + with open(args.training_config.ema_deepspeed_config_file, "r") as f: + ds_config = json.load(f) + + ema_transformer = create_ema_final( + accelerator=accelerator, + args=args, + transformer_cpu=transformer_cpu, + model_cls=model_cls, + ds_config=ds_config, + transformer_lora_config=lora_config, + ) diff --git a/Helios/helios/utils/train_config.py b/Helios/helios/utils/train_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ed1e35922844061567dbae0a9c094282407d3107 --- /dev/null +++ b/Helios/helios/utils/train_config.py @@ -0,0 +1,443 @@ +from dataclasses import dataclass, field +from typing import Optional + + +@dataclass +class ReportTo: + tracker_name: str = field(default="Spark-Wan") + wandb_name: str = field(default="test_run") + report_to: str = field( + default="wandb", + metadata={"choices": ["wandb", "tensorboard", "comet_ml", "all"]}, + ) + + +@dataclass +class DataConfig: + # ---- Base ---- + use_shuffle: bool = field(default=False) + pin_memory: bool = field(default=False) + persistent_workers: bool = field(default=False) + instance_data_root: list = field(default_factory=list) + instance_video_root: list = field(default_factory=list) + dataset_sampling_ratios: list = field(default_factory=list) + dataloader_num_workers: int = field(default=0) + prefetch_factor: int = field(default=2) + force_rebuild: bool = field(default=False) + stride: int = field(default=1) + resolution: int = field(default=640) + single_res: bool = field(default=False) + single_res: bool = field(default=False) + single_height: int = field(default=384) + single_width: int = field(default=640) + single_length: bool = field(default=False) + single_num_frame: int = field(default=81) + multi_res: bool = field(default=False) + caption_dropout_p: float = field(default=0.00) + id_token: str = field(default="") + negative_prompt: str = field( + default="Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" + ) + # ---- Stage 1 ---- + use_stage1_dataset: bool = field(default=False) + # ---- Stage 3 ---- + use_stage3_dataset: bool = field(default=False) + gan_data_root: Optional[list] = field(default_factory=list) + ode_data_root: Optional[list] = field(default_factory=list) + text_data_root: Optional[list] = field(default_factory=list) + + +@dataclass +class ModelConfig: + # ---- Path ---- + pretrained_model_name_or_path: Optional[str] = field(default=None) + transformer_model_name_or_path: Optional[str] = field(default=None) + siglip_model_name_or_path: Optional[str] = field(default=None) + lora_paths: Optional[list[str]] = field(default_factory=list) + subfolder: Optional[str] = field(default=None) + revision: Optional[str] = field(default=None) + variant: Optional[str] = field(default=None) + load_checkpoints_custom: bool = field(default=False) + load_model_path: Optional[str] = field(default=None) + load_dcp: bool = field(default=False) + load_dcp_path: Optional[str] = field(default=None) + # ---- Vae ---- + upcast_vae: bool = field(default=False) + enable_slicing: bool = field(default=False) + enable_tiling: bool = field(default=False) + # ---- Lora ---- + lora_rank: int = field(default=128) + lora_alpha: float = field(default=128.0) + lora_dropout: float = field(default=0.0) + lora_layers: Optional[str] = field(default=None) + lora_target_modules: list = field(default_factory=list) + lora_exclude_modules: list = field(default_factory=list) + # ---- Other ---- + train_norm_layers: bool = field(default=False) + bnb_quantization_config_path: Optional[str] = field(default=None) + # ----- Stage 3 ----- + critic_lora_name_or_path: Optional[str] = field(default=None) + critic_subfolder: Optional[str] = field(default=None) + critic_lora_rank: int = field(default=128) + critic_lora_alpha: float = field(default=128.0) + critic_lora_dropout: float = field(default=0.0) + real_score_model_name_or_path: Optional[str] = field(default=None) + # ---- Reward Parameters ---- + reward_model_name_or_path: Optional[str] = field(default=None) + + +@dataclass +class ValidationConfig: + validation_steps: int = field(default=100) + validation_height: int = field(default=480) + validation_width: int = field(default=832) + validation_max_num_frames: int = field(default=81) + validation_prompts: Optional[list[str]] = field(default_factory=lambda: ["A frog jumps on a lotus leaf."]) + validation_images: Optional[list[str]] = field(default_factory=lambda: ["example/input_images/frog.jpg"]) + validation_guidance_scale: float = field(default=9.0) + validation_latent_window_size: list[int] = field(default_factory=lambda: [9]) + validation_stream_chunk_size: list[int] = field(default_factory=lambda: [3]) + first_step_valid: bool = field(default=True) + num_validation_videos: int = field(default=1) + num_inference_steps: int = field(default=30) + # ---- Dynamic Shifting ---- + use_dynamic_shifting: bool = field(default=False) + time_shift_type: str = field( + default="linear", + metadata={"choices": ["exponential", "linear"]}, + ) + # ---- Stage 1 ---- + use_kv_cache: bool = field(default=False) + # ---- Stage 2 ---- + stage2_simulated_inference_steps: list[int] = field(default_factory=lambda: [10, 10, 10]) + + +@dataclass +class TrainingConfig: + # ---- Environment ---- + local_rank: int = field(default=-1) + allow_tf32: bool = field(default=False) + gradient_checkpointing: bool = field(default=True) + enable_xformers_memory_efficient_attention: bool = field(default=False) + enable_npu_flash_attention: bool = field(default=False) + upcast_before_saving: bool = field(default=False) + offload: bool = field(default=False) + mixed_precision: str = field( + default="bf16", + metadata={"choices": ["no", "fp16", "bf16"]}, + ) + profile_out_dir: Optional[str] = field(default=None) + # ---- Training Resource ---- + num_train_epochs: int = field(default=1) + max_train_steps: Optional[int] = field(default=None) + train_batch_size: int = field(default=1) + gradient_accumulation_steps: int = field(default=1) + checkpointing_steps: int = field(default=500) + checkpoints_total_limit: Optional[int] = field(default=None) + resume_from_checkpoint: Optional[str] = field(default=None) + save_checkpoints_custom: bool = field(default=False) + # ---- Optimizer ---- + learning_rate: float = field(default=2e-4) + scale_lr: bool = field(default=False) + lr_scheduler: str = field( + default="constant", + metadata={ + "choices": [ + "linear", + "cosine", + "cosine_with_restarts", + "polynomial", + "constant", + "constant_with_warmup", + ] + }, + ) + lr_warmup_steps: int = field(default=500) + lr_num_cycles: int = field(default=1) + lr_power: float = field(default=1.0) + optimizer: str = field( + default="adamw", + metadata={ + "choices": ["adam", "adamw", "prodigy"], + }, + ) + use_8bit_adam: bool = field(default=False) + adam_beta1: float = field(default=0.9) + adam_beta2: float = field(default=0.999) + prodigy_beta3: Optional[float] = field(default=None) + prodigy_decouple: bool = field(default=True) + prodigy_use_bias_correction: bool = field(default=True) + prodigy_safeguard_warmup: bool = field(default=True) + adam_weight_decay: float = field(default=1e-04) + adam_epsilon: float = field(default=1e-08) + max_grad_norm: float = field(default=1.0) + weighting_scheme: str = field( + default="logit_normal", + metadata={ + "choices": ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"], + }, + ) + logit_mean: float = field(default=0.0) + logit_std: float = field(default=1.0) + mode_scale: float = field(default=1.29) + # ---- Dynamic Shifting ---- + use_dynamic_shifting: bool = field(default=False) + time_shift_type: str = field( + default="linear", + metadata={"choices": ["exponential", "linear"]}, + ) + base_seq_len: Optional[int] = field(default=256) + max_seq_len: Optional[int] = field(default=4096) + base_shift: Optional[float] = field(default=0.5) + max_shift: Optional[float] = field(default=1.15) + # ---- VAE Decode Parameters ---- + vae_decode_type: str = field( + default="default", + metadata={ + "choices": ["default", "dafault_batch"], + }, + ) + # ---- EMA ---- + use_ema: bool = field(default=False) + use_ema_validation: bool = field(default=False) + ema_decay: float = field(default=0.999) + ema_start_step: int = field(default=0) + ema_zero3_port: int = field(default=10543) + ema_deepspeed_config_file: str = field(default="scripts/accelerate_configs/zero3.json") + # ---- Stage 1 Parameters ---- + is_enable_stage1: bool = field(default=False) + history_sizes: list[int] = field(default_factory=lambda: [16, 2, 1]) + latent_window_size: list[int] = field(default_factory=lambda: [9]) + is_random_drop: bool = field(default=False) + random_drop_i2v_ratio: float = field(default=0) + random_drop_v2v_ratio: float = field(default=0) + random_drop_t2v_ratio: float = field(default=0) + is_amplify_history: bool = field(default=False) + history_scale_mode: str = field( + default="per_head", + metadata={ + "choices": ["scalar", "per_head"], + }, + ) + # + has_multi_term_memory_patch: bool = field(default=False) + is_train_full_multi_term_memory_patchg: bool = field(default=False) + is_train_lora_multi_term_memory_patchg: bool = field(default=False) + is_train_full_patch_embedding: bool = field(default=False) + is_train_lora_patch_embedding: bool = field(default=False) + zero_history_timestep: bool = field(default=False) + restrict_self_attn: bool = field(default=False) + guidance_cross_attn: bool = field(default=False) + is_train_restrict_lora: bool = field(default=False) + restrict_lora: bool = field(default=False) + restrict_lora_rank: int = field(default=128) + # ---- Easy Anti-Drifting Parameters ---- + corrupt_model_input: bool = field(default=False) + corrupt_mode_model_input: str = field( + default="noise", + metadata={ + "choices": ["noise", "downsample", "random"], + }, + ) + corrupt_mode_prob_model_input: float = field(default=0.9) + is_frame_independent_corrupt_model_input: bool = field(default=False) + is_chunk_independent_corrupt_model_input: bool = field(default=False) + noise_corrupt_ratio_model_input: float = field(default=1 / 3) + noise_corrupt_clean_prob_model_input: float = field(default=0.1) + downsample_min_corrupt_ratio_model_input: float = field(default=0.9) + downsample_max_corrupt_ratio_model_input: float = field(default=1.0) + # + corrupt_history: bool = field(default=False) + corrupt_mode_history: str = field( + default="noise", + metadata={ + "choices": ["noise", "downsample", "random"], + }, + ) + corrupt_mode_prob_history: float = field(default=0.9) + is_frame_independent_corrupt_history: bool = field(default=False) + is_chunk_independent_corrupt_history: bool = field(default=False) + noise_corrupt_ratio_history_short: float = field(default=1 / 3) + noise_corrupt_ratio_history_mid: float = field(default=1 / 3) + noise_corrupt_ratio_history_long: float = field(default=1 / 3) + noise_corrupt_clean_prob_history: float = field(default=0.1) + downsample_min_corrupt_ratio_history: float = field(default=0.9) + downsample_max_corrupt_ratio_history: float = field(default=1.0) + # + is_add_saturation: bool = field(default=False) + saturation_ratio_min: float = field(default=0.3) + saturation_ratio_max: float = field(default=1.7) + saturation_ratio_clean_prob: float = field(default=0.1) + # ---- Stage 2 Parameters ---- + is_enable_stage2: bool = field(default=False) + is_navit_pyramid: bool = field(default=False) + stage2_num_stages: int = field(default=3) + stage2_timestep_shift: float = field(default=1.0) + stage2_scheduler_gamma: float = field(default=1 / 3) + stage2_stage_range: list[float] = field(default_factory=lambda: [0.0, 1 / 3, 2 / 3, 1]) + stage2_sample_ratios: list[int] = field(default_factory=lambda: [1, 2, 1]) + efficient_sample: bool = field(default=False) + # ---- Stage 3 VRAM Parameters ---- + dmd_is_low_vram_mode: bool = field(default=False) + is_gan_low_vram_mode: bool = field(default=False) + dmd_is_offload_grad: bool = field(default=False) + # ---- Stage 3 Parameters ---- + log_iters: int = field(default=200) + no_visualize: bool = field(default=False) + is_train_dmd: bool = field(default=False) + max_grad_norm_critic: float = field(default=1.0) + dmd_generator_deepspeed_config: Optional[str] = field(default=None) + dmd_critic_deepspeed_config: Optional[str] = field(default=None) + critic_learning_rate: Optional[float] = field(default=2e-6) + dfake_gen_update_ratio: Optional[int] = field(default=5) + dmd_denoising_step_list: list[int] = field(default_factory=lambda: [1000, 750, 500, 250]) + num_critic_input_frames: Optional[int] = field(default=21) + dmd_timestep_shift: Optional[float] = field(default=5.0) + dmd_last_step_only: bool = field(default=False) + dmd_last_section_grad_only: bool = field(default=False) + dmd_teacher_forcing: bool = field(default=False) + dmd_teacher_forcing_ratio: float = field(default=0.2) + fake_guidance_scale: float = field(default=0.0) + real_guidance_scale: float = field(default=3.0) + is_skip_first_section: bool = field(default=False) + is_amplify_first_chunk: bool = field(default=False) + # ---- GT History Parameters ---- + is_use_gt_history: bool = field(default=False) + use_gt_history_ratio: float = field(default=1.0) + is_use_gt_coherence_dmd: bool = field(default=False) + # ---- VAE Re-Encode ---- + is_dmd_vae_decode: bool = field(default=False) + # ---- Multi Stage Backward Simulated ---- + is_multi_pyramid_stage_backward_simulated: bool = field(default=False) + # ---- Consistency Align Parameters ---- + is_consistency_align: bool = field(default=False) + consistentcy_align_weight: float = field(default=0.25) + # ---- Smoothness Parameters ---- + is_smoothness_loss: bool = field(default=False) + smoothness_loss_weight: float = field(default=1e-2) + # ---- Mean-Variance Regularization Parameters ---- + is_mean_var_regular: bool = field(default=False) + mean_var_regular_weight: float = field(default=1.0) + regular_mean: Optional[float] = field(default=0.00657021) + regular_var: Optional[float] = field(default=0.85126512) + is_x0_mean_var_regular: bool = field(default=False) + mean_var_regular_x0_weight: float = field(default=1.0) + regular_x0_mean: Optional[float] = field(default=-0.01618061) + regular_x0_var: Optional[float] = field(default=0.27996052) + # + is_chunk_mean_var_regular: bool = field(default=False) + chunk_mean_var_regular_weight: float = field(default=1.0) + chunk_regular_mean: Optional[float] = field(default=0.01906107) + chunk_regular_var: Optional[float] = field(default=0.81397036) + is_chunk_x0_mean_var_regular: bool = field(default=False) + chunk_mean_var_regular_x0_weight: float = field(default=1.0) + chunk_regular_x0_mean: Optional[float] = field(default=-0.01578601) + chunk_regular_x0_var: Optional[float] = field(default=0.29913200) + # ---- ODE Regression ---- + is_use_ode_regression: bool = field(default=False) + is_only_ode_regression: bool = field(default=False) + ode_regression_weight: float = field(default=0.25) + ode_num_latent_sections_min: int = field(default=3) + ode_num_latent_sections_max: int = field(default=3) + # ---- GAN Parameters ---- + is_use_gan: bool = field(default=False) + gan_start_step: int = field(default=0) + is_separate_gan_grad: bool = field(default=False) + is_use_gan_hooks: bool = field(default=False) + is_use_gan_final: bool = field(default=False) + gan_cond_map_dim: int = field(default=768) + gan_hooks: list[int] = field(default_factory=lambda: [5, 15, 25, 35]) + gan_g_weight: float = field(default=1e-2) + gan_d_weight: float = field(default=1e-2) + aprox_r1: bool = field(default=False) + aprox_r2: bool = field(default=False) + r1_weight: float = field(default=0.0) + r2_weight: float = field(default=0.0) + r1_sigma: float = field(default=0.1) + r2_sigma: float = field(default=0.1) + # ---- Reward Parameters ---- + is_use_reward_model: bool = field(default=False) + reward_start_step: int = field(default=0) + reward_weight_vq: float = field(default=2.0) + reward_weight_mq: float = field(default=2.0) + reward_weight_ta: float = field(default=2.0) + # ---- Decouple Parameters ---- + is_decouple_dmd: bool = field(default=False) + decouple_ca_start_step: int = field(default=2000) + decouple_ca_end_step: int = field(default=3000) + # ---- Cold Start Parameters ---- + is_enable_cold_start: bool = field(default=False) + cold_start_step: int = field(default=1000) + stage_cold_start_step: Optional[int] = field(default=None) + # ---- Dynamic Timestep ---- + generator_is_forcing_low_renoise: bool = field(default=False) + generator_dynamic_alpha: float = field(default=4.0) + generator_dynamic_beta: float = field(default=1.5) + generator_dynamic_sample_type: str = field( + default="uniform", + metadata={ + "choices": ["uniform", "beta"], + }, + ) + generator_dynamic_step: int = field(default=1000) + critic_dynamic_alpha: float = field(default=4.0) + critic_dynamic_beta: float = field(default=1.5) + critic_dynamic_sample_type: str = field( + default="uniform", + metadata={ + "choices": ["uniform", "beta"], + }, + ) + critic_dynamic_step: int = field(default=1000) + # ---- Dynamic DMD Section ---- + dmd_num_latent_sections_min: Optional[int] = field(default=3) + dmd_num_latent_sections_max: Optional[int] = field(default=3) + dmd_dynamic_alpha: float = field(default=1.5) + dmd_dynamic_beta: float = field(default=4.0) + dmd_dynamic_sample_type: str = field( + default="uniform", + metadata={ + "choices": ["uniform", "beta"], + }, + ) + dmd_dynamic_step: int = field(default=1000) + # ---- Dynamic ODE Section ---- + ode_dynamic_alpha: float = field(default=1.5) + ode_dynamic_beta: float = field(default=4.0) + ode_dynamic_sample_type: str = field( + default="uniform", + metadata={ + "choices": ["uniform", "beta"], + }, + ) + ode_dynamic_step: int = field(default=1000) + # ---- Recycle ---- + use_error_recycling: bool = field(default=False) + y_error_sample_from_all_grids: bool = field(default=True) + + error_buffer_size: int = field(default=500) + buffer_replacement_strategy: str = field(default="l2_batch") + buffer_warmup_iter: int = field(default=50) + timestep_grid_size: int = field(default=25) + num_grids: int = field(default=50) + + y_error_num: int = field(default=6) + error_modulate_factor: float = field(default=0.0) + error_setting: int = field(default=1) + noise_prob: float = field(default=0.01) + y_prob: float = field(default=0.9) + latent_prob: float = field(default=0.9) + clean_prob: float = field(default=0.2) + clean_buffer_update_prob: float = field(default=0.1) + + +@dataclass +class Args: + output_dir: str = field(default="Helios") + seed: int = field(default=42) + report_to: ReportTo = field(default_factory=ReportTo) + data_config: DataConfig = field(default_factory=DataConfig) + model_config: ModelConfig = field(default_factory=ModelConfig) + validation_config: ValidationConfig = field(default_factory=ValidationConfig) + training_config: TrainingConfig = field(default_factory=TrainingConfig) + logging_dir: str = field(default="logs") diff --git a/Helios/helios/utils/utils_base.py b/Helios/helios/utils/utils_base.py new file mode 100644 index 0000000000000000000000000000000000000000..b41db36efcc554e7caca824a74e1e1666b98d1a4 --- /dev/null +++ b/Helios/helios/utils/utils_base.py @@ -0,0 +1,745 @@ +import gc +import html +import math +import os +import random +from typing import List, Literal, Optional, Union + +import ftfy +import regex as re +import torch +from accelerate.logging import get_logger + + +logger = get_logger(__name__) + +NORM_LAYER_PREFIXES = ["norm_q", "norm_k", "norm_added_q", "norm_added_k"] + + +# ======================================== memory monitoring ======================================== +def get_memory_stats(): + if torch.cuda.is_available(): + allocated = torch.cuda.memory_allocated() / 1024**3 # GB + reserved = torch.cuda.memory_reserved() / 1024**3 # GB + max_allocated = torch.cuda.max_memory_allocated() / 1024**3 + return {"allocated": allocated, "reserved": reserved, "max_allocated": max_allocated} + return None + + +def reset_memory_stats(): + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + gc.collect() + + +# ======================================== initialize ======================================== +def get_config_value(args, name): + if hasattr(args, name): + return getattr(args, name) + elif hasattr(args, "training_config") and hasattr(args.training_config, name): + return getattr(args.training_config, name) + else: + raise AttributeError(f"Neither args nor args.training_config has attribute '{name}'") + + +def compare_configs(existing_conf, current_conf, path="", ignore_keys=None): + if ignore_keys is None: + ignore_keys = set() + + mismatches = [] + + all_keys = set(existing_conf.keys()) | set(current_conf.keys()) + + for key in all_keys: + current_path = f"{path}.{key}" if path else key + + if current_path in ignore_keys or key in ignore_keys: + continue + + if key not in existing_conf: + mismatches.append(f"Key '{current_path}' missing in existing config") + elif key not in current_conf: + mismatches.append(f"Key '{current_path}' missing in current config") + else: + existing_val = existing_conf[key] + current_val = current_conf[key] + + if isinstance(existing_val, dict) and isinstance(current_val, dict): + mismatches.extend(compare_configs(existing_val, current_val, current_path, ignore_keys)) + elif existing_val != current_val: + mismatches.append(f"Key '{current_path}': existing={existing_val} vs current={current_val}") + + return mismatches + + +def get_optimizer(args, accelerator, params_to_optimize, use_deepspeed: bool = False): + # Use DeepSpeed optimizer + if use_deepspeed: + from accelerate.utils import DummyOptim + + return DummyOptim( + params_to_optimize, + lr=args.training_config.learning_rate, + betas=(args.training_config.adam_beta1, args.training_config.adam_beta2), + eps=args.training_config.adam_epsilon, + weight_decay=args.training_config.adam_weight_decay, + ) + + # Optimizer creation + supported_optimizers = ["adam", "adamw", "prodigy"] + if args.training_config.optimizer.lower() not in supported_optimizers: + accelerator.print( + f"Unsupported choice of optimizer: {args.training_config.optimizer}. Supported optimizers include {supported_optimizers}. Defaulting to AdamW" + ) + args.training_config.optimizer = "adamw" + + if args.training_config.use_8bit_adam and args.training_config.optimizer.lower() not in ["adam", "adamw"]: + accelerator.print( + f"use_8bit_adam is ignored when optimizer is not set to 'AdamW'. Optimizer was " + f"set to {args.training_config.optimizer.lower()}" + ) + + if args.training_config.use_8bit_adam: + try: + import bitsandbytes as bnb + except ImportError: + raise ImportError( + "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`." + ) + + if args.training_config.optimizer.lower() == "adamw": + optimizer_class = bnb.optim.AdamW8bit if args.training_config.use_8bit_adam else torch.optim.AdamW + + optimizer = optimizer_class( + params_to_optimize, + betas=(args.training_config.adam_beta1, args.training_config.adam_beta2), + eps=args.training_config.adam_epsilon, + weight_decay=args.training_config.adam_weight_decay, + ) + elif args.training_config.optimizer.lower() == "adam": + optimizer_class = bnb.optim.Adam8bit if args.training_config.use_8bit_adam else torch.optim.Adam + + optimizer = optimizer_class( + params_to_optimize, + betas=(args.training_config.adam_beta1, args.training_config.adam_beta2), + eps=args.training_config.adam_epsilon, + weight_decay=args.training_config.adam_weight_decay, + ) + elif args.training_config.optimizer.lower() == "prodigy": + try: + import prodigyopt + except ImportError: + raise ImportError("To use Prodigy, please install the prodigyopt library: `pip install prodigyopt`") + + optimizer_class = prodigyopt.Prodigy + + if args.training_config.learning_rate <= 0.1: + accelerator.print( + "Learning rate is too low. When using prodigy, it's generally better to set learning rate around 1.0" + ) + + optimizer = optimizer_class( + params_to_optimize, + betas=(args.training_config.adam_beta1, args.training_config.adam_beta2), + beta3=args.training_config.prodigy_beta3, + weight_decay=args.training_config.adam_weight_decay, + eps=args.training_config.adam_epsilon, + decouple=args.training_config.prodigy_decouple, + use_bias_correction=args.training_config.prodigy_use_bias_correction, + safeguard_warmup=args.training_config.prodigy_safeguard_warmup, + ) + + return optimizer + + +# ======================================== checkpoints related ======================================== +def save_extra_components(args, model=None, model_state_dict=None, output_dir=None): + if model is None and model_state_dict is None: + raise ValueError("Either 'model' or 'model_state_dict' must be provided") + + if output_dir is None: + raise ValueError("output_dir must be provided") + + os.makedirs(output_dir, exist_ok=True) + state_dict = {} + + # Determine whether to use model or model_state_dict + use_state_dict = model_state_dict is not None + + # 1. Save patch_short, patch_mid, patch_long (formerly multi_term_memory_patchg) + if args.training_config.is_enable_stage1 and ( + args.training_config.is_train_full_multi_term_memory_patchg + or args.training_config.is_train_lora_multi_term_memory_patchg + ): + patch_names = ["patch_short", "patch_mid", "patch_long"] + + if use_state_dict: + # Extract from state_dict + for k, v in model_state_dict.items(): + if any(k.startswith(f"{p}.") for p in patch_names): + state_dict[k] = v.detach().clone().cpu() if torch.is_tensor(v) else v + else: + # Extract from model + for p in patch_names: + if hasattr(model, p): + patch_module = getattr(model, p) + for k, v in patch_module.state_dict().items(): + state_dict[f"{p}.{k}"] = v.detach().clone().cpu() + + # 2. Save LoRA layers from all transformer blocks + if args.training_config.restrict_self_attn and args.training_config.is_train_restrict_lora: + if use_state_dict: + # Extract LoRA parameters from state_dict + for k, v in model_state_dict.items(): + if any(lora_key in k for lora_key in [".q_loras.", ".k_loras.", ".v_loras."]): + state_dict[k] = v.detach().clone().cpu() if torch.is_tensor(v) else v + else: + # Extract from model + for block_idx, block in enumerate(model.blocks): + if hasattr(block.attn1, "q_loras"): + for k, v in block.attn1.q_loras.state_dict().items(): + state_dict[f"blocks.{block_idx}.attn1.q_loras.{k}"] = v.detach().clone().cpu() + + if hasattr(block.attn1, "k_loras"): + for k, v in block.attn1.k_loras.state_dict().items(): + state_dict[f"blocks.{block_idx}.attn1.k_loras.{k}"] = v.detach().clone().cpu() + + if hasattr(block.attn1, "v_loras"): + for k, v in block.attn1.v_loras.state_dict().items(): + state_dict[f"blocks.{block_idx}.attn1.v_loras.{k}"] = v.detach().clone().cpu() + + # 3. Save History Scale parameters + if args.training_config.is_amplify_history: + if use_state_dict: + # Extract history_key_scale from state_dict + for k, v in model_state_dict.items(): + if "history_key_scale" in k: + state_dict[k] = v.detach().clone().cpu() if torch.is_tensor(v) else v + else: + # Extract from model + for block_idx, block in enumerate(model.blocks): + if hasattr(block.attn1, "history_key_scale"): + state_dict[f"blocks.{block_idx}.attn1.history_key_scale"] = ( + block.attn1.history_key_scale.detach().clone().cpu() + ) + + # 4. Save GAN parameters + if args.training_config.is_use_gan: + if use_state_dict: + # Extract GAN parameters from state_dict + for k, v in model_state_dict.items(): + if k.startswith("gan_heads.") or k.startswith("gan_final_head."): + state_dict[k] = v.detach().clone().cpu() if torch.is_tensor(v) else v + else: + # Extract from model + if hasattr(model, "gan_heads"): + for hook_name, gan_head in model.gan_heads.items(): + for k, v in gan_head.state_dict().items(): + state_dict[f"gan_heads.{hook_name}.{k}"] = v.detach().clone().cpu() + + if hasattr(model, "gan_final_head"): + for k, v in model.gan_final_head.state_dict().items(): + state_dict[f"gan_final_head.{k}"] = v.detach().clone().cpu() + + torch.save(state_dict, os.path.join(output_dir, "transformer_partial.pth")) + print(f"Saved checkpoint with {len(state_dict)} parameters to {output_dir}/transformer_partial.pth") + + +def load_extra_components(args, model, checkpoint_path): + """ + Load patch_short, patch_mid, patch_long, q_loras, k_loras, v_loras into the model + """ + state_dict = torch.load(checkpoint_path, map_location="cpu") + loaded_keys = set() + + # Load patch modules (formerly multi_term_memory_patchg) + if args.training_config.is_enable_stage1: + patch_names = ["patch_short", "patch_mid", "patch_long"] + + for p_name in patch_names: + patch_keys_in_sd = [k for k in state_dict.keys() if k.startswith(f"{p_name}.")] + if patch_keys_in_sd and hasattr(model, p_name): + patch_state = { + k.replace(f"{p_name}.", ""): v for k, v in state_dict.items() if k.startswith(f"{p_name}.") + } + patch_module = getattr(model, p_name) + load_info = patch_module.load_state_dict(patch_state, strict=False) + loaded_keys.update(patch_keys_in_sd) + + print(f"Loaded {len(patch_keys_in_sd)} parameters for {p_name}") + if load_info.missing_keys: + print(f" Missing keys in {p_name}: {load_info.missing_keys}") + if load_info.unexpected_keys: + print(f" Unexpected keys in {p_name}: {load_info.unexpected_keys}") + + # Load LoRA layers + lora_keys_count = 0 + if args.training_config.restrict_self_attn: + for block_idx, block in enumerate(model.blocks): + # Load q_loras + q_lora_keys_in_sd = [k for k in state_dict.keys() if k.startswith(f"blocks.{block_idx}.attn1.q_loras.")] + if q_lora_keys_in_sd: + q_lora_state = { + k.replace(f"blocks.{block_idx}.attn1.q_loras.", ""): v + for k, v in state_dict.items() + if k.startswith(f"blocks.{block_idx}.attn1.q_loras.") + } + load_info = block.attn1.q_loras.load_state_dict(q_lora_state, strict=False) + loaded_keys.update(q_lora_keys_in_sd) + lora_keys_count += len(q_lora_keys_in_sd) + if load_info.missing_keys: + print(f" Missing keys in blocks.{block_idx}.attn1.q_loras: {load_info.missing_keys}") + if load_info.unexpected_keys: + print(f" Unexpected keys in blocks.{block_idx}.attn1.q_loras: {load_info.unexpected_keys}") + + # Load k_loras + k_lora_keys_in_sd = [k for k in state_dict.keys() if k.startswith(f"blocks.{block_idx}.attn1.k_loras.")] + if k_lora_keys_in_sd: + k_lora_state = { + k.replace(f"blocks.{block_idx}.attn1.k_loras.", ""): v + for k, v in state_dict.items() + if k.startswith(f"blocks.{block_idx}.attn1.k_loras.") + } + load_info = block.attn1.k_loras.load_state_dict(k_lora_state, strict=False) + loaded_keys.update(k_lora_keys_in_sd) + lora_keys_count += len(k_lora_keys_in_sd) + if load_info.missing_keys: + print(f" Missing keys in blocks.{block_idx}.attn1.k_loras: {load_info.missing_keys}") + if load_info.unexpected_keys: + print(f" Unexpected keys in blocks.{block_idx}.attn1.k_loras: {load_info.unexpected_keys}") + + # Load v_loras + v_lora_keys_in_sd = [k for k in state_dict.keys() if k.startswith(f"blocks.{block_idx}.attn1.v_loras.")] + if v_lora_keys_in_sd: + v_lora_state = { + k.replace(f"blocks.{block_idx}.attn1.v_loras.", ""): v + for k, v in state_dict.items() + if k.startswith(f"blocks.{block_idx}.attn1.v_loras.") + } + load_info = block.attn1.v_loras.load_state_dict(v_lora_state, strict=False) + loaded_keys.update(v_lora_keys_in_sd) + lora_keys_count += len(v_lora_keys_in_sd) + if load_info.missing_keys: + print(f" Missing keys in blocks.{block_idx}.attn1.v_loras: {load_info.missing_keys}") + if load_info.unexpected_keys: + print(f" Unexpected keys in blocks.{block_idx}.attn1.v_loras: {load_info.unexpected_keys}") + + print(f"Loaded {lora_keys_count} parameters for Restrict Self Attn LoRA") + + # Load History Scale layers + history_keys_count = 0 + if args.training_config.is_amplify_history: + for block_idx, block in enumerate(model.blocks): + history_key_scale_key = f"blocks.{block_idx}.attn1.history_key_scale" + if history_key_scale_key in state_dict: + block.attn1.history_key_scale.data = state_dict[history_key_scale_key].to( + block.attn1.history_key_scale.device + ) + loaded_keys.add(history_key_scale_key) + history_keys_count += 1 + + print(f"Loaded {history_keys_count} parameters for History Scale") + + # Load GAN + gan_keys_count = 0 + if args.training_config.is_use_gan: + # Load intermediate gan_heads + if hasattr(model, "gan_heads"): + for hook_name, gan_head in model.gan_heads.items(): + gan_head_prefix = f"gan_heads.{hook_name}." + gan_head_keys_in_sd = [k for k in state_dict.keys() if k.startswith(gan_head_prefix)] + + if gan_head_keys_in_sd: + gan_head_state = { + k.replace(gan_head_prefix, ""): v + for k, v in state_dict.items() + if k.startswith(gan_head_prefix) + } + load_info = gan_head.load_state_dict(gan_head_state, strict=False) + loaded_keys.update(gan_head_keys_in_sd) + gan_keys_count += len(gan_head_keys_in_sd) + if load_info.missing_keys: + print(f" Missing keys in gan_heads.{hook_name}: {load_info.missing_keys}") + if load_info.unexpected_keys: + print(f" Unexpected keys in gan_heads.{hook_name}: {load_info.unexpected_keys}") + + # Load final gan head + if hasattr(model, "gan_final_head"): + gan_final_keys_in_sd = [k for k in state_dict.keys() if k.startswith("gan_final_head.")] + + if gan_final_keys_in_sd: + gan_final_state = { + k.replace("gan_final_head.", ""): v + for k, v in state_dict.items() + if k.startswith("gan_final_head.") + } + load_info = model.gan_final_head.load_state_dict(gan_final_state, strict=False) + loaded_keys.update(gan_final_keys_in_sd) + gan_keys_count += len(gan_final_keys_in_sd) + if load_info.missing_keys: + print(f" Missing keys in gan_final_head: {load_info.missing_keys}") + if load_info.unexpected_keys: + print(f" Unexpected keys in gan_final_head: {load_info.unexpected_keys}") + + if gan_keys_count > 0: + print(f"Loaded {gan_keys_count} parameters for GAN components") + + if not loaded_keys: + print("No extra components were loaded from the checkpoint.") + return + + all_sd_keys = set(state_dict.keys()) + unmatched_keys = all_sd_keys - loaded_keys + + print("\nCheckpoint loading completed.") + print(f"Total loaded keys: {len(loaded_keys)}") + if unmatched_keys: + print(f"The following keys in the checkpoint were not loaded into the model: {sorted(unmatched_keys)}\n") + else: + print("Load extra module successfully! All keys in the checkpoint were successfully processed or matched.\n") + + +def save_model_checkpoint( + transformer, + args, + save_path, + weight_dtype=None, + unwrap_model_fn=None, + get_peft_model_state_dict_fn=None, + collate_lora_metadata_fn=None, + save_extra_components_fn=None, + pipeline_class=None, + norm_layer_prefixes=None, +): + modules_to_save = {} + model_to_save = unwrap_model_fn(transformer) if unwrap_model_fn else transformer + + transformer_lora_layers = get_peft_model_state_dict_fn(model_to_save) + + if args.model_config.train_norm_layers: + norm_prefixes = norm_layer_prefixes or [] + transformer_norm_layers = { + f"transformer.{name}": param + for name, param in model_to_save.named_parameters() + if any(k in name for k in norm_prefixes) + } + transformer_lora_layers = { + **transformer_lora_layers, + **transformer_norm_layers, + } + + modules_to_save["transformer"] = model_to_save + + if pipeline_class and hasattr(pipeline_class, "save_lora_weights"): + lora_metadata = collate_lora_metadata_fn(modules_to_save) if collate_lora_metadata_fn else {} + pipeline_class.save_lora_weights( + save_directory=save_path, + transformer_lora_layers=transformer_lora_layers, + **lora_metadata, + ) + + if save_extra_components_fn: + save_extra_components_fn(args=args, model=model_to_save, output_dir=save_path) + + modules_to_save = None + lora_metadata = None + transformer_norm_layers = None + transformer_lora_layers = None + del modules_to_save + del lora_metadata + del transformer_norm_layers + del transformer_lora_layers + + +def load_model_checkpoint( + args, + checkpoint_path, + transformer, + pipeline_class=None, + norm_layer_prefixes=None, + convert_unet_state_dict_to_peft_fn=None, + set_peft_model_state_dict_fn=None, + cast_training_params_fn=None, +): + if not os.path.exists(checkpoint_path): + raise ValueError(f"Checkpoint path does not exist: {checkpoint_path}") + + lora_state_dict = None + if pipeline_class and hasattr(pipeline_class, "load_lora_weights"): + lora_state_dict = pipeline_class.lora_state_dict(checkpoint_path) + + transformer_state_dict = { + f"{k.replace('transformer.', '')}": v for k, v in lora_state_dict.items() if k.startswith("transformer.") + } + transformer_state_dict = convert_unet_state_dict_to_peft_fn(transformer_state_dict) + incompatible_keys = set_peft_model_state_dict_fn(transformer, transformer_state_dict, adapter_name="default") + if incompatible_keys is not None: + unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None) + if unexpected_keys: + print( + f"Loading adapter weights from state_dict led to unexpected keys not found in the model: " + f" {unexpected_keys}. " + ) + print(f"load lora from {checkpoint_path} successfully!") + + if args.model_config.train_norm_layers and lora_state_dict and norm_layer_prefixes: + transformer_norm_state_dict = { + k: v + for k, v in lora_state_dict.items() + if k.startswith("transformer.") and any(norm_k in k for norm_k in norm_layer_prefixes) + } + transformer._transformer_norm_layers = pipeline_class._load_norm_into_transformer( + transformer_norm_state_dict, + transformer=transformer, + discard_original_layers=False, + ) + + load_extra_components(args, transformer, os.path.join(checkpoint_path, "transformer_partial.pth")) + + if args.training_config.mixed_precision != "fp32": + models = [transformer] + cast_training_params_fn(models) + + +# ======================================== sigmas & timesteps ======================================== +def get_sigmas(noise_scheduler, timesteps, n_dim=4, device="cuda", dtype=torch.float32): + sigmas = noise_scheduler.sigmas.to(device=device, dtype=dtype) + schedule_timesteps = noise_scheduler.timesteps.to(device) + timesteps = timesteps.to(device) + step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps] + + sigma = sigmas[step_indices].flatten() + while len(sigma.shape) < n_dim: + sigma = sigma.unsqueeze(-1) + return sigma + + +def calculate_shift( + image_seq_len, + base_seq_len: int = 256, + max_seq_len: int = 4096, + base_shift: float = 0.5, + max_shift: float = 1.15, +): + m = (max_shift - base_shift) / (max_seq_len - base_seq_len) + b = base_shift - m * base_seq_len + mu = image_seq_len * m + b + return mu + + +def apply_schedule_shift( + sigmas, + noise, + sigmas_two=None, + base_seq_len: int = 256, + max_seq_len: int = 4096, + base_shift: float = 0.5, + max_shift: float = 1.15, + exp_max: float = 7.0, + time_shift_type: Literal["exponential", "linear"] = "linear", + mu: float = None, + return_mu: bool = False, +): + if mu is None: + # Resolution-dependent shifting of timestep schedules as per section 5.3.2 of SD3 paper + image_seq_len = (noise.shape[-1] * noise.shape[-2] * noise.shape[-3]) // 4 # patch size 1,2,2 + mu = calculate_shift( + image_seq_len, + base_seq_len if base_seq_len is not None else 256, + max_seq_len if max_seq_len is not None else 4096, + base_shift if base_shift is not None else 0.5, + max_shift if max_shift is not None else 1.15, + ) + if time_shift_type == "exponential": + mu = min(mu, math.log(exp_max)) + mu = math.exp(mu) + + if sigmas_two is not None: + sigmas = (sigmas * mu) / (1 + (mu - 1) * sigmas) + sigmas_two = (sigmas_two * mu) / (1 + (mu - 1) * sigmas_two) + if return_mu: + return sigmas, sigmas_two, mu + else: + return sigmas, sigmas_two + else: + sigmas = (sigmas * mu) / (1 + (mu - 1) * sigmas) + if return_mu: + return sigmas, mu + else: + return sigmas + + +# ======================================== clean prompt ======================================== + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r"\s+", " ", text) + text = text.strip() + return text + + +def prompt_clean(text): + text = whitespace_clean(basic_clean(text)) + return text + + +def _get_t5_prompt_embeds( + tokenizer, + text_encoder, + prompt: Union[str, List[str]] = None, + num_videos_per_prompt: int = 1, + max_sequence_length: int = 512, + caption_dropout_p: float = 0.0, + device: Optional[torch.device] = "cuda", + dtype: Optional[torch.dtype] = torch.bfloat16, +): + device = device + dtype = dtype + + prompt = [prompt] if isinstance(prompt, str) else prompt + prompt = [prompt_clean(u) for u in prompt] + batch_size = len(prompt) + + text_inputs = tokenizer( + prompt, + padding="max_length", + max_length=max_sequence_length, + truncation=True, + add_special_tokens=True, + return_attention_mask=True, + return_tensors="pt", + ) + text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask + + prompt_embeds = text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state + prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) + + if random.random() < caption_dropout_p: + prompt_embeds.fill_(0) + mask.fill_(False) + seq_lens = mask.gt(0).sum(dim=1).long() + + prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)] + prompt_embeds = torch.stack( + [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0 + ) + + # duplicate text embeddings for each generation per prompt, using mps friendly method + _, seq_len, _ = prompt_embeds.shape + prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1) + prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1) + + return prompt_embeds, text_inputs.attention_mask + + +def encode_prompt( + tokenizer, + text_encoder, + prompt: Union[str, List[str]], + num_videos_per_prompt: int = 1, + prompt_embeds: Optional[torch.Tensor] = None, + max_sequence_length: int = 512, + caption_dropout_p: float = 0.0, + device: Optional[torch.device] = "cuda", + dtype: Optional[torch.dtype] = torch.bfloat16, +): + prompt = [prompt] if isinstance(prompt, str) else prompt + + if prompt_embeds is None: + prompt_embeds, prompt_attention_mask = _get_t5_prompt_embeds( + tokenizer, + text_encoder, + prompt=prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + caption_dropout_p=caption_dropout_p, + device=device, + dtype=dtype, + ) + + return prompt_embeds, prompt_attention_mask + + +# ======================================== other techniques ======================================== + + +class AdaptiveAntiDrifting: + def __init__( + self, + rho_mu: float = 0.9, + rho_sigma: float = 0.9, + delta_mu: float = 0.15, + delta_sigma: float = 0.15, + device: torch.device = None, + dtype: torch.dtype = torch.float32, + ): + """ + Args: + rho_mu: EMA coefficient for mean (momentum parameter) + rho_sigma: EMA coefficient for variance (momentum parameter) + delta_mu: Threshold for mean drift detection + delta_sigma: Threshold for variance drift detection + device: Device for tensor operations + dtype: Data type for tensors + """ + self.rho_mu = rho_mu + self.rho_sigma = rho_sigma + self.delta_mu = delta_mu + self.delta_sigma = delta_sigma + self.device = device + self.dtype = dtype + + # Global statistics (initialized on first chunk) + self.global_mean = None + self.global_var = None + self.is_initialized = False + + def compute_latent_statistics(self, latent_chunk: torch.Tensor) -> tuple: + # Shape: (B, C, T, H, W) -> (B, C) + mean = latent_chunk.mean(dim=[2, 3, 4]) + var = latent_chunk.var(dim=[2, 3, 4]) + + return mean, var + + def update_global_statistics(self, current_mean: torch.Tensor, current_var: torch.Tensor): + if not self.is_initialized: + self.global_mean = current_mean.clone() + self.global_var = current_var.clone() + self.is_initialized = True + else: + self.global_mean = self.rho_mu * self.global_mean + (1 - self.rho_mu) * current_mean + self.global_var = self.rho_sigma * self.global_var + (1 - self.rho_sigma) * current_var + + def detect_drift(self, current_mean: torch.Tensor, current_var: torch.Tensor) -> bool: + if not self.is_initialized: + return False + + mean_drift = torch.norm(current_mean - self.global_mean, p=2, dim=-1).mean().item() + var_drift = torch.norm(current_var - self.global_var, p=2, dim=-1).mean().item() + + has_drift = (mean_drift > self.delta_mu) and (var_drift > self.delta_sigma) + + return has_drift + + def apply_frame_aware_corruption( + self, + history_latents: torch.Tensor, + corruption_strength: float = 0.1, + generator: Optional[torch.Generator] = None, + ) -> torch.Tensor: + noise = torch.randn_like(history_latents, generator=generator, device=history_latents.device) + corrupted_latents = history_latents + corruption_strength * noise + + return corrupted_latents + + def reset(self): + self.global_mean = None + self.global_var = None + self.is_initialized = False diff --git a/Helios/helios/utils/utils_helios_base.py b/Helios/helios/utils/utils_helios_base.py new file mode 100644 index 0000000000000000000000000000000000000000..f74c853fc3ae73ab2fc16cece89e4767b67c8c7e --- /dev/null +++ b/Helios/helios/utils/utils_helios_base.py @@ -0,0 +1,1091 @@ +import random + +import torch +import torch.nn.functional as F +from accelerate.logging import get_logger +from einops import rearrange + +from diffusers.training_utils import compute_density_for_timestep_sampling, compute_loss_weighting_for_sd3, free_memory + +from .utils_base import apply_schedule_shift, get_config_value +from .utils_recycle_batch import apply_error_injection, process_and_update_error_buffers + + +logger = get_logger(__name__) + + +# ======================================== flow loss ======================================== + + +def _flow_loss( + args, + accelerator, + lr_scheduler, + transformer, + prompt_embeds, + prompt_attention_masks, + noisy_model_input_list, + sigmas_list, + timesteps_list, + targets_list, + indices_hidden_states, + latents_history_short, + indices_latents_history_short, + latents_history_mid, + indices_latents_history_mid, + latents_history_long, + indices_latents_history_long, + recycle_vars, + global_step, + noise_scheduler_copy, + use_clean_input, +): + assert len(noisy_model_input_list) == len(sigmas_list) == len(timesteps_list) == len(targets_list) + + for noisy_model_input, sigmas, timesteps, target in zip( + noisy_model_input_list, sigmas_list, timesteps_list, targets_list + ): + # ----- w/o mini batch ------ + model_pred = transformer( + hidden_states=noisy_model_input, + timestep=timesteps, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, # torch.Size([2, 9]) + indices_latents_history_short=indices_latents_history_short, # torch.Size([2, 2]) + indices_latents_history_mid=indices_latents_history_mid, # torch.Size([2, 2]) + indices_latents_history_long=indices_latents_history_long, # torch.Size([2, 16]) + latents_history_short=latents_history_short, # torch.Size([2, 16, 2, 60, 104]) + latents_history_mid=latents_history_mid, # torch.Size([2, 16, 2, 60, 104]) + latents_history_long=latents_history_long, # torch.Size([2, 16, 16, 60, 104]) + return_dict=False, + )[0] + + # Compute regular loss. + if isinstance(model_pred, list): + loss_list = [] + for cur_model_pred, cur_target, cur_sigmas in zip(model_pred, target, sigmas): + cur_weighting = compute_loss_weighting_for_sd3( + weighting_scheme=args.training_config.weighting_scheme, sigmas=cur_sigmas + ) + loss = torch.mean( + (cur_weighting.float() * (cur_model_pred.float() - cur_target.float()) ** 2).reshape( + cur_target.shape[0], -1 + ), + 1, + ).mean() + loss_list.append(loss) + loss = torch.stack(loss_list, dim=0).mean() + del loss_list + else: + # these weighting schemes use a uniform timestep sampling + # and instead post-weight the loss + weighting = compute_loss_weighting_for_sd3( + weighting_scheme=args.training_config.weighting_scheme, sigmas=sigmas + ) + + loss = torch.mean( + (weighting.float() * (model_pred.float() - target.float()) ** 2).reshape(target.shape[0], -1), + 1, + ).mean() + + # loss = loss * (batch_size / total_sample_count) + assert loss.requires_grad, f"Loss should have gradient! Got {loss.requires_grad}" + assert loss.grad_fn is not None, "Loss should have grad_fn!" + accelerator.backward(loss) + + if args.training_config.use_error_recycling: + if isinstance(model_pred, list): + with torch.no_grad(): + for cur_model_pred, cur_target, cur_timesteps, cur_noisy_model_input in zip( + model_pred, target, timesteps, noisy_model_input + ): + process_and_update_error_buffers( + args, + recycle_vars, + accelerator, + global_step, + noise_scheduler_copy, + cur_model_pred, + cur_target, + cur_timesteps, + cur_noisy_model_input, + use_clean_input, + ) + else: + with torch.no_grad(): + process_and_update_error_buffers( + args, + recycle_vars, + accelerator, + global_step, + noise_scheduler_copy, + model_pred, + target, + timesteps, + noisy_model_input, + use_clean_input, + ) + + # Check if the gradient of each model parameter contains NaN + for name, param in transformer.named_parameters(): + if param.grad is not None and torch.isnan(param.grad).any(): + logger.error(f"Gradient for {name} contains NaN!") + + grad_norm = None + if accelerator.sync_gradients: + params_to_clip = transformer.parameters() + grad_norm = accelerator.clip_grad_norm_(params_to_clip, args.training_config.max_grad_norm) + + logs = { + "loss": loss.detach().item(), + "lr": lr_scheduler.get_last_lr()[0], + } + if grad_norm is not None: + logs["grad_norm"] = grad_norm.item() if hasattr(grad_norm, "item") else grad_norm + + del noisy_model_input_list + del sigmas_list + del timesteps_list + del targets_list + del noisy_model_input + del timesteps + del prompt_embeds + del prompt_attention_masks + del indices_hidden_states + del latents_history_short + del indices_latents_history_short + del latents_history_mid + del indices_latents_history_mid + del latents_history_long + del indices_latents_history_long + del model_pred + del target + del loss + free_memory() + + return logs + + +# ======================================== easy anti-drifting ======================================== + + +def downsample_corrupt(model_input, downsample_min_corrupt_ratio, downsample_max_corrupt_ratio): + corrupt_ratio = random.uniform(downsample_min_corrupt_ratio, downsample_max_corrupt_ratio) + + is_5d = model_input.ndim == 5 + + if is_5d: + B, C, T, H, W = model_input.shape + model_input = model_input.permute(0, 2, 1, 3, 4).reshape(B * T, C, H, W) + else: + B, C, H, W = model_input.shape + + h0, w0 = model_input.shape[-2:] + + h1 = max(1, int(round(h0 * corrupt_ratio))) + w1 = max(1, int(round(w0 * corrupt_ratio))) + + model_input = F.interpolate(model_input, size=(h1, w1), mode="bilinear", align_corners=False, antialias=True) + + model_input = F.interpolate(model_input, size=(h0, w0), mode="bilinear", align_corners=False, antialias=True) + + if is_5d: + model_input = model_input.reshape(B, T, C, H, W).permute(0, 2, 1, 3, 4) + + return model_input + + +def get_corrupt_noise_sigma(model_input, batch_size, corrupt_ratio=1 / 3, num_frames=None, is_frame_independent=False): + if is_frame_independent: + noise_sigma_shape = (batch_size, 1, num_frames) + else: + noise_sigma_shape = (batch_size,) + noise_sigma = ( + torch.rand(size=noise_sigma_shape, device=model_input.device, dtype=model_input.dtype) * corrupt_ratio + ) + while len(noise_sigma.shape) < model_input.ndim: + noise_sigma = noise_sigma.unsqueeze(-1) + return noise_sigma + + +def corrupt_model_input( + model_input, + # choose mode + corrupt_mode="noise", # "noise" | "downsample" | "random" + noise_mode_prob=0.9, # when corrupt_mode="random", select the probability of noise (select downsample for the remaining probability). + # for noise + is_frame_independent=False, + is_chunk_independent=False, + noise_corrupt_ratio=1 / 3, + noise_corrupt_clean_prob=0.1, + # for downsample + downsample_min_corrupt_ratio=0.9, + downsample_max_corrupt_ratio=1.0, +): + assert not (is_frame_independent and is_chunk_independent), ( + "is_frame_independent and is_chunk_independent cannot both be True" + ) + assert corrupt_mode in ("noise", "downsample", "random"), ( + f"corrupt_mode must be 'noise', 'downsample', or 'random', got '{corrupt_mode}'" + ) + + # ==================== choose mode ==================== + if corrupt_mode == "random": + mode = "noise" if random.random() < noise_mode_prob else "downsample" + else: + mode = corrupt_mode + + # ==================== downsample branch ==================== + if mode == "downsample": + model_input = downsample_corrupt( + model_input=model_input, + downsample_min_corrupt_ratio=downsample_min_corrupt_ratio, + downsample_max_corrupt_ratio=downsample_max_corrupt_ratio, + ) + return model_input + + # ==================== noise branch ==================== + clean_random = random.random() + if clean_random < noise_corrupt_clean_prob: + return model_input + + noise_sigma = get_corrupt_noise_sigma( + model_input=model_input, + batch_size=model_input.shape[0], + corrupt_ratio=noise_corrupt_ratio, + num_frames=model_input.shape[2], + is_frame_independent=is_frame_independent, + ) + + model_input = noise_sigma * torch.randn_like(model_input) + (1 - noise_sigma) * model_input + + return model_input + + +def corrupt_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=True, + # choose mode + corrupt_mode="noise", # "noise" | "downsample" | "random" + noise_mode_prob=0.9, # when corrupt_mode="random", select the probability of noise (select downsample for the remaining probability). + # for noise + is_frame_independent=False, + is_chunk_independent=False, + corrupt_ratio_1x=1 / 3, + corrupt_ratio_2x=1 / 3, + corrupt_ratio_4x=1 / 3, + noise_corrupt_clean_prob=0.1, + # for downsample + downsample_min_corrupt_ratio=0.9, + downsample_max_corrupt_ratio=1.0, +): + assert not (is_frame_independent and is_chunk_independent), ( + "is_frame_independent and is_chunk_independent cannot both be True" + ) + assert corrupt_mode in ("noise", "downsample", "random"), ( + f"corrupt_mode must be 'noise', 'downsample', or 'random', got '{corrupt_mode}'" + ) + + clean_random = random.random() + if clean_random < noise_corrupt_clean_prob: + return latents_history_short, latents_history_mid, latents_history_long + + # ==================== choose mode ==================== + if corrupt_mode == "random": + mode = "noise" if random.random() < noise_mode_prob else "downsample" + else: + mode = corrupt_mode + + # ==================== noise branch ==================== + if mode == "noise": + batch_size = latents_history_short.shape[0] + if not is_frame_independent and not is_chunk_independent: + noise_sigma = get_corrupt_noise_sigma( + model_input=latents_history_short, batch_size=batch_size, corrupt_ratio=corrupt_ratio_1x + ) + + len_4x = latents_history_long.shape[2] + len_2x = latents_history_mid.shape[2] + len_1x = latents_history_short.shape[2] + + hist_seq_len = len_4x + len_2x + len_1x + hist_seq_len_copy = hist_seq_len + + ori_len_1x = len_1x + if is_keep_x0: + len_1x -= 1 + hist_seq_len -= 1 + begin_num = 1 + else: + begin_num = 0 + + max_windows = hist_seq_len // latent_window_size + tail_num = hist_seq_len % latent_window_size + + assert hist_seq_len_copy == tail_num + max_windows * latent_window_size + begin_num + + tail_latents_history = None + begin_latents_history = None + + if tail_num != 0: + tail_latents_history = latents_history_long[:, :, :tail_num, :, :] + latents_history_long = latents_history_long[:, :, tail_num:, :, :] + if tail_latents_history.sum() != 0: + if mode == "downsample": + tail_latents_history = downsample_corrupt( + model_input=tail_latents_history, + downsample_min_corrupt_ratio=downsample_min_corrupt_ratio, + downsample_max_corrupt_ratio=downsample_max_corrupt_ratio, + ) + else: + noise_sigma = get_corrupt_noise_sigma( + model_input=latents_history_short, + batch_size=batch_size, + corrupt_ratio=corrupt_ratio_4x, + num_frames=tail_latents_history.shape[2], + is_frame_independent=is_frame_independent, + ) + tail_latents_history = ( + noise_sigma * torch.randn_like(tail_latents_history) + (1 - noise_sigma) * tail_latents_history + ) + + if begin_num != 0: + begin_latents_history = latents_history_short[:, :, :begin_num, :, :] + latents_history_short = latents_history_short[:, :, begin_num:, :, :] + if begin_latents_history.sum() != 0: + if mode == "downsample": + begin_latents_history = downsample_corrupt( + model_input=begin_latents_history, + downsample_min_corrupt_ratio=downsample_min_corrupt_ratio, + downsample_max_corrupt_ratio=downsample_max_corrupt_ratio, + ) + else: + noise_sigma = get_corrupt_noise_sigma( + model_input=latents_history_short, + batch_size=batch_size, + corrupt_ratio=corrupt_ratio_1x, + num_frames=begin_latents_history.shape[2], + is_frame_independent=is_frame_independent, + ) + begin_latents_history = ( + noise_sigma * torch.randn_like(begin_latents_history) + (1 - noise_sigma) * begin_latents_history + ) + + mid_latents_history = torch.cat([latents_history_long, latents_history_mid, latents_history_short], dim=2) + window_num = mid_latents_history.shape[2] // latent_window_size + assert mid_latents_history.shape[2] % latent_window_size == 0, ( + f"mid length {mid_latents_history.shape[2]} not divisible by window size {latent_window_size}" + ) + + seq_begin = 0 + for idx in range(window_num): + seq_end = seq_begin + latent_window_size + if mid_latents_history[:, :, seq_begin:seq_end, :, :].sum() != 0: + if idx == window_num - 1: + len_2x_end = seq_begin + len_2x + if mode == "downsample": + mid_latents_history[:, :, seq_begin:len_2x_end, :, :] = downsample_corrupt( + model_input=mid_latents_history[:, :, seq_begin:len_2x_end, :, :], + downsample_min_corrupt_ratio=downsample_min_corrupt_ratio, + downsample_max_corrupt_ratio=downsample_max_corrupt_ratio, + ) + else: + noise_sigma_4x = get_corrupt_noise_sigma( + model_input=latents_history_short, + batch_size=batch_size, + corrupt_ratio=corrupt_ratio_4x, + num_frames=len_2x, + is_frame_independent=is_frame_independent, + ) + mid_latents_history[:, :, seq_begin:len_2x_end, :, :] = ( + noise_sigma_4x * torch.randn_like(mid_latents_history[:, :, seq_begin:len_2x_end, :, :]) + + (1 - noise_sigma_4x) * mid_latents_history[:, :, seq_begin:len_2x_end, :, :] + ) + + remaining_frames = seq_end - len_2x_end + if mode == "downsample": + mid_latents_history[:, :, len_2x_end:seq_end, :, :] = downsample_corrupt( + model_input=mid_latents_history[:, :, len_2x_end:seq_end, :, :], + downsample_min_corrupt_ratio=downsample_min_corrupt_ratio, + downsample_max_corrupt_ratio=downsample_max_corrupt_ratio, + ) + else: + noise_sigma_2x = get_corrupt_noise_sigma( + model_input=latents_history_short, + batch_size=batch_size, + corrupt_ratio=corrupt_ratio_2x, + num_frames=remaining_frames, + is_frame_independent=is_frame_independent, + ) + mid_latents_history[:, :, len_2x_end:seq_end, :, :] = ( + noise_sigma_2x * torch.randn_like(mid_latents_history[:, :, len_2x_end:seq_end, :, :]) + + (1 - noise_sigma_2x) * mid_latents_history[:, :, len_2x_end:seq_end, :, :] + ) + else: + if mode == "downsample": + mid_latents_history[:, :, seq_begin:seq_end, :, :] = downsample_corrupt( + model_input=mid_latents_history[:, :, seq_begin:seq_end, :, :], + downsample_min_corrupt_ratio=downsample_min_corrupt_ratio, + downsample_max_corrupt_ratio=downsample_max_corrupt_ratio, + ) + else: + noise_sigma = get_corrupt_noise_sigma( + model_input=latents_history_short, + batch_size=batch_size, + corrupt_ratio=corrupt_ratio_4x, + num_frames=latent_window_size, + is_frame_independent=is_frame_independent, + ) + mid_latents_history[:, :, seq_begin:seq_end, :, :] = ( + noise_sigma * torch.randn_like(mid_latents_history[:, :, seq_begin:seq_end, :, :]) + + (1 - noise_sigma) * mid_latents_history[:, :, seq_begin:seq_end, :, :] + ) + seq_begin = seq_end + + recovers = [] + if tail_latents_history is not None: + recovers.append(tail_latents_history) + recovers.append(mid_latents_history[:, :, :-len_1x, :, :]) + if begin_latents_history is not None: + recovers.append(begin_latents_history) + recovers.append(mid_latents_history[:, :, -len_1x:, :, :]) + mid_latents_history = torch.cat(recovers, dim=2) + + # Split and update back to original tensors + latents_4x_recovered, latents_2x_recovered, latents_history_short_recovered = mid_latents_history.split( + [len_4x, len_2x, ori_len_1x], dim=2 + ) + + return ( + latents_history_short_recovered, + latents_2x_recovered, + latents_4x_recovered, + ) + + +def add_saturation_to_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=False, + saturation_ratio_min=0.7, + saturation_ratio_max=2.0, + saturation_clean_prob=0.2, +): + # clean_random = random.random() + # if clean_random < saturation_clean_prob: + # return latents_history_short, latents_history_mid, latents_history_long + + def get_saturation(x1, saturation_ratio_min, saturation_ratio_max): + if random.random() < 0.5: + sat_factor = random.uniform(saturation_ratio_min, 1.0 - 1e-3) + else: + sat_factor = random.uniform(1.0 + 1e-3, saturation_ratio_max) + latent_mean = torch.mean(x1, dim=1, keepdim=True) + x1_saturated = (x1 - latent_mean) * sat_factor + latent_mean + return x1_saturated + + len_4x = latents_history_long.shape[2] + len_2x = latents_history_mid.shape[2] + len_1x = latents_history_short.shape[2] + + hist_seq_len = len_4x + len_2x + len_1x + hist_seq_len_copy = hist_seq_len + + ori_len_1x = len_1x + if is_keep_x0: + len_1x -= 1 + hist_seq_len -= 1 + begin_num = 1 + else: + begin_num = 0 + + max_windows = hist_seq_len // latent_window_size + tail_num = hist_seq_len % latent_window_size + + assert hist_seq_len_copy == tail_num + max_windows * latent_window_size + begin_num + + tail_latents_history = None + begin_latents_history = None + + if tail_num != 0: + tail_latents_history = latents_history_long[:, :, :tail_num, :, :] + latents_history_long = latents_history_long[:, :, tail_num:, :, :] + if tail_latents_history.sum() != 0: + if random.random() < saturation_clean_prob: + tail_latents_history = tail_latents_history + else: + tail_latents_history = get_saturation( + tail_latents_history, + saturation_ratio_min=saturation_ratio_min, + saturation_ratio_max=saturation_ratio_max, + ) + + if begin_num != 0: + begin_latents_history = latents_history_short[:, :, :begin_num, :, :] + latents_history_short = latents_history_short[:, :, begin_num:, :, :] + # if begin_latents_history.sum() != 0: + # begin_latents_history = get_saturation( + # begin_latents_history, + # saturation_ratio_min=saturation_ratio_min, + # saturation_ratio_max=saturation_ratio_max, + # ) + + mid_latents_history = torch.cat([latents_history_long, latents_history_mid, latents_history_short], dim=2) + window_num = mid_latents_history.shape[2] // latent_window_size + assert mid_latents_history.shape[2] % latent_window_size == 0, ( + f"mid length {mid_latents_history.shape[2]} not divisible by window size {latent_window_size}" + ) + + seq_begin = 0 + for idx in range(window_num): + seq_end = seq_begin + latent_window_size + if mid_latents_history[:, :, seq_begin:seq_end, :, :].sum() != 0: + if idx == window_num - 1: + len_2x_end = seq_begin + len_2x + if random.random() < saturation_clean_prob: + mid_latents_history[:, :, seq_begin:len_2x_end, :, :] = mid_latents_history[ + :, :, seq_begin:len_2x_end, :, : + ] + else: + mid_latents_history[:, :, seq_begin:len_2x_end, :, :] = get_saturation( + mid_latents_history[:, :, seq_begin:len_2x_end, :, :], + saturation_ratio_min=saturation_ratio_min, + saturation_ratio_max=saturation_ratio_max, + ) + + if random.random() < saturation_clean_prob: + mid_latents_history[:, :, len_2x_end:seq_end, :, :] = mid_latents_history[ + :, :, len_2x_end:seq_end, :, : + ] + else: + mid_latents_history[:, :, len_2x_end:seq_end, :, :] = get_saturation( + mid_latents_history[:, :, len_2x_end:seq_end, :, :], + saturation_ratio_min=saturation_ratio_min, + saturation_ratio_max=saturation_ratio_max, + ) + else: + if random.random() < saturation_clean_prob: + mid_latents_history[:, :, seq_begin:seq_end, :, :] = mid_latents_history[ + :, :, seq_begin:seq_end, :, : + ] + else: + mid_latents_history[:, :, seq_begin:seq_end, :, :] = get_saturation( + mid_latents_history[:, :, seq_begin:seq_end, :, :], + saturation_ratio_min=saturation_ratio_min, + saturation_ratio_max=saturation_ratio_max, + ) + + seq_begin = seq_end + + recovers = [] + if tail_latents_history is not None: + recovers.append(tail_latents_history) + recovers.append(mid_latents_history[:, :, :-len_1x, :, :]) + if begin_latents_history is not None: + recovers.append(begin_latents_history) + recovers.append(mid_latents_history[:, :, -len_1x:, :, :]) + mid_latents_history = torch.cat(recovers, dim=2) + + # Split and update back to original tensors + latents_4x_recovered, latents_2x_recovered, latents_history_short_recovered = mid_latents_history.split( + [len_4x, len_2x, ori_len_1x], dim=2 + ) + + return ( + latents_history_short_recovered, + latents_2x_recovered, + latents_4x_recovered, + ) + + +# ======================================== prepare stage1 training ======================================== + + +def prepare_stage1_clean_input_from_latents( + history_latents, # VAE latents, (B, C_latent, F_latent, H_latent, W_latent) + target_latents, + x0_latents=None, + latent_window_size: int = 9, + history_sizes: list = [16, 2, 1], + is_random_drop: bool = False, + random_drop_i2v_ratio: float = 0, + random_drop_v2v_ratio: float = 0, + random_drop_t2v_ratio: float = 0, + is_keep_x0: bool = True, + dtype=torch.bfloat16, + device="cpu", +): + if is_keep_x0: + latents_prefix = x0_latents.to(device, dtype=dtype) + else: + assert x0_latents is None + + history_sizes = sorted(history_sizes, reverse=True) # From big to small + history_window_size = sum(history_sizes) + total_window_size = history_window_size + latent_window_size + assert total_window_size == history_latents.shape[2] + target_latents.shape[2], ( + f"total_window_size mismatch: expected {total_window_size}" + f"(history={history_latents.shape[2]} + target={target_latents.shape[2]}), " + f"but got {history_latents.shape[2] + target_latents.shape[2]}" + ) + + indices = ( + torch.arange(0, sum([1, *history_sizes, latent_window_size])).unsqueeze(0).expand(target_latents.shape[0], -1) + ) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=1) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=1) + + latents_history_long, latents_history_mid, latents_history_1x = history_latents.split(history_sizes, dim=2) + + if is_random_drop: + if random_drop_t2v_ratio != 0 and torch.rand(1).item() <= random_drop_t2v_ratio: + if is_keep_x0: + latents_prefix = torch.zeros_like( + latents_prefix, device=latents_history_1x.device, dtype=latents_history_1x.dtype + ) + latents_history_1x = torch.zeros_like( + latents_history_1x, + device=latents_history_1x.device, + dtype=latents_history_1x.dtype, + ) + latents_history_mid = torch.zeros_like( + latents_history_mid, + device=latents_history_1x.device, + dtype=latents_history_1x.dtype, + ) + latents_history_long = torch.zeros_like( + latents_history_long, + device=latents_history_1x.device, + dtype=latents_history_1x.dtype, + ) + else: + len_4x = latents_history_long.shape[2] + len_2x = latents_history_mid.shape[2] + len_1x = latents_history_1x.shape[2] + hist_seq_len = len_4x + len_2x + len_1x + + total_drop = 0 + is_drop_triggered = False + + if random_drop_i2v_ratio != 0 and torch.rand(1).item() <= random_drop_i2v_ratio: + total_drop = max(0, hist_seq_len - 1) + is_drop_triggered = True + elif random_drop_v2v_ratio != 0 and torch.rand(1).item() <= random_drop_v2v_ratio: + max_windows = hist_seq_len // latent_window_size + tail_num = hist_seq_len % latent_window_size + total_drop = tail_num + if max_windows > 0: + drop_windows = random.randint(0, max_windows) + total_drop += drop_windows * latent_window_size + is_drop_triggered = True + + if is_drop_triggered and total_drop > 0: + remaining_drop = total_drop + if remaining_drop > 0 and len_4x > 0: + drop_4x = min(remaining_drop, len_4x) + latents_history_long[:, :, :drop_4x, :, :] = 0 + remaining_drop -= drop_4x + if remaining_drop > 0 and len_2x > 0: + drop_2x = min(remaining_drop, len_2x) + latents_history_mid[:, :, :drop_2x, :, :] = 0 + remaining_drop -= drop_2x + if remaining_drop > 0 and len_1x > 0: + drop_1x = min(remaining_drop, len_1x) + latents_history_1x[:, :, :drop_1x, :, :] = 0 + + if is_keep_x0: + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + latents_history_short = latents_history_1x + + return ( + target_latents, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + ) + + +def prepare_stage1_noise_input( + args, + model_input, + noise_scheduler, + recycle_vars=None, + latents_history_short=None, + latents_history_mid=None, + latents_history_long=None, + latent_window_size=9, + is_keep_x0=True, + return_list=True, +): + # Sample noise that we'll add to the latents + noise = torch.randn_like(model_input) + bsz = model_input.shape[0] + + use_clean_input = False + noise_w_error = noise + model_input_w_error = model_input + + # Sample a random timestep for each image + # for weighting schemes where we sample timesteps non-uniformly + u = compute_density_for_timestep_sampling( + weighting_scheme=args.training_config.weighting_scheme, + batch_size=bsz, + logit_mean=args.training_config.logit_mean, + logit_std=args.training_config.logit_std, + mode_scale=args.training_config.mode_scale, + ) + indices = (u * noise_scheduler.config.num_train_timesteps).long() + + noise_scheduler.temp_sigmas = noise_scheduler.sigmas + noise_scheduler.temp_timesteps = noise_scheduler.timesteps + if args.training_config.use_dynamic_shifting: + noise_scheduler.temp_sigmas = apply_schedule_shift( + noise_scheduler.sigmas, + noise, + base_seq_len=args.training_config.base_seq_len, + max_seq_len=args.training_config.max_seq_len, + base_shift=args.training_config.base_shift, + max_shift=args.training_config.max_shift, + ) # torch.Size([2, 1, 1, 1, 1]) + + noise_scheduler.temp_timesteps = noise_scheduler.temp_sigmas * 1000.0 # rescale to [0, 1000.0) + while noise_scheduler.temp_timesteps.ndim > 1: + noise_scheduler.temp_timesteps = noise_scheduler.temp_timesteps.squeeze(-1) + + timesteps = noise_scheduler.temp_timesteps[indices].to( + device=model_input.device, non_blocking=True + ) # torch.Size([2]), torch.float32 + + # Add noise according to flow matching. + # zt = (1 - texp) * x + texp * z1 + sigmas = noise_scheduler.temp_sigmas[indices].flatten() + while len(sigmas.shape) < model_input.ndim: + sigmas = sigmas.unsqueeze(-1) + + sigmas = sigmas.to(model_input.device, dtype=model_input.dtype) + + if args.training_config.use_error_recycling: + ( + model_input_w_error, + noise_w_error, + latents_history_long, + latents_history_mid, + latents_history_short, + use_clean_input, + ) = apply_error_injection( + args, + recycle_vars, + model_input, + noise, + timesteps, + latents_history_long, + latents_history_mid, + latents_history_short, + model_input_w_error, + noise_w_error, + is_keep_x0, + latent_window_size, + ) + + if args.training_config.corrupt_history and latents_history_short is not None: + latents_history_short, latents_history_mid, latents_history_long = corrupt_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=True, + # choose mode + corrupt_mode=args.training_config.corrupt_mode_history, + noise_mode_prob=args.training_config.corrupt_mode_prob_history, + # for noise + is_frame_independent=args.training_config.is_frame_independent_corrupt_history, + is_chunk_independent=args.training_config.is_chunk_independent_corrupt_history, + corrupt_ratio_1x=args.training_config.noise_corrupt_ratio_history_short, + corrupt_ratio_2x=args.training_config.noise_corrupt_ratio_history_mid, + corrupt_ratio_4x=args.training_config.noise_corrupt_ratio_history_long, + noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_history, + # for downsample + downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_history, + downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_history, + ) + + if args.training_config.corrupt_model_input: + model_input_w_error = corrupt_model_input( + model_input_w_error, + # choose mode + corrupt_mode=args.training_config.corrupt_mode_model_input, + noise_mode_prob=args.training_config.corrupt_mode_prob_model_input, + # for noise + is_frame_independent=args.training_config.is_frame_independent_corrupt_model_input, + is_chunk_independent=args.training_config.is_chunk_independent_corrupt_model_input, + noise_corrupt_ratio=args.training_config.noise_corrupt_ratio_model_input, + noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_model_input, + # for downsample + downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_model_input, + downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_model_input, + ) + + # Get flow-matching target + noisy_model_input = (1.0 - sigmas) * model_input_w_error + sigmas * noise_w_error + target = noise_w_error - model_input + + noisy_model_input_list = [noisy_model_input] if return_list else noisy_model_input + sigmas_list = [sigmas] if return_list else sigmas + timesteps_list = [timesteps] if return_list else timesteps + targets_list = [target] if return_list else target + + return ( + noisy_model_input_list, + sigmas_list, + timesteps_list, + targets_list, + latents_history_short, + latents_history_mid, + latents_history_long, + use_clean_input, + ) + + +# ======================================== prepare stage2 training ======================================== + + +def prepare_stage2_clean_input( + args, + scheduler, + latents, # [b c t h w] + pyramid_stage_num=3, + stage2_sample_ratios=[1, 1, 1], +): + assert pyramid_stage_num == len(stage2_sample_ratios) + + # Get clen pyramid latent list + pyramid_latent_list = [] + pyramid_latent_list.append(latents) + num_frames, height, width = latents.shape[-3], latents.shape[-2], latents.shape[-1] + for _ in range(pyramid_stage_num - 1): + height //= 2 + width //= 2 + latents = rearrange(latents, "b c t h w -> (b t) c h w") + latents = torch.nn.functional.interpolate(latents, size=(height, width), mode="bilinear") + latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames) + pyramid_latent_list.append(latents) + pyramid_latent_list = list(reversed(pyramid_latent_list)) + + # Get pyramid noise list + noise = torch.randn_like(pyramid_latent_list[-1]) + device = noise.device + dtype = pyramid_latent_list[-1].dtype + latent_frame_num = noise.shape[2] + input_video_num = noise.shape[0] + + height, width = noise.shape[-2], noise.shape[-1] + noise_list = [noise] + cur_noise = noise + for i_s in range(pyramid_stage_num - 1): + height //= 2 + width //= 2 + cur_noise = rearrange(cur_noise, "b c t h w -> (b t) c h w") + cur_noise = F.interpolate(cur_noise, size=(height, width), mode="bilinear") * 2 + cur_noise = rearrange(cur_noise, "(b t) c h w -> b c t h w", t=latent_frame_num) + noise_list.append(cur_noise) + noise_list = list(reversed(noise_list)) # make sure from low res to high res + + # Get pyramid target list + # To calculate the batchsize + bsz = input_video_num + + # from low resolution to high resolution + noisy_latents_list = [] + sigmas_list = [] + targets_list = [] + timesteps_list = [] + training_steps = scheduler.config.num_train_timesteps + for i_s, cur_sample_ratio in zip(range(pyramid_stage_num), stage2_sample_ratios): + clean_latent = pyramid_latent_list[i_s] # [bs, c, t, h, w] + last_clean_latent = None if i_s == 0 else pyramid_latent_list[i_s - 1] + start_sigma = scheduler.start_sigmas[i_s] + end_sigma = scheduler.end_sigmas[i_s] + + if i_s == 0: + start_point = noise_list[i_s] + else: + # Get the upsampled latent + last_clean_latent = rearrange(last_clean_latent, "b c t h w -> (b t) c h w") + last_clean_latent = F.interpolate( + last_clean_latent, + size=( + last_clean_latent.shape[-2] * 2, + last_clean_latent.shape[-1] * 2, + ), + mode="nearest", + ) + last_clean_latent = rearrange(last_clean_latent, "(b t) c h w -> b c t h w", t=latent_frame_num) + start_point = start_sigma * noise_list[i_s] + (1 - start_sigma) * last_clean_latent + + if i_s == pyramid_stage_num - 1: + end_point = clean_latent + else: + end_point = end_sigma * noise_list[i_s] + (1 - end_sigma) * clean_latent + + for _ in range(cur_sample_ratio): + # Sample a random timestep for each image + # for weighting schemes where we sample timesteps non-uniformly + u = compute_density_for_timestep_sampling( + weighting_scheme=get_config_value(args, "weighting_scheme"), + batch_size=bsz, + logit_mean=get_config_value(args, "logit_mean"), + logit_std=get_config_value(args, "logit_std"), + mode_scale=get_config_value(args, "mode_scale"), + ) + indices = (u * training_steps).long() # Totally 1000 training steps per stage + indices = indices.clamp(0, training_steps - 1) + timesteps = scheduler.timesteps_per_stage[i_s][indices].to(device=device) + + # Add noise according to flow matching. + # zt = (1 - texp) * x + texp * z1 + sigmas = scheduler.sigmas_per_stage[i_s][indices].to(device=device) + while len(sigmas.shape) < start_point.ndim: + sigmas = sigmas.unsqueeze(-1) + + if get_config_value(args, "use_dynamic_shifting"): + temp_sigmas = apply_schedule_shift( + sigmas, + start_point, + base_seq_len=get_config_value(args, "base_seq_len"), + max_seq_len=get_config_value(args, "max_seq_len"), + base_shift=get_config_value(args, "base_shift"), + max_shift=get_config_value(args, "max_shift"), + ) # torch.Size([2, 1, 1, 1, 1]) + temp_timesteps = scheduler.timesteps_per_stage[i_s].min() + temp_sigmas * ( + scheduler.timesteps_per_stage[i_s].max() - scheduler.timesteps_per_stage[i_s].min() + ) + while temp_timesteps.ndim > 1: + temp_timesteps = temp_timesteps.squeeze(-1) + + sigmas = temp_sigmas + timesteps = temp_timesteps + + if args.training_config.corrupt_model_input: + end_point = corrupt_model_input( + end_point, + # choose mode + corrupt_mode=args.training_config.corrupt_mode_model_input, + noise_mode_prob=args.training_config.corrupt_mode_prob_model_input, + # for noise + is_frame_independent=args.training_config.is_frame_independent_corrupt_model_input, + is_chunk_independent=args.training_config.is_chunk_independent_corrupt_model_input, + noise_corrupt_ratio=args.training_config.noise_corrupt_ratio_model_input, + noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_model_input, + # for downsample + downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_model_input, + downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_model_input, + ) + + noisy_latents = sigmas * start_point + (1 - sigmas) * end_point + + # [stage1_latent, stage2_latent, ..., stagen_latent] + noisy_latents_list.append(noisy_latents.to(dtype)) + sigmas_list.append(sigmas.to(dtype)) + timesteps_list.append(timesteps) + targets_list.append(start_point - end_point) # The standard rectified flow matching objective + + return noisy_latents_list, sigmas_list, timesteps_list, targets_list + + +def prepare_stage2_noise_input( + args, + scheduler, + latents, # [b c t h w] + pyramid_stage_num=3, + stage2_sample_ratios=[1, 1, 1], + latents_history_short=None, + latents_history_mid=None, + latents_history_long=None, + latent_window_size=9, + return_list=True, + is_navit_pyramid=False, + is_efficient_sample=False, +): + noisy_model_input_list, sigmas_list, timesteps_list, targets_list = prepare_stage2_clean_input( + args=args, + scheduler=scheduler, + latents=latents, + pyramid_stage_num=pyramid_stage_num, + stage2_sample_ratios=stage2_sample_ratios, + ) + + if args.training_config.corrupt_history and latents_history_short is not None: + latents_history_short, latents_history_mid, latents_history_long = corrupt_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=True, + # choose mode + corrupt_mode=args.training_config.corrupt_mode_history, + noise_mode_prob=args.training_config.corrupt_mode_prob_history, + # for noise + is_frame_independent=args.training_config.is_frame_independent_corrupt_history, + is_chunk_independent=args.training_config.is_chunk_independent_corrupt_history, + corrupt_ratio_1x=args.training_config.noise_corrupt_ratio_history_short, + corrupt_ratio_2x=args.training_config.noise_corrupt_ratio_history_mid, + corrupt_ratio_4x=args.training_config.noise_corrupt_ratio_history_long, + noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_history, + # for downsample + downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_history, + downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_history, + ) + + if is_navit_pyramid: + return ( + [noisy_model_input_list], + [sigmas_list], + [timesteps_list], + [targets_list], + latents_history_short, + latents_history_mid, + latents_history_long, + ) + + if is_efficient_sample: + temp_list = list(range(len(noisy_model_input_list))) + random_index = random.choice(temp_list) + + noisy_model_input = noisy_model_input_list[random_index] + sigmas = sigmas_list[random_index] + timesteps = timesteps_list[random_index] + targets = targets_list[random_index] + + base_results = (noisy_model_input, sigmas, timesteps, targets) + additional_results = (latents_history_short, latents_history_mid, latents_history_long) + + if return_list: + return tuple([item] for item in base_results) + additional_results + else: + return base_results + additional_results + + return ( + noisy_model_input_list, + sigmas_list, + timesteps_list, + targets_list, + latents_history_short, + latents_history_mid, + latents_history_long, + ) diff --git a/Helios/helios/utils/utils_helios_post.py b/Helios/helios/utils/utils_helios_post.py new file mode 100644 index 0000000000000000000000000000000000000000..d75600581fb0c40850d08aaa0075710b606b546d --- /dev/null +++ b/Helios/helios/utils/utils_helios_post.py @@ -0,0 +1,3433 @@ +import math +import random +from typing import List, Literal, Optional + +import torch +import torch.nn.functional as F +from accelerate.logging import get_logger +from accelerate.utils import broadcast +from einops import rearrange + +from diffusers.training_utils import free_memory +from diffusers.utils.torch_utils import is_compiled_module + +from .utils_base import apply_schedule_shift +from .utils_helios_base import ( + add_saturation_to_history_latents, + corrupt_history_latents, + prepare_stage1_clean_input_from_latents, +) + + +logger = get_logger(__name__) + + +# ======================================== ODE Loss ======================================== + + +def _ode_regression_loss( + args, + accelerator, + transformer, + scheduler, + noise, + weight_dtype, + # For Stage 1 + is_keep_x0: bool = True, + history_sizes: list = [16, 2, 1], + # For Stage 2 + stage2_num_stages: int = 3, + # For ODE Main + last_step_only: bool = False, + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + is_backward_grad: bool = False, + ode_regression_weight: float = 0.25, + ode_latents: torch.Tensor = None, + ode_prompt_embeds: torch.Tensor = None, + ode_num_latent_sections_min: int = 3, + ode_num_latent_sections_max: int = 3, + # For Dynamic Num Sections + ode_dynamic_alpha: float = 1.5, + ode_dynamic_beta: float = 4.0, + ode_dynamic_sample_type: str = "uniform", + global_step: int = 0, + ode_dynamic_step: int = 1000, +): + _, num_channels_latents, latent_window_size, height, width = noise.shape + batch_size, _, _, _, _ = ode_latents[0][0]["latents"][0].shape + + history_sizes = sorted(history_sizes, reverse=True) # From large to small + if not is_keep_x0: + history_sizes[-1] = history_sizes[-1] + 1 + history_latents = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes), + height, + width, + device=accelerator.device, + dtype=torch.float32, + ) + max_history_frames = sum(history_sizes) + 1 + + ode_stage2_num_stages = len(ode_latents[0]) + assert ode_stage2_num_stages == stage2_num_stages + + total_ode_num_latent_sections = len(ode_latents) + assert ode_num_latent_sections_min <= ode_num_latent_sections_max + ode_num_latent_sections = sample_dynamic_dmd_num_latent_sections( + min_sections=ode_num_latent_sections_min, + max_sections=ode_num_latent_sections_max, + dmd_dynamic_alpha=ode_dynamic_alpha, + dmd_dynamic_beta=ode_dynamic_beta, + dmd_dynamic_sample_type=ode_dynamic_sample_type, + global_step=global_step, + dmd_dynamic_step=ode_dynamic_step, + device=accelerator.device, + ) + + # Step 1: Denoising loop + ode_loss_list = [] + image_latents = None + total_generated_latent_frames = 0 + selected_sections = sorted(random.sample(range(total_ode_num_latent_sections), ode_num_latent_sections)) + for k in range(total_ode_num_latent_sections): + should_compute_grad = k in selected_sections + is_first_section = k == 0 + if is_keep_x0: + if is_first_section: + history_sizes_first_section = [1] + history_sizes.copy() + history_latents_first_section = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes_first_section), + height, + width, + device=accelerator.device, + dtype=torch.float32, + ) + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix, latents_history_long, latents_history_mid, latents_history_1x = ( + history_latents_first_section[:, :, -sum(history_sizes_first_section) :].split( + history_sizes_first_section, dim=2 + ) + ) + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + history_latents_first_section = None + + del history_latents_first_section, indices + else: + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix = image_latents + latents_history_long, latents_history_mid, latents_history_1x = history_latents[ + :, :, -sum(history_sizes) : + ].split(history_sizes, dim=2) + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + + del indices + else: + raise NotImplementedError + + if should_compute_grad: + for i_s in range(stage2_num_stages): + exit_flag = generate_and_sync_flag( + accelerator, ode_latents[k][i_s]["timesteps"].shape[0], last_step_only, is_sync=False + ) + noisy_model_input = ode_latents[k][i_s]["latents"][exit_flag].to( + accelerator.device, dtype=weight_dtype + ) + gt_x0 = ode_latents[k][i_s]["latents"][-1].to(accelerator.device, dtype=weight_dtype) + timestep = ode_latents[k][i_s]["timesteps"][exit_flag].unsqueeze(0).to(accelerator.device) + + timesteps_per_stage = scheduler.timesteps_per_stage[i_s] + sigmas_per_stage = scheduler.sigmas_per_stage[i_s] + if use_dynamic_shifting: + temp_sigmas_per_stage = apply_schedule_shift( + sigmas_per_stage, + noisy_model_input, + base_seq_len=args.training_config.base_seq_len, + max_seq_len=args.training_config.max_seq_len, + base_shift=args.training_config.base_shift, + max_shift=args.training_config.max_shift, + time_shift_type=time_shift_type, + ) + temp_timesteps_per_stage = scheduler.timesteps_per_stage[i_s].min() + temp_sigmas_per_stage * ( + scheduler.timesteps_per_stage[i_s].max() - scheduler.timesteps_per_stage[i_s].min() + ) + sigmas_per_stage = temp_sigmas_per_stage + timesteps_per_stage = temp_timesteps_per_stage + + del temp_sigmas_per_stage, temp_timesteps_per_stage + + model_pred = transformer( + hidden_states=noisy_model_input, + timestep=timestep, + encoder_hidden_states=ode_prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short.to(ode_prompt_embeds.dtype), + latents_history_mid=latents_history_mid.to(ode_prompt_embeds.dtype), + latents_history_long=latents_history_long.to(ode_prompt_embeds.dtype), + return_dict=False, + )[0] + pred_x0 = convert_flow_pred_to_x0( + flow_pred=model_pred, + xt=noisy_model_input, + timestep=timestep, + sigmas=sigmas_per_stage, + timesteps=timesteps_per_stage, + ) + + temp_mse_loss = 0.5 * F.mse_loss(pred_x0.float(), gt_x0.float(), reduction="mean") + ode_loss_list.append(temp_mse_loss) + + del noisy_model_input, timestep, model_pred, pred_x0, temp_mse_loss + else: + gt_x0 = ode_latents[k][-1]["latents"][-1].to(accelerator.device, dtype=weight_dtype) + + if is_first_section and is_keep_x0: + image_latents = gt_x0[:, :, 0:1, :, :] + total_generated_latent_frames += latent_window_size + history_latents = torch.cat([history_latents, gt_x0], dim=2) + history_latents = history_latents[:, :, -max_history_frames:, :, :].contiguous() + + del gt_x0 + del latents_prefix, latents_history_long, latents_history_mid, latents_history_1x, latents_history_short + del indices_prefix, indices_latents_history_long, indices_latents_history_mid + del indices_latents_history_1x, indices_hidden_states, indices_latents_history_short + free_memory() + + ode_loss = torch.stack(ode_loss_list).mean() * ode_regression_weight + + del ode_loss_list + free_memory() + + assert ode_loss.requires_grad, f"ODE loss should have gradient! Got {ode_loss.requires_grad}" + assert ode_loss.grad_fn is not None, "ODE loss should have grad_fn!" + + logs = { + "ode_loss": ode_loss.detach().item(), + # "lr": lr_scheduler.get_last_lr()[0], + } + + if is_backward_grad: + accelerator.backward(ode_loss) + + # Check if the gradient of each model parameter contains NaN + for name, param in transformer.named_parameters(): + if param.grad is not None and torch.isnan(param.grad).any(): + logger.error(f"Gradient for {name} contains NaN!") + + grad_norm = None + if accelerator.sync_gradients: + params_to_clip = transformer.parameters() + grad_norm = accelerator.clip_grad_norm_(params_to_clip, args.training_config.max_grad_norm) + + if grad_norm is not None: + logs["ode_grad_norm"] = grad_norm.item() if hasattr(grad_norm, "item") else grad_norm + + ode_loss = None + grad_norm = None + del ode_loss + del grad_norm + + return logs["ode_loss"], logs + else: + return ode_loss, logs + + +# ======================================== VRAM management ======================================== + + +class OptimizedLowVRAMManager: + def __init__(self): + self.pinned_models = set() + self.grad_cache = {} + + def move_to_cpu(self, model, non_blocking=True, offload_grad=False): + model_to_move = model.module if hasattr(model, "module") else model + model_to_move.to("cpu", non_blocking=non_blocking) + + if id(model) not in self.pinned_models: + for buffer in model_to_move.buffers(): + if buffer.device.type == "cpu" and not buffer.is_pinned(): + buffer.data = buffer.data.pin_memory() + self.pinned_models.add(id(model)) + + if offload_grad: + model_id = id(model) + + if model_id not in self.grad_cache: + self.grad_cache[model_id] = {} + + for i, param in enumerate(model_to_move.parameters()): + if param.grad is not None: + if i not in self.grad_cache[model_id]: + self.grad_cache[model_id][i] = torch.empty_like(param.grad, device="cpu", pin_memory=True) + + self.grad_cache[model_id][i].copy_(param.grad, non_blocking=non_blocking) + param.grad = None + + free_memory() + + def move_to_gpu(self, model, device, non_blocking=True, load_grad=False): + model_to_move = model.module if hasattr(model, "module") else model + model_to_move.to(device, non_blocking=non_blocking) + + if load_grad: + model_id = id(model) + if model_id in self.grad_cache: + for i, param in enumerate(model_to_move.parameters()): + if i in self.grad_cache[model_id]: + if param.grad is None: + param.grad = self.grad_cache[model_id][i].to(device, non_blocking=non_blocking) + else: + param.grad.copy_(self.grad_cache[model_id][i], non_blocking=non_blocking) + + +class Gan_D_Loss_With_Cached_Grad(torch.autograd.Function): + @staticmethod + def forward( + ctx, + latent, + discriminator, + timestep, + prompt_embeds, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + label, + ): + latent_copy = latent.detach().requires_grad_(True) + + with torch.enable_grad(): + _, logits = discriminator( + hidden_states=latent_copy, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + gan_mode=True, + return_dict=False, + ) + temp_loss = cal_gan_loss(logits, label=label) + del logits + free_memory() + + grad = torch.autograd.grad( + temp_loss, + latent_copy, + retain_graph=False, + create_graph=False, + only_inputs=True, + )[0].detach() + + del latent_copy + free_memory() + + ctx.save_for_backward(grad) + return temp_loss.detach() + + @staticmethod + def backward(ctx, grad_output): + (grad,) = ctx.saved_tensors + return grad * grad_output, None, None, None, None, None, None, None, None, None, None, None + + +# ======================================== GAN Related ======================================== + + +def cal_gan_loss(logit, label=1): + if logit is None: + return 0 + elif isinstance(logit, list): + gan_loss = torch.tensor(0, device=torch.cuda.current_device()) + for logit_item in logit: + gan_loss = gan_loss + torch.mean(F.softplus(logit_item * label)) + return gan_loss / len(logit) + else: + return torch.mean(F.softplus(logit * label).float()) + + +def gan_crop_video_spatial(x, scale=0.5): + B, C, T, H, W = x.shape + H2 = int(H * scale) + W2 = int(W * scale) + tops = torch.randint(0, H - H2 + 1, (B,), device=x.device) + lefts = torch.randint(0, W - W2 + 1, (B,), device=x.device) + x2 = torch.zeros(B, C, T, H2, W2, device=x.device, dtype=x.dtype) + for i in range(B): + x2[i] = x[i, :, :, tops[i] : tops[i] + H2, lefts[i] : lefts[i] + W2] + return x2 + + +def prepare_real_latents_for_gan( + accelerator, + vae, + clean_all_latent, + latent_window_size, + history_sizes, + num_critic_input_frames, + dmd_is_low_vram_mode=False, + vram_manager=None, +): + if dmd_is_low_vram_mode: + vram_manager.move_to_gpu(vae, accelerator.device) + else: + vae.to(accelerator.device) + vae.requires_grad_(False) + vae.eval() + + latents_mean = torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(vae.device, vae.dtype) + latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to( + vae.device, vae.dtype + ) + + clean_all_latent = clean_all_latent[:, :, sum(history_sizes) :, :, :] + num_sections = math.ceil(clean_all_latent.shape[2] / latent_window_size) + total_frame_latent = [] + for i in range(num_sections): + start_idx = i * latent_window_size + end_idx = min((i + 1) * latent_window_size, clean_all_latent.shape[2]) + cur_section = clean_all_latent[:, :, start_idx:end_idx, :, :] + with torch.no_grad(): + decoded = vae.decode( + cur_section.to(vae.device, dtype=vae.dtype) / latents_std + latents_mean, return_dict=False + )[0] + total_frame_latent.append(decoded) + + num_rgb_frames = (num_critic_input_frames - 1) * 4 + 1 + combined_frames = torch.cat(total_frame_latent, dim=2).to(vae.device, dtype=vae.dtype) + max_start_idx = combined_frames.shape[2] - num_rgb_frames + start_idx = random.randint(0, max_start_idx) + selected_frames = combined_frames[:, :, start_idx : start_idx + num_rgb_frames, :, :] + with torch.no_grad(): + reconstructed_latent = vae.encode(selected_frames).latent_dist.sample() + gan_vae_latents = (reconstructed_latent - latents_mean) * latents_std + + if dmd_is_low_vram_mode: + vram_manager.move_to_cpu(vae) + + latents_mean = None + latents_std = None + decoded = None + total_frame_latent = None + combined_frames = None + selected_frames = None + reconstructed_latent = None + del latents_mean + del latents_std + del decoded + del total_frame_latent + del combined_frames + del selected_frames + del reconstructed_latent + free_memory() + + return gan_vae_latents + + +# ======================================== Coarse to Fine Learning ======================================== + + +def sample_dynamic_dmd_num_latent_sections( + min_sections: int = 3, + max_sections: int = 3, + dmd_dynamic_alpha: float = 1.5, + dmd_dynamic_beta: float = 4.0, + dmd_dynamic_sample_type: str = "uniform", + global_step: int = 0, + dmd_dynamic_step: int = 1000, + device: str = "cuda", +): + assert min_sections >= 1 + if min_sections == max_sections: + return min_sections + + dmd_dynamic_step = float(dmd_dynamic_step) + global_step = float(global_step) + + # Sample a value between 0 and 1 + if dmd_dynamic_sample_type == "uniform": + t = torch.rand(1, device=device).item() + elif dmd_dynamic_sample_type == "beta": + # Adjust alpha and beta based on training progress + if dmd_dynamic_step > 0: + progress = min(global_step / dmd_dynamic_step, 1.0) + # Cosine decay: starts at 1.0, decays to 0.0 + cosine_decay = 0.5 * (1.0 + torch.cos(torch.tensor(progress * torch.pi))) + # Gradually reduce alpha and beta towards 1.0 (uniform distribution) + alpha = 1.0 + (dmd_dynamic_alpha - 1.0) * cosine_decay + beta = 1.0 + (dmd_dynamic_beta - 1.0) * cosine_decay + else: + alpha = dmd_dynamic_alpha + beta = dmd_dynamic_beta + + t = torch.distributions.Beta(alpha, beta).sample((1,)).to(device).item() + else: + raise ValueError(f"Unsupported sample_type: {dmd_dynamic_sample_type}. Choose from ['uniform', 'beta'].") + + # Map to the range [min_sections, max_sections] + num_sections = min_sections + t * (max_sections - min_sections) + + # Round to nearest integer and clamp + num_sections = int(round(num_sections)) + num_sections = max(min_sections, min(max_sections, num_sections)) + + return num_sections + + +def sample_dynamic_timestep( + B: int, + num_train_timestep: int = 1000, + min_timestep: int = 0, + max_timestep: int = 1000, + min_step: int = 20, + max_step: int = 980, + timestep_shift: float = 1.0, + dynamic_alpha: float = 4.0, + dynamic_beta: float = 1.5, + dynamic_sample_type: str = "uniform", + global_step: int = 0, + dynamic_step: int = 1000, + device: str = "cuda", +): + dynamic_step = float(dynamic_step) + global_step = float(global_step) + + # dynamic timestep + if dynamic_sample_type == "uniform": + t = torch.rand(B, device=device) * (1.0 - 0.001) + 0.001 + elif dynamic_sample_type == "beta": + if dynamic_step > 0: + progress = min(global_step / dynamic_step, 1.0) + cosine_decay = 0.5 * (1.0 + torch.cos(torch.tensor(progress * torch.pi))) + dynamic_alpha = 1.0 + (dynamic_alpha - 1.0) * cosine_decay + dynamic_beta = 1.0 + (dynamic_beta - 1.0) * cosine_decay + t = torch.distributions.Beta(dynamic_alpha, dynamic_beta).sample((B,)).to(device) + else: + raise ValueError(f"Unsupported dynamic_sample_type: {dynamic_sample_type}. Choose from ['uniform', 'beta'].") + + # timestep warping + timestep = min_timestep + t * (max_timestep - min_timestep) + if timestep_shift > 1: + timestep = ( + timestep_shift + * (timestep / num_train_timestep) + / (1 + (timestep_shift - 1) * (timestep / num_train_timestep)) + * num_train_timestep + ) + timestep = timestep.clamp(min_step, max_step) + + return timestep.round().long() + + +# ======================================== Helper ======================================== + + +def merge_dict_list(dict_list): + if len(dict_list) == 1: + return dict_list[0] + + merged_dict = {} + for k, v in dict_list[0].items(): + if isinstance(v, torch.Tensor): + if v.ndim == 0: + merged_dict[k] = torch.stack([d[k] for d in dict_list], dim=0) + else: + merged_dict[k] = torch.cat([d[k] for d in dict_list], dim=0) + else: + # for non-tensor values, we just copy the value from the first item + merged_dict[k] = v + return merged_dict + + +def generate_and_sync_flag(accelerator, num_denoising_steps, last_step_only=False, is_sync=True): + if is_sync: + if accelerator.is_main_process: + if last_step_only: + step = num_denoising_steps - 1 + else: + step = torch.randint(low=0, high=num_denoising_steps, size=(), device=accelerator.device).item() + step_tensor = torch.tensor(step, dtype=torch.long, device=accelerator.device) + else: + step_tensor = torch.empty((), dtype=torch.long, device=accelerator.device) + + broadcast(step_tensor, from_process=0) + return step_tensor.item() + else: + if last_step_only: + step = num_denoising_steps - 1 + else: + step = torch.randint(low=0, high=num_denoising_steps, size=(), device=accelerator.device).item() + return step + + +def sample_block_noise(scheduler, batch_size, channel, num_frames, height, width): + gamma = scheduler.config.gamma + cov = torch.eye(4) * (1 + gamma) - torch.ones(4, 4) * gamma + dist = torch.distributions.MultivariateNormal(torch.zeros(4, device=cov.device), covariance_matrix=cov) + block_number = batch_size * channel * num_frames * (height // 2) * (width // 2) + + noise = dist.sample((block_number,)) # [block number, 4] + noise = noise.view(batch_size, channel, num_frames, height // 2, width // 2, 2, 2) + noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(batch_size, channel, num_frames, height, width) + return noise + + +def add_noise(original_samples, noise, timestep, sigmas, timesteps): + sigmas = sigmas.to(noise.device) + timesteps = timesteps.to(noise.device) + timestep_id = torch.argmin((timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1) + sigma = sigmas[timestep_id].reshape(-1, 1, 1, 1, 1) + sample = (1 - sigma) * original_samples + sigma * noise + return sample.type_as(noise) + + +def convert_flow_pred_to_x0(flow_pred, xt, timestep, sigmas, timesteps): + # use higher precision for calculations + original_dtype = flow_pred.dtype + device = flow_pred.device + flow_pred, xt, sigmas, timesteps = (x.double().to(device) for x in (flow_pred, xt, sigmas, timesteps)) + + timestep_id = torch.argmin((timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1) + sigma_t = sigmas[timestep_id].reshape(-1, 1, 1, 1, 1) + x0_pred = xt - sigma_t * flow_pred + return x0_pred.to(original_dtype) + + +def convert_xt_pred_to_x0(noise, xt, timestep, sigmas, timesteps): + # use higher precision for calculations + original_dtype = xt.dtype + device = xt.device + noise, xt, sigmas, timesteps = (x.double().to(device) for x in (noise, xt, sigmas, timesteps)) + + timestep_id = torch.argmin((timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1) + sigma_t = sigmas[timestep_id].reshape(-1, 1, 1, 1, 1) + x0_pred = (xt - sigma_t * noise) / (1 - sigma_t) + return x0_pred.to(original_dtype) + + +# ======================================== Staged Backward Simulation ======================================== + + +def inference_with_trajectory_stage1( + args, + accelerator, + transformer, + scheduler, + noise, + prompt_embeds, + # For Stage 1 + is_keep_x0: bool = True, + history_sizes: list = [16, 2, 1], + # For DMD Main + denoising_step_list: list = None, + last_step_only: bool = False, + last_section_grad_only: bool = False, + return_sim_step: bool = False, + sigmas: torch.Tensor = None, + timesteps: torch.Tensor = None, + timestep_shift: float = 1.0, + num_critic_input_frames: int = 21, + num_rollout_sections: int = 3, + is_skip_first_section: bool = False, + is_amplify_first_chunk: bool = False, + # For Easy Anti-Drifting + is_corrupt_history_latents: bool = False, + is_add_saturation: bool = False, + # For GT History + is_use_gt_history: bool = False, + gt_all_data: tuple = None, + # For VAE Re-Encode + is_dmd_vae_decode: bool = False, + # For Consistency Align + is_consistency_align: bool = False, + # For KV Cache + use_kv_cache: bool = True, +): + raise NotImplementedError + batch_size, num_channels_latents, latent_window_size, height, width = noise.shape + num_denoising_steps = len(denoising_step_list) + init_exit_flag = generate_and_sync_flag(accelerator, num_denoising_steps, last_step_only) + denoising_step_list = torch.tensor(denoising_step_list) + if timestep_shift > 1: + denoising_step_list = ( + timestep_shift + * (denoising_step_list / 1000) + / (1 + (timestep_shift - 1) * (denoising_step_list / 1000)) + * 1000 + ) + + consistency_align_loss = torch.tensor(0.0) + if is_consistency_align: + consistentcy_align_loss_list = [] + + history_sizes = sorted(history_sizes, reverse=True) # From large to small + if not is_keep_x0: + history_sizes[-1] = history_sizes[-1] + 1 + if is_use_gt_history: + ( + _, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + history_latents, + ) = gt_all_data + else: + history_latents = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes), + height, + width, + device=accelerator.device, + dtype=torch.float32, + ) + + assert num_rollout_sections * latent_window_size >= num_critic_input_frames + + dmd_num_input_frames_sections = (num_critic_input_frames + latent_window_size - 1) // latent_window_size + if num_rollout_sections <= dmd_num_input_frames_sections: + start_gradient_section_index = 0 + elif last_section_grad_only: + start_gradient_section_index = num_rollout_sections - 1 + else: + start_gradient_section_index = num_rollout_sections - dmd_num_input_frames_sections + + # Step 1: Denoising loop + image_latents = None + total_generated_latent_frames = 0 + for k in range(num_rollout_sections): + noisy_model_input = torch.randn(noise.shape, device=accelerator.device, dtype=noise.dtype) + is_first_section = k == 0 + is_second_section = k == 1 + if not is_use_gt_history: + if is_keep_x0: + if is_first_section: + history_sizes_first_section = [1] + history_sizes.copy() + history_latents_first_section = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes_first_section), + height, + width, + device=accelerator.device, + dtype=torch.float32, + ) + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix, latents_history_long, latents_history_mid, latents_history_1x = ( + history_latents_first_section[:, :, -sum(history_sizes_first_section) :].split( + history_sizes_first_section, dim=2 + ) + ) + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix = image_latents + latents_history_long, latents_history_mid, latents_history_1x = history_latents[ + :, :, -sum(history_sizes) : + ].split(history_sizes, dim=2) + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + raise NotImplementedError + + if not is_use_gt_history and is_corrupt_history_latents: + latents_history_short, latents_history_mid, latents_history_long = corrupt_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=True, + # choose mode + corrupt_mode=args.training_config.corrupt_mode_history, + noise_mode_prob=args.training_config.corrupt_mode_prob_history, + # for noise + is_frame_independent=args.training_config.is_frame_independent_corrupt_history, + is_chunk_independent=args.training_config.is_chunk_independent_corrupt_history, + corrupt_ratio_1x=args.training_config.noise_corrupt_ratio_history_short, + corrupt_ratio_2x=args.training_config.noise_corrupt_ratio_history_mid, + corrupt_ratio_4x=args.training_config.noise_corrupt_ratio_history_long, + noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_history, + # for downsample + downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_history, + downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_history, + ) + + if is_add_saturation: + latents_history_short, latents_history_mid, latents_history_long = add_saturation_to_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=True, + saturation_ratio_min=args.training_config.saturation_ratio_min, + saturation_ratio_max=args.training_config.saturation_ratio_max, + saturation_clean_prob=args.training_config.saturation_ratio_clean_prob, + ) + + should_compute_grad = k >= start_gradient_section_index + if is_consistency_align and should_compute_grad: + pred_x0_list = [] + for index, current_timestep in enumerate(denoising_step_list): + is_first_step = index == 0 + exit_flag = index == init_exit_flag + timestep = torch.ones([batch_size], device=accelerator.device, dtype=torch.int64) * current_timestep + + if not exit_flag: + with torch.no_grad(): + model_pred = transformer( + hidden_states=noisy_model_input, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid.to(prompt_embeds.dtype), + latents_history_long=latents_history_long.to(prompt_embeds.dtype), + return_dict=False, + is_first_denoising_step=is_first_step, + )[0] + pred_x0 = convert_flow_pred_to_x0( + flow_pred=model_pred, + xt=noisy_model_input, + timestep=timestep, + sigmas=sigmas, + timesteps=timesteps, + ) + next_timestep = denoising_step_list[index + 1] + noisy_model_input = add_noise( + pred_x0, + torch.randn_like(pred_x0, device=accelerator.device, dtype=noise.dtype), + next_timestep * torch.ones([batch_size], device=accelerator.device, dtype=torch.long), + sigmas, + timesteps, + ) + + if is_consistency_align and should_compute_grad: + pred_x0_list.append(pred_x0) + else: + # for getting real output + with torch.set_grad_enabled(should_compute_grad): + model_pred = transformer( + hidden_states=noisy_model_input, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid.to(prompt_embeds.dtype), + latents_history_long=latents_history_long.to(prompt_embeds.dtype), + return_dict=False, + is_first_denoising_step=is_first_step, + )[0] + pred_x0 = convert_flow_pred_to_x0( + flow_pred=model_pred, + xt=noisy_model_input, + timestep=timestep, + sigmas=sigmas, + timesteps=timesteps, + ) + if is_consistency_align and should_compute_grad: + pred_x0_list.append(pred_x0) + break + + if is_consistency_align and should_compute_grad and len(pred_x0_list) > 1: + prev_x0s = torch.stack(pred_x0_list[:-1]) + last_x0 = pred_x0_list[-1] + temp_mse_loss = 0.5 * F.mse_loss(prev_x0s, last_x0.unsqueeze(0).expand_as(prev_x0s), reduction="mean") + consistentcy_align_loss_list.append(temp_mse_loss) + + if use_kv_cache: + transformer.clear_kv_cache() + + if is_keep_x0 and (is_first_section or (is_skip_first_section and is_second_section)): + image_latents = pred_x0[:, :, 0:1, :, :] + total_generated_latent_frames += latent_window_size + history_latents = torch.cat([history_latents, pred_x0], dim=2) + + # Step 2: record the model's output + total_available_frames = history_latents.shape[2] - sum(history_sizes) + max_start_section_idx = max(0, (total_available_frames - num_critic_input_frames) // latent_window_size) + # --------------- + # Way 1, random + # start_section_idx = torch.randint(0, max_start_section_idx + 1, (1,)).item() + # Way 2, fix + start_section_idx = max_start_section_idx + # --------------- + start_frame = sum(history_sizes) + start_section_idx * latent_window_size + + if is_dmd_vae_decode: + end_frame = history_latents.shape[2] + else: + end_frame = start_frame + num_critic_input_frames + end_frame = min(end_frame, history_latents.shape[2]) + + output = history_latents[:, :, start_frame:end_frame, :, :] + + # Step 3: Return the denoised timestep + if init_exit_flag == len(denoising_step_list) - 1: + denoised_timestep_to = 0 + denoised_timestep_from = ( + 1000 - torch.argmin((timesteps - denoising_step_list[init_exit_flag]).abs(), dim=0).item() + ) + else: + denoised_timestep_to = ( + 1000 - torch.argmin((timesteps - denoising_step_list[init_exit_flag + 1]).abs(), dim=0).item() + ) + denoised_timestep_from = ( + 1000 - torch.argmin((timesteps - denoising_step_list[init_exit_flag]).abs(), dim=0).item() + ) + + if is_consistency_align and len(consistentcy_align_loss_list) > 0: + consistency_align_loss = torch.stack(consistentcy_align_loss_list).mean() + + if return_sim_step: + return output, denoised_timestep_from, denoised_timestep_to, consistency_align_loss, init_exit_flag + 1 + + return output, denoised_timestep_from, denoised_timestep_to, consistency_align_loss + + +def inference_with_trajectory_stage2( + args, + accelerator, + transformer, + scheduler, + noise, + prompt_embeds, + # For Stage 1 + is_keep_x0: bool = True, + history_sizes: list = [16, 2, 1], + # For Stage 2 + stage2_num_stages: int = 3, + stage2_num_inference_steps_list: list = [20, 20, 20], + # For DMD Main + denoising_step_list: list = None, + last_step_only: bool = False, + last_section_grad_only: bool = False, + return_sim_step: bool = False, + sigmas: torch.Tensor = None, + timesteps: torch.Tensor = None, + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + num_critic_input_frames: int = 21, + num_rollout_sections: int = 3, + is_skip_first_section: bool = False, + is_amplify_first_chunk: bool = False, + # For Easy Anti-Drifting + is_corrupt_history_latents: bool = False, + is_add_saturation: bool = False, + # For GT History + is_use_gt_history: bool = False, + gt_all_data: tuple = None, + # For VAE Re-Encode + is_dmd_vae_decode: bool = False, + # For Multi Stage Backward Simulated + is_multi_pyramid_stage_backward_simulated: bool = False, + init_pyramid_stage_flag: int = 2, + # For Consistency Align + is_consistency_align: bool = False, + # For KV Cache + use_kv_cache: bool = True, +): + batch_size, num_channels_latents, latent_window_size, height, width = noise.shape + + init_exit_flag_list = [] + for i_s in range(stage2_num_stages): + num_denoising_steps = stage2_num_inference_steps_list[i_s] + init_exit_flag_list.append(generate_and_sync_flag(accelerator, num_denoising_steps, last_step_only)) + + if is_multi_pyramid_stage_backward_simulated: + divisor = 2 ** (stage2_num_stages - 1 - init_pyramid_stage_flag) + pyramid_stage_videos = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes), + height // divisor, + width // divisor, + device=accelerator.device, + dtype=torch.float32, + ) + + consistency_align_loss = torch.tensor(0.0) + if is_consistency_align: + consistentcy_align_loss_list = [] + + history_sizes = sorted(history_sizes, reverse=True) # From large to small + if not is_keep_x0: + history_sizes[-1] = history_sizes[-1] + 1 + if is_use_gt_history: + ( + _, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + history_latents, + ) = gt_all_data + else: + history_latents = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes), + height, + width, + device=accelerator.device, + dtype=torch.float32, + ) + + assert num_rollout_sections * latent_window_size >= num_critic_input_frames + + dmd_num_input_frames_sections = (num_critic_input_frames + latent_window_size - 1) // latent_window_size + if num_rollout_sections <= dmd_num_input_frames_sections: + start_gradient_section_index = 0 + elif last_section_grad_only: + start_gradient_section_index = num_rollout_sections - 1 + else: + start_gradient_section_index = num_rollout_sections - dmd_num_input_frames_sections + + # Step 1: Denoising loop + image_latents = None + total_generated_latent_frames = 0 + for k in range(num_rollout_sections): + noisy_model_input = torch.randn(noise.shape, device=accelerator.device, dtype=noise.dtype) + + num_frmaes_pyramid, height_pyramid, width_pyramid = ( + noisy_model_input.shape[-3], + noisy_model_input.shape[-2], + noisy_model_input.shape[-1], + ) + noisy_model_input = rearrange(noisy_model_input, "b c t h w -> (b t) c h w") + # by default, we needs to start from the block noise + for _ in range(stage2_num_stages - 1): + height_pyramid //= 2 + width_pyramid //= 2 + noisy_model_input = ( + F.interpolate( + noisy_model_input, + size=(height_pyramid, width_pyramid), + mode="bilinear", + ) + * 2 + ) + noisy_model_input = rearrange(noisy_model_input, "(b t) c h w -> b c t h w", t=num_frmaes_pyramid) + + is_first_section = k == 0 + is_second_section = k == 1 + if not is_use_gt_history: + if is_keep_x0: + if is_first_section: + history_sizes_first_section = [1] + history_sizes.copy() + history_latents_first_section = torch.zeros( + batch_size, + num_channels_latents, + sum(history_sizes_first_section), + height, + width, + device=accelerator.device, + dtype=torch.float32, + ) + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix, latents_history_long, latents_history_mid, latents_history_1x = ( + history_latents_first_section[:, :, -sum(history_sizes_first_section) :].split( + history_sizes_first_section, dim=2 + ) + ) + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + indices = torch.arange(0, sum([1, *history_sizes, latent_window_size])) + ( + indices_prefix, + indices_latents_history_long, + indices_latents_history_mid, + indices_latents_history_1x, + indices_hidden_states, + ) = indices.split([1, *history_sizes, latent_window_size], dim=0) + indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0) + + latents_prefix = image_latents + latents_history_long, latents_history_mid, latents_history_1x = history_latents[ + :, :, -sum(history_sizes) : + ].split(history_sizes, dim=2) + latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2) + else: + raise NotImplementedError + + if not is_use_gt_history and is_corrupt_history_latents: + latents_history_short, latents_history_mid, latents_history_long = corrupt_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=True, + # choose mode + corrupt_mode=args.training_config.corrupt_mode_history, + noise_mode_prob=args.training_config.corrupt_mode_prob_history, + # for noise + is_frame_independent=args.training_config.is_frame_independent_corrupt_history, + is_chunk_independent=args.training_config.is_chunk_independent_corrupt_history, + corrupt_ratio_1x=args.training_config.noise_corrupt_ratio_history_short, + corrupt_ratio_2x=args.training_config.noise_corrupt_ratio_history_mid, + corrupt_ratio_4x=args.training_config.noise_corrupt_ratio_history_long, + noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_history, + # for downsample + downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_history, + downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_history, + ) + + if is_add_saturation: + latents_history_short, latents_history_mid, latents_history_long = add_saturation_to_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=True, + saturation_ratio_min=args.training_config.saturation_ratio_min, + saturation_ratio_max=args.training_config.saturation_ratio_max, + saturation_clean_prob=args.training_config.saturation_ratio_clean_prob, + ) + + pred_x0 = None + start_point_list = [noisy_model_input] + should_compute_grad = k >= start_gradient_section_index + for i_s in range(stage2_num_stages): + if is_consistency_align and should_compute_grad: + pred_x0_list = [] + + if is_amplify_first_chunk and is_first_section: + if not is_use_gt_history: + scheduler.set_timesteps( + stage2_num_inference_steps_list[i_s] * 2 + 1, i_s, device=accelerator.device + ) + elif ( + latents_history_short.sum() == 0 + and latents_history_mid.sum() == 0 + and latents_history_long.sum() == 0 + ): + scheduler.set_timesteps( + stage2_num_inference_steps_list[i_s] * 2 + 1, i_s, device=accelerator.device + ) + else: + scheduler.set_timesteps(stage2_num_inference_steps_list[i_s] + 1, i_s, device=accelerator.device) + else: + scheduler.set_timesteps(stage2_num_inference_steps_list[i_s] + 1, i_s, device=accelerator.device) + + original_timestep = scheduler.timesteps + scheduler.timesteps = scheduler.timesteps[:-1] + scheduler.sigmas = torch.cat([scheduler.sigmas[:-2], scheduler.sigmas[-1:]]) + + timesteps_per_stage = scheduler.timesteps_per_stage[i_s] + sigmas_per_stage = scheduler.sigmas_per_stage[i_s] + + if i_s > 0: + # important here !!! + assert pred_x0 is not None, "pred_x0 should be set in previous iteration" + noisy_model_input = pred_x0 + height_pyramid *= 2 + width_pyramid *= 2 + num_frames = noisy_model_input.shape[2] + noisy_model_input = rearrange(noisy_model_input, "b c t h w -> (b t) c h w") + noisy_model_input = F.interpolate( + noisy_model_input, size=(height_pyramid, width_pyramid), mode="nearest" + ) + noisy_model_input = rearrange(noisy_model_input, "(b t) c h w -> b c t h w", t=num_frames) + # Fix the stage + ori_sigma = 1 - scheduler.ori_start_sigmas[i_s] # the original coeff of signal + gamma = scheduler.config.gamma + alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma) + beta = alpha * (1 - ori_sigma) / math.sqrt(gamma) + + batch_size, channel, num_frames, height_pyramid, width_pyramid = noisy_model_input.shape + noise = sample_block_noise(scheduler, batch_size, channel, num_frames, height_pyramid, width_pyramid) + noise = noise.to(device=accelerator.device, dtype=noisy_model_input.dtype) + noisy_model_input = alpha * noisy_model_input + beta * noise # To fix the block artifact + + start_point_list.append(noisy_model_input) + + if use_dynamic_shifting: + temp_sigmas, temp_sigmas_per_stage = apply_schedule_shift( + scheduler.sigmas, + noisy_model_input, + sigmas_two=sigmas_per_stage, + base_seq_len=args.training_config.base_seq_len, + max_seq_len=args.training_config.max_seq_len, + base_shift=args.training_config.base_shift, + max_shift=args.training_config.max_shift, + time_shift_type=time_shift_type, + ) + + temp_timesteps = scheduler.timesteps_per_stage[i_s].min() + temp_sigmas[:-1] * ( + scheduler.timesteps_per_stage[i_s].max() - scheduler.timesteps_per_stage[i_s].min() + ) + scheduler.sigmas = temp_sigmas + scheduler.timesteps = temp_timesteps + + temp_timesteps_per_stage = scheduler.timesteps_per_stage[i_s].min() + temp_sigmas_per_stage * ( + scheduler.timesteps_per_stage[i_s].max() - scheduler.timesteps_per_stage[i_s].min() + ) + sigmas_per_stage = temp_sigmas_per_stage + timesteps_per_stage = temp_timesteps_per_stage + + denoising_step_list = scheduler.timesteps + + if is_amplify_first_chunk and is_first_section: + if not is_use_gt_history: + init_exit_flag = generate_and_sync_flag( + accelerator, stage2_num_inference_steps_list[i_s] * 2, last_step_only + ) + elif ( + latents_history_short.sum() == 0 + and latents_history_mid.sum() == 0 + and latents_history_long.sum() == 0 + ): + init_exit_flag = generate_and_sync_flag( + accelerator, stage2_num_inference_steps_list[i_s] * 2, last_step_only, is_sync=False + ) + else: + init_exit_flag = init_exit_flag_list[i_s] + else: + init_exit_flag = init_exit_flag_list[i_s] + + for index, current_timestep in enumerate(denoising_step_list): + is_first_step = i_s == 0 and index == 0 + exit_flag = index == init_exit_flag + timestep = torch.ones([batch_size], device=accelerator.device, dtype=torch.int64) * current_timestep + + if not exit_flag: + with torch.no_grad(): + model_pred = transformer( + hidden_states=noisy_model_input, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid.to(prompt_embeds.dtype), + latents_history_long=latents_history_long.to(prompt_embeds.dtype), + return_dict=False, + is_first_denoising_step=is_first_step, + )[0] + pred_x0 = convert_flow_pred_to_x0( + flow_pred=model_pred, + xt=noisy_model_input, + timestep=timestep, + sigmas=sigmas_per_stage, + timesteps=timesteps_per_stage, + ) + next_timestep = denoising_step_list[index + 1] + noisy_model_input = add_noise( + pred_x0, + start_point_list[i_s], + next_timestep * torch.ones([batch_size], device=accelerator.device, dtype=torch.long), + sigmas=sigmas_per_stage, + timesteps=timesteps_per_stage, + ) + + if is_consistency_align and should_compute_grad: + pred_x0_list.append(pred_x0) + else: + # for getting real output + with torch.set_grad_enabled(should_compute_grad): + model_pred = transformer( + hidden_states=noisy_model_input, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid.to(prompt_embeds.dtype), + latents_history_long=latents_history_long.to(prompt_embeds.dtype), + return_dict=False, + is_first_denoising_step=is_first_step, + )[0] + pred_x0 = convert_flow_pred_to_x0( + flow_pred=model_pred, + xt=noisy_model_input, + timestep=timestep, + sigmas=sigmas_per_stage, + timesteps=timesteps_per_stage, + ) + if is_consistency_align and should_compute_grad: + pred_x0_list.append(pred_x0) + break + + if is_multi_pyramid_stage_backward_simulated and i_s == init_pyramid_stage_flag: + if i_s != stage2_num_stages - 1: + pred_x0 = convert_xt_pred_to_x0( + noise=torch.randn_like(pred_x0, device=accelerator.device, dtype=pred_x0.dtype), + xt=pred_x0, + timestep=torch.ones([batch_size], device=accelerator.device, dtype=torch.int64) + * original_timestep[-1], + sigmas=sigmas, + timesteps=timesteps, + ) + pyramid_stage_videos = torch.cat([pyramid_stage_videos, pred_x0], dim=2) + + if is_consistency_align and should_compute_grad and len(pred_x0_list) > 1: + prev_x0s = torch.stack(pred_x0_list[:-1]) + last_x0 = pred_x0_list[-1] + temp_mse_loss = 0.5 * F.mse_loss(prev_x0s, last_x0.unsqueeze(0).expand_as(prev_x0s), reduction="mean") + consistentcy_align_loss_list.append(temp_mse_loss) + + if use_kv_cache: + transformer.clear_kv_cache() + + if is_keep_x0 and (is_first_section or (is_skip_first_section and is_second_section)): + image_latents = pred_x0[:, :, 0:1, :, :] + total_generated_latent_frames += latent_window_size + history_latents = torch.cat([history_latents, pred_x0], dim=2) + + # Step 2: record the model's output + total_available_frames = history_latents.shape[2] - sum(history_sizes) + max_start_section_idx = max(0, (total_available_frames - num_critic_input_frames) // latent_window_size) + # --------------- + # Way 1, random + # start_section_idx = torch.randint(0, max_start_section_idx + 1, (1,)).item() + # Way 2, fix + start_section_idx = max_start_section_idx + # --------------- + start_frame = sum(history_sizes) + start_section_idx * latent_window_size + + if is_dmd_vae_decode: + end_frame = history_latents.shape[2] + else: + end_frame = start_frame + num_critic_input_frames + end_frame = min(end_frame, history_latents.shape[2]) + + # Step 3: Return the denoised timestep + if is_multi_pyramid_stage_backward_simulated: + output = pyramid_stage_videos[:, :, start_frame:end_frame, :, :] + + stage_exit_flag = init_exit_flag_list[init_pyramid_stage_flag] + scheduler.set_timesteps( + stage2_num_inference_steps_list[init_pyramid_stage_flag] + 1, + init_pyramid_stage_flag, + device=accelerator.device, + ) + original_timestep = scheduler.timesteps + stage_denoising_step_list = scheduler.timesteps[:-1] + if stage_exit_flag == len(stage_denoising_step_list) - 1: + denoised_timestep_to = original_timestep[-1] + else: + denoised_timestep_to = stage_denoising_step_list[stage_exit_flag + 1] + denoised_timestep_from = stage_denoising_step_list[stage_exit_flag] + else: + output = history_latents[:, :, start_frame:end_frame, :, :] + if init_exit_flag == len(denoising_step_list) - 1: + denoised_timestep_to = original_timestep[-1] + else: + denoised_timestep_to = denoising_step_list[init_exit_flag + 1] + denoised_timestep_from = denoising_step_list[init_exit_flag] + + if is_consistency_align and len(consistentcy_align_loss_list) > 0: + consistency_align_loss = torch.stack(consistentcy_align_loss_list).mean() + + if return_sim_step: + return output, denoised_timestep_from, denoised_timestep_to, consistency_align_loss, init_exit_flag + 1 + + return output, denoised_timestep_from, denoised_timestep_to, consistency_align_loss + + +def consistency_backward_simulation( + args, + accelerator, + transformer, + scheduler, + noise, + prompt_embeds, + # For Stage 1 + is_keep_x0: bool = True, + history_sizes: list = [16, 2, 1], + # Stage 2 + is_enable_stage2: bool = False, + stage2_num_stages: int = 3, + stage2_num_inference_steps_list: list = [20, 20, 20], + # For DMD Main + denoising_step_list: list = None, + last_step_only: bool = False, + last_section_grad_only: bool = False, + return_sim_step: bool = False, + sigmas: torch.Tensor = None, + timesteps: torch.Tensor = None, + timestep_shift: float = 1.0, + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + num_critic_input_frames: int = 21, + num_rollout_sections: int = 3, + is_skip_first_section: bool = False, + is_amplify_first_chunk: bool = False, + # For Easy Anti-Drifting + is_corrupt_history_latents: bool = False, + is_add_saturation: bool = False, + # GT History + is_use_gt_history: bool = False, + gt_all_data: tuple = None, + # For VAE Re-Encode + is_dmd_vae_decode: bool = False, + # For Multi Stage Backward Simulated + is_multi_pyramid_stage_backward_simulated: bool = False, + init_pyramid_stage_flag: int = 2, + # For Consistency Align + is_consistency_align: bool = False, + # For KV Cache + use_kv_cache: bool = True, +) -> torch.Tensor: + common_kwargs = { + "args": args, + "accelerator": accelerator, + "transformer": transformer, + "scheduler": scheduler, + "noise": noise, + "prompt_embeds": prompt_embeds, + # For Stage 1 + "is_keep_x0": is_keep_x0, + "history_sizes": history_sizes, + # For DMD Main + "denoising_step_list": denoising_step_list, + "last_step_only": last_step_only, + "last_section_grad_only": last_section_grad_only, + "return_sim_step": return_sim_step, + "sigmas": sigmas, + "timesteps": timesteps, + "num_critic_input_frames": num_critic_input_frames, + "num_rollout_sections": num_rollout_sections, + "is_skip_first_section": is_skip_first_section, + "is_amplify_first_chunk": is_amplify_first_chunk, + # Easy Anti-Drifting + "is_corrupt_history_latents": is_corrupt_history_latents, + "is_add_saturation": is_add_saturation, + # For VAE Re-Encode + "is_dmd_vae_decode": is_dmd_vae_decode, + # Consistency Align + "is_consistency_align": is_consistency_align, + # For KV Cache + "use_kv_cache": use_kv_cache, + } + + if is_enable_stage2: + stage2_kwargs = { + "use_dynamic_shifting": use_dynamic_shifting, + "time_shift_type": time_shift_type, + # Stage 2 + "stage2_num_stages": stage2_num_stages, + "stage2_num_inference_steps_list": stage2_num_inference_steps_list, + # GT History + "is_use_gt_history": is_use_gt_history, + "gt_all_data": gt_all_data, + # Multi Stage Backward Simulated + "is_multi_pyramid_stage_backward_simulated": is_multi_pyramid_stage_backward_simulated, + "init_pyramid_stage_flag": init_pyramid_stage_flag, + } + return inference_with_trajectory_stage2(**common_kwargs, **stage2_kwargs) + else: + stage1_kwargs = { + "timestep_shift": timestep_shift, + } + return inference_with_trajectory_stage1(**common_kwargs, **stage1_kwargs) + + +def run_generator( + args, + accelerator, + transformer, + scheduler, + noise, + prompt_embeds, + # For VRAM manager + dmd_is_low_vram_mode: bool = False, + # For Stage 1 + is_keep_x0: bool = True, + history_sizes: list = [16, 2, 1], + # For Stage 2 + is_enable_stage2: bool = False, + stage2_num_stages: int = 3, + stage2_num_inference_steps_list: list = [20, 20, 20], + # For DMD Main + denoising_step_list: list = None, + last_step_only: bool = False, + last_section_grad_only: bool = False, + return_sim_step: bool = False, + sigmas: torch.Tensor = None, + timesteps: torch.Tensor = None, + timestep_shift: float = 1.0, + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + num_critic_input_frames: int = 21, + num_rollout_sections: int = 3, + is_skip_first_section: bool = False, + is_amplify_first_chunk: bool = False, + # For Easy Anti-Drifting + is_corrupt_history_latents: bool = False, + is_add_saturation: bool = False, + # For GT History + is_use_gt_history: bool = False, + gt_all_data: tuple = None, + # For VAE Re-Encode + is_dmd_vae_decode: bool = False, + # For Multi Stage Backward Simulated + is_multi_pyramid_stage_backward_simulated: bool = False, + init_pyramid_stage_flag: int = 2, + # For Consistency Align + is_consistency_align: bool = False, + # For KV Cache + use_kv_cache: bool = True, +): + if use_kv_cache: + transformer.disable_kv_cache() + + pred_image_or_video, denoised_timestep_from, denoised_timestep_to, consistency_align_loss = ( + consistency_backward_simulation( + args=args, + accelerator=accelerator, + transformer=transformer, + scheduler=scheduler, + noise=torch.randn(noise.shape, device=accelerator.device, dtype=noise.dtype), + prompt_embeds=prompt_embeds, + # For Stage 1 + is_keep_x0=is_keep_x0, + history_sizes=history_sizes, + # For Stage 2 + is_enable_stage2=is_enable_stage2, + stage2_num_stages=stage2_num_stages, + stage2_num_inference_steps_list=stage2_num_inference_steps_list, + # For DMD Main + denoising_step_list=denoising_step_list, + last_step_only=last_step_only, + last_section_grad_only=last_section_grad_only, + return_sim_step=return_sim_step, + sigmas=sigmas, + timesteps=timesteps, + timestep_shift=timestep_shift, + use_dynamic_shifting=use_dynamic_shifting, + time_shift_type=time_shift_type, + num_critic_input_frames=num_critic_input_frames, + num_rollout_sections=num_rollout_sections, + is_skip_first_section=is_skip_first_section, + is_amplify_first_chunk=is_amplify_first_chunk, + # For Easy Anti-Drifting + is_corrupt_history_latents=is_corrupt_history_latents, + is_add_saturation=is_add_saturation, + # For GT History + is_use_gt_history=is_use_gt_history, + gt_all_data=gt_all_data, + # For VAE Re-Encode + is_dmd_vae_decode=is_dmd_vae_decode, + # For Multi Stage Backward Simulated + is_multi_pyramid_stage_backward_simulated=is_multi_pyramid_stage_backward_simulated, + init_pyramid_stage_flag=init_pyramid_stage_flag, + # Consistency Align + is_consistency_align=is_consistency_align, + # For KV Cache + use_kv_cache=use_kv_cache, + ) + ) + + if use_kv_cache and dmd_is_low_vram_mode: + transformer.disable_kv_cache() + + pred_image_or_video_last_21 = pred_image_or_video + gradient_mask = None + + return ( + pred_image_or_video_last_21, + gradient_mask, + denoised_timestep_from, + denoised_timestep_to, + consistency_align_loss, + ) + + +# ======================================== Generator Loss ======================================== + + +def compute_kl_grad( + accelerator, + scheduler, + real_fake_score_model, + noisy_image_or_video, + estimated_clean_image_or_video, + prompt_embeds, + negative_prompt_embeds, + # For DMD Main + timestep, + sigmas, + timesteps, + fake_guidance_scale: float = 0.0, + real_guidance_scale: float = 3.0, + normalization: bool = True, + # For Decouple DMD + is_decouple_dmd: bool = False, + ca_noisy_image_or_video: torch.Tensor = None, + dm_noisy_image_or_video: torch.Tensor = None, + ca_timestep: torch.Tensor = None, + dm_timestep: torch.Tensor = None, + # For GT History + is_use_gt_history: bool = False, + gt_all_data: tuple = None, +): + def unwrap_model(model): + model = accelerator.unwrap_model(model) + model = model._orig_mod if is_compiled_module(model) else model + return model + + if is_use_gt_history: + ( + _, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + _, + ) = gt_all_data + else: + indices_hidden_states = None + indices_latents_history_short = None + indices_latents_history_mid = None + indices_latents_history_long = None + latents_history_short = None + latents_history_mid = None + latents_history_long = None + + # Step 1: Compute the fake score + pred_fake_image_cond = real_fake_score_model( + hidden_states=noisy_image_or_video if not is_decouple_dmd else dm_noisy_image_or_video, + timestep=timestep if not is_decouple_dmd else dm_timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + return_dict=False, + )[0] + pred_fake_image_cond = convert_flow_pred_to_x0( + flow_pred=pred_fake_image_cond, + xt=noisy_image_or_video if not is_decouple_dmd else dm_noisy_image_or_video, + timestep=timestep if not is_decouple_dmd else dm_timestep, + sigmas=sigmas, + timesteps=timesteps, + ) + + if fake_guidance_scale != 0.0 and not is_decouple_dmd: + pred_fake_image_uncond = real_fake_score_model( + hidden_states=noisy_image_or_video, + timestep=timestep, + encoder_hidden_states=negative_prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + return_dict=False, + )[0] + pred_fake_image_uncond = convert_flow_pred_to_x0( + flow_pred=pred_fake_image_uncond, + xt=noisy_image_or_video, + timestep=timestep, + sigmas=sigmas, + timesteps=timesteps, + ) + pred_fake_image = pred_fake_image_cond + (pred_fake_image_cond - pred_fake_image_uncond) * fake_guidance_scale + else: + pred_fake_image = pred_fake_image_cond + + # Step 2: Compute the real score + # We compute the conditional and unconditional prediction + # and add them together to achieve cfg (https://arxiv.org/abs/2207.12598) + unwrap_model(real_fake_score_model).disable_adapters() + + if is_decouple_dmd: + pred_real_image_cond_dm = real_fake_score_model( + hidden_states=noisy_image_or_video if not is_decouple_dmd else dm_noisy_image_or_video, + timestep=timestep if not is_decouple_dmd else dm_timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + return_dict=False, + )[0] + pred_real_image_cond_dm = convert_flow_pred_to_x0( + flow_pred=pred_real_image_cond_dm, + xt=noisy_image_or_video if not is_decouple_dmd else dm_noisy_image_or_video, + timestep=timestep if not is_decouple_dmd else dm_timestep, + sigmas=sigmas, + timesteps=timesteps, + ) + + pred_real_image_cond = real_fake_score_model( + hidden_states=noisy_image_or_video if not is_decouple_dmd else ca_noisy_image_or_video, + timestep=timestep if not is_decouple_dmd else ca_timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + return_dict=False, + )[0] + pred_real_image_cond = convert_flow_pred_to_x0( + flow_pred=pred_real_image_cond, + xt=noisy_image_or_video if not is_decouple_dmd else ca_noisy_image_or_video, + timestep=timestep if not is_decouple_dmd else ca_timestep, + sigmas=sigmas, + timesteps=timesteps, + ) + + if real_guidance_scale != 0.0 or is_decouple_dmd: + pred_real_image_uncond = real_fake_score_model( + hidden_states=noisy_image_or_video if not is_decouple_dmd else ca_noisy_image_or_video, + timestep=timestep if not is_decouple_dmd else ca_timestep, + encoder_hidden_states=negative_prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + return_dict=False, + )[0] + pred_real_image_uncond = convert_flow_pred_to_x0( + flow_pred=pred_real_image_uncond, + xt=noisy_image_or_video if not is_decouple_dmd else ca_noisy_image_or_video, + timestep=timestep if not is_decouple_dmd else ca_timestep, + sigmas=sigmas, + timesteps=timesteps, + ) + if not is_decouple_dmd: + pred_real_image = ( + pred_real_image_cond + (pred_real_image_cond - pred_real_image_uncond) * real_guidance_scale + ) + else: + pred_real_image = pred_real_image_cond + + unwrap_model(real_fake_score_model).enable_adapters() + + if is_decouple_dmd: + assert real_guidance_scale != 0.0 + ca_grad = real_guidance_scale * (pred_real_image_cond - pred_real_image_uncond) + dm_grad = pred_real_image_cond_dm - pred_fake_image_cond + + if normalization: + ca_normalizer = torch.abs(estimated_clean_image_or_video - pred_real_image_cond).mean( + dim=[1, 2, 3, 4], keepdim=True + ) + ca_grad = ca_grad / ca_normalizer + dm_normalizer = torch.abs(estimated_clean_image_or_video - pred_real_image_cond_dm).mean( + dim=[1, 2, 3, 4], keepdim=True + ) + dm_grad = dm_grad / dm_normalizer + + ca_grad = torch.nan_to_num(ca_grad) + dm_grad = torch.nan_to_num(dm_grad) + + return ( + None, + ca_grad, + dm_grad, + { + "dmdtrain_clean_latent": estimated_clean_image_or_video.detach(), + "dmdtrain_ca_noisy_latent": ca_noisy_image_or_video.detach(), + "dmdtrain_dm_noisy_latent": dm_noisy_image_or_video.detach(), + "dmdtrain_pred_real_image": pred_real_image_cond.detach(), + "dmdtrain_pred_fake_image": pred_fake_image_cond.detach(), + "dmdtrain_ca_gradient_norm": torch.mean(torch.abs(ca_grad)).detach(), + "dmdtrain_dm_gradient_norm": torch.mean(torch.abs(dm_grad)).detach(), + "ca_timestep": ca_timestep.detach(), + "dm_timestep": dm_timestep.detach(), + }, + ) + else: + # Step 3: Compute the DMD gradient (DMD paper eq. 7). + grad = pred_fake_image - pred_real_image + + if normalization: + # Step 4: Gradient normalization (DMD paper eq. 8). + p_real = estimated_clean_image_or_video - pred_real_image + normalizer = torch.abs(p_real).mean(dim=[1, 2, 3, 4], keepdim=True) + grad = grad / normalizer + grad = torch.nan_to_num(grad) + + return ( + grad, + None, + None, + { + "dmdtrain_clean_latent": estimated_clean_image_or_video.detach(), + "dmdtrain_noisy_latent": noisy_image_or_video.detach(), + "dmdtrain_pred_real_image": pred_real_image.detach(), + "dmdtrain_pred_fake_image": pred_fake_image.detach(), + "dmdtrain_gradient_norm": torch.mean(torch.abs(grad)).detach(), + "timestep": timestep.detach(), + }, + ) + + +def compute_distribution_matching_loss( + accelerator, + scheduler, + real_fake_score_model, + image_or_video, + prompt_embeds, + negative_prompt_embeds, + # For VRAM manager + dmd_is_low_vram_mode: bool = False, + vram_manager: OptimizedLowVRAMManager = None, + is_gan_low_vram_mode: bool = False, + # For Stage 2 + is_enable_stage2: bool = False, + # For DMD Main + gradient_mask: Optional[torch.Tensor] = None, + denoised_timestep_from: int = 0, + denoised_timestep_to: int = 0, + ts_schedule: bool = False, + ts_schedule_max: bool = False, + min_score_timestep: int = 0, + num_train_timestep: int = 1000, + sigmas: torch.Tensor = None, + timesteps: torch.Tensor = None, + timestep_shift: float = 1.0, + fake_guidance_scale: float = 0.0, + real_guidance_scale: float = 3.0, + # For GT History + is_use_gt_history: bool = False, + gt_all_data: tuple = None, + # For GAN + is_use_gan: bool = False, + # For Decouple DMD + is_decouple_dmd: bool = False, + decouple_ca_start_step: int = 2000, + decouple_ca_end_step: int = 3000, + # For Dynamic Timestep + is_forcing_low_renoise: bool = False, + dynamic_alpha: float = 4.0, + dynamic_beta: float = 1.5, + dynamic_sample_type: str = "uniform", + global_step: int = 0, + dynamic_step: int = 1000, +): + original_latent = image_or_video + batch_size = image_or_video.shape[0] + + timestep = None + ca_timestep = None + dm_timestep = None + noisy_fake_latent = None + ca_noisy_image_or_video = None + dm_noisy_image_or_video = None + with torch.no_grad(): + # Step 1: Randomly sample timestep based on the given schedule and corresponding noise + min_timestep = denoised_timestep_to if ts_schedule and denoised_timestep_to is not None else min_score_timestep + if is_forcing_low_renoise: + max_timestep = 500 + else: + max_timestep = ( + denoised_timestep_from + if ts_schedule_max and denoised_timestep_from is not None + else num_train_timestep + ) + min_step = int(0.02 * num_train_timestep) + max_step = int(0.98 * num_train_timestep) + + timestep = sample_dynamic_timestep( + B=batch_size, + num_train_timestep=num_train_timestep, + min_timestep=min_timestep, + max_timestep=max_timestep, + min_step=min_step, + max_step=max_step, + timestep_shift=timestep_shift, + dynamic_alpha=dynamic_alpha, + dynamic_beta=dynamic_beta, + dynamic_sample_type=dynamic_sample_type, + global_step=global_step, + dynamic_step=dynamic_step, + device=accelerator.device, + ) + + noise = torch.randn_like(image_or_video, device=accelerator.device, dtype=image_or_video.dtype) + noisy_fake_latent = add_noise( + image_or_video, + noise, + timestep, + sigmas, + timesteps, + ).detach() + + noisy_fake_latent = noisy_fake_latent.to(real_fake_score_model.device, dtype=real_fake_score_model.dtype) + prompt_embeds = prompt_embeds.to(real_fake_score_model.device, dtype=real_fake_score_model.dtype) + negative_prompt_embeds = negative_prompt_embeds.to( + real_fake_score_model.device, dtype=real_fake_score_model.dtype + ) + if negative_prompt_embeds.shape[0] != prompt_embeds.shape[0]: + negative_prompt_embeds = negative_prompt_embeds.repeat(prompt_embeds.shape[0], 1, 1) + + if is_decouple_dmd: + assert decouple_ca_start_step >= dynamic_step + assert decouple_ca_end_step >= dynamic_step + + # For dm + dm_noisy_image_or_video = noisy_fake_latent + dm_timestep = timestep + + # For ca + ca_min_timestep = min_score_timestep + if global_step < decouple_ca_start_step: + ca_max_timestep = max_timestep + elif decouple_ca_start_step <= global_step < decouple_ca_end_step: + ca_max_timestep = 565 # approx 564.6138 + else: + ca_max_timestep = int(denoised_timestep_from) + + ca_timestep = sample_dynamic_timestep( + B=batch_size, + num_train_timestep=num_train_timestep, + min_timestep=ca_min_timestep, + max_timestep=ca_max_timestep, + min_step=min_step, + max_step=max_step, + timestep_shift=timestep_shift if not is_enable_stage2 and timestep_shift > 1 else 1.0, + dynamic_alpha=dynamic_alpha, + dynamic_beta=dynamic_beta, + dynamic_sample_type=dynamic_sample_type, + global_step=global_step, + dynamic_step=dynamic_step, + device=accelerator.device, + ) + + ca_noise = torch.randn_like(image_or_video, device=accelerator.device, dtype=image_or_video.dtype) + ca_noisy_image_or_video = add_noise( + image_or_video, + ca_noise, + ca_timestep, + sigmas, + timesteps, + ).detach() + ca_noisy_image_or_video = ca_noisy_image_or_video.to( + real_fake_score_model.device, dtype=real_fake_score_model.dtype + ) + + # Step 2: Compute the KL grad + grad, ca_grad, dm_grad, dmd_log_dict = compute_kl_grad( + accelerator, + scheduler, + real_fake_score_model, + noisy_image_or_video=noisy_fake_latent, + estimated_clean_image_or_video=original_latent, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + # For DMD Main + timestep=timestep, + sigmas=sigmas, + timesteps=timesteps, + fake_guidance_scale=fake_guidance_scale, + real_guidance_scale=real_guidance_scale, + # For Decouple DMD + is_decouple_dmd=is_decouple_dmd, + ca_noisy_image_or_video=ca_noisy_image_or_video, + dm_noisy_image_or_video=dm_noisy_image_or_video, + ca_timestep=ca_timestep, + dm_timestep=dm_timestep, + # For GT History + is_use_gt_history=is_use_gt_history, + gt_all_data=gt_all_data, + ) + + ca_dmd_loss = torch.tensor(0.0) + dm_dmd_loss = torch.tensor(0.0) + if is_decouple_dmd: + if gradient_mask is not None: + ca_dmd_loss = 0.5 * F.mse_loss( + original_latent.double()[gradient_mask], + (original_latent.double() + ca_grad.double()).detach()[gradient_mask], + reduction="mean", + ) + dm_dmd_loss = 0.5 * F.mse_loss( + original_latent.double()[gradient_mask], + (original_latent.double() + dm_grad.double()).detach()[gradient_mask], + reduction="mean", + ) + else: + ca_dmd_loss = 0.5 * F.mse_loss( + original_latent.double(), (original_latent.double() + ca_grad.double()).detach(), reduction="mean" + ) + dm_dmd_loss = 0.5 * F.mse_loss( + original_latent.double(), (original_latent.double() + dm_grad.double()).detach(), reduction="mean" + ) + dmd_loss = ca_dmd_loss + dm_dmd_loss + else: + if gradient_mask is not None: + dmd_loss = 0.5 * F.mse_loss( + original_latent.double()[gradient_mask], + (original_latent.double() - grad.double()).detach()[gradient_mask], + reduction="mean", + ) + else: + dmd_loss = 0.5 * F.mse_loss( + original_latent.double(), (original_latent.double() - grad.double()).detach(), reduction="mean" + ) + + gan_G_loss = torch.tensor(0.0) + if is_use_gan: + ca_noisy_image_or_video = None + dm_noisy_image_or_video = None + ca_grad = None + dm_grad = None + grad = None + noisy_fake_latent = None + del ca_noisy_image_or_video + del dm_noisy_image_or_video + del ca_grad + del dm_grad + del grad + del noisy_fake_latent + free_memory() + + noise = torch.randn_like(image_or_video, device=accelerator.device, dtype=image_or_video.dtype) + + noisy_fake_latent_for_gan = add_noise( + image_or_video.clone(), + noise, + timestep, + sigmas, + timesteps, + ).to(real_fake_score_model.device, dtype=real_fake_score_model.dtype) + + if is_use_gt_history: + ( + _, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + _, + ) = gt_all_data + else: + indices_hidden_states = None + indices_latents_history_short = None + indices_latents_history_mid = None + indices_latents_history_long = None + latents_history_short = None + latents_history_mid = None + latents_history_long = None + + if is_gan_low_vram_mode: + gan_G_loss = Gan_D_Loss_With_Cached_Grad.apply( + gan_crop_video_spatial(noisy_fake_latent_for_gan), + real_fake_score_model, + timestep, + prompt_embeds, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + 1, + ) + del noisy_fake_latent_for_gan + else: + _, noisy_fake_logits = real_fake_score_model( + hidden_states=noisy_fake_latent_for_gan, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + gan_mode=True, + return_dict=False, + ) + gan_G_loss = cal_gan_loss(noisy_fake_logits, label=1) + del noisy_fake_latent_for_gan, noisy_fake_logits + + free_memory() + + return dmd_loss, ca_dmd_loss, dm_dmd_loss, gan_G_loss, dmd_log_dict + + +def _generator_loss( + args, + accelerator, + real_fake_score_model, + transformer, + scheduler, + noise, + prompt_embeds, + negative_prompt_embeds, + # For VRAM manager + dmd_is_low_vram_mode: bool = False, + vram_manager: OptimizedLowVRAMManager = None, + dmd_is_offload_grad: bool = False, + # For Stage 1 + is_keep_x0: bool = True, + history_sizes: list = [16, 2, 1], + # For Stage 2 + is_enable_stage2: bool = False, + stage2_num_stages: int = None, + stage2_num_inference_steps_list: list = None, + # For DMD Main + denoising_step_list: list = None, + last_step_only: bool = False, + last_section_grad_only: bool = False, + return_sim_step: bool = False, + ts_schedule: bool = False, + ts_schedule_max: bool = False, + min_score_timestep: int = 0, + num_train_timestep: int = 1000, + timestep_shift: float = 1, + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + fake_guidance_scale: float = 0.0, + real_guidance_scale: float = 3.0, + num_critic_input_frames: int = 21, + num_rollout_sections: int = 3, + is_skip_first_section: bool = False, + is_amplify_first_chunk: bool = False, + # For Easy Anti-Drifting + is_corrupt_history_latents: bool = False, + is_add_saturation: bool = False, + # For GT History + is_use_gt_history: bool = False, + gt_history_latents: torch.Tensor = None, + gt_target_latents: torch.Tensor = None, + gt_x0_latents: torch.Tensor = None, + # For VAE Re-Encode + vae=None, + is_dmd_vae_decode: bool = False, + # For Multi Stage Backward Simulated + is_multi_pyramid_stage_backward_simulated: bool = False, + # For Consistency Align + is_consistency_align: bool = False, + consistentcy_align_weight: float = 0.25, + # For Smoothness + is_smoothness_loss: bool = False, + smoothness_loss_weight: float = 1e-2, + # For KV Cache + use_kv_cache: bool = True, + # For Mean-Variance Regularization + is_mean_var_regular: bool = False, + mean_var_regular_weight: float = 1.0, + regular_mean: float = 0.00657021, + regular_var: float = 0.85126512, + is_x0_mean_var_regular: bool = False, + mean_var_regular_x0_weight: float = 1.0, + regular_x0_mean: float = -0.01618061, + regular_x0_var: float = 0.27996052, + # + is_chunk_mean_var_regular: bool = False, + chunk_mean_var_regular_weight: float = 1.0, + chunk_regular_mean: float = 0.01906107, + chunk_regular_var: float = 0.81397036, + is_chunk_x0_mean_var_regular: bool = False, + chunk_mean_var_regular_x0_weight: float = 1.0, + chunk_regular_x0_mean: float = -0.01578601, + chunk_regular_x0_var: float = 0.29913200, + # For GAN + is_use_gan: bool = False, + is_gan_low_vram_mode: bool = False, + gan_prompt_embeds: torch.Tensor = None, + gan_g_weight: float = 1e-2, + # For Reward + is_use_reward_model: bool = False, + reward_model=None, + reward_weight_vq: float = 1.0, + reward_weight_mq: float = 1.0, + reward_weight_ta: float = 1.0, + reward_texts: Optional[List[str]] = None, + # For Decouple DMD + is_decouple_dmd: bool = False, + decouple_ca_start_step: int = 2000, + decouple_ca_end_step: int = 3000, + # For Dynamic Timestep + is_forcing_low_renoise: bool = False, + dynamic_alpha: float = 4.0, + dynamic_beta: float = 1.5, + dynamic_sample_type: str = "uniform", + global_step: int = 0, + dynamic_step: int = 1000, +): + if is_use_gt_history: + assert gan_prompt_embeds is not None + prompt_embeds = gan_prompt_embeds + + if dmd_is_low_vram_mode: + vram_manager.move_to_cpu(real_fake_score_model) + if (is_smoothness_loss or is_dmd_vae_decode) and vae is not None: + vram_manager.move_to_cpu(vae) + if is_use_reward_model: + vram_manager.move_to_cpu(reward_model.model) + vram_manager.move_to_gpu(transformer, accelerator.device) + + init_pyramid_stage_flag = None + if is_multi_pyramid_stage_backward_simulated: + assert is_multi_pyramid_stage_backward_simulated, ( + "use_dynamic_shifting must be True when is_multi_pyramid_stage_backward_simulated is True" + ) + init_pyramid_stage_flag = random.randint(0, stage2_num_stages - 1) + + # Prepare all sigmas and timesteps + sigmas = torch.linspace( + 1.0, 1.0 / num_train_timestep, num_train_timestep, device=accelerator.device, dtype=torch.float64 + ) + if use_dynamic_shifting: + base_height, base_width = noise.shape[-2:] + if is_multi_pyramid_stage_backward_simulated: + divisor = 2 ** (stage2_num_stages - 1 - init_pyramid_stage_flag) + temp_height, temp_width = base_height // divisor, base_width // divisor + temp_tenosr = torch.randn(1, 16, num_critic_input_frames, temp_height, temp_width) + else: + temp_tenosr = torch.randn(1, 16, num_critic_input_frames, base_height, base_width) + + sigmas, timestep_shift = apply_schedule_shift( + sigmas, + temp_tenosr, + base_seq_len=args.training_config.base_seq_len, + max_seq_len=args.training_config.max_seq_len, + base_shift=args.training_config.base_shift, + max_shift=args.training_config.max_shift, + time_shift_type=time_shift_type, + return_mu=True, + ) + elif timestep_shift > 1: + sigmas = timestep_shift * sigmas / (1 + (timestep_shift - 1) * sigmas) + timesteps = sigmas * num_train_timestep + + gt_all_data = None + if is_use_gt_history: + latent_window_size = noise.shape[2] + ( + _, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + ) = prepare_stage1_clean_input_from_latents( + history_latents=gt_history_latents, + target_latents=gt_target_latents, + x0_latents=gt_x0_latents, + latent_window_size=latent_window_size, + history_sizes=history_sizes, + is_random_drop=args.training_config.is_random_drop, + random_drop_i2v_ratio=args.training_config.random_drop_i2v_ratio, + random_drop_v2v_ratio=args.training_config.random_drop_v2v_ratio, + random_drop_t2v_ratio=args.training_config.random_drop_t2v_ratio, + is_keep_x0=True, + dtype=noise.dtype, + device=accelerator.device, + ) + history_latents = torch.cat( + [latents_history_long, latents_history_mid, latents_history_short[:, :, 1:]], dim=2 + ) + latents_history_short, latents_history_mid, latents_history_long = corrupt_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=True, + # choose mode + corrupt_mode=args.training_config.corrupt_mode_history, + noise_mode_prob=args.training_config.corrupt_mode_prob_history, + # for noise + is_frame_independent=args.training_config.is_frame_independent_corrupt_history, + is_chunk_independent=args.training_config.is_chunk_independent_corrupt_history, + corrupt_ratio_1x=args.training_config.noise_corrupt_ratio_history_short, + corrupt_ratio_2x=args.training_config.noise_corrupt_ratio_history_mid, + corrupt_ratio_4x=args.training_config.noise_corrupt_ratio_history_long, + noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_history, + # for downsample + downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_history, + downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_history, + ) + gt_all_data = ( + _, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + history_latents, + ) + assert num_critic_input_frames == latent_window_size + assert num_rollout_sections == 1 + assert not is_smoothness_loss and not is_dmd_vae_decode + + # Step 1: Unroll generator to obtain fake videos + pred_image_or_video, gradient_mask, denoised_timestep_from, denoised_timestep_to, consistency_align_loss = ( + run_generator( + args=args, + accelerator=accelerator, + transformer=transformer, + scheduler=scheduler, + noise=noise, + prompt_embeds=prompt_embeds, + # For VRAM manager + dmd_is_low_vram_mode=dmd_is_low_vram_mode, + # For Stage 1 + is_keep_x0=is_keep_x0, + history_sizes=history_sizes, + # For Stage 2 + is_enable_stage2=is_enable_stage2, + stage2_num_stages=stage2_num_stages, + stage2_num_inference_steps_list=stage2_num_inference_steps_list, + # For DMD Main + denoising_step_list=denoising_step_list, + last_step_only=last_step_only, + last_section_grad_only=last_section_grad_only, + return_sim_step=return_sim_step, + sigmas=sigmas, + timesteps=timesteps, + timestep_shift=timestep_shift, + use_dynamic_shifting=use_dynamic_shifting, + time_shift_type=time_shift_type, + num_critic_input_frames=num_critic_input_frames, + num_rollout_sections=num_rollout_sections, + is_skip_first_section=is_skip_first_section, + is_amplify_first_chunk=is_amplify_first_chunk, + # Easy Anti-Drifting + is_corrupt_history_latents=is_corrupt_history_latents, + is_add_saturation=is_add_saturation, + # GT History + is_use_gt_history=is_use_gt_history, + gt_all_data=gt_all_data, + # For VAE Re-Encode + is_dmd_vae_decode=is_dmd_vae_decode, + # For Multi Stage Backward Simulated + is_multi_pyramid_stage_backward_simulated=is_multi_pyramid_stage_backward_simulated, + init_pyramid_stage_flag=init_pyramid_stage_flag, + # Consistency Align + is_consistency_align=is_consistency_align, + # KV Cache + use_kv_cache=use_kv_cache, + ) + ) + + if dmd_is_low_vram_mode: + vram_manager.move_to_cpu(transformer, offload_grad=dmd_is_offload_grad) + + # Step 2: Compute the Smoothness loss + selected_frames = None + smooth_count = 0 + smoothness_loss = torch.tensor(0.0, device=pred_image_or_video.device) + if is_smoothness_loss or is_dmd_vae_decode: + if dmd_is_low_vram_mode: + vram_manager.move_to_gpu(vae, accelerator.device) + else: + vae.to(accelerator.device) + vae.requires_grad_(False) + vae.eval() + + latents_mean = ( + torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(vae.device, vae.dtype) + ) + latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to( + vae.device, vae.dtype + ) + + latent_window_size = noise.shape[2] + assert pred_image_or_video.shape[2] % latent_window_size == 0 + num_sections = math.ceil(pred_image_or_video.shape[2] / latent_window_size) + + total_frame_latent = [] + prev_last_frame_latent = None + for i in range(num_sections): + start_idx = i * latent_window_size + end_idx = min((i + 1) * latent_window_size, pred_image_or_video.shape[2]) + cur_section = pred_image_or_video[:, :, start_idx:end_idx, :, :] + + if is_smoothness_loss: + cur_first_frame_latent = cur_section[:, :, :1, :, :].clone() + + if prev_last_frame_latent is not None: + prev_lat = prev_last_frame_latent.double() + cur_lat = cur_first_frame_latent.double() + + mse_loss = 0.5 * F.mse_loss(prev_lat, cur_lat, reduction="mean") + smoothness_loss += mse_loss + smooth_count += 1 + + with torch.no_grad(): + decoded = vae.decode(cur_section.to(vae.dtype) / latents_std + latents_mean, return_dict=False)[0] + + if is_dmd_vae_decode: + total_frame_latent.append(decoded) + + if is_smoothness_loss: + with torch.no_grad(): + prev_last_frame_latent = ( + vae.encode(decoded[:, :, -1:, :, :].to(vae.dtype)).latent_dist.sample() - latents_mean + ) * latents_std + + del prev_last_frame_latent + free_memory() + + if is_dmd_vae_decode: + num_rgb_frames = (num_critic_input_frames - 1) * 4 + 1 + combined_frames = torch.cat(total_frame_latent, dim=2).to(vae.device, dtype=vae.dtype) + + begin_flag = random.random() < 0.5 + if begin_flag: + selected_frames = combined_frames[:, :, :num_rgb_frames, :, :] + else: + selected_frames = combined_frames[:, :, -num_rgb_frames:, :, :] + + with torch.no_grad(): + reconstructed_latent = vae.encode(selected_frames).latent_dist.sample() + reconstructed_latent = (reconstructed_latent - latents_mean) * latents_std + + # Straight-Through Estimator + if begin_flag: + pred_image_or_video = ( + pred_image_or_video[:, :, :num_critic_input_frames, :, :] + + (reconstructed_latent - pred_image_or_video[:, :, :num_critic_input_frames, :, :]).detach() + ) + else: + pred_image_or_video = ( + pred_image_or_video[:, :, -num_critic_input_frames:, :, :] + + (reconstructed_latent - pred_image_or_video[:, :, -num_critic_input_frames:, :, :]).detach() + ) + + if smooth_count > 1: + smoothness_loss = smoothness_loss / smooth_count + + if dmd_is_low_vram_mode: + vram_manager.move_to_cpu(vae) + + # Step 3: Compute the Reward score + if is_use_reward_model: + if dmd_is_low_vram_mode: + vram_manager.move_to_gpu(reward_model.model, accelerator.device) + + processed_frames = ((selected_frames + 1) * 127.5).clamp(0, 255).to(torch.uint8).permute(0, 2, 1, 3, 4) + processed_frames = list(processed_frames) + + with torch.no_grad(): + reward = reward_model.reward( + videos=processed_frames, + prompts=reward_texts, + use_norm=True, + return_batch_score=True, + device=accelerator.device, + dtype=torch.float32, + ) + + if dmd_is_low_vram_mode: + vram_manager.move_to_cpu(reward_model.model) + + processed_frames = None + del processed_frames + + # Step 4: Compute the DMD loss + if dmd_is_low_vram_mode: + vram_manager.move_to_gpu(real_fake_score_model, accelerator.device) + + dmd_loss, ca_dmd_loss, dm_dmd_loss, gan_G_loss, dmd_log_dict = compute_distribution_matching_loss( + accelerator, + scheduler, + real_fake_score_model, + image_or_video=pred_image_or_video, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + # For VRAM manager + dmd_is_low_vram_mode=dmd_is_low_vram_mode, + vram_manager=vram_manager, + is_gan_low_vram_mode=is_gan_low_vram_mode, + # For Stage 2 + is_enable_stage2=is_enable_stage2, + # For DMD Main + gradient_mask=gradient_mask, + denoised_timestep_from=denoised_timestep_from, + denoised_timestep_to=denoised_timestep_to, + ts_schedule=ts_schedule, + ts_schedule_max=ts_schedule_max, + min_score_timestep=min_score_timestep, + num_train_timestep=num_train_timestep, + sigmas=sigmas, + timesteps=timesteps, + timestep_shift=timestep_shift, + fake_guidance_scale=fake_guidance_scale, + real_guidance_scale=real_guidance_scale, + # For GT History + is_use_gt_history=is_use_gt_history, + gt_all_data=gt_all_data, + # For GAN + is_use_gan=is_use_gan, + # For Decouple DMD + is_decouple_dmd=is_decouple_dmd, + decouple_ca_start_step=decouple_ca_start_step, + decouple_ca_end_step=decouple_ca_end_step, + # For Dynamic Timestep + is_forcing_low_renoise=is_forcing_low_renoise, + dynamic_alpha=dynamic_alpha, + dynamic_beta=dynamic_beta, + dynamic_sample_type=dynamic_sample_type, + global_step=global_step, + dynamic_step=dynamic_step, + ) + + if dmd_is_low_vram_mode: + vram_manager.move_to_cpu(real_fake_score_model) + vram_manager.move_to_gpu(transformer, accelerator.device, load_grad=dmd_is_offload_grad) + + if is_smoothness_loss or is_use_gan or is_use_reward_model or is_consistency_align: + dmd_log_dict["dmd_loss_raw"] = dmd_loss.detach().item() + + if is_consistency_align: + if consistency_align_loss != 0: + assert consistency_align_loss.requires_grad, ( + f"Consistentcy Align loss should have gradient! Got {consistency_align_loss.requires_grad}" + ) + assert consistency_align_loss.grad_fn is not None, "Consistentcy Align loss should have grad_fn!" + consistency_align_loss = consistency_align_loss * consistentcy_align_weight + dmd_log_dict["consistency_align_loss"] = consistency_align_loss.detach().item() + dmd_loss = dmd_loss + consistency_align_loss + + if is_smoothness_loss: + assert smoothness_loss.requires_grad, ( + f"Smoothness loss should have gradient! Got {smoothness_loss.requires_grad}" + ) + assert smoothness_loss.grad_fn is not None, "Smoothness loss should have grad_fn!" + smoothness_loss = smoothness_loss * smoothness_loss_weight + dmd_log_dict["smoothness_loss"] = smoothness_loss.detach().item() + dmd_loss = dmd_loss + smoothness_loss + + if is_mean_var_regular: + latent_window_size = noise.shape[2] + dims = list(range(1, pred_image_or_video.ndim)) + + pred_mean = pred_image_or_video.mean(dim=dims) + pred_variance = pred_image_or_video.var(dim=dims, unbiased=False) + pred_variance = pred_variance.clamp(min=1e-6) + + kl_mean_var_loss = ( + 0.5 + * ( + pred_variance / regular_var + + (pred_mean - regular_mean) ** 2 / regular_var + - 1.0 + - torch.log(pred_variance / regular_var) + ).mean() + ) + + kl_mean_var_loss = kl_mean_var_loss * mean_var_regular_weight + dmd_log_dict["kl_mean_var_loss"] = kl_mean_var_loss.detach().item() + dmd_log_dict["pred_mean_avg"] = pred_mean.mean().detach().item() + dmd_log_dict["pred_var_avg"] = pred_variance.mean().detach().item() + + if is_x0_mean_var_regular: + x0 = pred_image_or_video[:, :, :1, :, :] + pred_x0_mean = x0.mean(dim=dims) + pred_x0_variance = x0.var(dim=dims, unbiased=False) + pred_x0_variance = pred_x0_variance.clamp(min=1e-6) + + kl_mean_var_x0_loss = ( + 0.5 + * ( + pred_x0_variance / regular_x0_var + + (pred_x0_mean - regular_x0_mean) ** 2 / regular_x0_var + - 1.0 + - torch.log(pred_x0_variance / regular_x0_var) + ).mean() + ) + + if is_x0_mean_var_regular: + kl_mean_var_x0_loss = kl_mean_var_x0_loss * mean_var_regular_x0_weight + dmd_log_dict["kl_mean_var_x0_loss"] = kl_mean_var_x0_loss.detach().item() + dmd_log_dict["pred_x0_mean_avg"] = pred_x0_mean.mean().detach().item() + dmd_log_dict["pred_x0_var_avg"] = pred_x0_variance.mean().detach().item() + kl_mean_var_loss = 0.7 * kl_mean_var_loss + 0.3 * kl_mean_var_x0_loss + + dmd_loss = dmd_loss + kl_mean_var_loss + assert kl_mean_var_loss != 0, "kl_mean_var_loss should be non-zero when there are valid sections" + assert kl_mean_var_loss.requires_grad, ( + f"kl_mean_var_loss should have gradient! Got {kl_mean_var_loss.requires_grad}" + ) + assert kl_mean_var_loss.grad_fn is not None, "kl_mean_var_loss should have grad_fn!" + + if is_chunk_mean_var_regular: + latent_window_size = noise.shape[2] + num_sections = math.ceil(pred_image_or_video.shape[2] / latent_window_size) + + kl_chunk_mean_var_loss = 0 + total_chunk_pred_mean = 0 + total_chunk_pred_var = 0 + valid_sections_count = 0 + + if is_chunk_x0_mean_var_regular: + kl_chunk_mean_var_x0_loss = 0 + total_pred_x0_mean = 0 + total_pred_x0_var = 0 + + for i in range(num_sections): + start_idx = i * latent_window_size + end_idx = min((i + 1) * latent_window_size, pred_image_or_video.shape[2]) + + cur_section = pred_image_or_video[:, :, start_idx:end_idx, :, :] + + if cur_section.shape[2] >= latent_window_size: + dims = list(range(1, cur_section.ndim)) + pred_mean = cur_section.mean(dim=dims) + pred_variance = cur_section.var(dim=dims, unbiased=False) + pred_variance = pred_variance.clamp(min=1e-6) + + section_kl_loss = 0.5 * ( + pred_variance / chunk_regular_var + + (pred_mean - chunk_regular_mean) ** 2 / chunk_regular_var + - 1.0 + - torch.log(pred_variance / chunk_regular_var) + ) + kl_chunk_mean_var_loss += section_kl_loss.mean() + total_chunk_pred_mean += pred_mean.mean().item() + total_chunk_pred_var += pred_variance.mean().item() + valid_sections_count += 1 + + if is_chunk_x0_mean_var_regular: + x0_cur_section = cur_section[:, :, :1, :, :] + pred_x0_mean = x0_cur_section.mean(dim=dims) + pred_x0_variance = x0_cur_section.var(dim=dims, unbiased=False) + pred_x0_variance = pred_x0_variance.clamp(min=1e-6) + + section_x0_kl_loss = 0.5 * ( + pred_x0_variance / chunk_regular_x0_var + + (pred_x0_mean - chunk_regular_x0_mean) ** 2 / chunk_regular_x0_var + - 1.0 + - torch.log(pred_x0_variance / chunk_regular_x0_var) + ) + kl_chunk_mean_var_x0_loss += section_x0_kl_loss.mean() + total_pred_x0_mean += pred_x0_mean.mean().item() + total_pred_x0_var += pred_x0_variance.mean().item() + + if valid_sections_count > 0: + kl_chunk_mean_var_loss = (kl_chunk_mean_var_loss / valid_sections_count) * chunk_mean_var_regular_weight + dmd_log_dict["kl_chunk_mean_var_loss"] = kl_chunk_mean_var_loss.detach().item() + dmd_log_dict["pred_chunk_mean_avg"] = total_chunk_pred_mean / valid_sections_count + dmd_log_dict["pred_chunk_var_avg"] = total_chunk_pred_var / valid_sections_count + else: + kl_chunk_mean_var_loss = 0 + dmd_log_dict["kl_chunk_mean_var_loss"] = 0 + dmd_log_dict["pred_chunk_mean_avg"] = 0 + dmd_log_dict["pred_chunk_var_avg"] = 0 + + if is_chunk_x0_mean_var_regular: + kl_chunk_mean_var_x0_loss = (kl_chunk_mean_var_x0_loss / num_sections) * chunk_mean_var_regular_x0_weight + + if valid_sections_count > 0: + kl_chunk_mean_var_loss = 0.7 * kl_chunk_mean_var_loss + 0.3 * kl_chunk_mean_var_x0_loss + else: + kl_chunk_mean_var_loss = kl_chunk_mean_var_x0_loss + + dmd_log_dict["kl_chunk_mean_var_x0_loss"] = kl_chunk_mean_var_x0_loss.detach().item() + dmd_log_dict["pred_chunk_x0_mean_avg"] = total_pred_x0_mean / num_sections + dmd_log_dict["pred_chunk_x0_var_avg"] = total_pred_x0_var / num_sections + + dmd_loss = dmd_loss + kl_chunk_mean_var_loss + assert kl_chunk_mean_var_loss != 0, "kl_chunk_mean_var_loss should be non-zero when there are valid sections" + assert kl_chunk_mean_var_loss.requires_grad, ( + f"kl_chunk_mean_var_loss should have gradient! Got {kl_chunk_mean_var_loss.requires_grad}" + ) + assert kl_chunk_mean_var_loss.grad_fn is not None, "kl_chunk_mean_var_loss should have grad_fn!" + + if is_use_gan: + assert gan_G_loss.requires_grad, f"GAN G loss should have gradient! Got {gan_G_loss.requires_grad}" + assert gan_G_loss.grad_fn is not None, "GAN G loss should have grad_fn!" + gan_G_loss = gan_G_loss * gan_g_weight + dmd_log_dict["gan_G_loss"] = gan_G_loss.detach().item() + dmd_loss = dmd_loss + gan_G_loss + + if is_use_reward_model: + reward_scores = [] + if reward_weight_vq != 0: + reward_score_vq = reward_weight_vq * reward["VQ"].clamp(-5.0, 5.0) + reward_scores.append(reward_score_vq) + dmd_log_dict["reward_score_vq"] = reward["VQ"].detach().mean().item() + assert not reward_score_vq.requires_grad, ( + f"Reward Score VQ should not have gradient! Got {reward_score_vq.requires_grad}" + ) + else: + dmd_log_dict["reward_score_vq"] = 0 + + if reward_weight_mq != 0: + reward_score_mq = reward_weight_mq * reward["MQ"].clamp(-5.0, 5.0) + reward_scores.append(reward_score_mq) + dmd_log_dict["reward_score_mq"] = reward["MQ"].detach().mean().item() + assert not reward_score_mq.requires_grad, ( + f"Reward Score MQ should not have gradient! Got {reward_score_mq.requires_grad}" + ) + else: + dmd_log_dict["reward_score_mq"] = 0 + + if reward_weight_ta != 0: + reward_score_ta = reward_weight_ta * reward["TA"].clamp(-5.0, 5.0) + reward_scores.append(reward_score_ta) + dmd_log_dict["reward_score_ta"] = reward["TA"].detach().mean().item() + assert not reward_score_ta.requires_grad, ( + f"Reward Score TA should not have gradient! Got {reward_score_ta.requires_grad}" + ) + else: + dmd_log_dict["reward_score_ta"] = 0 + + reward_score = torch.stack(reward_scores).mean() + reward_score = torch.exp(reward_score) + + dmd_loss = dmd_loss * reward_score + + if is_decouple_dmd: + assert ca_dmd_loss.requires_grad, f"CA DMD loss should have gradient! Got {ca_dmd_loss.requires_grad}" + assert dm_dmd_loss.requires_grad, f"DM DMD loss should have gradient! Got {dm_dmd_loss.requires_grad}" + assert ca_dmd_loss.grad_fn is not None, "CA DMD loss should have grad_fn!" + assert dm_dmd_loss.grad_fn is not None, "DM DMD loss should have grad_fn!" + dmd_log_dict["ca_dmd_loss"] = ca_dmd_loss.detach().item() + dmd_log_dict["dm_dmd_loss"] = dm_dmd_loss.detach().item() + + assert dmd_loss.requires_grad, f"Final DMD loss should have gradient! Got {dmd_loss.requires_grad}" + assert dmd_loss.grad_fn is not None, "Final DMD loss should have grad_fn!" + + return dmd_loss, dmd_log_dict + + +# ======================================== Critic Loss ======================================== + + +def _critic_loss( + args, + critic_accelerator, + fake_score_model, + transformer, + scheduler, + noise, + prompt_embeds, + # For VRAM manager + dmd_is_low_vram_mode: bool = False, + vram_manager: OptimizedLowVRAMManager = None, + is_gan_low_vram_mode: bool = False, + # For Stage 1 + is_keep_x0: bool = True, + history_sizes: list = [16, 2, 1], + # For Stage 2 + is_enable_stage2: bool = False, + stage2_num_stages: int = None, + stage2_num_inference_steps_list: list = None, + # For DMD Main + denoising_step_list: list = None, + last_step_only: bool = False, + last_section_grad_only: bool = False, + return_sim_step: bool = False, + ts_schedule: bool = False, + ts_schedule_max: bool = False, + min_score_timestep: int = 0, + num_train_timestep: int = 1000, + timestep_shift: float = 1.0, + use_dynamic_shifting: bool = False, + time_shift_type: Literal["exponential", "linear"] = "linear", + num_critic_input_frames: int = 21, + num_rollout_sections: int = 3, + is_skip_first_section: bool = False, + is_amplify_first_chunk: bool = False, + # For Easy Anti-Drifting + is_corrupt_history_latents: bool = False, + is_add_saturation: bool = False, + # For GT History + is_use_gt_history: bool = False, + gt_history_latents: torch.Tensor = None, + gt_target_latents: torch.Tensor = None, + gt_x0_latents: torch.Tensor = None, + # For VAE Re-Encode + vae=None, + is_dmd_vae_decode: bool = False, + # For Multi Stage Backward Simulated + is_multi_pyramid_stage_backward_simulated: bool = False, + # For KV Cache + use_kv_cache: bool = True, + # For GAN + is_use_gan: bool = False, + is_separate_gan_grad: bool = False, + gan_base_critic_trainable_params: dict = None, + gan_extra_critic_trainable_params: dict = None, + gan_vae_latents: torch.Tensor = None, + gan_prompt_embeds: torch.Tensor = None, + gan_d_weight: float = 1e-2, + aprox_r1: bool = False, + aprox_r2: bool = False, + r1_weight: float = 0.0, + r2_weight: float = 0.0, + r1_sigma: float = 0.01, + r2_sigma: float = 0.01, + # For Dynamic Timestep + dynamic_alpha: float = 4.0, + dynamic_beta: float = 1.5, + dynamic_sample_type: str = "uniform", + global_step: int = 0, + dynamic_step: int = 1000, +): + if is_use_gt_history: + assert gan_prompt_embeds is not None + prompt_embeds = gan_prompt_embeds + + if dmd_is_low_vram_mode: + vram_manager.move_to_cpu(fake_score_model) + if is_dmd_vae_decode: + vram_manager.move_to_cpu(vae) + vram_manager.move_to_gpu(transformer, critic_accelerator.device) + + init_pyramid_stage_flag = None + if is_multi_pyramid_stage_backward_simulated: + assert is_multi_pyramid_stage_backward_simulated, ( + "use_dynamic_shifting must be True when is_multi_pyramid_stage_backward_simulated is True" + ) + init_pyramid_stage_flag = random.randint(0, stage2_num_stages - 1) + + # Prepare all sigmas and timesteps + sigmas = torch.linspace( + 1.0, 1.0 / num_train_timestep, num_train_timestep, device=critic_accelerator.device, dtype=torch.float64 + ) + if use_dynamic_shifting: + base_height, base_width = noise.shape[-2:] + if is_multi_pyramid_stage_backward_simulated: + divisor = 2 ** (stage2_num_stages - 1 - init_pyramid_stage_flag) + temp_height, temp_width = base_height // divisor, base_width // divisor + temp_tenosr = torch.randn(1, 16, num_critic_input_frames, temp_height, temp_width) + else: + temp_tenosr = torch.randn(1, 16, num_critic_input_frames, base_height, base_width) + + sigmas, timestep_shift = apply_schedule_shift( + sigmas, + temp_tenosr, + base_seq_len=args.training_config.base_seq_len, + max_seq_len=args.training_config.max_seq_len, + base_shift=args.training_config.base_shift, + max_shift=args.training_config.max_shift, + time_shift_type=time_shift_type, + return_mu=True, + ) + elif timestep_shift > 1: + sigmas = timestep_shift * sigmas / (1 + (timestep_shift - 1) * sigmas) + timesteps = sigmas * num_train_timestep + + noise = torch.randn(noise.shape, device=critic_accelerator.device, dtype=noise.dtype) + batch_size = noise.shape[0] + + if is_use_gt_history: + latent_window_size = noise.shape[2] + ( + _, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + ) = prepare_stage1_clean_input_from_latents( + history_latents=gt_history_latents, + target_latents=gt_target_latents, + x0_latents=gt_x0_latents, + latent_window_size=latent_window_size, + history_sizes=history_sizes, + is_random_drop=args.training_config.is_random_drop, + random_drop_i2v_ratio=args.training_config.random_drop_i2v_ratio, + random_drop_v2v_ratio=args.training_config.random_drop_v2v_ratio, + random_drop_t2v_ratio=args.training_config.random_drop_t2v_ratio, + is_keep_x0=True, + dtype=noise.dtype, + device=critic_accelerator.device, + ) + history_latents = torch.cat( + [latents_history_long, latents_history_mid, latents_history_short[:, :, 1:]], dim=2 + ) + latents_history_short, latents_history_mid, latents_history_long = corrupt_history_latents( + latents_history_short, + latents_history_mid, + latents_history_long, + latent_window_size, + is_keep_x0=True, + # choose mode + corrupt_mode=args.training_config.corrupt_mode_history, + noise_mode_prob=args.training_config.corrupt_mode_prob_history, + # for noise + is_frame_independent=args.training_config.is_frame_independent_corrupt_history, + is_chunk_independent=args.training_config.is_chunk_independent_corrupt_history, + corrupt_ratio_1x=args.training_config.noise_corrupt_ratio_history_short, + corrupt_ratio_2x=args.training_config.noise_corrupt_ratio_history_mid, + corrupt_ratio_4x=args.training_config.noise_corrupt_ratio_history_long, + noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_history, + # for downsample + downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_history, + downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_history, + ) + gt_all_data = ( + _, + indices_hidden_states, + indices_latents_history_short, + indices_latents_history_mid, + indices_latents_history_long, + latents_history_short, + latents_history_mid, + latents_history_long, + history_latents, + ) + assert num_critic_input_frames == latent_window_size + assert num_rollout_sections == 1 + assert not is_dmd_vae_decode + else: + gt_all_data = None + indices_hidden_states = None + indices_latents_history_short = None + indices_latents_history_mid = None + indices_latents_history_long = None + latents_history_short = None + latents_history_mid = None + latents_history_long = None + + # Step 1: Run generator on backward simulated noisy input + with torch.no_grad(): + generated_image_or_video, _, denoised_timestep_from, denoised_timestep_to, _ = run_generator( + args=args, + accelerator=critic_accelerator, + transformer=transformer, + scheduler=scheduler, + noise=noise, + prompt_embeds=prompt_embeds, + # For VRAM manager + dmd_is_low_vram_mode=dmd_is_low_vram_mode, + # For Stage 1 + is_keep_x0=is_keep_x0, + history_sizes=history_sizes, + # For Stage 2 + is_enable_stage2=is_enable_stage2, + stage2_num_stages=stage2_num_stages, + stage2_num_inference_steps_list=stage2_num_inference_steps_list, + # For DMD Main + denoising_step_list=denoising_step_list, + last_step_only=last_step_only, + last_section_grad_only=last_section_grad_only, + return_sim_step=return_sim_step, + sigmas=sigmas, + timesteps=timesteps, + timestep_shift=timestep_shift, + use_dynamic_shifting=use_dynamic_shifting, + time_shift_type=time_shift_type, + num_critic_input_frames=num_critic_input_frames, + num_rollout_sections=num_rollout_sections, + is_skip_first_section=is_skip_first_section, + is_amplify_first_chunk=is_amplify_first_chunk, + # Easy Anti-Drifting + is_corrupt_history_latents=is_corrupt_history_latents, + is_add_saturation=is_add_saturation, + # GT History + is_use_gt_history=is_use_gt_history, + gt_all_data=gt_all_data, + # For VAE Re-Encode + is_dmd_vae_decode=is_dmd_vae_decode, + # For Multi Stage Backward Simulated + is_multi_pyramid_stage_backward_simulated=is_multi_pyramid_stage_backward_simulated, + init_pyramid_stage_flag=init_pyramid_stage_flag, + # KV Cache + use_kv_cache=use_kv_cache, + ) + + if dmd_is_low_vram_mode: + vram_manager.move_to_cpu(transformer) + + # Step 2: Compute the Smoothness loss + if is_dmd_vae_decode: + if dmd_is_low_vram_mode: + vram_manager.move_to_gpu(vae, critic_accelerator.device) + else: + vae.to(critic_accelerator.device) + vae.requires_grad_(False) + vae.eval() + + latents_mean = ( + torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(vae.device, vae.dtype) + ) + latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to( + vae.device, vae.dtype + ) + + latent_window_size = noise.shape[2] + assert generated_image_or_video.shape[2] % latent_window_size == 0 + num_sections = math.ceil(generated_image_or_video.shape[2] / latent_window_size) + total_frame_latent = [] + for i in range(num_sections): + start_idx = i * latent_window_size + end_idx = min((i + 1) * latent_window_size, generated_image_or_video.shape[2]) + cur_section = generated_image_or_video[:, :, start_idx:end_idx, :, :] + + with torch.no_grad(): + decoded = vae.decode(cur_section.to(vae.dtype) / latents_std + latents_mean, return_dict=False)[0] + total_frame_latent.append(decoded) + + num_rgb_frames = (num_critic_input_frames - 1) * 4 + 1 + combined_frames = torch.cat(total_frame_latent, dim=2).to(vae.device, dtype=vae.dtype) + + max_start_idx = combined_frames.shape[2] - num_rgb_frames + start_idx = random.randint(0, max_start_idx) + selected_frames = combined_frames[:, :, start_idx : start_idx + num_rgb_frames, :, :] + + with torch.no_grad(): + reconstructed_latent = vae.encode(selected_frames).latent_dist.sample() + reconstructed_latent = (reconstructed_latent - latents_mean) * latents_std + + generated_image_or_video = reconstructed_latent + + if dmd_is_low_vram_mode: + vram_manager.move_to_cpu(vae) + + free_memory() + + # Step 3: Compute the fake prediction + if dmd_is_low_vram_mode: + vram_manager.move_to_gpu(fake_score_model, critic_accelerator.device) + + min_timestep = denoised_timestep_to if ts_schedule and denoised_timestep_to is not None else min_score_timestep + max_timestep = ( + denoised_timestep_from if ts_schedule_max and denoised_timestep_from is not None else num_train_timestep + ) + min_step = int(0.02 * num_train_timestep) + max_step = int(0.98 * num_train_timestep) + + critic_timestep = sample_dynamic_timestep( + B=batch_size, + num_train_timestep=num_train_timestep, + min_timestep=min_timestep, + max_timestep=max_timestep, + min_step=min_step, + max_step=max_step, + timestep_shift=timestep_shift, + dynamic_alpha=dynamic_alpha, + dynamic_beta=dynamic_beta, + dynamic_sample_type=dynamic_sample_type, + global_step=global_step, + dynamic_step=dynamic_step, + device=critic_accelerator.device, + ) + + critic_noise = torch.randn_like(generated_image_or_video, device=critic_accelerator.device, dtype=noise.dtype) + noisy_fake_latent = add_noise( + generated_image_or_video, + critic_noise, + critic_timestep, + sigmas, + timesteps, + ) + + gan_D_loss = torch.tensor(0.0) + r1_loss = torch.tensor(0.0) + r2_loss = torch.tensor(0.0) + if is_use_gan: + if gan_prompt_embeds is None: + gan_prompt_embeds = prompt_embeds + + if is_gan_low_vram_mode: + if is_separate_gan_grad: + for name, param in fake_score_model.named_parameters(): + if name in gan_extra_critic_trainable_params: + param.requires_grad = False + + flow_fake_pred = fake_score_model( + hidden_states=noisy_fake_latent, + timestep=critic_timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + return_dict=False, + )[0] + denoising_loss = torch.mean( + (flow_fake_pred.float() - (critic_noise - generated_image_or_video).float()) ** 2 + ) + + assert denoising_loss.requires_grad, ( + f"Denoising loss should have gradient! Got {denoising_loss.requires_grad}" + ) + assert denoising_loss.grad_fn is not None, "Denoising loss should have grad_fn!" + critic_accelerator.backward(denoising_loss) + + if is_separate_gan_grad: + for name, param in fake_score_model.named_parameters(): + if name in gan_base_critic_trainable_params: + param.requires_grad = False + if name in gan_extra_critic_trainable_params: + param.requires_grad = True + + noisy_real_latent = add_noise( + gan_vae_latents, + critic_noise, + critic_timestep, + sigmas, + timesteps, + ) + hidden_states_list = [noisy_fake_latent, noisy_real_latent] + timestep_list = [critic_timestep, critic_timestep] + embeds_list = [prompt_embeds, gan_prompt_embeds] + + if is_use_gt_history: + indices_latents_list = [indices_hidden_states, indices_hidden_states] + indices_latents_history_short_list = [indices_latents_history_short, indices_latents_history_short] + indices_latents_history_mid_list = [indices_latents_history_mid, indices_latents_history_mid] + indices_latents_history_long_list = [indices_latents_history_long, indices_latents_history_long] + latents_history_short_list = [latents_history_short, latents_history_short] + latents_history_mid_list = [latents_history_mid, latents_history_mid] + latents_history_long_list = [latents_history_long, latents_history_long] + + # Prepare R1 perturbed input + r1_enabled = r1_weight > 0.0 + if r1_enabled: + noisy_real_latent_perturbed = noisy_real_latent.clone() + epsilon_real = r1_sigma * torch.randn_like(noisy_real_latent_perturbed) + noisy_real_latent_perturbed = noisy_real_latent_perturbed + epsilon_real + hidden_states_list.append(noisy_real_latent_perturbed) + timestep_list.append(critic_timestep) + embeds_list.append(gan_prompt_embeds) + if is_use_gt_history: + indices_latents_list.append(indices_hidden_states) + indices_latents_history_short_list.append(indices_latents_history_short) + indices_latents_history_mid_list.append(indices_latents_history_mid) + indices_latents_history_long_list.append(indices_latents_history_long) + latents_history_short_list.append(latents_history_short) + latents_history_mid_list.append(latents_history_mid) + latents_history_long_list.append(latents_history_long) + + # Prepare R2 perturbed input + r2_enabled = r2_weight > 0.0 + if r2_enabled: + noisy_fake_latent_perturbed = noisy_fake_latent.clone() + epsilon_generated = r2_sigma * torch.randn_like(noisy_fake_latent_perturbed) + noisy_fake_latent_perturbed = noisy_fake_latent_perturbed + epsilon_generated + hidden_states_list.append(noisy_fake_latent_perturbed) + timestep_list.append(critic_timestep) + embeds_list.append(prompt_embeds) + if is_use_gt_history: + indices_latents_list.append(indices_hidden_states) + indices_latents_history_short_list.append(indices_latents_history_short) + indices_latents_history_mid_list.append(indices_latents_history_mid) + indices_latents_history_long_list.append(indices_latents_history_long) + latents_history_short_list.append(latents_history_short) + latents_history_mid_list.append(latents_history_mid) + latents_history_long_list.append(latents_history_long) + + # Single forward pass for everything + hidden_states_list = [gan_crop_video_spatial(x) for x in hidden_states_list] + _, all_logits = fake_score_model( + hidden_states=torch.cat(hidden_states_list, dim=0), + timestep=torch.cat(timestep_list, dim=0), + encoder_hidden_states=torch.cat(embeds_list, dim=0), + indices_hidden_states=torch.cat(indices_latents_list, dim=0) if is_use_gt_history else None, + indices_latents_history_short=torch.cat(indices_latents_history_short_list, dim=0) + if is_use_gt_history + else None, + indices_latents_history_mid=torch.cat(indices_latents_history_mid_list, dim=0) + if is_use_gt_history + else None, + indices_latents_history_long=torch.cat(indices_latents_history_long_list, dim=0) + if is_use_gt_history + else None, + latents_history_short=torch.cat(latents_history_short_list, dim=0) if is_use_gt_history else None, + latents_history_mid=torch.cat(latents_history_mid_list, dim=0) if is_use_gt_history else None, + latents_history_long=torch.cat(latents_history_long_list, dim=0) if is_use_gt_history else None, + gan_mode=True, + return_dict=False, + ) + + # Split outputs + num_outputs = 2 + int(r1_enabled) + int(r2_enabled) + logits_split = all_logits.chunk(num_outputs, dim=0) + noisy_fake_logits = logits_split[0] + noisy_real_logits = logits_split[1] + + idx = 2 + if r1_enabled: + noisy_real_logit_perturbed = logits_split[idx] + idx += 1 + if r2_enabled: + noisy_fake_logit_perturbed = logits_split[idx] + + # Calculate GAN losses + gan_D_fake_loss = cal_gan_loss(noisy_fake_logits, -1) * gan_d_weight + gan_D_real_loss = cal_gan_loss(noisy_real_logits, 1) * gan_d_weight + gan_D_loss = gan_D_fake_loss.detach() + gan_D_real_loss.detach() + + assert gan_D_fake_loss.requires_grad + assert gan_D_fake_loss.grad_fn is not None + assert gan_D_real_loss.requires_grad + assert gan_D_real_loss.grad_fn is not None + + # Calculate regularization losses + total_regular_loss = None + + if r1_enabled: + if aprox_r1: + r1_loss = r1_weight * torch.nn.functional.mse_loss( + noisy_real_logits.float(), noisy_real_logit_perturbed.float(), reduction="mean" + ) + else: + r1_grad = (noisy_real_logit_perturbed.float() - noisy_real_logits.float()) / r1_sigma + r1_loss = r1_weight * torch.mean(r1_grad**2) + total_regular_loss = r1_loss + + if r2_enabled: + if aprox_r2: + r2_loss = r2_weight * torch.nn.functional.mse_loss( + noisy_fake_logits.float(), noisy_fake_logit_perturbed.float(), reduction="mean" + ) + else: + r2_grad = (noisy_fake_logit_perturbed.float() - noisy_fake_logits.float()) / r2_sigma + r2_loss = r2_weight * torch.mean(r2_grad**2) + total_regular_loss = r2_loss if total_regular_loss is None else total_regular_loss + r2_loss + + if total_regular_loss is not None: + assert total_regular_loss.requires_grad + assert total_regular_loss.grad_fn is not None + critic_accelerator.backward(total_regular_loss + gan_D_real_loss + gan_D_fake_loss) + else: + critic_accelerator.backward(gan_D_real_loss + gan_D_fake_loss) + + else: + raise NotImplementedError + noisy_real_latent = add_noise( + gan_vae_latents, + critic_noise, + critic_timestep, + sigmas, + timesteps, + ) + flow_preds, noisy_logits = fake_score_model( + hidden_states=torch.cat((noisy_fake_latent, noisy_real_latent), dim=0), + timestep=torch.cat((critic_timestep, critic_timestep), dim=0), + encoder_hidden_states=torch.cat((prompt_embeds, gan_prompt_embeds), dim=0), + gan_mode=True, + return_dict=False, + ) + flow_fake_pred, flow_real_pred = flow_preds.chunk(2, dim=0) + noisy_fake_logits, noisy_real_logits = noisy_logits.chunk(2, dim=0) + + denoising_loss = torch.mean( + (flow_fake_pred.float() - (critic_noise - generated_image_or_video).float()) ** 2 + ) + gan_D_loss = (cal_gan_loss(noisy_fake_logits, -1) + cal_gan_loss(noisy_real_logits, 1)) * gan_d_weight + + assert denoising_loss.requires_grad, ( + f"Denoising loss should have gradient! Got {denoising_loss.requires_grad}" + ) + assert gan_D_loss.requires_grad, f"GAN D loss should have gradient! Got {gan_D_loss.requires_grad}" + assert denoising_loss.grad_fn is not None, "Denoising loss should have grad_fn!" + assert gan_D_loss.grad_fn is not None, "GAN D loss should have grad_fn!" + + # R1 & R2 regularization + if r1_weight > 0.0 or r2_weight > 0.0: + perturbed_latents = [] + perturbed_timesteps = [] + perturbed_embeds = [] + + # Prepare R1 perturbed input + if r1_weight > 0.0: + noisy_real_latent_perturbed = noisy_real_latent.clone() + epsilon_real = r1_sigma * torch.randn_like(noisy_real_latent_perturbed) + noisy_real_latent_perturbed = noisy_real_latent_perturbed + epsilon_real + perturbed_latents.append(noisy_real_latent_perturbed) + perturbed_timesteps.append(critic_timestep) + perturbed_embeds.append(gan_prompt_embeds) + + # Prepare R2 perturbed input + if r2_weight > 0.0: + noisy_fake_latent_perturbed = noisy_fake_latent.clone() + epsilon_generated = r2_sigma * torch.randn_like(noisy_fake_latent_perturbed) + noisy_fake_latent_perturbed = noisy_fake_latent_perturbed + epsilon_generated + perturbed_latents.append(noisy_fake_latent_perturbed) + perturbed_timesteps.append(critic_timestep) + perturbed_embeds.append(prompt_embeds) + + # Batch forward pass + batched_latents = torch.cat(perturbed_latents, dim=0) + batched_timesteps = ( + torch.cat(perturbed_timesteps, dim=0) + if isinstance(critic_timestep, torch.Tensor) + else critic_timestep + ) + batched_embeds = torch.cat(perturbed_embeds, dim=0) + + _, batched_logits = fake_score_model( + hidden_states=batched_latents, + timestep=batched_timesteps, + encoder_hidden_states=batched_embeds, + gan_mode=True, + return_dict=False, + ) + + # Split results and compute losses + idx = 0 + if r1_weight > 0.0: + batch_size = noisy_real_latent.shape[0] + noisy_real_logit_perturbed = batched_logits[idx : idx + batch_size] + if aprox_r1: + r1_loss = r1_weight * torch.nn.functional.mse_loss( + noisy_real_logits.float(), noisy_real_logit_perturbed.float(), reduction="mean" + ) + else: + r1_grad = (noisy_real_logit_perturbed.float() - noisy_real_logits.float()) / r1_sigma + r1_loss = r1_weight * torch.mean(r1_grad**2) + + assert r1_loss.requires_grad, f"R1 loss should have gradient! Got {r1_loss.requires_grad}" + assert r1_loss.grad_fn is not None, "R1 loss should have grad_fn!" + idx += batch_size + + if r2_weight > 0.0: + batch_size = noisy_fake_latent.shape[0] + noisy_fake_logit_perturbed = batched_logits[idx : idx + batch_size] + if aprox_r2: + r2_loss = r2_weight * torch.nn.functional.mse_loss( + noisy_fake_logits.float(), noisy_fake_logit_perturbed.float(), reduction="mean" + ) + else: + r2_grad = (noisy_fake_logit_perturbed.float() - noisy_fake_logits.float()) / r2_sigma + r2_loss = r2_weight * torch.mean(r2_grad**2) + + assert r2_loss.requires_grad, f"R2 loss should have gradient! Got {r2_loss.requires_grad}" + assert r2_loss.grad_fn is not None, "R2 loss should have grad_fn!" + else: + flow_fake_pred = fake_score_model( + hidden_states=noisy_fake_latent, + timestep=critic_timestep, + encoder_hidden_states=prompt_embeds, + indices_hidden_states=indices_hidden_states, + indices_latents_history_short=indices_latents_history_short, + indices_latents_history_mid=indices_latents_history_mid, + indices_latents_history_long=indices_latents_history_long, + latents_history_short=latents_history_short, + latents_history_mid=latents_history_mid, + latents_history_long=latents_history_long, + return_dict=False, + )[0] + denoising_loss = torch.mean((flow_fake_pred.float() - (critic_noise - generated_image_or_video).float()) ** 2) + + assert denoising_loss.requires_grad, f"Denoising loss should have gradient! Got {denoising_loss.requires_grad}" + assert denoising_loss.grad_fn is not None, "Denoising loss should have grad_fn!" + + pred_fake_image = convert_flow_pred_to_x0( + flow_pred=flow_fake_pred, + xt=noisy_fake_latent, + timestep=critic_timestep, + sigmas=sigmas, + timesteps=timesteps, + ) + + final_loss = denoising_loss + gan_D_loss + r1_loss + r2_loss + assert final_loss.requires_grad, f"Final loss should have gradient! Got {final_loss.requires_grad}" + assert final_loss.grad_fn is not None, "Final loss should have grad_fn!" + + # Step 5: Debugging Log + critic_log_dict = { + "critictrain_latent": generated_image_or_video.detach(), + "critictrain_noisy_latent": noisy_fake_latent.detach(), + "critictrain_pred_image": pred_fake_image.detach(), + "critic_timestep": critic_timestep.detach(), + } + + if is_use_gan: + critic_log_dict["denoising_loss"] = denoising_loss.detach().item() + critic_log_dict["gan_D_loss"] = gan_D_loss.detach().item() + critic_log_dict["r1_loss"] = r1_loss.detach().item() + critic_log_dict["r2_loss"] = r2_loss.detach().item() + + return final_loss, critic_log_dict diff --git a/Helios/helios/utils/utils_recycle_batch.py b/Helios/helios/utils/utils_recycle_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..4f5b9522a264e8c5ccacda6be28829b05283d7dc --- /dev/null +++ b/Helios/helios/utils/utils_recycle_batch.py @@ -0,0 +1,724 @@ +import random + +import torch + +from .utils_base import apply_schedule_shift + + +def apply_error_injection( + args, + recycle_vars, + model_input, + noise, + timesteps, + latents_history_long, + latents_history_mid, + latents_history_short, + model_input_w_error, + noise_w_error, + is_keep_x0, + latent_window_size, +): + batch_size, _, _, h, w = noise.shape + + # Get grid indices for all batch items + current_grid_indices = get_timestep_grid(args, recycle_vars, timesteps, noise) + + # Handle single item (backward compatibility) + if isinstance(current_grid_indices, int): + current_grid_indices = torch.tensor([current_grid_indices], device=noise.device) + + # Check buffer availability for each batch item + has_latent_buffer_data = torch.tensor( + [len(recycle_vars.latent_error_buffer[(h, w)][grid_idx.item()]) > 0 for grid_idx in current_grid_indices], + device=noise.device, + ) + + has_y_buffer_data = any(len(buffer) > 0 for buffer in recycle_vars.y_error_buffer[(h, w)].values()) + + # Generate random decisions for each batch item + latent_random = torch.rand(batch_size, device=noise.device) + noise_random = torch.rand(batch_size, device=noise.device) + y_random = torch.rand(batch_size, device=noise.device) + clean_random = torch.rand(batch_size, device=noise.device) + + # Determine which operations to apply for each batch item + add_error_latent = latent_random < args.training_config.latent_prob + add_error_noise = noise_random < args.training_config.noise_prob + add_error_y = y_random < args.training_config.y_prob + use_clean_input = clean_random < args.training_config.clean_prob + + # Clean input overrides all errors + add_error_noise = add_error_noise & ~use_clean_input + add_error_y = add_error_y & ~use_clean_input + add_error_latent = add_error_latent & ~use_clean_input + + # Apply noise error + if add_error_noise.any() and has_latent_buffer_data.any(): + noise_error_sampled = sample_noise_error_from_noise_buffer( + args, recycle_vars, model_input, timesteps, model_input.dtype, model_input.device + ) + mask = add_error_noise & has_latent_buffer_data + if mask.any(): + noise_w_error[mask] = noise[mask] + noise_error_sampled[mask].to(model_input.dtype) + + # Apply y error for selected batch items + if add_error_y.any() and has_y_buffer_data: + len_4x = latents_history_long.shape[2] + len_2x = latents_history_mid.shape[2] + len_1x = latents_history_short.shape[2] + + hist_seq_len = len_4x + len_2x + len_1x + hist_seq_len_copy = hist_seq_len + + ori_len_1x = len_1x + if is_keep_x0: + len_1x -= 1 + hist_seq_len -= 1 + begin_num = 1 + else: + begin_num = 0 + + max_windows = hist_seq_len // latent_window_size + tail_num = hist_seq_len % latent_window_size + + assert hist_seq_len_copy == tail_num + max_windows * latent_window_size + begin_num + + # Process each batch item independently + for batch_idx in range(batch_size): + if not add_error_y[batch_idx]: + continue + + # Split history for this batch item + tail_latents_history = None + begin_latents_history = None + + latents_4x_item = latents_history_long[batch_idx : batch_idx + 1] + latents_2x_item = latents_history_mid[batch_idx : batch_idx + 1] + latents_clean_item = latents_history_short[batch_idx : batch_idx + 1] + + if tail_num != 0: + tail_latents_history = latents_4x_item[:, :, :tail_num, :, :] + latents_4x_item = latents_4x_item[:, :, tail_num:, :, :] + # Apply tail error + if tail_latents_history.sum() != 0 and random.random() < args.training_config.y_prob: + y_error_sampled = sample_y_error_from_latent_buffer( + args, + recycle_vars, + model_input[batch_idx : batch_idx + 1], + model_input.dtype, + model_input.device, + ) + random_error_num = torch.randint(1, tail_num + 1, (1,)).item() + tail_latents_history[:, :, -random_error_num:, ...] = ( + tail_latents_history[:, :, -random_error_num:, ...] + + y_error_sampled[:, :, -random_error_num:, ...] + ) + + if begin_num != 0: + begin_latents_history = latents_clean_item[:, :, :begin_num, :, :] + latents_clean_item = latents_clean_item[:, :, begin_num:, :, :] + # Apply begin error + if begin_latents_history.sum() != 0 and random.random() < args.training_config.y_prob: + y_error_sampled = sample_y_error_from_latent_buffer( + args, + recycle_vars, + model_input[batch_idx : batch_idx + 1], + model_input.dtype, + model_input.device, + ) + begin_latents_history = begin_latents_history + y_error_sampled[:, :, :1, ...] + + # Process mid windows + mid_latents_history = torch.cat([latents_4x_item, latents_2x_item, latents_clean_item], dim=2) + window_num = mid_latents_history.shape[2] // latent_window_size + assert mid_latents_history.shape[2] % latent_window_size == 0, ( + f"mid length {mid_latents_history.shape[2]} not divisible by window size {latent_window_size}" + ) + + seq_begin = 0 + for _ in range(window_num): + seq_end = seq_begin + latent_window_size + if ( + mid_latents_history[:, :, seq_begin:seq_end, :, :].sum() != 0 + and random.random() < args.training_config.y_prob + ): + y_error_sampled = sample_y_error_from_latent_buffer( + args, + recycle_vars, + model_input[batch_idx : batch_idx + 1], + model_input.dtype, + model_input.device, + ) + max_start_idx = max(0, y_error_sampled.shape[2] - args.training_config.y_error_num) + random_frame_idx = torch.randint(0, max_start_idx + 1, (1,)).item() + error_to_add = y_error_sampled[ + :, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, ... + ] + # Modify + mid_latents_history[:, :, seq_begin:seq_end, :, :][ + :, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, :, : + ] = ( + mid_latents_history[:, :, seq_begin:seq_end, :, :][ + :, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, :, : + ] + + error_to_add + ) + seq_begin = seq_end + + # Recover structure + recovers = [] + if tail_latents_history is not None: + recovers.append(tail_latents_history) + recovers.append(mid_latents_history[:, :, :-len_1x, :, :]) + if begin_latents_history is not None: + recovers.append(begin_latents_history) + recovers.append(mid_latents_history[:, :, -len_1x:, :, :]) + mid_latents_history = torch.cat(recovers, dim=2) + + # Split and update back to original tensors + latents_4x_recovered, latents_2x_recovered, latents_clean_recovered = mid_latents_history.split( + [len_4x, len_2x, ori_len_1x], dim=2 + ) + latents_history_long[batch_idx : batch_idx + 1] = latents_4x_recovered + latents_history_mid[batch_idx : batch_idx + 1] = latents_2x_recovered + latents_history_short[batch_idx : batch_idx + 1] = latents_clean_recovered + + # Apply latent error + if add_error_latent.any() and has_latent_buffer_data.any(): + latent_error_sampled = sample_latent_error_from_latent_buffer( + args, recycle_vars, model_input, timesteps, model_input.dtype, model_input.device + ) + mask = add_error_latent & has_latent_buffer_data + if mask.any(): + model_input_w_error[mask] = model_input[mask] + latent_error_sampled[mask].to(model_input.dtype) + + return ( + model_input_w_error, + noise_w_error, + latents_history_long, + latents_history_mid, + latents_history_short, + use_clean_input, + ) + + +def step_recycle(scheduler, model_output, timestep, sample, to_final=False, self_corr=False): + """ + Args: + timestep: scalar, 1D tensor with shape [batch_size], or tensor that can be flattened + """ + # Normalize timestep to 1D tensor + if isinstance(timestep, torch.Tensor): + timestep_vals = timestep.flatten().cpu() + else: + # Scalar value, convert to tensor + timestep_vals = torch.tensor([timestep]) + + batch_size = timestep_vals.shape[0] + + # Find timestep indices for all batch items + # timestep_vals: [batch_size], scheduler.temp_timesteps: [num_timesteps] + diffs = torch.abs( + scheduler.temp_timesteps.unsqueeze(0) - timestep_vals.unsqueeze(-1) + ) # [batch_size, num_timesteps] + timestep_ids = torch.argmin(diffs, dim=-1) # [batch_size] + + # Get sigmas for all batch items + sigmas = scheduler.temp_sigmas[timestep_ids] # [batch_size] + + # Calculate next sigmas + if to_final: + # All items go to final + sigmas_next = torch.ones(batch_size) if self_corr else torch.zeros(batch_size) + else: + # Check which items are at the end + at_end = timestep_ids + 1 >= len(scheduler.temp_timesteps) + + # Get next sigmas (clamped to valid range) + next_ids = torch.clamp(timestep_ids + 1, 0, len(scheduler.temp_timesteps) - 1) + sigmas_next = scheduler.temp_sigmas[next_ids] # [batch_size] + + # Override with 1 or 0 for items at the end + if self_corr: + sigmas_next[at_end] = 1.0 + else: + sigmas_next[at_end] = 0.0 + + # Move sigmas to same device as sample + sigmas = sigmas.to(sample.device, dtype=sample.dtype) + sigmas_next = sigmas_next.to(sample.device, dtype=sample.dtype) + + # Compute prev_sample for all batch items + # Reshape sigmas to broadcast correctly: [batch_size, 1, 1, 1, 1] for 5D tensors + shape = [batch_size] + [1] * (sample.ndim - 1) + sigma_diff = (sigmas_next - sigmas).view(*shape) + + prev_sample = sample + model_output * sigma_diff + + return prev_sample + + +def get_timesteps( + num_inference_steps=50, + denoising_strength=1, + shift=1.0, + num_train_timesteps=1000, + sigma_max=1.0, + sigma_min=0.0, + inverse_timesteps=False, + extra_one_step=True, + reverse_sigmas=False, +): + sigma_start = sigma_min + (sigma_max - sigma_min) * denoising_strength + if extra_one_step: + sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps + 1)[:-1] + else: + sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps) + if inverse_timesteps: + sigmas = torch.flip(sigmas, dims=[0]) + sigmas = shift * sigmas / (1 + (shift - 1) * sigmas) + if reverse_sigmas: + sigmas = 1 - sigmas + timesteps = sigmas * num_train_timesteps + return timesteps, sigmas + + +def get_timestep_grid(args, recycle_vars, timesteps, noise): + """Get the grid index for a given timesteps.""" + _, _, _, h, w = noise.shape + + # Handle different timesteps formats (scalar tensor, tensor with batch dim, etc.) + if isinstance(timesteps, torch.Tensor): + timestep_vals = timesteps.flatten() + else: + # Already a scalar value + timestep_vals = torch.tensor([timesteps], device=noise.device if hasattr(noise, "device") else "cpu") + + if args.training_config.use_dynamic_shifting: + temp_sigmas = apply_schedule_shift( + recycle_vars.recycle_sigmas, + noise, + base_seq_len=args.training_config.base_seq_len, + max_seq_len=args.training_config.max_seq_len, + base_shift=args.training_config.base_shift, + max_shift=args.training_config.max_shift, + ) # torch.Size([2, 1, 1, 1, 1]) + + temp_inferece_timesteps = temp_sigmas * 1000.0 # rescale to [0, 1000.0) + while temp_inferece_timesteps.ndim > 1: + temp_inferece_timesteps = temp_inferece_timesteps.squeeze(-1) + else: + temp_inferece_timesteps = recycle_vars.recycle_inferece_timesteps + + # Ensure timesteps is within valid range and calculate grid index + timestep_vals = torch.clamp(timestep_vals, 0, 999) + grid_timesteps = temp_inferece_timesteps.to(timestep_vals.device) + + diffs = torch.abs(grid_timesteps.unsqueeze(0) - timestep_vals.unsqueeze(-1)) + grid_indices = torch.argmin(diffs, dim=-1) + + # Ensure grid index is within valid range + max_grid_idx = len(recycle_vars.latent_error_buffer[(h, w)]) - 1 + grid_indices = torch.clamp(grid_indices, 0, max_grid_idx) + + return grid_indices + + +def sample_noise_error_from_noise_buffer(args, recycle_vars, latents, timestep, dtype=torch.bfloat16, device="cpu"): + """Randomly sample an error from the buffer based on timestep grid.""" + batch_size, _, _, h, w = latents.shape + grid_indices = get_timestep_grid(args, recycle_vars, timestep, latents) + + # Handle single item (backward compatibility) + if isinstance(grid_indices, int): + grid_indices = torch.tensor([grid_indices], device=device) + + # Initialize output tensor + error_samples = torch.zeros_like(latents) + + # Sample error for each item in batch + for i, grid_idx in enumerate(grid_indices): + grid_idx = grid_idx.item() + + if not recycle_vars.latent_error_buffer[(h, w)][grid_idx]: + continue # Keep zeros for this batch item + + # Randomly select one sample from the corresponding grid + selected_sample = random.choice(recycle_vars.latent_error_buffer[(h, w)][grid_idx]) + + # Apply random intensity modulation + min_mod = 1.0 - args.training_config.error_modulate_factor + max_mod = 1.0 + args.training_config.error_modulate_factor + intensity_mod = random.uniform(min_mod, max_mod) + + error_sample = selected_sample * intensity_mod + error_sample = error_sample + + # Assign to the i-th batch item + error_samples[i] = error_sample + + error_samples = error_samples.to(device, dtype=dtype) + + return error_samples + + +def sample_latent_error_from_latent_buffer(args, recycle_vars, latents, timestep, dtype=torch.bfloat16, device="cpu"): + """Randomly sample an error from the buffer based on timestep grid.""" + batch_size, _, _, h, w = latents.shape + grid_indices = get_timestep_grid(args, recycle_vars, timestep, latents) + + # Handle single item (backward compatibility) + if isinstance(grid_indices, int): + grid_indices = torch.tensor([grid_indices], device=device) + + # Initialize output tensor + error_samples = torch.zeros_like(latents) + + # Sample error for each item in batch + for i, grid_idx in enumerate(grid_indices): + grid_idx = grid_idx.item() + + if not recycle_vars.y_error_buffer[(h, w)][grid_idx]: + continue # Keep zeros for this batch item + + # Randomly select one sample from the corresponding grid + selected_sample = random.choice(recycle_vars.y_error_buffer[(h, w)][grid_idx]) + + # Apply random intensity modulation + min_mod = 1.0 - args.training_config.error_modulate_factor + max_mod = 1.0 + args.training_config.error_modulate_factor + intensity_mod = random.uniform(min_mod, max_mod) + + error_sample = selected_sample * intensity_mod + error_sample = error_sample + + # Assign to the i-th batch item + error_samples[i] = error_sample + + error_samples = error_samples.to(device, dtype=dtype) + + return error_samples + + +def sample_y_error_from_latent_buffer(args, recycle_vars, latents, dtype=torch.bfloat16, device="cpu"): + """Specially sample y_error from buffer - can be configured to sample from all grids or custom range.""" + batch_size, _, _, h, w = latents.shape + + # Sample from all grids that have data + all_samples = [] + for grid_idx, buffer in recycle_vars.y_error_buffer[(h, w)].items(): + if buffer: # Only add non-empty buffers + all_samples.extend(buffer) + + if not all_samples: + return torch.zeros_like(latents) + + # Initialize output tensor + error_samples = torch.zeros_like(latents) + + # Sample independently for each batch item + for i in range(batch_size): + # Randomly select one sample from all available samples + selected_sample = random.choice(all_samples) + + # Apply random intensity modulation + min_mod = 1.0 - args.training_config.error_modulate_factor + max_mod = 1.0 + args.training_config.error_modulate_factor + intensity_mod = random.uniform(min_mod, max_mod) + + error_sample = selected_sample * intensity_mod + error_sample = error_sample + + # Assign to the i-th batch item + error_samples[i] = error_sample + + error_samples = error_samples.to(device, dtype=dtype) + + return error_samples + + +def compute_l2_distance_batch(new_tensor, stored_tensors): + """Compute L2 distances between new tensor and all stored tensors efficiently.""" + if not stored_tensors: + return torch.tensor([]) + + # Stack all stored tensors for batch computation + stored_stack = torch.stack(stored_tensors) # [num_stored, ...] + new_flat = new_tensor.flatten() + stored_flat = stored_stack.flatten(start_dim=1) # [num_stored, flattened_size] + + # Compute L2 distances in batch + distances = torch.norm(stored_flat - new_flat.unsqueeze(0), p=2, dim=1) + return distances + + +def compute_l2_distance(tensor1, tensor2): + """Compute L2 distance between two tensors""" + # Flatten tensors + flat1 = tensor1.flatten() + flat2 = tensor2.flatten() + + # Compute L2 distance (Euclidean distance) + l2_distance = torch.norm(flat1 - flat2, p=2) + return l2_distance.item() + + +def add_error_to_latent_buffer(args, recycle_vars, error_sample, timestep, noisy_model_input): + """Add error sample to buffer using specified replacement strategy based on timestep grid.""" + batch_size, _, _, h, w = noisy_model_input.shape + grid_indices = get_timestep_grid(args, recycle_vars, timestep, noisy_model_input) + error_cpu = error_sample.detach().cpu() + + # Process each batch item + for i, grid_idx in enumerate(grid_indices): + grid_idx = grid_idx.item() + error_cpu = error_sample[i].detach().cpu() + + if len(recycle_vars.latent_error_buffer[(h, w)][grid_idx]) < args.training_config.error_buffer_size: + # Buffer not full, simply add + recycle_vars.latent_error_buffer[(h, w)][grid_idx].append(error_cpu) + else: + # Buffer full, use specified replacement strategy + if args.training_config.buffer_replacement_strategy == "random": + # Random replacement - O(1), fastest + replace_idx = random.randint(0, len(recycle_vars.latent_error_buffer[(h, w)][grid_idx]) - 1) + recycle_vars.latent_error_buffer[(h, w)][grid_idx][replace_idx] = error_cpu + + elif args.training_config.buffer_replacement_strategy == "fifo": + # First-in-first-out - O(1), simple queue behavior + recycle_vars.latent_error_buffer[(h, w)][grid_idx].pop(0) + recycle_vars.latent_error_buffer[(h, w)][grid_idx].append(error_cpu) + + elif args.training_config.buffer_replacement_strategy == "l2_batch": + # Batch L2 computation - O(n) but vectorized, much faster than original + distances = compute_l2_distance_batch(error_cpu, recycle_vars.latent_error_buffer[(h, w)][grid_idx]) + most_similar_idx = torch.argmin(distances).item() + recycle_vars.latent_error_buffer[(h, w)][grid_idx][most_similar_idx] = error_cpu + + elif args.training_config.buffer_replacement_strategy == "l2_similarity": + # Original L2 similarity method - O(n), slowest but most precise + min_distance = float("inf") + most_similar_idx = -1 + + for j, stored_error in enumerate(recycle_vars.latent_error_buffer[(h, w)][grid_idx]): + distance = compute_l2_distance(error_cpu, stored_error) + if distance < min_distance: + min_distance = distance + most_similar_idx = j + + if most_similar_idx != -1: + recycle_vars.latent_error_buffer[(h, w)][grid_idx][most_similar_idx] = error_cpu + + +def add_error_to_y_buffer(args, recycle_vars, error_sample, timestep, noisy_model_input): + """Add error sample to buffer using specified replacement strategy based on timestep grid.""" + batch_size, _, _, h, w = noisy_model_input.shape + grid_indices = get_timestep_grid(args, recycle_vars, timestep, noisy_model_input) + error_cpu = error_sample.detach().cpu() + + # Process each batch item + for i, grid_idx in enumerate(grid_indices): + grid_idx = grid_idx.item() + error_cpu = error_sample[i].detach().cpu() + + if len(recycle_vars.y_error_buffer[(h, w)][grid_idx]) < args.training_config.error_buffer_size: + # Buffer not full, simply add + recycle_vars.y_error_buffer[(h, w)][grid_idx].append(error_cpu) + else: + # Buffer full, use specified replacement strategy + if args.training_config.buffer_replacement_strategy == "random": + # Random replacement - O(1), fastest + replace_idx = random.randint(0, len(recycle_vars.y_error_buffer[(h, w)][grid_idx]) - 1) + recycle_vars.y_error_buffer[(h, w)][grid_idx][replace_idx] = error_cpu + + elif args.training_config.buffer_replacement_strategy == "fifo": + # First-in-first-out - O(1), simple queue behavior + recycle_vars.y_error_buffer[(h, w)][grid_idx].pop(0) + recycle_vars.y_error_buffer[(h, w)][grid_idx].append(error_cpu) + + elif args.training_config.buffer_replacement_strategy == "l2_batch": + # Batch L2 computation - O(n) but vectorized, much faster than original + distances = compute_l2_distance_batch(error_cpu, recycle_vars.y_error_buffer[(h, w)][grid_idx]) + most_similar_idx = torch.argmin(distances).item() + recycle_vars.y_error_buffer[(h, w)][grid_idx][most_similar_idx] = error_cpu + + elif args.training_config.buffer_replacement_strategy == "l2_similarity": + # Original L2 similarity method - O(n), slowest but most precise + min_distance = float("inf") + most_similar_idx = -1 + + for j, stored_error in enumerate(recycle_vars.y_error_buffer[(h, w)][grid_idx]): + distance = compute_l2_distance(error_cpu, stored_error) + if distance < min_distance: + min_distance = distance + most_similar_idx = j + + if most_similar_idx != -1: + recycle_vars.y_error_buffer[(h, w)][grid_idx][most_similar_idx] = error_cpu + + +def update_error_buffers_distributed( + args, recycle_vars, gathered_noise_errors, gathered_y_errors, gathered_timesteps, noisy_model_input +): + """Update error buffers with samples gathered from all processes. + Args: + gathered_noise_errors: shape [num_gpus, batch_size, ...] + gathered_y_errors: shape [num_gpus, batch_size, ...] + gathered_timesteps: shape [num_gpus, batch_size] + """ + num_gpus = gathered_noise_errors.shape[0] + + # Process each GPU's batch + for gpu_idx in range(num_gpus): + noise_error_batch = gathered_noise_errors[gpu_idx] # [batch_size, ...] + y_error_batch = gathered_y_errors[gpu_idx] # [batch_size, ...] + timestep_batch = gathered_timesteps[gpu_idx] # [batch_size] + + # Add the entire batch to buffers + add_error_to_latent_buffer(args, recycle_vars, noise_error_batch, timestep_batch, noisy_model_input) + add_error_to_y_buffer(args, recycle_vars, y_error_batch, timestep_batch, noisy_model_input) + + +def update_error_buffers_local(args, recycle_vars, noise_error, y_error, timestep, noisy_model_input): + """Update error buffers with samples from local GPU only (post-warmup). + Args: + noise_error: shape [batch_size, ...] + y_error: shape [batch_size, ...] + timestep: shape [batch_size] or scalar + """ + add_error_to_latent_buffer(args, recycle_vars, noise_error, timestep, noisy_model_input) + add_error_to_y_buffer(args, recycle_vars, y_error, timestep, noisy_model_input) + + +def process_and_update_error_buffers( + args, + recycle_vars, + accelerator, + global_step, + noise_scheduler_copy, + model_pred, + target, + timesteps, + noisy_model_input, + use_clean_input, +): + x_0_pred = step_recycle( + noise_scheduler_copy, + model_pred, + timesteps, + noisy_model_input, + to_final=True, + self_corr=True, + ) + noise_corr_gt = step_recycle( + noise_scheduler_copy, + target, + timesteps, + noisy_model_input, + to_final=True, + self_corr=True, + ) + noise_error = x_0_pred - noise_corr_gt + + x_1_pred = step_recycle( + noise_scheduler_copy, + model_pred, + timesteps, + noisy_model_input, + to_final=True, + self_corr=False, + ) + latent_corr_gt = step_recycle( + noise_scheduler_copy, + target, + timesteps, + noisy_model_input, + to_final=True, + self_corr=False, + ) + y_error = x_1_pred - latent_corr_gt + + # Check if we're in warmup phase + if global_step <= args.training_config.buffer_warmup_iter: + + def gather_with_optional_gpu_dim(tensor, keep_gpu_dim=False): + gathered = accelerator.gather(tensor) + + if keep_gpu_dim: + num_processes = accelerator.num_processes + batch_size = tensor.shape[0] + gathered = gathered.view(num_processes, batch_size, *gathered.shape[1:]) + + return gathered + + # During warmup: gather errors and timesteps from all GPUs and update buffers + gathered_noise_errors = gather_with_optional_gpu_dim(noise_error, keep_gpu_dim=True) + gathered_y_errors = gather_with_optional_gpu_dim(y_error, keep_gpu_dim=True) + gathered_timesteps = gather_with_optional_gpu_dim(timesteps, keep_gpu_dim=True) + gathered_use_clean = gather_with_optional_gpu_dim(use_clean_input, keep_gpu_dim=True) + # Shape: [num_gpus, batch_size] + + clean_mask = gathered_use_clean # [num_gpus, batch_size] + non_clean_mask = ~clean_mask # [num_gpus, batch_size] + num_gpus = gathered_noise_errors.shape[0] + + # Process clean samples: update with probability for each one + if clean_mask.any(): + for gpu_idx in range(num_gpus): + gpu_clean_mask = clean_mask[gpu_idx] + if gpu_clean_mask.any(): + p = random.random() + if p < args.training_config.clean_buffer_update_prob: + update_error_buffers_distributed( + args, + recycle_vars, + gathered_noise_errors[gpu_idx : gpu_idx + 1, gpu_clean_mask], + gathered_y_errors[gpu_idx : gpu_idx + 1, gpu_clean_mask], + gathered_timesteps[gpu_idx : gpu_idx + 1, gpu_clean_mask], + noisy_model_input, + ) + + # Process non-clean samples: always update + if non_clean_mask.any(): + for gpu_idx in range(num_gpus): + gpu_non_clean_mask = non_clean_mask[gpu_idx] + if gpu_non_clean_mask.any(): + update_error_buffers_distributed( + args, + recycle_vars, + gathered_noise_errors[gpu_idx : gpu_idx + 1, gpu_non_clean_mask], + gathered_y_errors[gpu_idx : gpu_idx + 1, gpu_non_clean_mask], + gathered_timesteps[gpu_idx : gpu_idx + 1, gpu_non_clean_mask], + noisy_model_input, + ) + + else: + # After warmup: only use local GPU errors + # Separate clean and non-clean samples + clean_mask = use_clean_input # Boolean tensor + non_clean_mask = ~use_clean_input + + # Process clean samples: update with probability + if clean_mask.any(): + p = random.random() + if p < args.training_config.clean_buffer_update_prob: + update_error_buffers_local( + args, + recycle_vars, + noise_error[clean_mask], + y_error[clean_mask], + timesteps[clean_mask], + noisy_model_input, + ) + + # Process non-clean samples: always update + if non_clean_mask.any(): + update_error_buffers_local( + args, + recycle_vars, + noise_error[non_clean_mask], + y_error[non_clean_mask], + timesteps[non_clean_mask], + noisy_model_input, + ) diff --git a/Helios/helios/utils/utils_recycle_single.py b/Helios/helios/utils/utils_recycle_single.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a574008fcd6872482da206f6a5afadf6810137 --- /dev/null +++ b/Helios/helios/utils/utils_recycle_single.py @@ -0,0 +1,437 @@ +import random + +import torch + +from .utils_base import apply_schedule_shift + + +def apply_error_injection( + args, + recycle_vars, + model_input, + noise, + timesteps, + latents_history_long, + latents_history_mid, + latents_history_short, + model_input_w_error, + noise_w_error, + is_keep_x0, + latent_window_size, +): + # Check if buffer has data for the current timestep grid + current_grid_idx = get_timestep_grid(args, recycle_vars, timesteps, noise) + has_latent_buffer_data = len(recycle_vars.latent_error_buffer[current_grid_idx]) > 0 + has_y_buffer_data = any(len(buffer) > 0 for buffer in recycle_vars.y_error_buffer.values()) + + add_error_latent = False + add_error_noise = False + add_error_y = False + use_clean_input = False + + latent_random = random.random() + noise_random = random.random() + y_random = random.random() + clean_random = random.random() + + if latent_random < args.training_config.latent_prob: + add_error_latent = True + if noise_random < args.training_config.noise_prob: + add_error_noise = True + if y_random < args.training_config.y_prob: + add_error_y = True + if clean_random < args.training_config.clean_prob: + add_error_noise = False + add_error_y = False + add_error_latent = False + use_clean_input = True + + if add_error_noise and has_latent_buffer_data: + noise_error_sampled = sample_noise_error_from_noise_buffer( + args, recycle_vars, model_input, timesteps, model_input.dtype, model_input.device + ) + noise_w_error = noise + noise_error_sampled.to(model_input.dtype) + + if add_error_y and has_y_buffer_data: + len_4x = latents_history_long.shape[2] + len_2x = latents_history_mid.shape[2] + len_1x = latents_history_short.shape[2] + + hist_seq_len = len_4x + len_2x + len_1x + hist_seq_len_copy = hist_seq_len + + ori_len_1x = len_1x + if is_keep_x0: + len_1x -= 1 + hist_seq_len -= 1 + begin_num = 1 + else: + begin_num = 0 + + max_windows = hist_seq_len // latent_window_size + tail_num = hist_seq_len % latent_window_size + + assert hist_seq_len_copy == tail_num + max_windows * latent_window_size + begin_num + + tail_latents_history = None + begin_latents_history = None + if tail_num != 0: + tail_latents_history, latents_history_long = ( + latents_history_long[:, :, :tail_num, :, :], + latents_history_long[:, :, tail_num:, :, :], + ) + # for tail + if random.random() < args.training_config.y_prob: + y_error_sampled = sample_y_error_from_latent_buffer( + args, recycle_vars, model_input, model_input.dtype, model_input.device + ) + random_error_num = torch.randint(1, tail_num + 1, (1,)).item() + tail_latents_history[:, :, -random_error_num:, ...] = ( + tail_latents_history[:, :, -random_error_num:, ...] + + y_error_sampled[:, :, -random_error_num:, ...] + ) + if begin_num != 0: + begin_latents_history, latents_history_short = ( + latents_history_short[:, :, :begin_num, :, :], + latents_history_short[:, :, begin_num:, :, :], + ) + # for begin + if random.random() < args.training_config.y_prob: + y_error_sampled = sample_y_error_from_latent_buffer( + args, recycle_vars, model_input, model_input.dtype, model_input.device + ) + begin_latents_history = begin_latents_history + y_error_sampled[:, :, :1, ...] + + # for mid + mid_latents_history = torch.cat([latents_history_long, latents_history_mid, latents_history_short], dim=2) + window_num = mid_latents_history.shape[2] // latent_window_size + assert mid_latents_history.shape[2] % latent_window_size == 0, ( + f"mid length {mid_latents_history.shape[2]} not divisible by window size {latent_window_size}" + ) + seq_begin = 0 + for _ in range(window_num): + seq_end = seq_begin + latent_window_size + if random.random() < args.training_config.y_prob: + y_error_sampled = sample_y_error_from_latent_buffer( + args, recycle_vars, model_input, model_input.dtype, model_input.device + ) + max_start_idx = max(0, y_error_sampled.shape[2] - args.training_config.y_error_num) + random_frame_idx = torch.randint(0, max_start_idx + 1, (1,)).item() + error_to_add = y_error_sampled[ + :, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, ... + ] + # Modify + mid_latents_history[:, :, seq_begin:seq_end, :, :][ + :, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, :, : + ] = ( + mid_latents_history[:, :, seq_begin:seq_end, :, :][ + :, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, :, : + ] + + error_to_add + ) + seq_begin = seq_end + + # recover + recovers = [] + if tail_latents_history is not None: + recovers.append(tail_latents_history) + recovers.append(mid_latents_history[:, :, :-len_1x, :, :]) + if begin_latents_history is not None: + recovers.append(begin_latents_history) + recovers.append(mid_latents_history[:, :, -len_1x:, :, :]) + mid_latents_history = torch.cat(recovers, dim=2) + latents_history_long, latents_history_mid, latents_history_short = mid_latents_history.split( + [len_4x, len_2x, ori_len_1x], dim=2 + ) + + if add_error_latent and has_latent_buffer_data: + latent_error_sampled = sample_latent_error_from_latent_buffer( + args, recycle_vars, model_input, timesteps, model_input.dtype, model_input.device + ) + model_input_w_error = model_input + latent_error_sampled.to(model_input.dtype) + + return ( + model_input_w_error, + noise_w_error, + latents_history_long, + latents_history_mid, + latents_history_short, + use_clean_input, + ) + + +def step_recycle(scheduler, model_output, timestep, sample, to_final=False, self_corr=False): + if isinstance(timestep, torch.Tensor): + timestep = timestep.cpu() + timestep_id = torch.argmin((scheduler.temp_timesteps - timestep).abs()) + sigma = scheduler.temp_sigmas[timestep_id] + if to_final or timestep_id + 1 >= len(scheduler.temp_timesteps): + sigma_ = 1 if self_corr else 0 + else: + sigma_ = scheduler.temp_sigmas[timestep_id + 1] + prev_sample = sample + model_output * (sigma_ - sigma) + return prev_sample + + +def get_timesteps( + num_inference_steps=50, + denoising_strength=1, + shift=1.0, + num_train_timesteps=1000, + sigma_max=1.0, + sigma_min=0.0, + inverse_timesteps=False, + extra_one_step=True, + reverse_sigmas=False, +): + sigma_start = sigma_min + (sigma_max - sigma_min) * denoising_strength + if extra_one_step: + sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps + 1)[:-1] + else: + sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps) + if inverse_timesteps: + sigmas = torch.flip(sigmas, dims=[0]) + sigmas = shift * sigmas / (1 + (shift - 1) * sigmas) + if reverse_sigmas: + sigmas = 1 - sigmas + timesteps = sigmas * num_train_timesteps + return timesteps, sigmas + + +def get_timestep_grid(args, recycle_vars, timesteps, noise): + """Get the grid index for a given timesteps.""" + # Handle different timesteps formats (scalar tensor, tensor with batch dim, etc.) + if isinstance(timesteps, torch.Tensor): + if timesteps.numel() == 1: + # Single timesteps value + timestep_val = timesteps.item() + else: + # Tensor with batch dimension, take the first element + timestep_val = timesteps.flatten()[0].item() + else: + # Already a scalar value + timestep_val = timesteps + + if args.training_config.use_dynamic_shifting: + temp_sigmas = apply_schedule_shift( + recycle_vars.recycle_sigmas, + noise, + base_seq_len=args.training_config.base_seq_len, + max_seq_len=args.training_config.max_seq_len, + base_shift=args.training_config.base_shift, + max_shift=args.training_config.max_shift, + ) # torch.Size([2, 1, 1, 1, 1]) + + temp_inferece_timesteps = temp_sigmas * 1000.0 # rescale to [0, 1000.0) + while temp_inferece_timesteps.ndim > 1: + temp_inferece_timesteps = temp_inferece_timesteps.squeeze(-1) + else: + temp_inferece_timesteps = recycle_vars.recycle_inferece_timesteps + + # Ensure timesteps is within valid range and calculate grid index + timestep_val = max(0, min(timestep_val, 999)) # Clamp to [0, 999] + grid_idx = torch.argmin((temp_inferece_timesteps - timestep_val).abs()).item() + + # Ensure grid index is within valid range + max_grid_idx = len(recycle_vars.latent_error_buffer) - 1 + grid_idx = min(grid_idx, max_grid_idx) + + return grid_idx + + +def sample_noise_error_from_noise_buffer(args, recycle_vars, latents, timestep, dtype=torch.bfloat16, device="cpu"): + """Randomly sample an error from the buffer based on timestep grid.""" + grid_idx = get_timestep_grid(args, recycle_vars, timestep, latents) + + if not recycle_vars.latent_error_buffer[grid_idx]: + return torch.zeros_like(latents) + + # Randomly select one sample from the corresponding grid + selected_sample = random.choice(recycle_vars.latent_error_buffer[grid_idx]) + error_sample = selected_sample + + min_mod = 1.0 - args.training_config.error_modulate_factor + max_mod = 1.0 + args.training_config.error_modulate_factor + intensity_mod = random.uniform(min_mod, max_mod) + error_sample = error_sample * intensity_mod + + error_sample = error_sample.to(device, dtype=dtype) + + return error_sample + + +def sample_latent_error_from_latent_buffer(args, recycle_vars, latents, timestep, dtype=torch.bfloat16, device="cpu"): + """Randomly sample an error from the buffer based on timestep grid.""" + grid_idx = get_timestep_grid(args, recycle_vars, timestep, latents) + + if not recycle_vars.y_error_buffer[grid_idx]: + return torch.zeros_like(latents) + + # Randomly select one sample from the corresponding grid + selected_sample = random.choice(recycle_vars.y_error_buffer[grid_idx]) + error_sample = selected_sample + + min_mod = 1.0 - args.training_config.error_modulate_factor + max_mod = 1.0 + args.training_config.error_modulate_factor + intensity_mod = random.uniform(min_mod, max_mod) + error_sample = error_sample * intensity_mod + + error_sample = error_sample.to(device, dtype=dtype) + + return error_sample + + +def sample_y_error_from_latent_buffer(args, recycle_vars, latents, dtype=torch.bfloat16, device="cpu"): + """Specially sample y_error from buffer - can be configured to sample from all grids or custom range.""" + # Sample from all grids that have data + all_samples = [] + for grid_idx, buffer in recycle_vars.y_error_buffer.items(): + if buffer: # Only add non-empty buffers + all_samples.extend(buffer) + + if not all_samples: + return torch.zeros_like(latents) + + # Randomly select one sample from all available samples + selected_sample = random.choice(all_samples) + error_sample = selected_sample + + min_mod = 1.0 - args.training_config.error_modulate_factor + max_mod = 1.0 + args.training_config.error_modulate_factor + intensity_mod = random.uniform(min_mod, max_mod) + error_sample = error_sample * intensity_mod + + error_sample = error_sample.to(device, dtype=dtype) + + return error_sample + + +def compute_l2_distance_batch(new_tensor, stored_tensors): + """Compute L2 distances between new tensor and all stored tensors efficiently.""" + if not stored_tensors: + return torch.tensor([]) + + # Stack all stored tensors for batch computation + stored_stack = torch.stack(stored_tensors) # [num_stored, ...] + new_flat = new_tensor.flatten() + stored_flat = stored_stack.flatten(start_dim=1) # [num_stored, flattened_size] + + # Compute L2 distances in batch + distances = torch.norm(stored_flat - new_flat.unsqueeze(0), p=2, dim=1) + return distances + + +def compute_l2_distance(tensor1, tensor2): + """Compute L2 distance between two tensors""" + # Flatten tensors + flat1 = tensor1.flatten() + flat2 = tensor2.flatten() + + # Compute L2 distance (Euclidean distance) + l2_distance = torch.norm(flat1 - flat2, p=2) + return l2_distance.item() + + +def add_error_to_latent_buffer(args, recycle_vars, error_sample, timestep, noisy_model_input): + """Add error sample to buffer using specified replacement strategy based on timestep grid.""" + grid_idx = get_timestep_grid(args, recycle_vars, timestep, noisy_model_input) + error_cpu = error_sample.detach().cpu() + + if len(recycle_vars.latent_error_buffer[grid_idx]) < args.training_config.error_buffer_size: + # Buffer not full, simply add + recycle_vars.latent_error_buffer[grid_idx].append(error_cpu) + else: + # Buffer full, use specified replacement strategy + if args.training_config.buffer_replacement_strategy == "random": + # Random replacement - O(1), fastest + replace_idx = random.randint(0, len(recycle_vars.latent_error_buffer[grid_idx]) - 1) + recycle_vars.latent_error_buffer[grid_idx][replace_idx] = error_cpu + + elif args.training_config.buffer_replacement_strategy == "fifo": + # First-in-first-out - O(1), simple queue behavior + recycle_vars.latent_error_buffer[grid_idx].pop(0) + recycle_vars.latent_error_buffer[grid_idx].append(error_cpu) + + elif args.training_config.buffer_replacement_strategy == "l2_batch": + # Batch L2 computation - O(n) but vectorized, much faster than original + distances = compute_l2_distance_batch(error_cpu, recycle_vars.latent_error_buffer[grid_idx]) + most_similar_idx = torch.argmin(distances).item() + recycle_vars.latent_error_buffer[grid_idx][most_similar_idx] = error_cpu + + elif args.training_config.buffer_replacement_strategy == "l2_similarity": + # Original L2 similarity method - O(n), slowest but most precise + min_distance = float("inf") + most_similar_idx = -1 + + for i, stored_error in enumerate(recycle_vars.latent_error_buffer[grid_idx]): + distance = compute_l2_distance(error_cpu, stored_error) + if distance < min_distance: + min_distance = distance + most_similar_idx = i + + if most_similar_idx != -1: + recycle_vars.latent_error_buffer[grid_idx][most_similar_idx] = error_cpu + + +def add_error_to_y_buffer(args, recycle_vars, error_sample, timestep, noisy_model_input): + """Add error sample to buffer using specified replacement strategy based on timestep grid.""" + grid_idx = get_timestep_grid(args, recycle_vars, timestep, noisy_model_input) + error_cpu = error_sample.detach().cpu() + + if len(recycle_vars.y_error_buffer[grid_idx]) < args.training_config.error_buffer_size: + # Buffer not full, simply add + recycle_vars.y_error_buffer[grid_idx].append(error_cpu) + else: + # Buffer full, use specified replacement strategy + if args.training_config.buffer_replacement_strategy == "random": + # Random replacement - O(1), fastest + replace_idx = random.randint(0, len(recycle_vars.y_error_buffer[grid_idx]) - 1) + recycle_vars.y_error_buffer[grid_idx][replace_idx] = error_cpu + + elif args.training_config.buffer_replacement_strategy == "fifo": + # First-in-first-out - O(1), simple queue behavior + recycle_vars.y_error_buffer[grid_idx].pop(0) + recycle_vars.y_error_buffer[grid_idx].append(error_cpu) + + elif args.training_config.buffer_replacement_strategy == "l2_batch": + # Batch L2 computation - O(n) but vectorized, much faster than original + distances = compute_l2_distance_batch(error_cpu, recycle_vars.y_error_buffer[grid_idx]) + most_similar_idx = torch.argmin(distances).item() + recycle_vars.y_error_buffer[grid_idx][most_similar_idx] = error_cpu + + elif args.training_config.buffer_replacement_strategy == "l2_similarity": + # Original L2 similarity method - O(n), slowest but most precise + min_distance = float("inf") + most_similar_idx = -1 + + for i, stored_error in enumerate(recycle_vars.y_error_buffer[grid_idx]): + distance = compute_l2_distance(error_cpu, stored_error) + if distance < min_distance: + min_distance = distance + most_similar_idx = i + + if most_similar_idx != -1: + recycle_vars.y_error_buffer[grid_idx][most_similar_idx] = error_cpu + + +def update_error_buffers_distributed( + args, recycle_vars, gathered_noise_errors, gathered_y_errors, gathered_timesteps, noisy_model_input +): + """Update error buffers with samples gathered from all processes.""" + # gathered_tensors have shape [num_gpus, batch_size, ...] for errors + # gathered_timesteps have shape [num_gpus, batch_size] for timesteps + # In this case, batch_size is 1, so shapes are [num_gpus, 1, ...] and [num_gpus, 1] + num_gpus = gathered_noise_errors.shape[0] + for i in range(num_gpus): + noise_error_sample = gathered_noise_errors[i] + y_error_sample = gathered_y_errors[i] + timestep_sample = gathered_timesteps[i] # Get the corresponding timestep for this GPU + + add_error_to_latent_buffer(args, recycle_vars, noise_error_sample, timestep_sample, noisy_model_input) + add_error_to_y_buffer(args, recycle_vars, y_error_sample, timestep_sample, noisy_model_input) + + +def update_error_buffers_local(args, recycle_vars, noise_error, y_error, timestep, noisy_model_input): + """Update error buffers with samples from local GPU only (post-warmup).""" + add_error_to_latent_buffer(args, recycle_vars, noise_error, timestep, noisy_model_input) + add_error_to_y_buffer(args, recycle_vars, y_error, timestep, noisy_model_input) diff --git a/Helios/helios/videoalign/__init__.py b/Helios/helios/videoalign/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios/helios/videoalign/data.py b/Helios/helios/videoalign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1f314608903b2f5e8704cfef9fdbc6a6a2163c --- /dev/null +++ b/Helios/helios/videoalign/data.py @@ -0,0 +1,278 @@ +from dataclasses import dataclass +from typing import List, Union + +import torch + +from .prompt_template import build_prompt +from .vision_process import process_vision_info + + +@dataclass +class DataConfig: + meta_data: str = "/path/to/dataset/meta_data.csv" + data_dir: str = "/path/to/dataset" + meta_data_test: str = None + max_frame_pixels: int = 240 * 320 + num_frames: float = None + fps: float = 2.0 + p_shuffle_frames: float = 0.0 + p_color_jitter: float = 0.0 + eval_dim: Union[str, List[str]] = "VQ" + prompt_template_type: str = "none" + add_noise: bool = False + sample_type: str = "uniform" + use_tied_data: bool = True + + +def convert_GSB_csv_to_reward_data( + example, + data_dir, + eval_dims=["VQ"], + max_pixels=448 * 448, + fps=2.0, + num_frames=None, + prompt_template_type="none", + sample_type="uniform", +): + """ + Convert Good/Same/Bad csv data to reward data. + + Args: + example (dict): A dataframe containing the GSB csv data. + data_dir (str): The directory path to the video files. + eval_dim (str): The dimension to evaluate ("VQ"/"MQ"/"TA"). + max_pixels (int): The maximum number of pixels allowed for videos. + num_frames (float): Number of frames. + prompt_template_type (str): The type of prompt template to use ("none"/"simple"/"video_score"). + + Returns: + dict: A dictionary containing the reward data. + """ + + A_data = [ + { + "role": "user", + "content": [ + { + "type": "video", + "video": f"file://{data_dir}/{example['path_A']}", + "max_pixels": max_pixels, + "fps": fps if num_frames is None else None, + "nframes": min(num_frames, example["num_frames_A"]) if num_frames is not None else None, + "sample_type": sample_type, + }, + {"type": "text", "text": build_prompt(example["prompt"], eval_dims, prompt_template_type)}, + ], + } + ] + B_data = [ + { + "role": "user", + "content": [ + { + "type": "video", + "video": f"file://{data_dir}/{example['path_B']}", + "max_pixels": max_pixels, + "fps": fps if num_frames is None else None, + "nframes": min(num_frames, example["num_frames_B"]) if num_frames is not None else None, + "sample_type": sample_type, + }, + {"type": "text", "text": build_prompt(example["prompt"], eval_dims, prompt_template_type)}, + ], + } + ] + + chosen_labels = [] + A_scores = [] + B_scores = [] + + for eval_dim in eval_dims: + ### chosen_label: 1 if A is chosen, -1 if B is chosen, 0 if tied. + ### 22 if invalid. ooaaeeaa o.O + try: + if example[f"{eval_dim}"] is not None: + if example[f"{eval_dim}"] == "A": + chosen_label = 1 + elif example[f"{eval_dim}"] == "B": + chosen_label = -1 + elif example[f"{eval_dim}"] == "same": + chosen_label = 0 + elif example[f"{eval_dim}"] == "invalid": + chosen_label = 22 + else: + chosen_label = 22 + else: + chosen_label = 22 + except Exception: + chosen_label = 22 + + chosen_labels.append(chosen_label) + if f"MOS_A_{eval_dim}" in example and f"MOS_B_{eval_dim}" in example: + try: + A_score = example[f"MOS_A_{eval_dim}"] if example[f"MOS_A_{eval_dim}"] is not None else 0.0 + B_score = example[f"MOS_B_{eval_dim}"] if example[f"MOS_B_{eval_dim}"] is not None else 0.0 + except Exception: + A_score = 0.0 + B_score = 0.0 + A_scores.append(A_score) + B_scores.append(B_score) + else: + A_scores.append(0.0) + B_scores.append(0.0) + + chosen_labels = torch.tensor(chosen_labels, dtype=torch.long) + A_scores = torch.tensor(A_scores, dtype=torch.float) + B_scores = torch.tensor(B_scores, dtype=torch.float) + metainfo_idx = None + if "metainfo_idx" in example: + metainfo_idx = example["metainfo_idx"] + + return { + "A_data": A_data, + "B_data": B_data, + "A_scores": A_scores, + "B_scores": B_scores, + "chosen_label": chosen_labels, + "metainfo_idx": metainfo_idx, + } + + +class QWen2VLDataCollator: + def __init__(self, processor, add_noise=False, p_shuffle_frames=0.0, p_color_jitter=0.0): + self.processor = processor + self.add_noise = add_noise + self.set_noise_step = None + + self.p_shuffle_frames = p_shuffle_frames + self.p_color_jitter = p_color_jitter + + self.noise_adder = None + + def _clean_message(self, message): + """ + remove unnecessary keys from message(very very necessary) + """ + out_message = [ + { + "role": "user", + "content": [ + { + "type": "video", + "video": message[0]["content"][0]["video"], + "max_pixels": message[0]["content"][0]["max_pixels"], + "fps": message[0]["content"][0]["fps"] if "fps" in message[0]["content"][0] else None, + "nframes": message[0]["content"][0]["nframes"] + if "nframes" in message[0]["content"][0] + else None, + "sample_type": message[0]["content"][0]["sample_type"] + if "sample_type" in message[0]["content"][0] + else "uniform", + }, + {"type": "text", "text": message[0]["content"][1]["text"]}, + ], + } + ] + + if out_message[0]["content"][0]["fps"] is None: + out_message[0]["content"][0].pop("fps") + if out_message[0]["content"][0]["nframes"] is None: + out_message[0]["content"][0].pop("nframes") + + return out_message + + def _pad_sequence(self, sequences, attention_mask, max_len, padding_side="right"): + """ + Pad the sequences to the maximum length. + """ + assert padding_side in ["right", "left"] + if sequences.shape[1] >= max_len: + return sequences, attention_mask + + pad_len = max_len - sequences.shape[1] + padding = (0, pad_len) if padding_side == "right" else (pad_len, 0) + + sequences_padded = torch.nn.functional.pad( + sequences, padding, "constant", self.processor.tokenizer.pad_token_id + ) + attention_mask_padded = torch.nn.functional.pad(attention_mask, padding, "constant", 0) + + return sequences_padded, attention_mask_padded + + def __call__(self, features, enable_noise=True): + """ + Preprocess inputs to token sequences and return a batch + """ + # try: + features_A = [] + features_B = [] + # check if we have a margin. If we do, we need to batch it as well + # has_margin = "margin" in features[0] + has_idx = "metainfo_idx" in features[0] and features[0]["metainfo_idx"] is not None + + for idx, feature in enumerate(features): + features_A.append(self._clean_message(feature["A_data"])) + features_B.append(self._clean_message(feature["B_data"])) + + # import pdb; pdb.set_trace() + image_inputs_A, video_inputs_A = process_vision_info(features_A) + image_inputs_B, video_inputs_B = process_vision_info(features_B) + + video_inputs_A = [video_inputs_A[i].float() / 255.0 for i in range(len(video_inputs_A))] + video_inputs_B = [video_inputs_B[i].float() / 255.0 for i in range(len(video_inputs_B))] + do_rescale = False + # print(f"{video_inputs_A[0].shape}, {video_inputs_B[0].shape}") + + # if not enable_noise: + # print("Not training, no noise added.") + batch_A = self.processor( + text=self.processor.apply_chat_template(features_A, tokenize=False, add_generation_prompt=True), + images=image_inputs_A, + videos=video_inputs_A, + padding=True, + return_tensors="pt", + videos_kwargs={"do_rescale": do_rescale}, + ) + batch_B = self.processor( + text=self.processor.apply_chat_template(features_B, tokenize=False, add_generation_prompt=True), + images=image_inputs_B, + videos=video_inputs_B, + padding=True, + return_tensors="pt", + videos_kwargs={"do_rescale": do_rescale}, + ) + + # pdb.set_trace() + max_len = max(batch_A["input_ids"].shape[1], batch_B["input_ids"].shape[1]) + batch_A["input_ids"], batch_A["attention_mask"] = self._pad_sequence( + batch_A["input_ids"], batch_A["attention_mask"], max_len, "right" + ) + batch_B["input_ids"], batch_B["attention_mask"] = self._pad_sequence( + batch_B["input_ids"], batch_B["attention_mask"], max_len, "right" + ) + # print(f"Batch A: {batch_A['input_ids'].shape}, Batch B: {batch_B['input_ids'].shape}") + + chosen_label = torch.stack([torch.tensor(feature["chosen_label"]) for feature in features]) + + A_scores = torch.stack([torch.tensor(feature["A_scores"]) for feature in features]) + B_scores = torch.stack([torch.tensor(feature["B_scores"]) for feature in features]) + + batch = { + "A": batch_A, + "B": batch_B, + "return_loss": True, + "chosen_label": chosen_label, + "A_scores": A_scores, + "B_scores": B_scores, + } + + if has_idx: + metainfo_idx = torch.stack([torch.tensor(feature["metainfo_idx"]) for feature in features]) + batch["metainfo_idx"] = metainfo_idx + + # pdb.set_trace() + return batch + + # except Exception as e: + # print(f"Error processing batch: {e} in reading.") + # # get next batch + # return None diff --git a/Helios/helios/videoalign/inference.py b/Helios/helios/videoalign/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..4e6a06c9ab8b62cb2dfe23734e900c3f81bed70d --- /dev/null +++ b/Helios/helios/videoalign/inference.py @@ -0,0 +1,321 @@ +import json +import os + + +os.environ["TOKENIZERS_PARALLELISM"] = "false" +from collections.abc import Mapping + +import torch + +from .data import DataConfig +from .prompt_template import build_prompt +from .train_reward import create_model_and_processor +from .utils import ModelConfig, PEFTLoraConfig, TrainingConfig, load_model_from_checkpoint +from .vision_process import process_video_tensor, process_vision_info + + +def load_configs_from_json(config_path): + with open(config_path, "r") as f: + config_dict = json.load(f) + + # del config_dict["training_args"]["_n_gpu"] + del config_dict["data_config"]["meta_data"] + del config_dict["data_config"]["data_dir"] + + return ( + config_dict["data_config"], + None, + config_dict["model_config"], + config_dict["peft_lora_config"], + config_dict["inference_config"] if "inference_config" in config_dict else None, + ) + + +class VideoVLMRewardInference: + def __init__(self, load_from_pretrained, load_from_pretrained_step=-1, device="cuda", dtype=torch.bfloat16): + config_path = os.path.join(load_from_pretrained, "model_config.json") + data_config, _, model_config, peft_lora_config, inference_config = load_configs_from_json(config_path) + data_config = DataConfig(**data_config) + model_config = ModelConfig(**model_config) + peft_lora_config = PEFTLoraConfig(**peft_lora_config) + + training_args = TrainingConfig( + load_from_pretrained=load_from_pretrained, + load_from_pretrained_step=load_from_pretrained_step, + gradient_checkpointing=False, + disable_flash_attn2=False, + bf16=True if dtype == torch.bfloat16 else False, + fp16=True if dtype == torch.float16 else False, + output_dir="", + ) + + model, processor, peft_config = create_model_and_processor( + model_config=model_config, + peft_lora_config=peft_lora_config, + training_args=training_args, + ) + + self.device = device + + model, checkpoint_step = load_model_from_checkpoint(model, load_from_pretrained, load_from_pretrained_step) + model.eval() + + self.model = model + self.processor = processor + + self.model.to(self.device) + + self.data_config = data_config + + self.inference_config = inference_config + + def _norm(self, reward): + if self.inference_config is None: + return reward + else: + reward["VQ"] = (reward["VQ"] - self.inference_config["VQ_mean"]) / self.inference_config["VQ_std"] + reward["MQ"] = (reward["MQ"] - self.inference_config["MQ_mean"]) / self.inference_config["MQ_std"] + reward["TA"] = (reward["TA"] - self.inference_config["TA_mean"]) / self.inference_config["TA_std"] + return reward + + def _pad_sequence(self, sequences, attention_mask, max_len, padding_side="right"): + """ + Pad the sequences to the maximum length. + """ + assert padding_side in ["right", "left"] + if sequences.shape[1] >= max_len: + return sequences, attention_mask + + pad_len = max_len - sequences.shape[1] + padding = (0, pad_len) if padding_side == "right" else (pad_len, 0) + + sequences_padded = torch.nn.functional.pad( + sequences, padding, "constant", self.processor.tokenizer.pad_token_id + ) + attention_mask_padded = torch.nn.functional.pad(attention_mask, padding, "constant", 0) + + return sequences_padded, attention_mask_padded + + def _prepare_input(self, data): + """ + Prepare `inputs` before feeding them to the model, converting them to tensors if they are not already and + handling potential state. + """ + if isinstance(data, Mapping): + return type(data)({k: self._prepare_input(v) for k, v in data.items()}) + elif isinstance(data, (tuple, list)): + return type(data)(self._prepare_input(v) for v in data) + elif isinstance(data, torch.Tensor): + kwargs = {"device": self.device} + ## TODO: Maybe need to add dtype + # if self.is_deepspeed_enabled and (torch.is_floating_point(data) or torch.is_complex(data)): + # # NLP models inputs are int/uint and those get adjusted to the right dtype of the + # # embedding. Other models such as wav2vec2's inputs are already float and thus + # # may need special handling to match the dtypes of the model + # kwargs.update({"dtype": self.accelerator.state.deepspeed_plugin.hf_ds_config.dtype()}) + return data.to(**kwargs) + return data + + def _prepare_inputs(self, inputs): + """ + Prepare `inputs` before feeding them to the model, converting them to tensors if they are not already and + handling potential state. + """ + inputs = self._prepare_input(inputs) + if len(inputs) == 0: + raise ValueError + return inputs + + def prepare_batch(self, videos, prompts, fps=None, num_frames=None, max_pixels=None): + """ + Modified to accept either file paths (str) or Tensors (torch.Tensor) in 'videos'. + """ + fps = self.data_config.fps if fps is None else fps + num_frames = self.data_config.num_frames if num_frames is None else num_frames + max_pixels = self.data_config.max_frame_pixels if max_pixels is None else max_pixels + + if isinstance(videos, list) and all(isinstance(v, torch.Tensor) for v in videos): + chat_data = [ + [ + { + "role": "user", + "content": [ + {"type": "video", "video": "file://dummy_path"}, + { + "type": "text", + "text": build_prompt( + prompt, self.data_config.eval_dim, self.data_config.prompt_template_type + ), + }, + ], + } + ] + for prompt in prompts + ] + + image_inputs = None + video_inputs = [process_video_tensor(tensor) for tensor in videos] + else: + if num_frames is None: + chat_data = [ + [ + { + "role": "user", + "content": [ + { + "type": "video", + "video": f"file://{video_path}", + "max_pixels": max_pixels, + "fps": fps, + "sample_type": self.data_config.sample_type, + }, + { + "type": "text", + "text": build_prompt( + prompt, self.data_config.eval_dim, self.data_config.prompt_template_type + ), + }, + ], + }, + ] + for video_path, prompt in zip(videos, prompts) + ] + else: + chat_data = [ + [ + { + "role": "user", + "content": [ + { + "type": "video", + "video": f"file://{video_path}", + "max_pixels": max_pixels, + "nframes": num_frames, + "sample_type": self.data_config.sample_type, + }, + { + "type": "text", + "text": build_prompt( + prompt, self.data_config.eval_dim, self.data_config.prompt_template_type + ), + }, + ], + }, + ] + for video_path, prompt in zip(videos, prompts) + ] + image_inputs, video_inputs = process_vision_info(chat_data) + + batch = self.processor( + text=self.processor.apply_chat_template(chat_data, tokenize=False, add_generation_prompt=True), + images=image_inputs, + videos=video_inputs, + padding=True, + return_tensors="pt", + videos_kwargs={"do_rescale": True}, + ) + batch = self._prepare_inputs(batch) + return batch + + def reward( + self, + videos, + prompts, + fps=None, + num_frames=None, + max_pixels=None, + use_norm=True, + return_batch_score=False, + device="cpu", + dtype=torch.float32, + ): + """ + videos: List[str] (paths) OR List[torch.Tensor] + """ + assert fps is None or num_frames is None, "fps and num_frames cannot be set at the same time." + + batch = self.prepare_batch(videos, prompts, fps, num_frames, max_pixels) + rewards = self.model(return_dict=True, **batch)["logits"] + + rewards = [{"VQ": reward[0].item(), "MQ": reward[1].item(), "TA": reward[2].item()} for reward in rewards] + for i in range(len(rewards)): + if use_norm: + rewards[i] = self._norm(rewards[i]) + rewards[i]["Overall"] = rewards[i]["VQ"] + rewards[i]["MQ"] + rewards[i]["TA"] + if return_batch_score: + batch_score = { + "VQ": torch.tensor(sum(r["VQ"] for r in rewards) / len(rewards), device=device, dtype=dtype), + "MQ": torch.tensor(sum(r["MQ"] for r in rewards) / len(rewards), device=device, dtype=dtype), + "TA": torch.tensor(sum(r["TA"] for r in rewards) / len(rewards), device=device, dtype=dtype), + "Overall": torch.tensor(sum(r["Overall"] for r in rewards) / len(rewards), device=device, dtype=dtype), + } + return batch_score + + return rewards + + +def main(): + load_from_pretrained = "/mnt/bn/yufan-dev-my/ysh_new/Ckpts/Videoreward" + device = "cuda:0" + dtype = torch.bfloat16 + + inferencer = VideoVLMRewardInference(load_from_pretrained, device=device, dtype=dtype) + + video_paths = [ + "/mnt/bn/yufan-dev-my/ysh_new/Codes/0_exps/0_results/t2v/short/sana-video/2_240_ori81.mp4", + "/mnt/bn/yufan-dev-my/ysh_new/Codes/0_exps/0_results/t2v/short/sana-video/4_240_ori81.mp4", + "/mnt/bn/yufan-dev-my/ysh_new/Codes/0_exps/0_results/t2v/short/sana-video/5_240_ori81.mp4", + ] + + prompts = [ + "A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity.", + "A drone view of waves crashing against the rugged cliffs along Big Sur’s Garay Point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore, casting long shadows. In the distance, a small island with a lighthouse stands tall, its beam piercing the twilight. Green shrubbery covers the cliff’s edge, and the steep drop from the road down to the beach is a dramatic feat, with the cliff’s edges jutting out over the sea. The camera angle provides a bird's-eye view, capturing the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway. The scene is bathed in a warm, golden hue, highlighting the textures and details of the rocky terrain.", + "A close-up 3D animated scene of a short, fluffy monster kneeling beside a melting red candle. The monster has large, wide eyes and an open mouth, gazing at the flame with a look of wonder and curiosity. Its soft, fluffy fur contrasts with the warm, dramatic lighting that highlights every detail of its gentle, innocent expression. The pose conveys a sense of playfulness and exploration, as if the creature is discovering the world for the first time. The background features a cozy, warmly lit room with subtle hints of a fireplace and soft furnishings, enhancing the overall atmosphere. The use of warm colors and dramatic lighting creates a captivating and inviting scene.", + ] + + # # Way 1 + print(f"\n{'=' * 20} Way 1: File Path Input {'=' * 20}") + with torch.no_grad(): + rewards_path = inferencer.reward(video_paths, prompts, use_norm=True) + print(rewards_path) + + # Way 2 + print(f"\n{'=' * 20} Way 2: Tensor Input {'=' * 20}") + from video_reader import PyVideoReader + + video_tensors = [] + print("Loading videos into Tensors manually...") + for i, path in enumerate(video_paths): + vr = PyVideoReader(path, threads=0) + frames = vr.get_batch(range(len(vr))) + tensor_input = torch.tensor(frames).permute(0, 3, 1, 2) + video_tensors.append(tensor_input) + del video_paths + + print(f"Loaded {len(video_tensors)} tensors.") + + with torch.no_grad(): + rewards_tensor = inferencer.reward( + video_tensors, # [torch.Size([249, 3, 480, 832]), torch.Size([249, 3, 480, 832]), torch.Size([249, 3, 480, 832])] + prompts, + use_norm=True, + return_batch_score=False, + ) + print(rewards_tensor) + + # --- 验证环节 --- + print(f"\n{'=' * 20} Verification {'=' * 20}") + for i, (r_path, r_tensor) in enumerate(zip(rewards_path, rewards_tensor)): + score_path = r_path["Overall"] + score_tensor = r_tensor["Overall"] + diff = abs(score_path - score_tensor) + + status = "✅ CONSISTENT" if diff < 1e-3 else "❌ MISMATCH" + print(f"Video {i + 1}:") + print(f" Path Input Score: {score_path:.4f}") + print(f" Tensor Input Score: {score_tensor:.4f}") + print(f" Difference: {diff:.6f} -> {status}") + + +if __name__ == "__main__": + main() diff --git a/Helios/helios/videoalign/prompt_template.py b/Helios/helios/videoalign/prompt_template.py new file mode 100644 index 0000000000000000000000000000000000000000..88aca67afe33e3b4f6110178eb93a3440404b7cf --- /dev/null +++ b/Helios/helios/videoalign/prompt_template.py @@ -0,0 +1,129 @@ +VIDEOSCORE_QUERY_PROMPT = """ +Suppose you are an expert in judging and evaluating the quality of AI-generated videos, +please watch the frames of a given video and see the text prompt for generating the video, +then give scores based on its {dimension_name}, i.e., {dimension_description}. +Output a float number from 1.0 to 5.0 for this dimension, +the higher the number is, the better the video performs in that sub-score, +the lowest 1.0 means Bad, the highest 5.0 means Perfect/Real (the video is like a real video). +The text prompt used for generation is "{text_prompt}". +""" + +DIMENSION_DESCRIPTIONS = { + "VQ": ["visual quality", "the quality of the video in terms of clearness, resolution, brightness, and color"], + "TA": ["text-to-video alignment", "the alignment between the text prompt and the video content and motion"], + "MQ": ["motion quality", "the quality of the motion in terms of consistency, smoothness, and completeness"], + "Overall": [ + "Overall Performance", + "the overall performance of the video in terms of visual quality, text-to-video alignment, and motion quality", + ], +} + +SIMPLE_PROMPT = """ +Please evaluate the {dimension_name} of a generated video. Consider {dimension_description}. +The text prompt used for generation is "{text_prompt}". +""" + +DETAILED_PROMPT_WITH_SPECIAL_TOKEN = """ +You are tasked with evaluating a generated video based on three distinct criteria: Visual Quality, Motion Quality, and Text Alignment. Please provide a rating from 0 to 10 for each of the three categories, with 0 being the worst and 10 being the best. Each evaluation should be independent of the others. + +**Visual Quality:** +Evaluate the overall visual quality of the video, with a focus on static factors. The following sub-dimensions should be considered: +- **Reasonableness:** The video should not contain any significant biological or logical errors, such as abnormal body structures or nonsensical environmental setups. +- **Clarity:** Evaluate the sharpness and visibility of the video. The image should be clear and easy to interpret, with no blurring or indistinct areas. +- **Detail Richness:** Consider the level of detail in textures, materials, lighting, and other visual elements (e.g., hair, clothing, shadows). +- **Aesthetic and Creativity:** Assess the artistic aspects of the video, including the color scheme, composition, atmosphere, depth of field, and the overall creative appeal. The scene should convey a sense of harmony and balance. +- **Safety:** The video should not contain harmful or inappropriate content, such as political, violent, or adult material. If such content is present, the image quality and satisfaction score should be the lowest possible. + +Please provide the ratings of Visual Quality: <|VQ_reward|> +END + +**Motion Quality:** +Assess the dynamic aspects of the video, with a focus on dynamic factors. Consider the following sub-dimensions: +- **Stability:** Evaluate the continuity and stability between frames. There should be no sudden, unnatural jumps, and the video should maintain stable attributes (e.g., no fluctuating colors, textures, or missing body parts). +- **Naturalness:** The movement should align with physical laws and be realistic. For example, clothing should flow naturally with motion, and facial expressions should change appropriately (e.g., blinking, mouth movements). +- **Aesthetic Quality:** The movement should be smooth and fluid. The transitions between different motions or camera angles should be seamless, and the overall dynamic feel should be visually pleasing. +- **Fusion:** Ensure that elements in motion (e.g., edges of the subject, hair, clothing) blend naturally with the background, without obvious artifacts or the feeling of cut-and-paste effects. +- **Clarity of Motion:** The video should be clear and smooth in motion. Pay attention to any areas where the video might have blurry or unsteady sections that hinder visual continuity. +- **Amplitude:** If the video is largely static or has little movement, assign a low score for motion quality. + +Please provide the ratings of Motion Quality: <|MQ_reward|> +END + +**Text Alignment:** +Assess how well the video matches the textual prompt across the following sub-dimensions: +- **Subject Relevance** Evaluate how accurately the subject(s) in the video (e.g., person, animal, object) align with the textual description. The subject should match the description in terms of number, appearance, and behavior. +- **Motion Relevance:** Evaluate if the dynamic actions (e.g., gestures, posture, facial expressions like talking or blinking) align with the described prompt. The motion should match the prompt in terms of type, scale, and direction. +- **Environment Relevance:** Assess whether the background and scene fit the prompt. This includes checking if real-world locations or scenes are accurately represented, though some stylistic adaptation is acceptable. +- **Style Relevance:** If the prompt specifies a particular artistic or stylistic style, evaluate how well the video adheres to this style. +- **Camera Movement Relevance:** Check if the camera movements (e.g., following the subject, focus shifts) are consistent with the expected behavior from the prompt. + +Textual prompt - {text_prompt} +Please provide the ratings of Text Alignment: <|TA_reward|> +END +""" + +DETAILED_PROMPT = """ +You are tasked with evaluating a generated video based on three distinct criteria: Visual Quality, Motion Quality, and Text Alignment. Please provide a rating from 0 to 10 for each of the three categories, with 0 being the worst and 10 being the best. Each evaluation should be independent of the others. + +**Visual Quality:** +Evaluate the overall visual quality of the video, with a focus on static factors. The following sub-dimensions should be considered: +- **Reasonableness:** The video should not contain any significant biological or logical errors, such as abnormal body structures or nonsensical environmental setups. +- **Clarity:** Evaluate the sharpness and visibility of the video. The image should be clear and easy to interpret, with no blurring or indistinct areas. +- **Detail Richness:** Consider the level of detail in textures, materials, lighting, and other visual elements (e.g., hair, clothing, shadows). +- **Aesthetic and Creativity:** Assess the artistic aspects of the video, including the color scheme, composition, atmosphere, depth of field, and the overall creative appeal. The scene should convey a sense of harmony and balance. +- **Safety:** The video should not contain harmful or inappropriate content, such as political, violent, or adult material. If such content is present, the image quality and satisfaction score should be the lowest possible. + +**Motion Quality:** +Assess the dynamic aspects of the video, with a focus on dynamic factors. Consider the following sub-dimensions: +- **Stability:** Evaluate the continuity and stability between frames. There should be no sudden, unnatural jumps, and the video should maintain stable attributes (e.g., no fluctuating colors, textures, or missing body parts). +- **Naturalness:** The movement should align with physical laws and be realistic. For example, clothing should flow naturally with motion, and facial expressions should change appropriately (e.g., blinking, mouth movements). +- **Aesthetic Quality:** The movement should be smooth and fluid. The transitions between different motions or camera angles should be seamless, and the overall dynamic feel should be visually pleasing. +- **Fusion:** Ensure that elements in motion (e.g., edges of the subject, hair, clothing) blend naturally with the background, without obvious artifacts or the feeling of cut-and-paste effects. +- **Clarity of Motion:** The video should be clear and smooth in motion. Pay attention to any areas where the video might have blurry or unsteady sections that hinder visual continuity. +- **Amplitude:** If the video is largely static or has little movement, assign a low score for motion quality. + + +**Text Alignment:** +Assess how well the video matches the textual prompt across the following sub-dimensions: +- **Subject Relevance** Evaluate how accurately the subject(s) in the video (e.g., person, animal, object) align with the textual description. The subject should match the description in terms of number, appearance, and behavior. +- **Motion Relevance:** Evaluate if the dynamic actions (e.g., gestures, posture, facial expressions like talking or blinking) align with the described prompt. The motion should match the prompt in terms of type, scale, and direction. +- **Environment Relevance:** Assess whether the background and scene fit the prompt. This includes checking if real-world locations or scenes are accurately represented, though some stylistic adaptation is acceptable. +- **Style Relevance:** If the prompt specifies a particular artistic or stylistic style, evaluate how well the video adheres to this style. +- **Camera Movement Relevance:** Check if the camera movements (e.g., following the subject, focus shifts) are consistent with the expected behavior from the prompt. + +Textual prompt - {text_prompt} +Please provide the ratings of Visual Quality, Motion Quality, and Text Alignment. +""" + +SIMPLE_PROMPT_NO_PROMPT = """ +Please evaluate the {dimension_name} of a generated video. Consider {dimension_description}. +""" + + +def build_prompt(prompt, dimension, template_type): + if isinstance(dimension, list) and len(dimension) > 1: + dimension_name = ", ".join([DIMENSION_DESCRIPTIONS[d][0] for d in dimension]) + dimension_name = f"overall performance({dimension_name})" + dimension_description = "the overall performance of the video" + else: + if isinstance(dimension, list): + dimension = dimension[0] + dimension_name = DIMENSION_DESCRIPTIONS[dimension][0] + dimension_description = DIMENSION_DESCRIPTIONS[dimension][1] + + if template_type == "none": + return prompt + elif template_type == "simple": + return SIMPLE_PROMPT.format( + dimension_name=dimension_name, dimension_description=dimension_description, text_prompt=prompt + ) + elif template_type == "video_score": + return VIDEOSCORE_QUERY_PROMPT.format( + dimension_name=dimension_name, dimension_description=dimension_description, text_prompt=prompt + ) + elif template_type == "detailed_special": + return DETAILED_PROMPT_WITH_SPECIAL_TOKEN.format(text_prompt=prompt) + elif template_type == "detailed": + return DETAILED_PROMPT.format(text_prompt=prompt) + else: + raise ValueError("Invalid template type") diff --git a/Helios/helios/videoalign/train_reward.py b/Helios/helios/videoalign/train_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..7311aa1a75765a1ef5fb5fcb8fede16a52e1d880 --- /dev/null +++ b/Helios/helios/videoalign/train_reward.py @@ -0,0 +1,118 @@ +import torch +from peft import LoraConfig, get_peft_model +from transformers import AutoProcessor + +from diffusers.utils import is_flash_attn_3_available, is_flash_attn_available + +from .trainer import Qwen2VLRewardModelBT + + +def find_target_linear_names(model, num_lora_modules=-1, lora_namespan_exclude=[], verbose=False): + """ + Find the target linear modules for LoRA. + """ + linear_cls = torch.nn.Linear + embedding_cls = torch.nn.Embedding + lora_module_names = [] + + for name, module in model.named_modules(): + if any(ex_keyword in name for ex_keyword in lora_namespan_exclude): + # print(f"Excluding module: {name}") + continue + + if isinstance(module, (linear_cls, embedding_cls)): + lora_module_names.append(name) + + if num_lora_modules > 0: + lora_module_names = lora_module_names[-num_lora_modules:] + if verbose: + print(f"Found {len(lora_module_names)} lora modules: {lora_module_names}") + return lora_module_names + + +def set_requires_grad(parameters, requires_grad): + for p in parameters: + p.requires_grad = requires_grad + + +def create_model_and_processor( + model_config, + peft_lora_config, + training_args, + cache_dir=None, +): + # create model + torch_dtype = ( + model_config.torch_dtype + if model_config.torch_dtype in ["auto", None] + else getattr(torch, model_config.torch_dtype) + ) + model_kwargs = { + "revision": model_config.model_revision, + "use_cache": True if training_args.gradient_checkpointing else False, + } + # pdb.set_trace() + + # create processor and set padding + processor = AutoProcessor.from_pretrained( + model_config.model_name_or_path, padding_side="right", cache_dir=cache_dir + ) + + special_token_ids = None + if model_config.use_special_tokens: + special_tokens = ["<|VQ_reward|>", "<|MQ_reward|>", "<|TA_reward|>"] + processor.tokenizer.add_special_tokens({"additional_special_tokens": special_tokens}) + special_token_ids = processor.tokenizer.convert_tokens_to_ids(special_tokens) + + if is_flash_attn_3_available(): + attn_implementation = "flash_attention_3" + elif is_flash_attn_available(): + attn_implementation = "flash_attention_2" + else: + attn_implementation = "sdpa" + + print(f"Using {attn_implementation} for Reward!") + + model = Qwen2VLRewardModelBT.from_pretrained( + model_config.model_name_or_path, + output_dim=model_config.output_dim, + reward_token=model_config.reward_token, + special_token_ids=special_token_ids, + dtype=torch_dtype, + attn_implementation=attn_implementation, + cache_dir=cache_dir, + **model_kwargs, + ) + if model_config.use_special_tokens: + model.resize_token_embeddings(len(processor.tokenizer)) + + if training_args.bf16: + model.to(torch.bfloat16) + if training_args.fp16: + model.to(torch.float16) + + # create lora and peft model + if peft_lora_config.lora_enable: + target_modules = find_target_linear_names( + model, + num_lora_modules=peft_lora_config.num_lora_modules, + lora_namespan_exclude=peft_lora_config.lora_namespan_exclude, + ) + peft_config = LoraConfig( + target_modules=target_modules, + r=peft_lora_config.lora_r, + lora_alpha=peft_lora_config.lora_alpha, + lora_dropout=peft_lora_config.lora_dropout, + task_type=peft_lora_config.lora_task_type, + use_rslora=peft_lora_config.use_rslora, + bias="none", + modules_to_save=peft_lora_config.lora_modules_to_save, + ) + model = get_peft_model(model, peft_config) + else: + peft_config = None + + model.config.tokenizer_padding_side = processor.tokenizer.padding_side + model.config.pad_token_id = processor.tokenizer.pad_token_id + + return model, processor, peft_config diff --git a/Helios/helios/videoalign/trainer.py b/Helios/helios/videoalign/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6d35c848af5bfcd6821bf08d610211126d9521 --- /dev/null +++ b/Helios/helios/videoalign/trainer.py @@ -0,0 +1,133 @@ +# from training.train_utils import get_peft_state_maybe_zero_3, get_peft_state_non_lora_maybe_zero_3 +from typing import List, Optional + +import torch +import torch.nn as nn +from transformers import Qwen2VLForConditionalGeneration +from transformers.trainer import ( + is_torch_xla_available, +) + + +if is_torch_xla_available(): + pass +else: + IS_XLA_FSDPV2_POST_2_2 = False + + +class Qwen2VLRewardModelBT(Qwen2VLForConditionalGeneration): + def __init__(self, config, output_dim=4, reward_token="last", special_token_ids=None): + super().__init__(config) + # pdb.set_trace() + self.output_dim = output_dim + self.rm_head = nn.Linear(config.hidden_size, output_dim, bias=False) + self.reward_token = reward_token + + self.special_token_ids = special_token_ids + if self.special_token_ids is not None: + self.reward_token = "special" + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + pixel_values: Optional[torch.Tensor] = None, + pixel_values_videos: Optional[torch.FloatTensor] = None, + image_grid_thw: Optional[torch.LongTensor] = None, + video_grid_thw: Optional[torch.LongTensor] = None, + rope_deltas: Optional[torch.LongTensor] = None, + ): + ## modified from the origin class Qwen2VLForConditionalGeneration + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + # pdb.set_trace() + if inputs_embeds is None: + # inputs_embeds = self.model.embed_tokens(input_ids) + inputs_embeds = self.get_input_embeddings()(input_ids) + if pixel_values is not None: + pixel_values = pixel_values.type(self.visual.get_dtype()) + image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw) + image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds) + image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) + + if pixel_values_videos is not None: + pixel_values_videos = pixel_values_videos.type(self.visual.get_dtype()) + video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw) + video_mask = (input_ids == self.config.video_token_id).unsqueeze(-1).expand_as(inputs_embeds) + video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) + + if attention_mask is not None: + attention_mask = attention_mask.to(inputs_embeds.device) + + outputs = self.model( + input_ids=None, + position_ids=position_ids, + attention_mask=attention_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] # [B, L, D] + + logits = self.rm_head(hidden_states) # [B, L, N] + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + + ## get sequence length + if self.config.pad_token_id is None and batch_size != 1: + raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility + sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1 + sequence_lengths = sequence_lengths % input_ids.shape[-1] + sequence_lengths = sequence_lengths.to(logits.device) + else: + sequence_lengths = -1 + + ## get the last token's logits + if self.reward_token == "last": + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + elif self.reward_token == "mean": + ## get the mean of all valid tokens' logits + valid_lengths = torch.clamp(sequence_lengths, min=0, max=logits.size(1) - 1) + pooled_logits = torch.stack([logits[i, : valid_lengths[i]].mean(dim=0) for i in range(batch_size)]) + elif self.reward_token == "special": + # special_token_ids = self.tokenizer.convert_tokens_to_ids(self.special_tokens) + # create a mask for special tokens + special_token_mask = torch.zeros_like(input_ids, dtype=torch.bool) + for special_token_id in self.special_token_ids: + special_token_mask = special_token_mask | (input_ids == special_token_id) + pooled_logits = logits[special_token_mask, ...] + pooled_logits = pooled_logits.view(batch_size, 3, -1) # [B, 3, N] assert 3 attributes + if self.output_dim == 3: + pooled_logits = pooled_logits.diagonal(dim1=1, dim2=2) + pooled_logits = pooled_logits.view(batch_size, -1) + + # pdb.set_trace() + else: + raise ValueError("Invalid reward_token") + + return {"logits": pooled_logits} diff --git a/Helios/helios/videoalign/utils.py b/Helios/helios/videoalign/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6237c8a2c78a86300087043dbccb5ed888ab8d9c --- /dev/null +++ b/Helios/helios/videoalign/utils.py @@ -0,0 +1,236 @@ +import glob +import os +from dataclasses import dataclass, field +from typing import List, Literal, Optional + +import safetensors +import torch +from transformers import TrainingArguments + + +########## DataClass For Configure ########## + + +@dataclass +class TrainingConfig(TrainingArguments): + max_length: Optional[int] = None + dataset_num_proc: Optional[int] = None + center_rewards_coefficient: Optional[float] = None + disable_flash_attn2: bool = field(default=False) + + vision_lr: Optional[float] = None + merger_lr: Optional[float] = None + special_token_lr: Optional[float] = None + + conduct_eval: Optional[bool] = True + load_from_pretrained: str = None + load_from_pretrained_step: int = None + logging_epochs: Optional[float] = None + eval_epochs: Optional[float] = None + save_epochs: Optional[float] = None + remove_unused_columns: Optional[bool] = False + + save_full_model: Optional[bool] = False + + +@dataclass +class PEFTLoraConfig: + lora_enable: bool = False + vision_lora: bool = False + lora_r: int = 16 + lora_alpha: int = 32 + lora_dropout: float = 0.05 + lora_target_modules: Optional[List[str]] = None + lora_namespan_exclude: Optional[List[str]] = None + lora_modules_to_save: Optional[List[str]] = None + lora_task_type: str = "CAUSAL_LM" + use_rslora: bool = False + num_lora_modules: int = -1 + + def __post_init__(self): + if isinstance(self.lora_target_modules, list) and len(self.lora_target_modules) == 1: + self.lora_target_modules = self.lora_target_modules[0] + + if isinstance(self.lora_namespan_exclude, list) and len(self.lora_namespan_exclude) == 1: + self.lora_namespan_exclude = self.lora_namespan_exclude[0] + + +@dataclass +class ModelConfig: + model_name_or_path: Optional[str] = None + model_revision: str = "main" + + output_dim: int = 1 + + use_special_tokens: bool = False + + freeze_vision_tower: bool = field(default=False) + freeze_llm: bool = field(default=False) + tune_merger: bool = field(default=False) + + torch_dtype: Optional[Literal["auto", "bfloat16", "float16", "float32"]] = None + trust_remote_code: bool = False + attn_implementation: Optional[str] = None + load_in_8bit: bool = False + load_in_4bit: bool = False + bnb_4bit_quant_type: Literal["fp4", "nf4"] = "nf4" + use_bnb_nested_quant: bool = False + reward_token: Literal["last", "mean", "special"] = "last" + loss_type: Literal["bt", "reg", "btt", "margin", "constant_margin", "scaled"] = "regular" + + def __post_init__(self): + if self.load_in_8bit and self.load_in_4bit: + raise ValueError("You can't use 8 bit and 4 bit precision at the same time") + + # if isinstance(self.lora_target_modules, list) and len(self.lora_target_modules) == 1: + # self.lora_target_modules = self.lora_target_modules[0] + + # if isinstance(self.lora_namespan_exclude, list) and len(self.lora_namespan_exclude) == 1: + # self.lora_namespan_exclude = self.lora_namespan_exclude[0] + + +########## Functions for get trainable modules' parameters ########## + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + + if hasattr(param, "ds_id"): + # if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + # if not ignore_status: + # logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +# Borrowed from peft.utils.get_peft_model_state_dict +def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} + return to_return + + +def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): + to_return = {k: t for k, t in named_params if "lora_" not in k} + if require_grad_only: + to_return = {k: t for k, t in to_return.items() if t.requires_grad} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +########## Load Models From Folder ########## + + +def _insert_adapter_name_into_state_dict( + state_dict: dict[str, torch.Tensor], adapter_name: str, parameter_prefix: str +) -> dict[str, torch.Tensor]: + """Utility function to remap the state_dict keys to fit the PEFT model by inserting the adapter name.""" + peft_model_state_dict = {} + for key, val in state_dict.items(): + if parameter_prefix in key: + suffix = key.split(parameter_prefix)[1] + if "." in suffix: + suffix_to_replace = ".".join(suffix.split(".")[1:]) + key = key.replace(suffix_to_replace, f"{adapter_name}.{suffix_to_replace}") + else: + key = f"{key}.{adapter_name}" + peft_model_state_dict[key] = val + else: + peft_model_state_dict[key] = val + return peft_model_state_dict + + +def save_video(tensor, path): + from torchvision.io import write_video + + tensor = tensor * 255.0 + tensor = tensor.permute(0, 2, 3, 1) + tensor = tensor.clamp(0, 255).byte() + write_video(path, tensor, 4, video_codec="h264") + + +def load_model_from_checkpoint(model, checkpoint_dir, checkpoint_step): + checkpoint_paths = glob.glob(os.path.join(checkpoint_dir, "checkpoint-*")) + checkpoint_paths.sort(key=lambda x: int(x.split("-")[-1]), reverse=True) + + if checkpoint_step is None or checkpoint_step == -1: + # get the latest checkpoint + checkpoint_path = checkpoint_paths[0] + print(f"===> Checkpoint step is not provided, using the latest checkpoint: {checkpoint_path}") + else: + checkpoint_path = os.path.join(checkpoint_dir, f"checkpoint-{checkpoint_step}") + if checkpoint_path not in checkpoint_paths: + checkpoint_path = checkpoint_paths[0] + print(f"===> Checkpoint step {checkpoint_step} not found, using the latest checkpoint: {checkpoint_path}") + else: + print(f"===> Checkpoint step {checkpoint_step} found, using the specified checkpoint: {checkpoint_path}") + + checkpoint_step = checkpoint_path.split("checkpoint-")[-1].split("/")[0] + + full_ckpt = os.path.join(checkpoint_path, "model.pth") + lora_ckpt = os.path.join(checkpoint_path, "adapter_model.safetensors") + non_lora_ckpt = os.path.join(checkpoint_path, "non_lora_state_dict.pth") + if os.path.exists(full_ckpt): + model_state_dict = torch.load(full_ckpt, map_location="cpu", weights_only=True) + # Create a new state_dict to store the modified key-value pairs + new_state_dict = {} + + # for key, value in model_state_dict.items(): + # if key.startswith("base_model.model.model"): + # new_key = "base_model.model.model.language_model" + key[len("base_model.model.model"):] + # new_state_dict[new_key] = value + # elif key.startswith("base_model.model.visual"): + # new_key = "base_model.model.model.visual" + key[len("base_model.model.visual"):] + # new_state_dict[new_key] = value + # else: + # new_state_dict[key] = value + for key, value in model_state_dict.items(): + if key.startswith("base_model.model.model"): + new_key = "base_model.model.model.language_model" + key[len("base_model.model.model") :] + new_state_dict[new_key] = value + elif key.startswith("base_model.model.visual"): + new_key = "base_model.model.model.visual" + key[len("base_model.model.visual") :] + new_state_dict[new_key] = value + else: + new_state_dict[key] = value + + # Load the modified state_dict into the model + model.load_state_dict(new_state_dict) + # model_state_dict = torch.load(full_ckpt, map_location="cpu") + # model.load_state_dict(model_state_dict) + else: + lora_state_dict = safetensors.torch.load_file(lora_ckpt) + non_lora_state_dict = torch.load(non_lora_ckpt, map_location="cpu") + + lora_state_dict = _insert_adapter_name_into_state_dict( + lora_state_dict, adapter_name="default", parameter_prefix="lora_" + ) + + model_state_dict = model.state_dict() + model_state_dict.update(non_lora_state_dict) + model_state_dict.update(lora_state_dict) + model.load_state_dict(model_state_dict) + + return model, checkpoint_step diff --git a/Helios/helios/videoalign/vision_process.py b/Helios/helios/videoalign/vision_process.py new file mode 100644 index 0000000000000000000000000000000000000000..065db90d4df499410d38dde181b065bd8cea0099 --- /dev/null +++ b/Helios/helios/videoalign/vision_process.py @@ -0,0 +1,396 @@ +import base64 +import logging +import math +import os +import sys +import warnings +from functools import lru_cache +from io import BytesIO + +import requests +import torch +import torchvision +from packaging import version +from PIL import Image +from torchvision import io, transforms +from torchvision.transforms import InterpolationMode + + +logger = logging.getLogger(__name__) + +IMAGE_FACTOR = 28 +MIN_PIXELS = 4 * 28 * 28 +MAX_PIXELS = 16384 * 28 * 28 +MAX_RATIO = 200 + +VIDEO_MIN_PIXELS = 128 * 28 * 28 +VIDEO_MAX_PIXELS = 768 * 28 * 28 +VIDEO_TOTAL_PIXELS = 24576 * 28 * 28 +FRAME_FACTOR = 2 +FPS = 2.0 +FPS_MIN_FRAMES = 4 +FPS_MAX_FRAMES = 768 + + +def round_by_factor(number: int, factor: int) -> int: + """Returns the closest integer to 'number' that is divisible by 'factor'.""" + return round(number / factor) * factor + + +def ceil_by_factor(number: int, factor: int) -> int: + """Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'.""" + return math.ceil(number / factor) * factor + + +def floor_by_factor(number: int, factor: int) -> int: + """Returns the largest integer less than or equal to 'number' that is divisible by 'factor'.""" + return math.floor(number / factor) * factor + + +def smart_resize( + height: int, width: int, factor: int = IMAGE_FACTOR, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS +) -> tuple[int, int]: + """ + Rescales the image so that the following conditions are met: + + 1. Both dimensions (height and width) are divisible by 'factor'. + + 2. The total number of pixels is within the range ['min_pixels', 'max_pixels']. + + 3. The aspect ratio of the image is maintained as closely as possible. + """ + if max(height, width) / min(height, width) > MAX_RATIO: + raise ValueError( + f"absolute aspect ratio must be smaller than {MAX_RATIO}, got {max(height, width) / min(height, width)}" + ) + h_bar = max(factor, round_by_factor(height, factor)) + w_bar = max(factor, round_by_factor(width, factor)) + if h_bar * w_bar > max_pixels: + beta = math.sqrt((height * width) / max_pixels) + h_bar = floor_by_factor(height / beta, factor) + w_bar = floor_by_factor(width / beta, factor) + elif h_bar * w_bar < min_pixels: + beta = math.sqrt(min_pixels / (height * width)) + h_bar = ceil_by_factor(height * beta, factor) + w_bar = ceil_by_factor(width * beta, factor) + return h_bar, w_bar + + +def fetch_image(ele: dict[str, str | Image.Image], size_factor: int = IMAGE_FACTOR) -> Image.Image: + if "image" in ele: + image = ele["image"] + else: + image = ele["image_url"] + image_obj = None + if isinstance(image, Image.Image): + image_obj = image + elif image.startswith("http://") or image.startswith("https://"): + image_obj = Image.open(requests.get(image, stream=True).raw) + elif image.startswith("file://"): + image_obj = Image.open(image[7:]) + elif image.startswith("data:image"): + if "base64," in image: + _, base64_data = image.split("base64,", 1) + data = base64.b64decode(base64_data) + image_obj = Image.open(BytesIO(data)) + else: + image_obj = Image.open(image) + if image_obj is None: + raise ValueError(f"Unrecognized image input, support local path, http url, base64 and PIL.Image, got {image}") + image = image_obj.convert("RGB") + ## resize + if "resized_height" in ele and "resized_width" in ele: + resized_height, resized_width = smart_resize( + ele["resized_height"], + ele["resized_width"], + factor=size_factor, + ) + else: + width, height = image.size + min_pixels = ele.get("min_pixels", MIN_PIXELS) + max_pixels = ele.get("max_pixels", MAX_PIXELS) + resized_height, resized_width = smart_resize( + height, + width, + factor=size_factor, + min_pixels=min_pixels, + max_pixels=max_pixels, + ) + image = image.resize((resized_width, resized_height)) + + return image + + +def smart_nframes( + ele: dict, + total_frames: int, + video_fps: int | float, +) -> int: + """calculate the number of frames for video used for model inputs. + + Args: + ele (dict): a dict contains the configuration of video. + support either `fps` or `nframes`: + - nframes: the number of frames to extract for model inputs. + - fps: the fps to extract frames for model inputs. + - min_frames: the minimum number of frames of the video, only used when fps is provided. + - max_frames: the maximum number of frames of the video, only used when fps is provided. + total_frames (int): the original total number of frames of the video. + video_fps (int | float): the original fps of the video. + + Raises: + ValueError: nframes should in interval [FRAME_FACTOR, total_frames]. + + Returns: + int: the number of frames for video used for model inputs. + """ + assert not ("fps" in ele and "nframes" in ele), "Only accept either `fps` or `nframes`" + if "nframes" in ele: + nframes = round_by_factor(ele["nframes"], FRAME_FACTOR) + else: + fps = ele.get("fps", FPS) + min_frames = ceil_by_factor(ele.get("min_frames", FPS_MIN_FRAMES), FRAME_FACTOR) + max_frames = floor_by_factor(ele.get("max_frames", min(FPS_MAX_FRAMES, total_frames)), FRAME_FACTOR) + nframes = total_frames / video_fps * fps + nframes = min(max(nframes, min_frames), max_frames) + nframes = round_by_factor(nframes, FRAME_FACTOR) + if nframes > total_frames: + nframes = total_frames + if not (FRAME_FACTOR <= nframes and nframes <= total_frames): + raise ValueError(f"nframes should in interval [{FRAME_FACTOR}, {total_frames}], but got {nframes}.") + return nframes + + +def _read_video_torchvision( + ele: dict, +) -> torch.Tensor: + """read video using torchvision.io.read_video + + Args: + ele (dict): a dict contains the configuration of video. + support keys: + - video: the path of video. support "file://", "http://", "https://" and local path. + - video_start: the start time of video. + - video_end: the end time of video. + Returns: + torch.Tensor: the video tensor with shape (T, C, H, W). + """ + video_path = ele["video"] + if version.parse(torchvision.__version__) < version.parse("0.19.0"): + if "http://" in video_path or "https://" in video_path: + warnings.warn("torchvision < 0.19.0 does not support http/https video path, please upgrade to 0.19.0.") + if "file://" in video_path: + video_path = video_path[7:] + # st = time.time() + video, audio, info = io.read_video( + video_path, + start_pts=ele.get("video_start", 0.0), + end_pts=ele.get("video_end", None), + pts_unit="sec", + output_format="TCHW", + ) + + total_frames, video_fps = video.size(0), info["video_fps"] + # logger.info(f"torchvision: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s") + if ele["sample_type"] == "uniform": + nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps) + idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist() + elif ele["sample_type"] == "multi_pts": + frames_each_pts = 6 + num_pts = 4 + fps = 8 + nframes = int(total_frames * fps // video_fps) + frames_idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist() + + start_pt = int(frames_each_pts // 2) + end_pt = int(nframes - frames_each_pts // 2 - 1) + pts = torch.linspace(start_pt, end_pt, num_pts).round().long().tolist() + idx = [] + for pt in pts: + idx.extend(frames_idx[pt - frames_each_pts // 2 : pt + frames_each_pts // 2]) + + video = video[idx] + return video + + +def is_video_reader_available() -> bool: + import importlib.util + + return importlib.util.find_spec("video_reader") is not None + + +def _read_video_video_reader( + ele: dict, +) -> torch.Tensor: + """read video using video_reader.VideoReader + + Args: + ele (dict): a dict contains the configuration of video. + support keys: + - video: the path of video. support "file://", "http://", "https://" and local path. + - video_start: the start time of video. + - video_end: the end time of video. + Returns: + torch.Tensor: the video tensor with shape (T, C, H, W). + """ + from video_reader import PyVideoReader + + video_path = ele["video"] + # st = time.time() + vr = PyVideoReader(video_path, threads=0) + # TODO: support start_pts and end_pts + if "video_start" in ele or "video_end" in ele: + raise NotImplementedError("not support start_pts and end_pts in video_reader for now.") + total_frames, video_fps = int(len(vr)), float(vr.get_info()["fps"]) + if total_frames <= 93: + video_fps = 16 + elif total_frames <= 49: + video_fps = 8 + # logger.info(f"video_reader: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s") + if ele["sample_type"] == "uniform": + nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps) + # nframes = max(nframes, 8) + # import pdb; pdb.set_trace() + idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist() + elif ele["sample_type"] == "multi_pts": + frames_each_pts = 6 + num_pts = 4 + fps = 8 + nframes = int(total_frames * fps // video_fps) + frames_idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist() + + start_pt = int(frames_each_pts // 2) + end_pt = int(nframes - frames_each_pts // 2 - 1) + pts = torch.linspace(start_pt, end_pt, num_pts).round().long().tolist() + idx = [] + for pt in pts: + idx.extend(frames_idx[pt - frames_each_pts // 2 : pt + frames_each_pts // 2]) + video = vr.get_batch(idx) + video = torch.tensor(video).permute(0, 3, 1, 2) # Convert to TCHW format + return video + + +VIDEO_READER_BACKENDS = { + "video_reader": _read_video_video_reader, + "torchvision": _read_video_torchvision, +} + +FORCE_QWENVL_VIDEO_READER = os.getenv("FORCE_QWENVL_VIDEO_READER", None) + + +@lru_cache(maxsize=1) +def get_video_reader_backend() -> str: + if FORCE_QWENVL_VIDEO_READER is not None: + video_reader_backend = FORCE_QWENVL_VIDEO_READER + elif is_video_reader_available(): + video_reader_backend = "video_reader" + else: + video_reader_backend = "torchvision" + print(f"qwen-vl-utils using {video_reader_backend} to read video.", file=sys.stderr) + return video_reader_backend + + +def fetch_video(ele: dict, image_factor: int = IMAGE_FACTOR) -> torch.Tensor | list[Image.Image]: + if isinstance(ele["video"], str): + video_reader_backend = get_video_reader_backend() + video = VIDEO_READER_BACKENDS[video_reader_backend](ele) + # import pdb; pdb.set_trace() + nframes, _, height, width = video.shape + + min_pixels = ele.get("min_pixels", VIDEO_MIN_PIXELS) + total_pixels = ele.get("total_pixels", VIDEO_TOTAL_PIXELS) + max_pixels = max(min(VIDEO_MAX_PIXELS, total_pixels / nframes * FRAME_FACTOR), int(min_pixels * 1.05)) + max_pixels = ele.get("max_pixels", max_pixels) + if "resized_height" in ele and "resized_width" in ele: + resized_height, resized_width = smart_resize( + ele["resized_height"], + ele["resized_width"], + factor=image_factor, + ) + else: + resized_height, resized_width = smart_resize( + height, + width, + factor=image_factor, + min_pixels=min_pixels, + max_pixels=max_pixels, + ) + video = transforms.functional.resize( + video, + [resized_height, resized_width], + interpolation=InterpolationMode.BICUBIC, + antialias=True, + ).float() + return video + else: + assert isinstance(ele["video"], (list, tuple)) + process_info = ele.copy() + process_info.pop("type", None) + process_info.pop("video", None) + images = [ + fetch_image({"image": video_element, **process_info}, size_factor=image_factor) + for video_element in ele["video"] + ] + nframes = ceil_by_factor(len(images), FRAME_FACTOR) + if len(images) < nframes: + images.extend([images[-1]] * (nframes - len(images))) + return images + + +def extract_vision_info(conversations: list[dict] | list[list[dict]]) -> list[dict]: + vision_infos = [] + if isinstance(conversations[0], dict): + conversations = [conversations] + for conversation in conversations: + for message in conversation: + if isinstance(message["content"], list): + for ele in message["content"]: + if ( + "image" in ele + or "image_url" in ele + or "video" in ele + or ele["type"] in ("image", "image_url", "video") + ): + vision_infos.append(ele) + return vision_infos + + +def process_vision_info( + conversations: list[dict] | list[list[dict]], +) -> tuple[list[Image.Image] | None, list[torch.Tensor | list[Image.Image]] | None]: + vision_infos = extract_vision_info(conversations) + ## Read images or videos + image_inputs = [] + video_inputs = [] + for vision_info in vision_infos: + if "image" in vision_info or "image_url" in vision_info: + image_inputs.append(fetch_image(vision_info)) + elif "video" in vision_info: + video_inputs.append(fetch_video(vision_info)) + else: + raise ValueError("image, image_url or video should in content.") + if len(image_inputs) == 0: + image_inputs = None + if len(video_inputs) == 0: + video_inputs = None + return image_inputs, video_inputs + + +def process_video_tensor( + video: torch.Tensor, + nframes: int = 20, + resized_height: int = 336, + resized_width: int = 588, +) -> torch.Tensor: + T, C, H, W = video.shape + + idx = torch.linspace(0, T - 1, nframes).round().long() + video = video[idx] + + video = transforms.functional.resize( + video, + [resized_height, resized_width], + interpolation=InterpolationMode.BICUBIC, + antialias=True, + ).float() + return video