app.py CHANGED
@@ -1,17 +1,18 @@
 
1
  from functools import lru_cache
2
  import gradio as gr
3
  from gradio_toggle import Toggle
4
  import torch
5
- from huggingface_hub import snapshot_download
6
  from transformers import CLIPProcessor, CLIPModel
7
 
8
- from xora.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
9
- from xora.models.transformers.transformer3d import Transformer3DModel
10
- from xora.models.transformers.symmetric_patchifier import SymmetricPatchifier
11
- from xora.schedulers.rf import RectifiedFlowScheduler
12
- from xora.pipelines.pipeline_xora_video import XoraVideoPipeline
13
  from transformers import T5EncoderModel, T5Tokenizer
14
- from xora.utils.conditioning_method import ConditioningMethod
15
  from pathlib import Path
16
  import safetensors.torch
17
  import json
@@ -25,6 +26,8 @@ from openai import OpenAI
25
  import csv
26
  from datetime import datetime
27
 
 
 
28
 
29
  # Load Hugging Face token if needed
30
  hf_token = os.getenv("HF_TOKEN")
@@ -39,10 +42,10 @@ with open(system_prompt_i2v_path, "r") as f:
39
  system_prompt_i2v = f.read()
40
 
41
  # Set model download directory within Hugging Face Spaces
42
- model_path = "asset"
43
- if not os.path.exists(model_path):
44
- snapshot_download("Lightricks/LTX-Video", local_dir=model_path, repo_type="model", token=hf_token)
45
-
46
  # Global variables to load components
47
  vae_dir = Path(model_path) / "vae"
48
  unet_dir = Path(model_path) / "unet"
@@ -140,30 +143,15 @@ def compute_clip_embedding(text=None, image=None):
140
 
141
 
142
  def load_vae(vae_dir):
143
- vae_ckpt_path = vae_dir / "vae_diffusion_pytorch_model.safetensors"
144
- vae_config_path = vae_dir / "config.json"
145
- with open(vae_config_path, "r") as f:
146
- vae_config = json.load(f)
147
- vae = CausalVideoAutoencoder.from_config(vae_config)
148
- vae_state_dict = safetensors.torch.load_file(vae_ckpt_path)
149
- vae.load_state_dict(vae_state_dict)
150
- return vae.to(device=device, dtype=torch.bfloat16)
151
 
152
 
153
  def load_unet(unet_dir):
154
- unet_ckpt_path = unet_dir / "unet_diffusion_pytorch_model.safetensors"
155
- unet_config_path = unet_dir / "config.json"
156
- transformer_config = Transformer3DModel.load_config(unet_config_path)
157
- transformer = Transformer3DModel.from_config(transformer_config)
158
- unet_state_dict = safetensors.torch.load_file(unet_ckpt_path)
159
- transformer.load_state_dict(unet_state_dict, strict=True)
160
- return transformer.to(device=device, dtype=torch.bfloat16)
161
 
162
 
163
  def load_scheduler(scheduler_dir):
164
- scheduler_config_path = scheduler_dir / "scheduler_config.json"
165
- scheduler_config = RectifiedFlowScheduler.load_config(scheduler_config_path)
166
- return RectifiedFlowScheduler.from_config(scheduler_config)
167
 
168
 
169
  # Helper function for image processing
@@ -288,7 +276,7 @@ pipeline = XoraVideoPipeline(
288
  vae=vae,
289
  ).to(device)
290
 
291
-
292
  def generate_video_from_text(
293
  prompt="",
294
  enhance_prompt_toggle=False,
@@ -302,6 +290,10 @@ def generate_video_from_text(
302
  width=768,
303
  num_frames=121,
304
  progress=gr.Progress(),
 
 
 
 
305
  ):
306
  if len(prompt.strip()) < 50:
307
  raise gr.Error(
@@ -334,7 +326,7 @@ def generate_video_from_text(
334
  "media_items": None,
335
  }
336
 
337
- generator = torch.Generator(device="cpu").manual_seed(seed)
338
 
339
  def gradio_progress_callback(self, step, timestep, kwargs):
340
  progress((step + 1) / num_inference_steps)
@@ -357,6 +349,11 @@ def generate_video_from_text(
357
  conditioning_method=ConditioningMethod.UNCONDITIONAL,
358
  mixed_precision=True,
359
  callback_on_step_end=gradio_progress_callback,
 
 
 
 
 
360
  ).images
361
  except Exception as e:
362
  raise gr.Error(
@@ -382,7 +379,7 @@ def generate_video_from_text(
382
  torch.cuda.empty_cache()
383
  return output_path
384
 
385
-
386
  def generate_video_from_image(
387
  image_path,
388
  prompt="",
@@ -397,6 +394,10 @@ def generate_video_from_image(
397
  width=768,
398
  num_frames=121,
399
  progress=gr.Progress(),
 
 
 
 
400
  ):
401
 
402
  print("Height: ", height)
@@ -445,7 +446,7 @@ def generate_video_from_image(
445
  "media_items": media_items,
446
  }
447
 
448
- generator = torch.Generator(device="cpu").manual_seed(seed)
449
 
450
  def gradio_progress_callback(self, step, timestep, kwargs):
451
  progress((step + 1) / num_inference_steps)
@@ -468,6 +469,11 @@ def generate_video_from_image(
468
  conditioning_method=ConditioningMethod.FIRST_FRAME,
469
  mixed_precision=True,
470
  callback_on_step_end=gradio_progress_callback,
 
 
 
 
 
471
  ).images
472
 
473
  output_path = tempfile.mktemp(suffix=".mp4")
@@ -767,7 +773,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as iface:
767
  outputs=txt2vid_output,
768
  concurrency_limit=1,
769
  concurrency_id="generate_video",
770
- queue=True,
771
  )
772
 
773
  img2vid_preset.change(fn=preset_changed, inputs=[img2vid_preset], outputs=img2vid_advanced[3:])
@@ -786,8 +791,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as iface:
786
  outputs=img2vid_output,
787
  concurrency_limit=1,
788
  concurrency_id="generate_video",
789
- queue=True,
790
  )
791
 
792
  if __name__ == "__main__":
793
- iface.queue(max_size=64, default_concurrency_limit=1, api_open=False).launch(share=True, show_api=False)
 
1
+ import spaces
2
  from functools import lru_cache
3
  import gradio as gr
4
  from gradio_toggle import Toggle
5
  import torch
6
+ from huggingface_hub import hf_hub_download
7
  from transformers import CLIPProcessor, CLIPModel
8
 
9
+ from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
10
+ from ltx_video.models.transformers.transformer3d import Transformer3DModel
11
+ from ltx_video.models.transformers.symmetric_patchifier import SymmetricPatchifier
12
+ from ltx_video.schedulers.rf import RectifiedFlowScheduler
13
+ from ltx_video.pipelines.pipeline_ltx_video import LTXVideoPipeline as XoraVideoPipeline
14
  from transformers import T5EncoderModel, T5Tokenizer
15
+ from ltx_video.utils.conditioning_method import ConditioningMethod
16
  from pathlib import Path
17
  import safetensors.torch
18
  import json
 
26
  import csv
27
  from datetime import datetime
28
 
29
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
30
+
31
 
32
  # Load Hugging Face token if needed
33
  hf_token = os.getenv("HF_TOKEN")
 
42
  system_prompt_i2v = f.read()
43
 
44
  # Set model download directory within Hugging Face Spaces
45
+ model_path = Path("/home/elevin/xora-core/assets/")
46
+ cpkt_path = Path("/home/elevin/xora-core/assets/ltx-video-2b-v0.9.1.safetensors")
47
+ if not os.path.exists(cpkt_path):
48
+ hf_hub_download(repo_id="Lightricks/LTX-Video", filename="ltx-video-2b-v0.9.1.safetensors", local_dir=model_path, local_dir_use_symlinks=False, repo_type='model')
49
  # Global variables to load components
50
  vae_dir = Path(model_path) / "vae"
51
  unet_dir = Path(model_path) / "unet"
 
143
 
144
 
145
  def load_vae(vae_dir):
146
+ return CausalVideoAutoencoder.from_pretrained(cpkt_path).to(device=device, dtype=torch.bfloat16)
 
 
 
 
 
 
 
147
 
148
 
149
  def load_unet(unet_dir):
150
+ return Transformer3DModel.from_pretrained(cpkt_path).to(device=device, dtype=torch.bfloat16)
 
 
 
 
 
 
151
 
152
 
153
  def load_scheduler(scheduler_dir):
154
+ return RectifiedFlowScheduler.from_pretrained(cpkt_path)
 
 
155
 
156
 
157
  # Helper function for image processing
 
276
  vae=vae,
277
  ).to(device)
278
 
279
+ @spaces.GPU(duration=120)
280
  def generate_video_from_text(
281
  prompt="",
282
  enhance_prompt_toggle=False,
 
290
  width=768,
291
  num_frames=121,
292
  progress=gr.Progress(),
293
+ stg_scale=1.0,
294
+ stg_rescale=0.7,
295
+ stg_mode="stg_a",
296
+ stg_skip_layers="19",
297
  ):
298
  if len(prompt.strip()) < 50:
299
  raise gr.Error(
 
326
  "media_items": None,
327
  }
328
 
329
+ generator = torch.Generator(device=device).manual_seed(seed)
330
 
331
  def gradio_progress_callback(self, step, timestep, kwargs):
332
  progress((step + 1) / num_inference_steps)
 
349
  conditioning_method=ConditioningMethod.UNCONDITIONAL,
350
  mixed_precision=True,
351
  callback_on_step_end=gradio_progress_callback,
352
+ stg_scale=stg_scale,
353
+ do_rescaling=stg_rescale != 1,
354
+ rescaling_scale=stg_rescale,
355
+ skip_layer_strategy=SkipLayerStrategy.Attention if stg_mode == "stg_a" else SkipLayerStrategy.Residual,
356
+ skip_block_list=[int(x.strip()) for x in stg_skip_layers.split(",")]
357
  ).images
358
  except Exception as e:
359
  raise gr.Error(
 
379
  torch.cuda.empty_cache()
380
  return output_path
381
 
382
+ @spaces.GPU(duration=120)
383
  def generate_video_from_image(
384
  image_path,
385
  prompt="",
 
394
  width=768,
395
  num_frames=121,
396
  progress=gr.Progress(),
397
+ stg_scale=1.0,
398
+ stg_rescale=0.7,
399
+ stg_mode="stg_a",
400
+ stg_skip_layers="19",
401
  ):
402
 
403
  print("Height: ", height)
 
446
  "media_items": media_items,
447
  }
448
 
449
+ generator = torch.Generator(device=device).manual_seed(seed)
450
 
451
  def gradio_progress_callback(self, step, timestep, kwargs):
452
  progress((step + 1) / num_inference_steps)
 
469
  conditioning_method=ConditioningMethod.FIRST_FRAME,
470
  mixed_precision=True,
471
  callback_on_step_end=gradio_progress_callback,
472
+ stg_scale=stg_scale,
473
+ do_rescaling=stg_rescale != 1,
474
+ rescaling_scale=stg_rescale,
475
+ skip_layer_strategy=SkipLayerStrategy.Attention if stg_mode == "stg_a" else SkipLayerStrategy.Residual,
476
+ skip_block_list=[int(x.strip()) for x in stg_skip_layers.split(",")]
477
  ).images
478
 
479
  output_path = tempfile.mktemp(suffix=".mp4")
 
773
  outputs=txt2vid_output,
774
  concurrency_limit=1,
775
  concurrency_id="generate_video",
 
776
  )
777
 
778
  img2vid_preset.change(fn=preset_changed, inputs=[img2vid_preset], outputs=img2vid_advanced[3:])
 
791
  outputs=img2vid_output,
792
  concurrency_limit=1,
793
  concurrency_id="generate_video",
 
794
  )
795
 
796
  if __name__ == "__main__":
797
+ iface.launch(share=True, show_api=False)
ltx_video/.DS_Store ADDED
Binary file (6.15 kB). View file
 
ltx_video/.github/workflows/poetry_lock_verify.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Poetry Lock Verification
2
+
3
+ on: [push]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ matrix:
10
+ python-version: ["3.10"]
11
+ steps:
12
+ - uses: actions/checkout@v3
13
+ - name: Set up Python ${{ matrix.python-version }}
14
+ uses: actions/setup-python@v3
15
+ with:
16
+ python-version: ${{ matrix.python-version }}
17
+ - name: Install Poetry
18
+ run: curl -sSL https://install.python-poetry.org | python3 -
19
+
20
+ - name: Install dependencies
21
+ run: poetry install --no-root
22
+
23
+ - name: Check if poetry.lock is in sync
24
+ run: poetry check
25
+
26
+ - name: Verify if poetry.lock is in sync
27
+ run: |
28
+ if git diff --name-only HEAD | grep -qE '(pyproject\.toml|poetry\.lock)'; then
29
+ echo "::error::'pyproject.toml' or 'poetry.lock' is out of sync. Please run 'poetry lock' locally and commit the changes."
30
+ exit 1
31
+ fi
ltx_video/.github/workflows/pylint.yml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Ruff
2
+
3
+ on: [push]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ matrix:
10
+ python-version: ["3.10"]
11
+ steps:
12
+ - uses: actions/checkout@v3
13
+ - name: Set up Python ${{ matrix.python-version }}
14
+ uses: actions/setup-python@v3
15
+ with:
16
+ python-version: ${{ matrix.python-version }}
17
+ - name: Install dependencies
18
+ run: |
19
+ python -m pip install --upgrade pip
20
+ pip install ruff==0.2.2 black==24.2.0
21
+ - name: Analyzing the code with ruff
22
+ run: |
23
+ ruff $(git ls-files '*.py')
24
+ - name: Verify that no Black changes are required
25
+ run: |
26
+ black --check $(git ls-files 'txt2img/*/*.py')
ltx_video/.github/workflows/run_tests.yml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Pytest
2
+
3
+ on: [push]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ matrix:
10
+ python-version: ["3.10"]
11
+ steps:
12
+ - uses: actions/checkout@v3
13
+ - name: Set up Python ${{ matrix.python-version }}
14
+ uses: actions/setup-python@v3
15
+ with:
16
+ python-version: ${{ matrix.python-version }}
17
+ - name: Install Poetry
18
+ run: curl -sSL https://install.python-poetry.org | python3 -
19
+
20
+ - name: Install dependencies
21
+ run: poetry install --with dev
22
+
23
+ - name: Set PYTHONPATH
24
+ run: echo "PYTHONPATH=$PWD" >> $GITHUB_ENV
25
+
26
+ - name: Run pytest
27
+ run: poetry run pytest ./tests -v -m "not slow"
ltx_video/__init__.py ADDED
File without changes
ltx_video/models/__init__.py ADDED
File without changes
ltx_video/models/autoencoders/__init__.py ADDED
File without changes
ltx_video/models/autoencoders/causal_conv3d.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+
7
+ class CausalConv3d(nn.Module):
8
+ def __init__(
9
+ self,
10
+ in_channels,
11
+ out_channels,
12
+ kernel_size: int = 3,
13
+ stride: Union[int, Tuple[int]] = 1,
14
+ dilation: int = 1,
15
+ groups: int = 1,
16
+ **kwargs,
17
+ ):
18
+ super().__init__()
19
+
20
+ self.in_channels = in_channels
21
+ self.out_channels = out_channels
22
+
23
+ kernel_size = (kernel_size, kernel_size, kernel_size)
24
+ self.time_kernel_size = kernel_size[0]
25
+
26
+ dilation = (dilation, 1, 1)
27
+
28
+ height_pad = kernel_size[1] // 2
29
+ width_pad = kernel_size[2] // 2
30
+ padding = (0, height_pad, width_pad)
31
+
32
+ self.conv = nn.Conv3d(
33
+ in_channels,
34
+ out_channels,
35
+ kernel_size,
36
+ stride=stride,
37
+ dilation=dilation,
38
+ padding=padding,
39
+ padding_mode="zeros",
40
+ groups=groups,
41
+ )
42
+
43
+ def forward(self, x, causal: bool = True):
44
+ if causal:
45
+ first_frame_pad = x[:, :, :1, :, :].repeat(
46
+ (1, 1, self.time_kernel_size - 1, 1, 1)
47
+ )
48
+ x = torch.concatenate((first_frame_pad, x), dim=2)
49
+ else:
50
+ first_frame_pad = x[:, :, :1, :, :].repeat(
51
+ (1, 1, (self.time_kernel_size - 1) // 2, 1, 1)
52
+ )
53
+ last_frame_pad = x[:, :, -1:, :, :].repeat(
54
+ (1, 1, (self.time_kernel_size - 1) // 2, 1, 1)
55
+ )
56
+ x = torch.concatenate((first_frame_pad, x, last_frame_pad), dim=2)
57
+ x = self.conv(x)
58
+ return x
59
+
60
+ @property
61
+ def weight(self):
62
+ return self.conv.weight
ltx_video/models/autoencoders/causal_video_autoencoder.py ADDED
@@ -0,0 +1,1335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from functools import partial
4
+ from types import SimpleNamespace
5
+ from typing import Any, Mapping, Optional, Tuple, Union, List
6
+ from pathlib import Path
7
+
8
+ import torch
9
+ import numpy as np
10
+ from einops import rearrange
11
+ from torch import nn
12
+ from diffusers.utils import logging
13
+ import torch.nn.functional as F
14
+ from diffusers.models.embeddings import PixArtAlphaCombinedTimestepSizeEmbeddings
15
+ from safetensors import safe_open
16
+
17
+
18
+ from ltx_video.models.autoencoders.conv_nd_factory import make_conv_nd, make_linear_nd
19
+ from ltx_video.models.autoencoders.pixel_norm import PixelNorm
20
+ from ltx_video.models.autoencoders.vae import AutoencoderKLWrapper
21
+ from ltx_video.models.transformers.attention import Attention
22
+ from ltx_video.utils.diffusers_config_mapping import (
23
+ diffusers_and_ours_config_mapping,
24
+ make_hashable_key,
25
+ VAE_KEYS_RENAME_DICT,
26
+ )
27
+
28
+ PER_CHANNEL_STATISTICS_PREFIX = "per_channel_statistics."
29
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
30
+
31
+
32
+ class CausalVideoAutoencoder(AutoencoderKLWrapper):
33
+ @classmethod
34
+ def from_pretrained(
35
+ cls,
36
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
37
+ *args,
38
+ **kwargs,
39
+ ):
40
+ pretrained_model_name_or_path = Path(pretrained_model_name_or_path)
41
+ if (
42
+ pretrained_model_name_or_path.is_dir()
43
+ and (pretrained_model_name_or_path / "autoencoder.pth").exists()
44
+ ):
45
+ config_local_path = pretrained_model_name_or_path / "config.json"
46
+ config = cls.load_config(config_local_path, **kwargs)
47
+
48
+ model_local_path = pretrained_model_name_or_path / "autoencoder.pth"
49
+ state_dict = torch.load(model_local_path, map_location=torch.device("cpu"))
50
+
51
+ statistics_local_path = (
52
+ pretrained_model_name_or_path / "per_channel_statistics.json"
53
+ )
54
+ if statistics_local_path.exists():
55
+ with open(statistics_local_path, "r") as file:
56
+ data = json.load(file)
57
+ transposed_data = list(zip(*data["data"]))
58
+ data_dict = {
59
+ col: torch.tensor(vals)
60
+ for col, vals in zip(data["columns"], transposed_data)
61
+ }
62
+ std_of_means = data_dict["std-of-means"]
63
+ mean_of_means = data_dict.get(
64
+ "mean-of-means", torch.zeros_like(data_dict["std-of-means"])
65
+ )
66
+ state_dict[f"{PER_CHANNEL_STATISTICS_PREFIX}std-of-means"] = (
67
+ std_of_means
68
+ )
69
+ state_dict[f"{PER_CHANNEL_STATISTICS_PREFIX}mean-of-means"] = (
70
+ mean_of_means
71
+ )
72
+
73
+ elif pretrained_model_name_or_path.is_dir():
74
+ config_path = pretrained_model_name_or_path / "vae" / "config.json"
75
+ with open(config_path, "r") as f:
76
+ config = make_hashable_key(json.load(f))
77
+
78
+ assert config in diffusers_and_ours_config_mapping, (
79
+ "Provided diffusers checkpoint config for VAE is not suppported. "
80
+ "We only support diffusers configs found in Lightricks/LTX-Video."
81
+ )
82
+
83
+ config = diffusers_and_ours_config_mapping[config]
84
+
85
+ state_dict_path = (
86
+ pretrained_model_name_or_path
87
+ / "vae"
88
+ / "diffusion_pytorch_model.safetensors"
89
+ )
90
+
91
+ state_dict = {}
92
+ with safe_open(state_dict_path, framework="pt", device="cpu") as f:
93
+ for k in f.keys():
94
+ state_dict[k] = f.get_tensor(k)
95
+ for key in list(state_dict.keys()):
96
+ new_key = key
97
+ for replace_key, rename_key in VAE_KEYS_RENAME_DICT.items():
98
+ new_key = new_key.replace(replace_key, rename_key)
99
+
100
+ state_dict[new_key] = state_dict.pop(key)
101
+
102
+ elif pretrained_model_name_or_path.is_file() and str(
103
+ pretrained_model_name_or_path
104
+ ).endswith(".safetensors"):
105
+ state_dict = {}
106
+ with safe_open(
107
+ pretrained_model_name_or_path, framework="pt", device="cpu"
108
+ ) as f:
109
+ metadata = f.metadata()
110
+ for k in f.keys():
111
+ state_dict[k] = f.get_tensor(k)
112
+ configs = json.loads(metadata["config"])
113
+ config = configs["vae"]
114
+
115
+ video_vae = cls.from_config(config)
116
+ if "torch_dtype" in kwargs:
117
+ video_vae.to(kwargs["torch_dtype"])
118
+ video_vae.load_state_dict(state_dict)
119
+ return video_vae
120
+
121
+ @staticmethod
122
+ def from_config(config):
123
+ assert (
124
+ config["_class_name"] == "CausalVideoAutoencoder"
125
+ ), "config must have _class_name=CausalVideoAutoencoder"
126
+ if isinstance(config["dims"], list):
127
+ config["dims"] = tuple(config["dims"])
128
+
129
+ assert config["dims"] in [2, 3, (2, 1)], "dims must be 2, 3 or (2, 1)"
130
+
131
+ double_z = config.get("double_z", True)
132
+ latent_log_var = config.get(
133
+ "latent_log_var", "per_channel" if double_z else "none"
134
+ )
135
+ use_quant_conv = config.get("use_quant_conv", True)
136
+
137
+ if use_quant_conv and latent_log_var == "uniform":
138
+ raise ValueError("uniform latent_log_var requires use_quant_conv=False")
139
+
140
+ encoder = Encoder(
141
+ dims=config["dims"],
142
+ in_channels=config.get("in_channels", 3),
143
+ out_channels=config["latent_channels"],
144
+ blocks=config.get("encoder_blocks", config.get("blocks")),
145
+ patch_size=config.get("patch_size", 1),
146
+ latent_log_var=latent_log_var,
147
+ norm_layer=config.get("norm_layer", "group_norm"),
148
+ base_channels=config.get("encoder_base_channels", 128),
149
+ )
150
+
151
+ decoder = Decoder(
152
+ dims=config["dims"],
153
+ in_channels=config["latent_channels"],
154
+ out_channels=config.get("out_channels", 3),
155
+ blocks=config.get("decoder_blocks", config.get("blocks")),
156
+ patch_size=config.get("patch_size", 1),
157
+ norm_layer=config.get("norm_layer", "group_norm"),
158
+ causal=config.get("causal_decoder", False),
159
+ timestep_conditioning=config.get("timestep_conditioning", False),
160
+ base_channels=config.get("decoder_base_channels", 128),
161
+ )
162
+
163
+ dims = config["dims"]
164
+ return CausalVideoAutoencoder(
165
+ encoder=encoder,
166
+ decoder=decoder,
167
+ latent_channels=config["latent_channels"],
168
+ dims=dims,
169
+ use_quant_conv=use_quant_conv,
170
+ )
171
+
172
+ @property
173
+ def config(self):
174
+ return SimpleNamespace(
175
+ _class_name="CausalVideoAutoencoder",
176
+ dims=self.dims,
177
+ in_channels=self.encoder.conv_in.in_channels // self.encoder.patch_size**2,
178
+ out_channels=self.decoder.conv_out.out_channels
179
+ // self.decoder.patch_size**2,
180
+ latent_channels=self.decoder.conv_in.in_channels,
181
+ encoder_blocks=self.encoder.blocks_desc,
182
+ decoder_blocks=self.decoder.blocks_desc,
183
+ scaling_factor=1.0,
184
+ norm_layer=self.encoder.norm_layer,
185
+ patch_size=self.encoder.patch_size,
186
+ latent_log_var=self.encoder.latent_log_var,
187
+ use_quant_conv=self.use_quant_conv,
188
+ causal_decoder=self.decoder.causal,
189
+ timestep_conditioning=self.decoder.timestep_conditioning,
190
+ )
191
+
192
+ @property
193
+ def is_video_supported(self):
194
+ """
195
+ Check if the model supports video inputs of shape (B, C, F, H, W). Otherwise, the model only supports 2D images.
196
+ """
197
+ return self.dims != 2
198
+
199
+ @property
200
+ def spatial_downscale_factor(self):
201
+ return (
202
+ 2
203
+ ** len(
204
+ [
205
+ block
206
+ for block in self.encoder.blocks_desc
207
+ if block[0] in ["compress_space", "compress_all"]
208
+ ]
209
+ )
210
+ * self.encoder.patch_size
211
+ )
212
+
213
+ @property
214
+ def temporal_downscale_factor(self):
215
+ return 2 ** len(
216
+ [
217
+ block
218
+ for block in self.encoder.blocks_desc
219
+ if block[0] in ["compress_time", "compress_all"]
220
+ ]
221
+ )
222
+
223
+ def to_json_string(self) -> str:
224
+ import json
225
+
226
+ return json.dumps(self.config.__dict__)
227
+
228
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
229
+ if any([key.startswith("vae.") for key in state_dict.keys()]):
230
+ state_dict = {
231
+ key.replace("vae.", ""): value
232
+ for key, value in state_dict.items()
233
+ if key.startswith("vae.")
234
+ }
235
+ ckpt_state_dict = {
236
+ key: value
237
+ for key, value in state_dict.items()
238
+ if not key.startswith(PER_CHANNEL_STATISTICS_PREFIX)
239
+ }
240
+
241
+ model_keys = set(name for name, _ in self.named_parameters())
242
+
243
+ key_mapping = {
244
+ ".resnets.": ".res_blocks.",
245
+ "downsamplers.0": "downsample",
246
+ "upsamplers.0": "upsample",
247
+ }
248
+ converted_state_dict = {}
249
+ for key, value in ckpt_state_dict.items():
250
+ for k, v in key_mapping.items():
251
+ key = key.replace(k, v)
252
+
253
+ if "norm" in key and key not in model_keys:
254
+ logger.info(
255
+ f"Removing key {key} from state_dict as it is not present in the model"
256
+ )
257
+ continue
258
+
259
+ converted_state_dict[key] = value
260
+
261
+ super().load_state_dict(converted_state_dict, strict=strict)
262
+
263
+ data_dict = {
264
+ key.removeprefix(PER_CHANNEL_STATISTICS_PREFIX): value
265
+ for key, value in state_dict.items()
266
+ if key.startswith(PER_CHANNEL_STATISTICS_PREFIX)
267
+ }
268
+ if len(data_dict) > 0:
269
+ self.register_buffer("std_of_means", data_dict["std-of-means"])
270
+ self.register_buffer(
271
+ "mean_of_means",
272
+ data_dict.get(
273
+ "mean-of-means", torch.zeros_like(data_dict["std-of-means"])
274
+ ),
275
+ )
276
+
277
+ def last_layer(self):
278
+ if hasattr(self.decoder, "conv_out"):
279
+ if isinstance(self.decoder.conv_out, nn.Sequential):
280
+ last_layer = self.decoder.conv_out[-1]
281
+ else:
282
+ last_layer = self.decoder.conv_out
283
+ else:
284
+ last_layer = self.decoder.layers[-1]
285
+ return last_layer
286
+
287
+ def set_use_tpu_flash_attention(self):
288
+ for block in self.decoder.up_blocks:
289
+ if isinstance(block, UNetMidBlock3D) and block.attention_blocks:
290
+ for attention_block in block.attention_blocks:
291
+ attention_block.set_use_tpu_flash_attention()
292
+
293
+
294
+ class Encoder(nn.Module):
295
+ r"""
296
+ The `Encoder` layer of a variational autoencoder that encodes its input into a latent representation.
297
+
298
+ Args:
299
+ dims (`int` or `Tuple[int, int]`, *optional*, defaults to 3):
300
+ The number of dimensions to use in convolutions.
301
+ in_channels (`int`, *optional*, defaults to 3):
302
+ The number of input channels.
303
+ out_channels (`int`, *optional*, defaults to 3):
304
+ The number of output channels.
305
+ blocks (`List[Tuple[str, int]]`, *optional*, defaults to `[("res_x", 1)]`):
306
+ The blocks to use. Each block is a tuple of the block name and the number of layers.
307
+ base_channels (`int`, *optional*, defaults to 128):
308
+ The number of output channels for the first convolutional layer.
309
+ norm_num_groups (`int`, *optional*, defaults to 32):
310
+ The number of groups for normalization.
311
+ patch_size (`int`, *optional*, defaults to 1):
312
+ The patch size to use. Should be a power of 2.
313
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
314
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
315
+ latent_log_var (`str`, *optional*, defaults to `per_channel`):
316
+ The number of channels for the log variance. Can be either `per_channel`, `uniform`, or `none`.
317
+ """
318
+
319
+ def __init__(
320
+ self,
321
+ dims: Union[int, Tuple[int, int]] = 3,
322
+ in_channels: int = 3,
323
+ out_channels: int = 3,
324
+ blocks: List[Tuple[str, Union[int, dict]]] = [("res_x", 1)],
325
+ base_channels: int = 128,
326
+ norm_num_groups: int = 32,
327
+ patch_size: Union[int, Tuple[int]] = 1,
328
+ norm_layer: str = "group_norm", # group_norm, pixel_norm
329
+ latent_log_var: str = "per_channel",
330
+ ):
331
+ super().__init__()
332
+ self.patch_size = patch_size
333
+ self.norm_layer = norm_layer
334
+ self.latent_channels = out_channels
335
+ self.latent_log_var = latent_log_var
336
+ self.blocks_desc = blocks
337
+
338
+ in_channels = in_channels * patch_size**2
339
+ output_channel = base_channels
340
+
341
+ self.conv_in = make_conv_nd(
342
+ dims=dims,
343
+ in_channels=in_channels,
344
+ out_channels=output_channel,
345
+ kernel_size=3,
346
+ stride=1,
347
+ padding=1,
348
+ causal=True,
349
+ )
350
+
351
+ self.down_blocks = nn.ModuleList([])
352
+
353
+ for block_name, block_params in blocks:
354
+ input_channel = output_channel
355
+ if isinstance(block_params, int):
356
+ block_params = {"num_layers": block_params}
357
+
358
+ if block_name == "res_x":
359
+ block = UNetMidBlock3D(
360
+ dims=dims,
361
+ in_channels=input_channel,
362
+ num_layers=block_params["num_layers"],
363
+ resnet_eps=1e-6,
364
+ resnet_groups=norm_num_groups,
365
+ norm_layer=norm_layer,
366
+ )
367
+ elif block_name == "res_x_y":
368
+ output_channel = block_params.get("multiplier", 2) * output_channel
369
+ block = ResnetBlock3D(
370
+ dims=dims,
371
+ in_channels=input_channel,
372
+ out_channels=output_channel,
373
+ eps=1e-6,
374
+ groups=norm_num_groups,
375
+ norm_layer=norm_layer,
376
+ )
377
+ elif block_name == "compress_time":
378
+ block = make_conv_nd(
379
+ dims=dims,
380
+ in_channels=input_channel,
381
+ out_channels=output_channel,
382
+ kernel_size=3,
383
+ stride=(2, 1, 1),
384
+ causal=True,
385
+ )
386
+ elif block_name == "compress_space":
387
+ block = make_conv_nd(
388
+ dims=dims,
389
+ in_channels=input_channel,
390
+ out_channels=output_channel,
391
+ kernel_size=3,
392
+ stride=(1, 2, 2),
393
+ causal=True,
394
+ )
395
+ elif block_name == "compress_all":
396
+ block = make_conv_nd(
397
+ dims=dims,
398
+ in_channels=input_channel,
399
+ out_channels=output_channel,
400
+ kernel_size=3,
401
+ stride=(2, 2, 2),
402
+ causal=True,
403
+ )
404
+ elif block_name == "compress_all_x_y":
405
+ output_channel = block_params.get("multiplier", 2) * output_channel
406
+ block = make_conv_nd(
407
+ dims=dims,
408
+ in_channels=input_channel,
409
+ out_channels=output_channel,
410
+ kernel_size=3,
411
+ stride=(2, 2, 2),
412
+ causal=True,
413
+ )
414
+ elif block_name == "compress_all_res":
415
+ output_channel = block_params.get("multiplier", 2) * output_channel
416
+ block = SpaceToDepthDownsample(
417
+ dims=dims,
418
+ in_channels=input_channel,
419
+ out_channels=output_channel,
420
+ stride=(2, 2, 2),
421
+ )
422
+ elif block_name == "compress_space_res":
423
+ output_channel = block_params.get("multiplier", 2) * output_channel
424
+ block = SpaceToDepthDownsample(
425
+ dims=dims,
426
+ in_channels=input_channel,
427
+ out_channels=output_channel,
428
+ stride=(1, 2, 2),
429
+ )
430
+ elif block_name == "compress_time_res":
431
+ output_channel = block_params.get("multiplier", 2) * output_channel
432
+ block = SpaceToDepthDownsample(
433
+ dims=dims,
434
+ in_channels=input_channel,
435
+ out_channels=output_channel,
436
+ stride=(2, 1, 1),
437
+ )
438
+ else:
439
+ raise ValueError(f"unknown block: {block_name}")
440
+
441
+ self.down_blocks.append(block)
442
+
443
+ # out
444
+ if norm_layer == "group_norm":
445
+ self.conv_norm_out = nn.GroupNorm(
446
+ num_channels=output_channel, num_groups=norm_num_groups, eps=1e-6
447
+ )
448
+ elif norm_layer == "pixel_norm":
449
+ self.conv_norm_out = PixelNorm()
450
+ elif norm_layer == "layer_norm":
451
+ self.conv_norm_out = LayerNorm(output_channel, eps=1e-6)
452
+
453
+ self.conv_act = nn.SiLU()
454
+
455
+ conv_out_channels = out_channels
456
+ if latent_log_var == "per_channel":
457
+ conv_out_channels *= 2
458
+ elif latent_log_var == "uniform":
459
+ conv_out_channels += 1
460
+ elif latent_log_var != "none":
461
+ raise ValueError(f"Invalid latent_log_var: {latent_log_var}")
462
+ self.conv_out = make_conv_nd(
463
+ dims, output_channel, conv_out_channels, 3, padding=1, causal=True
464
+ )
465
+
466
+ self.gradient_checkpointing = False
467
+
468
+ def forward(self, sample: torch.FloatTensor) -> torch.FloatTensor:
469
+ r"""The forward method of the `Encoder` class."""
470
+
471
+ sample = patchify(sample, patch_size_hw=self.patch_size, patch_size_t=1)
472
+ sample = self.conv_in(sample)
473
+
474
+ checkpoint_fn = (
475
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
476
+ if self.gradient_checkpointing and self.training
477
+ else lambda x: x
478
+ )
479
+
480
+ for down_block in self.down_blocks:
481
+ sample = checkpoint_fn(down_block)(sample)
482
+
483
+ sample = self.conv_norm_out(sample)
484
+ sample = self.conv_act(sample)
485
+ sample = self.conv_out(sample)
486
+
487
+ if self.latent_log_var == "uniform":
488
+ last_channel = sample[:, -1:, ...]
489
+ num_dims = sample.dim()
490
+
491
+ if num_dims == 4:
492
+ # For shape (B, C, H, W)
493
+ repeated_last_channel = last_channel.repeat(
494
+ 1, sample.shape[1] - 2, 1, 1
495
+ )
496
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
497
+ elif num_dims == 5:
498
+ # For shape (B, C, F, H, W)
499
+ repeated_last_channel = last_channel.repeat(
500
+ 1, sample.shape[1] - 2, 1, 1, 1
501
+ )
502
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
503
+ else:
504
+ raise ValueError(f"Invalid input shape: {sample.shape}")
505
+
506
+ return sample
507
+
508
+
509
+ class Decoder(nn.Module):
510
+ r"""
511
+ The `Decoder` layer of a variational autoencoder that decodes its latent representation into an output sample.
512
+
513
+ Args:
514
+ dims (`int` or `Tuple[int, int]`, *optional*, defaults to 3):
515
+ The number of dimensions to use in convolutions.
516
+ in_channels (`int`, *optional*, defaults to 3):
517
+ The number of input channels.
518
+ out_channels (`int`, *optional*, defaults to 3):
519
+ The number of output channels.
520
+ blocks (`List[Tuple[str, int]]`, *optional*, defaults to `[("res_x", 1)]`):
521
+ The blocks to use. Each block is a tuple of the block name and the number of layers.
522
+ base_channels (`int`, *optional*, defaults to 128):
523
+ The number of output channels for the first convolutional layer.
524
+ norm_num_groups (`int`, *optional*, defaults to 32):
525
+ The number of groups for normalization.
526
+ patch_size (`int`, *optional*, defaults to 1):
527
+ The patch size to use. Should be a power of 2.
528
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
529
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
530
+ causal (`bool`, *optional*, defaults to `True`):
531
+ Whether to use causal convolutions or not.
532
+ """
533
+
534
+ def __init__(
535
+ self,
536
+ dims,
537
+ in_channels: int = 3,
538
+ out_channels: int = 3,
539
+ blocks: List[Tuple[str, Union[int, dict]]] = [("res_x", 1)],
540
+ base_channels: int = 128,
541
+ layers_per_block: int = 2,
542
+ norm_num_groups: int = 32,
543
+ patch_size: int = 1,
544
+ norm_layer: str = "group_norm",
545
+ causal: bool = True,
546
+ timestep_conditioning: bool = False,
547
+ ):
548
+ super().__init__()
549
+ self.patch_size = patch_size
550
+ self.layers_per_block = layers_per_block
551
+ out_channels = out_channels * patch_size**2
552
+ self.causal = causal
553
+ self.blocks_desc = blocks
554
+
555
+ # Compute output channel to be product of all channel-multiplier blocks
556
+ output_channel = base_channels
557
+ for block_name, block_params in list(reversed(blocks)):
558
+ block_params = block_params if isinstance(block_params, dict) else {}
559
+ if block_name == "res_x_y":
560
+ output_channel = output_channel * block_params.get("multiplier", 2)
561
+ if block_name == "compress_all":
562
+ output_channel = output_channel * block_params.get("multiplier", 1)
563
+
564
+ self.conv_in = make_conv_nd(
565
+ dims,
566
+ in_channels,
567
+ output_channel,
568
+ kernel_size=3,
569
+ stride=1,
570
+ padding=1,
571
+ causal=True,
572
+ )
573
+
574
+ self.up_blocks = nn.ModuleList([])
575
+
576
+ for block_name, block_params in list(reversed(blocks)):
577
+ input_channel = output_channel
578
+ if isinstance(block_params, int):
579
+ block_params = {"num_layers": block_params}
580
+
581
+ if block_name == "res_x":
582
+ block = UNetMidBlock3D(
583
+ dims=dims,
584
+ in_channels=input_channel,
585
+ num_layers=block_params["num_layers"],
586
+ resnet_eps=1e-6,
587
+ resnet_groups=norm_num_groups,
588
+ norm_layer=norm_layer,
589
+ inject_noise=block_params.get("inject_noise", False),
590
+ timestep_conditioning=timestep_conditioning,
591
+ )
592
+ elif block_name == "attn_res_x":
593
+ block = UNetMidBlock3D(
594
+ dims=dims,
595
+ in_channels=input_channel,
596
+ num_layers=block_params["num_layers"],
597
+ resnet_groups=norm_num_groups,
598
+ norm_layer=norm_layer,
599
+ inject_noise=block_params.get("inject_noise", False),
600
+ timestep_conditioning=timestep_conditioning,
601
+ attention_head_dim=block_params["attention_head_dim"],
602
+ )
603
+ elif block_name == "res_x_y":
604
+ output_channel = output_channel // block_params.get("multiplier", 2)
605
+ block = ResnetBlock3D(
606
+ dims=dims,
607
+ in_channels=input_channel,
608
+ out_channels=output_channel,
609
+ eps=1e-6,
610
+ groups=norm_num_groups,
611
+ norm_layer=norm_layer,
612
+ inject_noise=block_params.get("inject_noise", False),
613
+ timestep_conditioning=False,
614
+ )
615
+ elif block_name == "compress_time":
616
+ block = DepthToSpaceUpsample(
617
+ dims=dims, in_channels=input_channel, stride=(2, 1, 1)
618
+ )
619
+ elif block_name == "compress_space":
620
+ block = DepthToSpaceUpsample(
621
+ dims=dims, in_channels=input_channel, stride=(1, 2, 2)
622
+ )
623
+ elif block_name == "compress_all":
624
+ output_channel = output_channel // block_params.get("multiplier", 1)
625
+ block = DepthToSpaceUpsample(
626
+ dims=dims,
627
+ in_channels=input_channel,
628
+ stride=(2, 2, 2),
629
+ residual=block_params.get("residual", False),
630
+ out_channels_reduction_factor=block_params.get("multiplier", 1),
631
+ )
632
+ else:
633
+ raise ValueError(f"unknown layer: {block_name}")
634
+
635
+ self.up_blocks.append(block)
636
+
637
+ if norm_layer == "group_norm":
638
+ self.conv_norm_out = nn.GroupNorm(
639
+ num_channels=output_channel, num_groups=norm_num_groups, eps=1e-6
640
+ )
641
+ elif norm_layer == "pixel_norm":
642
+ self.conv_norm_out = PixelNorm()
643
+ elif norm_layer == "layer_norm":
644
+ self.conv_norm_out = LayerNorm(output_channel, eps=1e-6)
645
+
646
+ self.conv_act = nn.SiLU()
647
+ self.conv_out = make_conv_nd(
648
+ dims, output_channel, out_channels, 3, padding=1, causal=True
649
+ )
650
+
651
+ self.gradient_checkpointing = False
652
+
653
+ self.timestep_conditioning = timestep_conditioning
654
+
655
+ if timestep_conditioning:
656
+ self.timestep_scale_multiplier = nn.Parameter(
657
+ torch.tensor(1000.0, dtype=torch.float32)
658
+ )
659
+ self.last_time_embedder = PixArtAlphaCombinedTimestepSizeEmbeddings(
660
+ output_channel * 2, 0
661
+ )
662
+ self.last_scale_shift_table = nn.Parameter(
663
+ torch.randn(2, output_channel) / output_channel**0.5
664
+ )
665
+
666
+ def forward(
667
+ self,
668
+ sample: torch.FloatTensor,
669
+ target_shape,
670
+ timestep: Optional[torch.Tensor] = None,
671
+ ) -> torch.FloatTensor:
672
+ r"""The forward method of the `Decoder` class."""
673
+ assert target_shape is not None, "target_shape must be provided"
674
+ batch_size = sample.shape[0]
675
+
676
+ sample = self.conv_in(sample, causal=self.causal)
677
+
678
+ upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
679
+
680
+ checkpoint_fn = (
681
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
682
+ if self.gradient_checkpointing and self.training
683
+ else lambda x: x
684
+ )
685
+
686
+ sample = sample.to(upscale_dtype)
687
+
688
+ if self.timestep_conditioning:
689
+ assert (
690
+ timestep is not None
691
+ ), "should pass timestep with timestep_conditioning=True"
692
+ scaled_timestep = timestep * self.timestep_scale_multiplier
693
+
694
+ for up_block in self.up_blocks:
695
+ if self.timestep_conditioning and isinstance(up_block, UNetMidBlock3D):
696
+ sample = checkpoint_fn(up_block)(
697
+ sample, causal=self.causal, timestep=scaled_timestep
698
+ )
699
+ else:
700
+ sample = checkpoint_fn(up_block)(sample, causal=self.causal)
701
+
702
+ sample = self.conv_norm_out(sample)
703
+
704
+ if self.timestep_conditioning:
705
+ embedded_timestep = self.last_time_embedder(
706
+ timestep=scaled_timestep.flatten(),
707
+ resolution=None,
708
+ aspect_ratio=None,
709
+ batch_size=sample.shape[0],
710
+ hidden_dtype=sample.dtype,
711
+ )
712
+ embedded_timestep = embedded_timestep.view(
713
+ batch_size, embedded_timestep.shape[-1], 1, 1, 1
714
+ )
715
+ ada_values = self.last_scale_shift_table[
716
+ None, ..., None, None, None
717
+ ] + embedded_timestep.reshape(
718
+ batch_size,
719
+ 2,
720
+ -1,
721
+ embedded_timestep.shape[-3],
722
+ embedded_timestep.shape[-2],
723
+ embedded_timestep.shape[-1],
724
+ )
725
+ shift, scale = ada_values.unbind(dim=1)
726
+ sample = sample * (1 + scale) + shift
727
+
728
+ sample = self.conv_act(sample)
729
+ sample = self.conv_out(sample, causal=self.causal)
730
+
731
+ sample = unpatchify(sample, patch_size_hw=self.patch_size, patch_size_t=1)
732
+
733
+ return sample
734
+
735
+
736
+ class UNetMidBlock3D(nn.Module):
737
+ """
738
+ A 3D UNet mid-block [`UNetMidBlock3D`] with multiple residual blocks.
739
+
740
+ Args:
741
+ in_channels (`int`): The number of input channels.
742
+ dropout (`float`, *optional*, defaults to 0.0): The dropout rate.
743
+ num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.
744
+ resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.
745
+ resnet_groups (`int`, *optional*, defaults to 32):
746
+ The number of groups to use in the group normalization layers of the resnet blocks.
747
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
748
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
749
+ inject_noise (`bool`, *optional*, defaults to `False`):
750
+ Whether to inject noise into the hidden states.
751
+ timestep_conditioning (`bool`, *optional*, defaults to `False`):
752
+ Whether to condition the hidden states on the timestep.
753
+ attention_head_dim (`int`, *optional*, defaults to -1):
754
+ The dimension of the attention head. If -1, no attention is used.
755
+
756
+ Returns:
757
+ `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,
758
+ in_channels, height, width)`.
759
+
760
+ """
761
+
762
+ def __init__(
763
+ self,
764
+ dims: Union[int, Tuple[int, int]],
765
+ in_channels: int,
766
+ dropout: float = 0.0,
767
+ num_layers: int = 1,
768
+ resnet_eps: float = 1e-6,
769
+ resnet_groups: int = 32,
770
+ norm_layer: str = "group_norm",
771
+ inject_noise: bool = False,
772
+ timestep_conditioning: bool = False,
773
+ attention_head_dim: int = -1,
774
+ ):
775
+ super().__init__()
776
+ resnet_groups = (
777
+ resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
778
+ )
779
+ self.timestep_conditioning = timestep_conditioning
780
+
781
+ if timestep_conditioning:
782
+ self.time_embedder = PixArtAlphaCombinedTimestepSizeEmbeddings(
783
+ in_channels * 4, 0
784
+ )
785
+
786
+ self.res_blocks = nn.ModuleList(
787
+ [
788
+ ResnetBlock3D(
789
+ dims=dims,
790
+ in_channels=in_channels,
791
+ out_channels=in_channels,
792
+ eps=resnet_eps,
793
+ groups=resnet_groups,
794
+ dropout=dropout,
795
+ norm_layer=norm_layer,
796
+ inject_noise=inject_noise,
797
+ timestep_conditioning=timestep_conditioning,
798
+ )
799
+ for _ in range(num_layers)
800
+ ]
801
+ )
802
+
803
+ self.attention_blocks = None
804
+
805
+ if attention_head_dim > 0:
806
+ if attention_head_dim > in_channels:
807
+ raise ValueError(
808
+ "attention_head_dim must be less than or equal to in_channels"
809
+ )
810
+
811
+ self.attention_blocks = nn.ModuleList(
812
+ [
813
+ Attention(
814
+ query_dim=in_channels,
815
+ heads=in_channels // attention_head_dim,
816
+ dim_head=attention_head_dim,
817
+ bias=True,
818
+ out_bias=True,
819
+ qk_norm="rms_norm",
820
+ residual_connection=True,
821
+ )
822
+ for _ in range(num_layers)
823
+ ]
824
+ )
825
+
826
+ def forward(
827
+ self,
828
+ hidden_states: torch.FloatTensor,
829
+ causal: bool = True,
830
+ timestep: Optional[torch.Tensor] = None,
831
+ ) -> torch.FloatTensor:
832
+ timestep_embed = None
833
+ if self.timestep_conditioning:
834
+ assert (
835
+ timestep is not None
836
+ ), "should pass timestep with timestep_conditioning=True"
837
+ batch_size = hidden_states.shape[0]
838
+ timestep_embed = self.time_embedder(
839
+ timestep=timestep.flatten(),
840
+ resolution=None,
841
+ aspect_ratio=None,
842
+ batch_size=batch_size,
843
+ hidden_dtype=hidden_states.dtype,
844
+ )
845
+ timestep_embed = timestep_embed.view(
846
+ batch_size, timestep_embed.shape[-1], 1, 1, 1
847
+ )
848
+
849
+ if self.attention_blocks:
850
+ for resnet, attention in zip(self.res_blocks, self.attention_blocks):
851
+ hidden_states = resnet(
852
+ hidden_states, causal=causal, timestep=timestep_embed
853
+ )
854
+
855
+ # Reshape the hidden states to be (batch_size, frames * height * width, channel)
856
+ batch_size, channel, frames, height, width = hidden_states.shape
857
+ hidden_states = hidden_states.view(
858
+ batch_size, channel, frames * height * width
859
+ ).transpose(1, 2)
860
+
861
+ if attention.use_tpu_flash_attention:
862
+ # Pad the second dimension to be divisible by block_k_major (block in flash attention)
863
+ seq_len = hidden_states.shape[1]
864
+ block_k_major = 512
865
+ pad_len = (block_k_major - seq_len % block_k_major) % block_k_major
866
+ if pad_len > 0:
867
+ hidden_states = F.pad(
868
+ hidden_states, (0, 0, 0, pad_len), "constant", 0
869
+ )
870
+
871
+ # Create a mask with ones for the original sequence length and zeros for the padded indexes
872
+ mask = torch.ones(
873
+ (hidden_states.shape[0], seq_len),
874
+ device=hidden_states.device,
875
+ dtype=hidden_states.dtype,
876
+ )
877
+ if pad_len > 0:
878
+ mask = F.pad(mask, (0, pad_len), "constant", 0)
879
+
880
+ hidden_states = attention(
881
+ hidden_states,
882
+ attention_mask=(
883
+ None if not attention.use_tpu_flash_attention else mask
884
+ ),
885
+ )
886
+
887
+ if attention.use_tpu_flash_attention:
888
+ # Remove the padding
889
+ if pad_len > 0:
890
+ hidden_states = hidden_states[:, :-pad_len, :]
891
+
892
+ # Reshape the hidden states back to (batch_size, channel, frames, height, width, channel)
893
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
894
+ batch_size, channel, frames, height, width
895
+ )
896
+ else:
897
+ for resnet in self.res_blocks:
898
+ hidden_states = resnet(
899
+ hidden_states, causal=causal, timestep=timestep_embed
900
+ )
901
+
902
+ return hidden_states
903
+
904
+
905
+ class SpaceToDepthDownsample(nn.Module):
906
+ def __init__(self, dims, in_channels, out_channels, stride):
907
+ super().__init__()
908
+ self.stride = stride
909
+ self.group_size = in_channels * np.prod(stride) // out_channels
910
+ self.conv = make_conv_nd(
911
+ dims=dims,
912
+ in_channels=in_channels,
913
+ out_channels=out_channels // np.prod(stride),
914
+ kernel_size=3,
915
+ stride=1,
916
+ causal=True,
917
+ )
918
+
919
+ def forward(self, x, causal: bool = True):
920
+ if self.stride[0] == 2:
921
+ x = torch.cat(
922
+ [x, x[:, :, -1:, :, :]], dim=2
923
+ ) # duplicate last frames for padding
924
+
925
+ # skip connection
926
+ x_in = rearrange(
927
+ x,
928
+ "b c (d p1) (h p2) (w p3) -> b (c p1 p2 p3) d h w",
929
+ p1=self.stride[0],
930
+ p2=self.stride[1],
931
+ p3=self.stride[2],
932
+ )
933
+ x_in = rearrange(x_in, "b (c g) d h w -> b c g d h w", g=self.group_size)
934
+ x_in = x_in.mean(dim=2)
935
+
936
+ # conv
937
+ x = self.conv(x, causal=causal)
938
+ x = rearrange(
939
+ x,
940
+ "b c (d p1) (h p2) (w p3) -> b (c p1 p2 p3) d h w",
941
+ p1=self.stride[0],
942
+ p2=self.stride[1],
943
+ p3=self.stride[2],
944
+ )
945
+
946
+ x = x + x_in
947
+
948
+ return x
949
+
950
+
951
+ class DepthToSpaceUpsample(nn.Module):
952
+ def __init__(
953
+ self, dims, in_channels, stride, residual=False, out_channels_reduction_factor=1
954
+ ):
955
+ super().__init__()
956
+ self.stride = stride
957
+ self.out_channels = (
958
+ np.prod(stride) * in_channels // out_channels_reduction_factor
959
+ )
960
+ self.conv = make_conv_nd(
961
+ dims=dims,
962
+ in_channels=in_channels,
963
+ out_channels=self.out_channels,
964
+ kernel_size=3,
965
+ stride=1,
966
+ causal=True,
967
+ )
968
+ self.residual = residual
969
+ self.out_channels_reduction_factor = out_channels_reduction_factor
970
+
971
+ def forward(self, x, causal: bool = True):
972
+ if self.residual:
973
+ # Reshape and duplicate the input to match the output shape
974
+ x_in = rearrange(
975
+ x,
976
+ "b (c p1 p2 p3) d h w -> b c (d p1) (h p2) (w p3)",
977
+ p1=self.stride[0],
978
+ p2=self.stride[1],
979
+ p3=self.stride[2],
980
+ )
981
+ num_repeat = np.prod(self.stride) // self.out_channels_reduction_factor
982
+ x_in = x_in.repeat(1, num_repeat, 1, 1, 1)
983
+ if self.stride[0] == 2:
984
+ x_in = x_in[:, :, 1:, :, :]
985
+ x = self.conv(x, causal=causal)
986
+ x = rearrange(
987
+ x,
988
+ "b (c p1 p2 p3) d h w -> b c (d p1) (h p2) (w p3)",
989
+ p1=self.stride[0],
990
+ p2=self.stride[1],
991
+ p3=self.stride[2],
992
+ )
993
+ if self.stride[0] == 2:
994
+ x = x[:, :, 1:, :, :]
995
+ if self.residual:
996
+ x = x + x_in
997
+ return x
998
+
999
+
1000
+ class LayerNorm(nn.Module):
1001
+ def __init__(self, dim, eps, elementwise_affine=True) -> None:
1002
+ super().__init__()
1003
+ self.norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=elementwise_affine)
1004
+
1005
+ def forward(self, x):
1006
+ x = rearrange(x, "b c d h w -> b d h w c")
1007
+ x = self.norm(x)
1008
+ x = rearrange(x, "b d h w c -> b c d h w")
1009
+ return x
1010
+
1011
+
1012
+ class ResnetBlock3D(nn.Module):
1013
+ r"""
1014
+ A Resnet block.
1015
+
1016
+ Parameters:
1017
+ in_channels (`int`): The number of channels in the input.
1018
+ out_channels (`int`, *optional*, default to be `None`):
1019
+ The number of output channels for the first conv layer. If None, same as `in_channels`.
1020
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
1021
+ groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
1022
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
1023
+ """
1024
+
1025
+ def __init__(
1026
+ self,
1027
+ dims: Union[int, Tuple[int, int]],
1028
+ in_channels: int,
1029
+ out_channels: Optional[int] = None,
1030
+ dropout: float = 0.0,
1031
+ groups: int = 32,
1032
+ eps: float = 1e-6,
1033
+ norm_layer: str = "group_norm",
1034
+ inject_noise: bool = False,
1035
+ timestep_conditioning: bool = False,
1036
+ ):
1037
+ super().__init__()
1038
+ self.in_channels = in_channels
1039
+ out_channels = in_channels if out_channels is None else out_channels
1040
+ self.out_channels = out_channels
1041
+ self.inject_noise = inject_noise
1042
+
1043
+ if norm_layer == "group_norm":
1044
+ self.norm1 = nn.GroupNorm(
1045
+ num_groups=groups, num_channels=in_channels, eps=eps, affine=True
1046
+ )
1047
+ elif norm_layer == "pixel_norm":
1048
+ self.norm1 = PixelNorm()
1049
+ elif norm_layer == "layer_norm":
1050
+ self.norm1 = LayerNorm(in_channels, eps=eps, elementwise_affine=True)
1051
+
1052
+ self.non_linearity = nn.SiLU()
1053
+
1054
+ self.conv1 = make_conv_nd(
1055
+ dims,
1056
+ in_channels,
1057
+ out_channels,
1058
+ kernel_size=3,
1059
+ stride=1,
1060
+ padding=1,
1061
+ causal=True,
1062
+ )
1063
+
1064
+ if inject_noise:
1065
+ self.per_channel_scale1 = nn.Parameter(torch.zeros((in_channels, 1, 1)))
1066
+
1067
+ if norm_layer == "group_norm":
1068
+ self.norm2 = nn.GroupNorm(
1069
+ num_groups=groups, num_channels=out_channels, eps=eps, affine=True
1070
+ )
1071
+ elif norm_layer == "pixel_norm":
1072
+ self.norm2 = PixelNorm()
1073
+ elif norm_layer == "layer_norm":
1074
+ self.norm2 = LayerNorm(out_channels, eps=eps, elementwise_affine=True)
1075
+
1076
+ self.dropout = torch.nn.Dropout(dropout)
1077
+
1078
+ self.conv2 = make_conv_nd(
1079
+ dims,
1080
+ out_channels,
1081
+ out_channels,
1082
+ kernel_size=3,
1083
+ stride=1,
1084
+ padding=1,
1085
+ causal=True,
1086
+ )
1087
+
1088
+ if inject_noise:
1089
+ self.per_channel_scale2 = nn.Parameter(torch.zeros((in_channels, 1, 1)))
1090
+
1091
+ self.conv_shortcut = (
1092
+ make_linear_nd(
1093
+ dims=dims, in_channels=in_channels, out_channels=out_channels
1094
+ )
1095
+ if in_channels != out_channels
1096
+ else nn.Identity()
1097
+ )
1098
+
1099
+ self.norm3 = (
1100
+ LayerNorm(in_channels, eps=eps, elementwise_affine=True)
1101
+ if in_channels != out_channels
1102
+ else nn.Identity()
1103
+ )
1104
+
1105
+ self.timestep_conditioning = timestep_conditioning
1106
+
1107
+ if timestep_conditioning:
1108
+ self.scale_shift_table = nn.Parameter(
1109
+ torch.randn(4, in_channels) / in_channels**0.5
1110
+ )
1111
+
1112
+ def _feed_spatial_noise(
1113
+ self, hidden_states: torch.FloatTensor, per_channel_scale: torch.FloatTensor
1114
+ ) -> torch.FloatTensor:
1115
+ spatial_shape = hidden_states.shape[-2:]
1116
+ device = hidden_states.device
1117
+ dtype = hidden_states.dtype
1118
+
1119
+ # similar to the "explicit noise inputs" method in style-gan
1120
+ spatial_noise = torch.randn(spatial_shape, device=device, dtype=dtype)[None]
1121
+ scaled_noise = (spatial_noise * per_channel_scale)[None, :, None, ...]
1122
+ hidden_states = hidden_states + scaled_noise
1123
+
1124
+ return hidden_states
1125
+
1126
+ def forward(
1127
+ self,
1128
+ input_tensor: torch.FloatTensor,
1129
+ causal: bool = True,
1130
+ timestep: Optional[torch.Tensor] = None,
1131
+ ) -> torch.FloatTensor:
1132
+ hidden_states = input_tensor
1133
+ batch_size = hidden_states.shape[0]
1134
+
1135
+ hidden_states = self.norm1(hidden_states)
1136
+ if self.timestep_conditioning:
1137
+ assert (
1138
+ timestep is not None
1139
+ ), "should pass timestep with timestep_conditioning=True"
1140
+ ada_values = self.scale_shift_table[
1141
+ None, ..., None, None, None
1142
+ ] + timestep.reshape(
1143
+ batch_size,
1144
+ 4,
1145
+ -1,
1146
+ timestep.shape[-3],
1147
+ timestep.shape[-2],
1148
+ timestep.shape[-1],
1149
+ )
1150
+ shift1, scale1, shift2, scale2 = ada_values.unbind(dim=1)
1151
+
1152
+ hidden_states = hidden_states * (1 + scale1) + shift1
1153
+
1154
+ hidden_states = self.non_linearity(hidden_states)
1155
+
1156
+ hidden_states = self.conv1(hidden_states, causal=causal)
1157
+
1158
+ if self.inject_noise:
1159
+ hidden_states = self._feed_spatial_noise(
1160
+ hidden_states, self.per_channel_scale1
1161
+ )
1162
+
1163
+ hidden_states = self.norm2(hidden_states)
1164
+
1165
+ if self.timestep_conditioning:
1166
+ hidden_states = hidden_states * (1 + scale2) + shift2
1167
+
1168
+ hidden_states = self.non_linearity(hidden_states)
1169
+
1170
+ hidden_states = self.dropout(hidden_states)
1171
+
1172
+ hidden_states = self.conv2(hidden_states, causal=causal)
1173
+
1174
+ if self.inject_noise:
1175
+ hidden_states = self._feed_spatial_noise(
1176
+ hidden_states, self.per_channel_scale2
1177
+ )
1178
+
1179
+ input_tensor = self.norm3(input_tensor)
1180
+
1181
+ batch_size = input_tensor.shape[0]
1182
+
1183
+ input_tensor = self.conv_shortcut(input_tensor)
1184
+
1185
+ output_tensor = input_tensor + hidden_states
1186
+
1187
+ return output_tensor
1188
+
1189
+
1190
+ def patchify(x, patch_size_hw, patch_size_t=1):
1191
+ if patch_size_hw == 1 and patch_size_t == 1:
1192
+ return x
1193
+ if x.dim() == 4:
1194
+ x = rearrange(
1195
+ x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size_hw, r=patch_size_hw
1196
+ )
1197
+ elif x.dim() == 5:
1198
+ x = rearrange(
1199
+ x,
1200
+ "b c (f p) (h q) (w r) -> b (c p r q) f h w",
1201
+ p=patch_size_t,
1202
+ q=patch_size_hw,
1203
+ r=patch_size_hw,
1204
+ )
1205
+ else:
1206
+ raise ValueError(f"Invalid input shape: {x.shape}")
1207
+
1208
+ return x
1209
+
1210
+
1211
+ def unpatchify(x, patch_size_hw, patch_size_t=1):
1212
+ if patch_size_hw == 1 and patch_size_t == 1:
1213
+ return x
1214
+
1215
+ if x.dim() == 4:
1216
+ x = rearrange(
1217
+ x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size_hw, r=patch_size_hw
1218
+ )
1219
+ elif x.dim() == 5:
1220
+ x = rearrange(
1221
+ x,
1222
+ "b (c p r q) f h w -> b c (f p) (h q) (w r)",
1223
+ p=patch_size_t,
1224
+ q=patch_size_hw,
1225
+ r=patch_size_hw,
1226
+ )
1227
+
1228
+ return x
1229
+
1230
+
1231
+ def create_video_autoencoder_config(
1232
+ latent_channels: int = 64,
1233
+ ):
1234
+ encoder_blocks = [
1235
+ ("res_x", {"num_layers": 4}),
1236
+ ("compress_all_x_y", {"multiplier": 3}),
1237
+ ("res_x", {"num_layers": 4}),
1238
+ ("compress_all_x_y", {"multiplier": 2}),
1239
+ ("res_x", {"num_layers": 4}),
1240
+ ("compress_all", {}),
1241
+ ("res_x", {"num_layers": 3}),
1242
+ ("res_x", {"num_layers": 4}),
1243
+ ]
1244
+ decoder_blocks = [
1245
+ ("res_x", {"num_layers": 4}),
1246
+ ("compress_all", {"residual": True}),
1247
+ ("res_x_y", {"multiplier": 3}),
1248
+ ("res_x", {"num_layers": 3}),
1249
+ ("compress_all", {"residual": True}),
1250
+ ("res_x_y", {"multiplier": 2}),
1251
+ ("res_x", {"num_layers": 3}),
1252
+ ("compress_all", {"residual": True}),
1253
+ ("res_x", {"num_layers": 3}),
1254
+ ("res_x", {"num_layers": 4}),
1255
+ ]
1256
+ return {
1257
+ "_class_name": "CausalVideoAutoencoder",
1258
+ "dims": 3,
1259
+ "encoder_blocks": encoder_blocks,
1260
+ "decoder_blocks": decoder_blocks,
1261
+ "latent_channels": latent_channels,
1262
+ "norm_layer": "pixel_norm",
1263
+ "patch_size": 4,
1264
+ "latent_log_var": "uniform",
1265
+ "use_quant_conv": False,
1266
+ "causal_decoder": False,
1267
+ "timestep_conditioning": True,
1268
+ }
1269
+
1270
+
1271
+ def test_vae_patchify_unpatchify():
1272
+ import torch
1273
+
1274
+ x = torch.randn(2, 3, 8, 64, 64)
1275
+ x_patched = patchify(x, patch_size_hw=4, patch_size_t=4)
1276
+ x_unpatched = unpatchify(x_patched, patch_size_hw=4, patch_size_t=4)
1277
+ assert torch.allclose(x, x_unpatched)
1278
+
1279
+
1280
+ def demo_video_autoencoder_forward_backward():
1281
+ # Configuration for the VideoAutoencoder
1282
+ config = create_video_autoencoder_config()
1283
+
1284
+ # Instantiate the VideoAutoencoder with the specified configuration
1285
+ video_autoencoder = CausalVideoAutoencoder.from_config(config)
1286
+
1287
+ print(video_autoencoder)
1288
+ video_autoencoder.eval()
1289
+ # Print the total number of parameters in the video autoencoder
1290
+ total_params = sum(p.numel() for p in video_autoencoder.parameters())
1291
+ print(f"Total number of parameters in VideoAutoencoder: {total_params:,}")
1292
+
1293
+ # Create a mock input tensor simulating a batch of videos
1294
+ # Shape: (batch_size, channels, depth, height, width)
1295
+ # E.g., 4 videos, each with 3 color channels, 16 frames, and 64x64 pixels per frame
1296
+ input_videos = torch.randn(2, 3, 17, 64, 64)
1297
+
1298
+ # Forward pass: encode and decode the input videos
1299
+ latent = video_autoencoder.encode(input_videos).latent_dist.mode()
1300
+ print(f"input shape={input_videos.shape}")
1301
+ print(f"latent shape={latent.shape}")
1302
+
1303
+ timestep = torch.ones(input_videos.shape[0]) * 0.1
1304
+ reconstructed_videos = video_autoencoder.decode(
1305
+ latent, target_shape=input_videos.shape, timestep=timestep
1306
+ ).sample
1307
+
1308
+ print(f"reconstructed shape={reconstructed_videos.shape}")
1309
+
1310
+ # Validate that single image gets treated the same way as first frame
1311
+ input_image = input_videos[:, :, :1, :, :]
1312
+ image_latent = video_autoencoder.encode(input_image).latent_dist.mode()
1313
+ _ = video_autoencoder.decode(
1314
+ image_latent, target_shape=image_latent.shape, timestep=timestep
1315
+ ).sample
1316
+
1317
+ # first_frame_latent = latent[:, :, :1, :, :]
1318
+
1319
+ # assert torch.allclose(image_latent, first_frame_latent, atol=1e-6)
1320
+ # assert torch.allclose(reconstructed_image, reconstructed_videos[:, :, :1, :, :], atol=1e-6)
1321
+ # assert (image_latent == first_frame_latent).all()
1322
+ # assert (reconstructed_image == reconstructed_videos[:, :, :1, :, :]).all()
1323
+
1324
+ # Calculate the loss (e.g., mean squared error)
1325
+ loss = torch.nn.functional.mse_loss(input_videos, reconstructed_videos)
1326
+
1327
+ # Perform backward pass
1328
+ loss.backward()
1329
+
1330
+ print(f"Demo completed with loss: {loss.item()}")
1331
+
1332
+
1333
+ # Ensure to call the demo function to execute the forward and backward pass
1334
+ if __name__ == "__main__":
1335
+ demo_video_autoencoder_forward_backward()
ltx_video/models/autoencoders/conv_nd_factory.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, Union
2
+
3
+ import torch
4
+
5
+ from ltx_video.models.autoencoders.dual_conv3d import DualConv3d
6
+ from ltx_video.models.autoencoders.causal_conv3d import CausalConv3d
7
+
8
+
9
+ def make_conv_nd(
10
+ dims: Union[int, Tuple[int, int]],
11
+ in_channels: int,
12
+ out_channels: int,
13
+ kernel_size: int,
14
+ stride=1,
15
+ padding=0,
16
+ dilation=1,
17
+ groups=1,
18
+ bias=True,
19
+ causal=False,
20
+ ):
21
+ if dims == 2:
22
+ return torch.nn.Conv2d(
23
+ in_channels=in_channels,
24
+ out_channels=out_channels,
25
+ kernel_size=kernel_size,
26
+ stride=stride,
27
+ padding=padding,
28
+ dilation=dilation,
29
+ groups=groups,
30
+ bias=bias,
31
+ )
32
+ elif dims == 3:
33
+ if causal:
34
+ return CausalConv3d(
35
+ in_channels=in_channels,
36
+ out_channels=out_channels,
37
+ kernel_size=kernel_size,
38
+ stride=stride,
39
+ padding=padding,
40
+ dilation=dilation,
41
+ groups=groups,
42
+ bias=bias,
43
+ )
44
+ return torch.nn.Conv3d(
45
+ in_channels=in_channels,
46
+ out_channels=out_channels,
47
+ kernel_size=kernel_size,
48
+ stride=stride,
49
+ padding=padding,
50
+ dilation=dilation,
51
+ groups=groups,
52
+ bias=bias,
53
+ )
54
+ elif dims == (2, 1):
55
+ return DualConv3d(
56
+ in_channels=in_channels,
57
+ out_channels=out_channels,
58
+ kernel_size=kernel_size,
59
+ stride=stride,
60
+ padding=padding,
61
+ bias=bias,
62
+ )
63
+ else:
64
+ raise ValueError(f"unsupported dimensions: {dims}")
65
+
66
+
67
+ def make_linear_nd(
68
+ dims: int,
69
+ in_channels: int,
70
+ out_channels: int,
71
+ bias=True,
72
+ ):
73
+ if dims == 2:
74
+ return torch.nn.Conv2d(
75
+ in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias
76
+ )
77
+ elif dims == 3 or dims == (2, 1):
78
+ return torch.nn.Conv3d(
79
+ in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias
80
+ )
81
+ else:
82
+ raise ValueError(f"unsupported dimensions: {dims}")
ltx_video/models/autoencoders/dual_conv3d.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Tuple, Union
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from einops import rearrange
8
+
9
+
10
+ class DualConv3d(nn.Module):
11
+ def __init__(
12
+ self,
13
+ in_channels,
14
+ out_channels,
15
+ kernel_size,
16
+ stride: Union[int, Tuple[int, int, int]] = 1,
17
+ padding: Union[int, Tuple[int, int, int]] = 0,
18
+ dilation: Union[int, Tuple[int, int, int]] = 1,
19
+ groups=1,
20
+ bias=True,
21
+ ):
22
+ super(DualConv3d, self).__init__()
23
+
24
+ self.in_channels = in_channels
25
+ self.out_channels = out_channels
26
+ # Ensure kernel_size, stride, padding, and dilation are tuples of length 3
27
+ if isinstance(kernel_size, int):
28
+ kernel_size = (kernel_size, kernel_size, kernel_size)
29
+ if kernel_size == (1, 1, 1):
30
+ raise ValueError(
31
+ "kernel_size must be greater than 1. Use make_linear_nd instead."
32
+ )
33
+ if isinstance(stride, int):
34
+ stride = (stride, stride, stride)
35
+ if isinstance(padding, int):
36
+ padding = (padding, padding, padding)
37
+ if isinstance(dilation, int):
38
+ dilation = (dilation, dilation, dilation)
39
+
40
+ # Set parameters for convolutions
41
+ self.groups = groups
42
+ self.bias = bias
43
+
44
+ # Define the size of the channels after the first convolution
45
+ intermediate_channels = (
46
+ out_channels if in_channels < out_channels else in_channels
47
+ )
48
+
49
+ # Define parameters for the first convolution
50
+ self.weight1 = nn.Parameter(
51
+ torch.Tensor(
52
+ intermediate_channels,
53
+ in_channels // groups,
54
+ 1,
55
+ kernel_size[1],
56
+ kernel_size[2],
57
+ )
58
+ )
59
+ self.stride1 = (1, stride[1], stride[2])
60
+ self.padding1 = (0, padding[1], padding[2])
61
+ self.dilation1 = (1, dilation[1], dilation[2])
62
+ if bias:
63
+ self.bias1 = nn.Parameter(torch.Tensor(intermediate_channels))
64
+ else:
65
+ self.register_parameter("bias1", None)
66
+
67
+ # Define parameters for the second convolution
68
+ self.weight2 = nn.Parameter(
69
+ torch.Tensor(
70
+ out_channels, intermediate_channels // groups, kernel_size[0], 1, 1
71
+ )
72
+ )
73
+ self.stride2 = (stride[0], 1, 1)
74
+ self.padding2 = (padding[0], 0, 0)
75
+ self.dilation2 = (dilation[0], 1, 1)
76
+ if bias:
77
+ self.bias2 = nn.Parameter(torch.Tensor(out_channels))
78
+ else:
79
+ self.register_parameter("bias2", None)
80
+
81
+ # Initialize weights and biases
82
+ self.reset_parameters()
83
+
84
+ def reset_parameters(self):
85
+ nn.init.kaiming_uniform_(self.weight1, a=math.sqrt(5))
86
+ nn.init.kaiming_uniform_(self.weight2, a=math.sqrt(5))
87
+ if self.bias:
88
+ fan_in1, _ = nn.init._calculate_fan_in_and_fan_out(self.weight1)
89
+ bound1 = 1 / math.sqrt(fan_in1)
90
+ nn.init.uniform_(self.bias1, -bound1, bound1)
91
+ fan_in2, _ = nn.init._calculate_fan_in_and_fan_out(self.weight2)
92
+ bound2 = 1 / math.sqrt(fan_in2)
93
+ nn.init.uniform_(self.bias2, -bound2, bound2)
94
+
95
+ def forward(self, x, use_conv3d=False, skip_time_conv=False):
96
+ if use_conv3d:
97
+ return self.forward_with_3d(x=x, skip_time_conv=skip_time_conv)
98
+ else:
99
+ return self.forward_with_2d(x=x, skip_time_conv=skip_time_conv)
100
+
101
+ def forward_with_3d(self, x, skip_time_conv):
102
+ # First convolution
103
+ x = F.conv3d(
104
+ x,
105
+ self.weight1,
106
+ self.bias1,
107
+ self.stride1,
108
+ self.padding1,
109
+ self.dilation1,
110
+ self.groups,
111
+ )
112
+
113
+ if skip_time_conv:
114
+ return x
115
+
116
+ # Second convolution
117
+ x = F.conv3d(
118
+ x,
119
+ self.weight2,
120
+ self.bias2,
121
+ self.stride2,
122
+ self.padding2,
123
+ self.dilation2,
124
+ self.groups,
125
+ )
126
+
127
+ return x
128
+
129
+ def forward_with_2d(self, x, skip_time_conv):
130
+ b, c, d, h, w = x.shape
131
+
132
+ # First 2D convolution
133
+ x = rearrange(x, "b c d h w -> (b d) c h w")
134
+ # Squeeze the depth dimension out of weight1 since it's 1
135
+ weight1 = self.weight1.squeeze(2)
136
+ # Select stride, padding, and dilation for the 2D convolution
137
+ stride1 = (self.stride1[1], self.stride1[2])
138
+ padding1 = (self.padding1[1], self.padding1[2])
139
+ dilation1 = (self.dilation1[1], self.dilation1[2])
140
+ x = F.conv2d(x, weight1, self.bias1, stride1, padding1, dilation1, self.groups)
141
+
142
+ _, _, h, w = x.shape
143
+
144
+ if skip_time_conv:
145
+ x = rearrange(x, "(b d) c h w -> b c d h w", b=b)
146
+ return x
147
+
148
+ # Second convolution which is essentially treated as a 1D convolution across the 'd' dimension
149
+ x = rearrange(x, "(b d) c h w -> (b h w) c d", b=b)
150
+
151
+ # Reshape weight2 to match the expected dimensions for conv1d
152
+ weight2 = self.weight2.squeeze(-1).squeeze(-1)
153
+ # Use only the relevant dimension for stride, padding, and dilation for the 1D convolution
154
+ stride2 = self.stride2[0]
155
+ padding2 = self.padding2[0]
156
+ dilation2 = self.dilation2[0]
157
+ x = F.conv1d(x, weight2, self.bias2, stride2, padding2, dilation2, self.groups)
158
+ x = rearrange(x, "(b h w) c d -> b c d h w", b=b, h=h, w=w)
159
+
160
+ return x
161
+
162
+ @property
163
+ def weight(self):
164
+ return self.weight2
165
+
166
+
167
+ def test_dual_conv3d_consistency():
168
+ # Initialize parameters
169
+ in_channels = 3
170
+ out_channels = 5
171
+ kernel_size = (3, 3, 3)
172
+ stride = (2, 2, 2)
173
+ padding = (1, 1, 1)
174
+
175
+ # Create an instance of the DualConv3d class
176
+ dual_conv3d = DualConv3d(
177
+ in_channels=in_channels,
178
+ out_channels=out_channels,
179
+ kernel_size=kernel_size,
180
+ stride=stride,
181
+ padding=padding,
182
+ bias=True,
183
+ )
184
+
185
+ # Example input tensor
186
+ test_input = torch.randn(1, 3, 10, 10, 10)
187
+
188
+ # Perform forward passes with both 3D and 2D settings
189
+ output_conv3d = dual_conv3d(test_input, use_conv3d=True)
190
+ output_2d = dual_conv3d(test_input, use_conv3d=False)
191
+
192
+ # Assert that the outputs from both methods are sufficiently close
193
+ assert torch.allclose(
194
+ output_conv3d, output_2d, atol=1e-6
195
+ ), "Outputs are not consistent between 3D and 2D convolutions."
ltx_video/models/autoencoders/pixel_norm.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ class PixelNorm(nn.Module):
6
+ def __init__(self, dim=1, eps=1e-8):
7
+ super(PixelNorm, self).__init__()
8
+ self.dim = dim
9
+ self.eps = eps
10
+
11
+ def forward(self, x):
12
+ return x / torch.sqrt(torch.mean(x**2, dim=self.dim, keepdim=True) + self.eps)
ltx_video/models/autoencoders/vae.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+
3
+ import torch
4
+ import inspect
5
+ import math
6
+ import torch.nn as nn
7
+ from diffusers import ConfigMixin, ModelMixin
8
+ from diffusers.models.autoencoders.vae import (
9
+ DecoderOutput,
10
+ DiagonalGaussianDistribution,
11
+ )
12
+ from diffusers.models.modeling_outputs import AutoencoderKLOutput
13
+ from ltx_video.models.autoencoders.conv_nd_factory import make_conv_nd
14
+
15
+
16
+ class AutoencoderKLWrapper(ModelMixin, ConfigMixin):
17
+ """Variational Autoencoder (VAE) model with KL loss.
18
+
19
+ VAE from the paper Auto-Encoding Variational Bayes by Diederik P. Kingma and Max Welling.
20
+ This model is a wrapper around an encoder and a decoder, and it adds a KL loss term to the reconstruction loss.
21
+
22
+ Args:
23
+ encoder (`nn.Module`):
24
+ Encoder module.
25
+ decoder (`nn.Module`):
26
+ Decoder module.
27
+ latent_channels (`int`, *optional*, defaults to 4):
28
+ Number of latent channels.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ encoder: nn.Module,
34
+ decoder: nn.Module,
35
+ latent_channels: int = 4,
36
+ dims: int = 2,
37
+ sample_size=512,
38
+ use_quant_conv: bool = True,
39
+ ):
40
+ super().__init__()
41
+
42
+ # pass init params to Encoder
43
+ self.encoder = encoder
44
+ self.use_quant_conv = use_quant_conv
45
+
46
+ # pass init params to Decoder
47
+ quant_dims = 2 if dims == 2 else 3
48
+ self.decoder = decoder
49
+ if use_quant_conv:
50
+ self.quant_conv = make_conv_nd(
51
+ quant_dims, 2 * latent_channels, 2 * latent_channels, 1
52
+ )
53
+ self.post_quant_conv = make_conv_nd(
54
+ quant_dims, latent_channels, latent_channels, 1
55
+ )
56
+ else:
57
+ self.quant_conv = nn.Identity()
58
+ self.post_quant_conv = nn.Identity()
59
+ self.use_z_tiling = False
60
+ self.use_hw_tiling = False
61
+ self.dims = dims
62
+ self.z_sample_size = 1
63
+
64
+ self.decoder_params = inspect.signature(self.decoder.forward).parameters
65
+
66
+ # only relevant if vae tiling is enabled
67
+ self.set_tiling_params(sample_size=sample_size, overlap_factor=0.25)
68
+
69
+ def set_tiling_params(self, sample_size: int = 512, overlap_factor: float = 0.25):
70
+ self.tile_sample_min_size = sample_size
71
+ num_blocks = len(self.encoder.down_blocks)
72
+ self.tile_latent_min_size = int(sample_size / (2 ** (num_blocks - 1)))
73
+ self.tile_overlap_factor = overlap_factor
74
+
75
+ def enable_z_tiling(self, z_sample_size: int = 8):
76
+ r"""
77
+ Enable tiling during VAE decoding.
78
+
79
+ When this option is enabled, the VAE will split the input tensor in tiles to compute decoding in several
80
+ steps. This is useful to save some memory and allow larger batch sizes.
81
+ """
82
+ self.use_z_tiling = z_sample_size > 1
83
+ self.z_sample_size = z_sample_size
84
+ assert (
85
+ z_sample_size % 8 == 0 or z_sample_size == 1
86
+ ), f"z_sample_size must be a multiple of 8 or 1. Got {z_sample_size}."
87
+
88
+ def disable_z_tiling(self):
89
+ r"""
90
+ Disable tiling during VAE decoding. If `use_tiling` was previously invoked, this method will go back to computing
91
+ decoding in one step.
92
+ """
93
+ self.use_z_tiling = False
94
+
95
+ def enable_hw_tiling(self):
96
+ r"""
97
+ Enable tiling during VAE decoding along the height and width dimension.
98
+ """
99
+ self.use_hw_tiling = True
100
+
101
+ def disable_hw_tiling(self):
102
+ r"""
103
+ Disable tiling during VAE decoding along the height and width dimension.
104
+ """
105
+ self.use_hw_tiling = False
106
+
107
+ def _hw_tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True):
108
+ overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
109
+ blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
110
+ row_limit = self.tile_latent_min_size - blend_extent
111
+
112
+ # Split the image into 512x512 tiles and encode them separately.
113
+ rows = []
114
+ for i in range(0, x.shape[3], overlap_size):
115
+ row = []
116
+ for j in range(0, x.shape[4], overlap_size):
117
+ tile = x[
118
+ :,
119
+ :,
120
+ :,
121
+ i : i + self.tile_sample_min_size,
122
+ j : j + self.tile_sample_min_size,
123
+ ]
124
+ tile = self.encoder(tile)
125
+ tile = self.quant_conv(tile)
126
+ row.append(tile)
127
+ rows.append(row)
128
+ result_rows = []
129
+ for i, row in enumerate(rows):
130
+ result_row = []
131
+ for j, tile in enumerate(row):
132
+ # blend the above tile and the left tile
133
+ # to the current tile and add the current tile to the result row
134
+ if i > 0:
135
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
136
+ if j > 0:
137
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
138
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
139
+ result_rows.append(torch.cat(result_row, dim=4))
140
+
141
+ moments = torch.cat(result_rows, dim=3)
142
+ return moments
143
+
144
+ def blend_z(
145
+ self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
146
+ ) -> torch.Tensor:
147
+ blend_extent = min(a.shape[2], b.shape[2], blend_extent)
148
+ for z in range(blend_extent):
149
+ b[:, :, z, :, :] = a[:, :, -blend_extent + z, :, :] * (
150
+ 1 - z / blend_extent
151
+ ) + b[:, :, z, :, :] * (z / blend_extent)
152
+ return b
153
+
154
+ def blend_v(
155
+ self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
156
+ ) -> torch.Tensor:
157
+ blend_extent = min(a.shape[3], b.shape[3], blend_extent)
158
+ for y in range(blend_extent):
159
+ b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (
160
+ 1 - y / blend_extent
161
+ ) + b[:, :, :, y, :] * (y / blend_extent)
162
+ return b
163
+
164
+ def blend_h(
165
+ self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
166
+ ) -> torch.Tensor:
167
+ blend_extent = min(a.shape[4], b.shape[4], blend_extent)
168
+ for x in range(blend_extent):
169
+ b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (
170
+ 1 - x / blend_extent
171
+ ) + b[:, :, :, :, x] * (x / blend_extent)
172
+ return b
173
+
174
+ def _hw_tiled_decode(self, z: torch.FloatTensor, target_shape):
175
+ overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
176
+ blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)
177
+ row_limit = self.tile_sample_min_size - blend_extent
178
+ tile_target_shape = (
179
+ *target_shape[:3],
180
+ self.tile_sample_min_size,
181
+ self.tile_sample_min_size,
182
+ )
183
+ # Split z into overlapping 64x64 tiles and decode them separately.
184
+ # The tiles have an overlap to avoid seams between tiles.
185
+ rows = []
186
+ for i in range(0, z.shape[3], overlap_size):
187
+ row = []
188
+ for j in range(0, z.shape[4], overlap_size):
189
+ tile = z[
190
+ :,
191
+ :,
192
+ :,
193
+ i : i + self.tile_latent_min_size,
194
+ j : j + self.tile_latent_min_size,
195
+ ]
196
+ tile = self.post_quant_conv(tile)
197
+ decoded = self.decoder(tile, target_shape=tile_target_shape)
198
+ row.append(decoded)
199
+ rows.append(row)
200
+ result_rows = []
201
+ for i, row in enumerate(rows):
202
+ result_row = []
203
+ for j, tile in enumerate(row):
204
+ # blend the above tile and the left tile
205
+ # to the current tile and add the current tile to the result row
206
+ if i > 0:
207
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
208
+ if j > 0:
209
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
210
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
211
+ result_rows.append(torch.cat(result_row, dim=4))
212
+
213
+ dec = torch.cat(result_rows, dim=3)
214
+ return dec
215
+
216
+ def encode(
217
+ self, z: torch.FloatTensor, return_dict: bool = True
218
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
219
+ if self.use_z_tiling and z.shape[2] > self.z_sample_size > 1:
220
+ num_splits = z.shape[2] // self.z_sample_size
221
+ sizes = [self.z_sample_size] * num_splits
222
+ sizes = (
223
+ sizes + [z.shape[2] - sum(sizes)]
224
+ if z.shape[2] - sum(sizes) > 0
225
+ else sizes
226
+ )
227
+ tiles = z.split(sizes, dim=2)
228
+ moments_tiles = [
229
+ (
230
+ self._hw_tiled_encode(z_tile, return_dict)
231
+ if self.use_hw_tiling
232
+ else self._encode(z_tile)
233
+ )
234
+ for z_tile in tiles
235
+ ]
236
+ moments = torch.cat(moments_tiles, dim=2)
237
+
238
+ else:
239
+ moments = (
240
+ self._hw_tiled_encode(z, return_dict)
241
+ if self.use_hw_tiling
242
+ else self._encode(z)
243
+ )
244
+
245
+ posterior = DiagonalGaussianDistribution(moments)
246
+ if not return_dict:
247
+ return (posterior,)
248
+
249
+ return AutoencoderKLOutput(latent_dist=posterior)
250
+
251
+ def _encode(self, x: torch.FloatTensor) -> AutoencoderKLOutput:
252
+ h = self.encoder(x)
253
+ moments = self.quant_conv(h)
254
+ return moments
255
+
256
+ def _decode(
257
+ self,
258
+ z: torch.FloatTensor,
259
+ target_shape=None,
260
+ timestep: Optional[torch.Tensor] = None,
261
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
262
+ z = self.post_quant_conv(z)
263
+ if "timestep" in self.decoder_params:
264
+ dec = self.decoder(z, target_shape=target_shape, timestep=timestep)
265
+ else:
266
+ dec = self.decoder(z, target_shape=target_shape)
267
+ return dec
268
+
269
+ def decode(
270
+ self,
271
+ z: torch.FloatTensor,
272
+ return_dict: bool = True,
273
+ target_shape=None,
274
+ timestep: Optional[torch.Tensor] = None,
275
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
276
+ assert target_shape is not None, "target_shape must be provided for decoding"
277
+ if self.use_z_tiling and z.shape[2] > self.z_sample_size > 1:
278
+ reduction_factor = int(
279
+ self.encoder.patch_size_t
280
+ * 2
281
+ ** (
282
+ len(self.encoder.down_blocks)
283
+ - 1
284
+ - math.sqrt(self.encoder.patch_size)
285
+ )
286
+ )
287
+ split_size = self.z_sample_size // reduction_factor
288
+ num_splits = z.shape[2] // split_size
289
+
290
+ # copy target shape, and divide frame dimension (=2) by the context size
291
+ target_shape_split = list(target_shape)
292
+ target_shape_split[2] = target_shape[2] // num_splits
293
+
294
+ decoded_tiles = [
295
+ (
296
+ self._hw_tiled_decode(z_tile, target_shape_split)
297
+ if self.use_hw_tiling
298
+ else self._decode(z_tile, target_shape=target_shape_split)
299
+ )
300
+ for z_tile in torch.tensor_split(z, num_splits, dim=2)
301
+ ]
302
+ decoded = torch.cat(decoded_tiles, dim=2)
303
+ else:
304
+ decoded = (
305
+ self._hw_tiled_decode(z, target_shape)
306
+ if self.use_hw_tiling
307
+ else self._decode(z, target_shape=target_shape, timestep=timestep)
308
+ )
309
+
310
+ if not return_dict:
311
+ return (decoded,)
312
+
313
+ return DecoderOutput(sample=decoded)
314
+
315
+ def forward(
316
+ self,
317
+ sample: torch.FloatTensor,
318
+ sample_posterior: bool = False,
319
+ return_dict: bool = True,
320
+ generator: Optional[torch.Generator] = None,
321
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
322
+ r"""
323
+ Args:
324
+ sample (`torch.FloatTensor`): Input sample.
325
+ sample_posterior (`bool`, *optional*, defaults to `False`):
326
+ Whether to sample from the posterior.
327
+ return_dict (`bool`, *optional*, defaults to `True`):
328
+ Whether to return a [`DecoderOutput`] instead of a plain tuple.
329
+ generator (`torch.Generator`, *optional*):
330
+ Generator used to sample from the posterior.
331
+ """
332
+ x = sample
333
+ posterior = self.encode(x).latent_dist
334
+ if sample_posterior:
335
+ z = posterior.sample(generator=generator)
336
+ else:
337
+ z = posterior.mode()
338
+ dec = self.decode(z, target_shape=sample.shape).sample
339
+
340
+ if not return_dict:
341
+ return (dec,)
342
+
343
+ return DecoderOutput(sample=dec)
ltx_video/models/autoencoders/vae_encode.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers import AutoencoderKL
3
+ from einops import rearrange
4
+ from torch import Tensor
5
+
6
+
7
+ from ltx_video.models.autoencoders.causal_video_autoencoder import (
8
+ CausalVideoAutoencoder,
9
+ )
10
+ from ltx_video.models.autoencoders.video_autoencoder import (
11
+ Downsample3D,
12
+ VideoAutoencoder,
13
+ )
14
+
15
+ try:
16
+ import torch_xla.core.xla_model as xm
17
+ except ImportError:
18
+ xm = None
19
+
20
+
21
+ def vae_encode(
22
+ media_items: Tensor,
23
+ vae: AutoencoderKL,
24
+ split_size: int = 1,
25
+ vae_per_channel_normalize=False,
26
+ ) -> Tensor:
27
+ """
28
+ Encodes media items (images or videos) into latent representations using a specified VAE model.
29
+ The function supports processing batches of images or video frames and can handle the processing
30
+ in smaller sub-batches if needed.
31
+
32
+ Args:
33
+ media_items (Tensor): A torch Tensor containing the media items to encode. The expected
34
+ shape is (batch_size, channels, height, width) for images or (batch_size, channels,
35
+ frames, height, width) for videos.
36
+ vae (AutoencoderKL): An instance of the `AutoencoderKL` class from the `diffusers` library,
37
+ pre-configured and loaded with the appropriate model weights.
38
+ split_size (int, optional): The number of sub-batches to split the input batch into for encoding.
39
+ If set to more than 1, the input media items are processed in smaller batches according to
40
+ this value. Defaults to 1, which processes all items in a single batch.
41
+
42
+ Returns:
43
+ Tensor: A torch Tensor of the encoded latent representations. The shape of the tensor is adjusted
44
+ to match the input shape, scaled by the model's configuration.
45
+
46
+ Examples:
47
+ >>> import torch
48
+ >>> from diffusers import AutoencoderKL
49
+ >>> vae = AutoencoderKL.from_pretrained('your-model-name')
50
+ >>> images = torch.rand(10, 3, 8 256, 256) # Example tensor with 10 videos of 8 frames.
51
+ >>> latents = vae_encode(images, vae)
52
+ >>> print(latents.shape) # Output shape will depend on the model's latent configuration.
53
+
54
+ Note:
55
+ In case of a video, the function encodes the media item frame-by frame.
56
+ """
57
+ is_video_shaped = media_items.dim() == 5
58
+ batch_size, channels = media_items.shape[0:2]
59
+
60
+ if channels != 3:
61
+ raise ValueError(f"Expects tensors with 3 channels, got {channels}.")
62
+
63
+ if is_video_shaped and not isinstance(
64
+ vae, (VideoAutoencoder, CausalVideoAutoencoder)
65
+ ):
66
+ media_items = rearrange(media_items, "b c n h w -> (b n) c h w")
67
+ if split_size > 1:
68
+ if len(media_items) % split_size != 0:
69
+ raise ValueError(
70
+ "Error: The batch size must be divisible by 'train.vae_bs_split"
71
+ )
72
+ encode_bs = len(media_items) // split_size
73
+ # latents = [vae.encode(image_batch).latent_dist.sample() for image_batch in media_items.split(encode_bs)]
74
+ latents = []
75
+ if media_items.device.type == "xla":
76
+ xm.mark_step()
77
+ for image_batch in media_items.split(encode_bs):
78
+ latents.append(vae.encode(image_batch).latent_dist.sample())
79
+ if media_items.device.type == "xla":
80
+ xm.mark_step()
81
+ latents = torch.cat(latents, dim=0)
82
+ else:
83
+ latents = vae.encode(media_items).latent_dist.sample()
84
+
85
+ latents = normalize_latents(latents, vae, vae_per_channel_normalize)
86
+ if is_video_shaped and not isinstance(
87
+ vae, (VideoAutoencoder, CausalVideoAutoencoder)
88
+ ):
89
+ latents = rearrange(latents, "(b n) c h w -> b c n h w", b=batch_size)
90
+ return latents
91
+
92
+
93
+ def vae_decode(
94
+ latents: Tensor,
95
+ vae: AutoencoderKL,
96
+ is_video: bool = True,
97
+ split_size: int = 1,
98
+ vae_per_channel_normalize=False,
99
+ timestep=None,
100
+ ) -> Tensor:
101
+ is_video_shaped = latents.dim() == 5
102
+ batch_size = latents.shape[0]
103
+
104
+ if is_video_shaped and not isinstance(
105
+ vae, (VideoAutoencoder, CausalVideoAutoencoder)
106
+ ):
107
+ latents = rearrange(latents, "b c n h w -> (b n) c h w")
108
+ if split_size > 1:
109
+ if len(latents) % split_size != 0:
110
+ raise ValueError(
111
+ "Error: The batch size must be divisible by 'train.vae_bs_split"
112
+ )
113
+ encode_bs = len(latents) // split_size
114
+ image_batch = [
115
+ _run_decoder(
116
+ latent_batch, vae, is_video, vae_per_channel_normalize, timestep
117
+ )
118
+ for latent_batch in latents.split(encode_bs)
119
+ ]
120
+ images = torch.cat(image_batch, dim=0)
121
+ else:
122
+ images = _run_decoder(
123
+ latents, vae, is_video, vae_per_channel_normalize, timestep
124
+ )
125
+
126
+ if is_video_shaped and not isinstance(
127
+ vae, (VideoAutoencoder, CausalVideoAutoencoder)
128
+ ):
129
+ images = rearrange(images, "(b n) c h w -> b c n h w", b=batch_size)
130
+ return images
131
+
132
+
133
+ def _run_decoder(
134
+ latents: Tensor,
135
+ vae: AutoencoderKL,
136
+ is_video: bool,
137
+ vae_per_channel_normalize=False,
138
+ timestep=None,
139
+ ) -> Tensor:
140
+ if isinstance(vae, (VideoAutoencoder, CausalVideoAutoencoder)):
141
+ *_, fl, hl, wl = latents.shape
142
+ temporal_scale, spatial_scale, _ = get_vae_size_scale_factor(vae)
143
+ latents = latents.to(vae.dtype)
144
+ vae_decode_kwargs = {}
145
+ if timestep is not None:
146
+ vae_decode_kwargs["timestep"] = timestep
147
+ image = vae.decode(
148
+ un_normalize_latents(latents, vae, vae_per_channel_normalize),
149
+ return_dict=False,
150
+ target_shape=(
151
+ 1,
152
+ 3,
153
+ fl * temporal_scale if is_video else 1,
154
+ hl * spatial_scale,
155
+ wl * spatial_scale,
156
+ ),
157
+ **vae_decode_kwargs,
158
+ )[0]
159
+ else:
160
+ image = vae.decode(
161
+ un_normalize_latents(latents, vae, vae_per_channel_normalize),
162
+ return_dict=False,
163
+ )[0]
164
+ return image
165
+
166
+
167
+ def get_vae_size_scale_factor(vae: AutoencoderKL) -> float:
168
+ if isinstance(vae, CausalVideoAutoencoder):
169
+ spatial = vae.spatial_downscale_factor
170
+ temporal = vae.temporal_downscale_factor
171
+ else:
172
+ down_blocks = len(
173
+ [
174
+ block
175
+ for block in vae.encoder.down_blocks
176
+ if isinstance(block.downsample, Downsample3D)
177
+ ]
178
+ )
179
+ spatial = vae.config.patch_size * 2**down_blocks
180
+ temporal = (
181
+ vae.config.patch_size_t * 2**down_blocks
182
+ if isinstance(vae, VideoAutoencoder)
183
+ else 1
184
+ )
185
+
186
+ return (temporal, spatial, spatial)
187
+
188
+
189
+ def normalize_latents(
190
+ latents: Tensor, vae: AutoencoderKL, vae_per_channel_normalize: bool = False
191
+ ) -> Tensor:
192
+ return (
193
+ (latents - vae.mean_of_means.to(latents.dtype).view(1, -1, 1, 1, 1))
194
+ / vae.std_of_means.to(latents.dtype).view(1, -1, 1, 1, 1)
195
+ if vae_per_channel_normalize
196
+ else latents * vae.config.scaling_factor
197
+ )
198
+
199
+
200
+ def un_normalize_latents(
201
+ latents: Tensor, vae: AutoencoderKL, vae_per_channel_normalize: bool = False
202
+ ) -> Tensor:
203
+ return (
204
+ latents * vae.std_of_means.to(latents.dtype).view(1, -1, 1, 1, 1)
205
+ + vae.mean_of_means.to(latents.dtype).view(1, -1, 1, 1, 1)
206
+ if vae_per_channel_normalize
207
+ else latents / vae.config.scaling_factor
208
+ )
ltx_video/models/autoencoders/video_autoencoder.py ADDED
@@ -0,0 +1,1045 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from functools import partial
4
+ from types import SimpleNamespace
5
+ from typing import Any, Mapping, Optional, Tuple, Union
6
+
7
+ import torch
8
+ from einops import rearrange
9
+ from torch import nn
10
+ from torch.nn import functional
11
+
12
+ from diffusers.utils import logging
13
+
14
+ from ltx_video.utils.torch_utils import Identity
15
+ from ltx_video.models.autoencoders.conv_nd_factory import make_conv_nd, make_linear_nd
16
+ from ltx_video.models.autoencoders.pixel_norm import PixelNorm
17
+ from ltx_video.models.autoencoders.vae import AutoencoderKLWrapper
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class VideoAutoencoder(AutoencoderKLWrapper):
23
+ @classmethod
24
+ def from_pretrained(
25
+ cls,
26
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
27
+ *args,
28
+ **kwargs,
29
+ ):
30
+ config_local_path = pretrained_model_name_or_path / "config.json"
31
+ config = cls.load_config(config_local_path, **kwargs)
32
+ video_vae = cls.from_config(config)
33
+ video_vae.to(kwargs["torch_dtype"])
34
+
35
+ model_local_path = pretrained_model_name_or_path / "autoencoder.pth"
36
+ ckpt_state_dict = torch.load(model_local_path)
37
+ video_vae.load_state_dict(ckpt_state_dict)
38
+
39
+ statistics_local_path = (
40
+ pretrained_model_name_or_path / "per_channel_statistics.json"
41
+ )
42
+ if statistics_local_path.exists():
43
+ with open(statistics_local_path, "r") as file:
44
+ data = json.load(file)
45
+ transposed_data = list(zip(*data["data"]))
46
+ data_dict = {
47
+ col: torch.tensor(vals)
48
+ for col, vals in zip(data["columns"], transposed_data)
49
+ }
50
+ video_vae.register_buffer("std_of_means", data_dict["std-of-means"])
51
+ video_vae.register_buffer(
52
+ "mean_of_means",
53
+ data_dict.get(
54
+ "mean-of-means", torch.zeros_like(data_dict["std-of-means"])
55
+ ),
56
+ )
57
+
58
+ return video_vae
59
+
60
+ @staticmethod
61
+ def from_config(config):
62
+ assert (
63
+ config["_class_name"] == "VideoAutoencoder"
64
+ ), "config must have _class_name=VideoAutoencoder"
65
+ if isinstance(config["dims"], list):
66
+ config["dims"] = tuple(config["dims"])
67
+
68
+ assert config["dims"] in [2, 3, (2, 1)], "dims must be 2, 3 or (2, 1)"
69
+
70
+ double_z = config.get("double_z", True)
71
+ latent_log_var = config.get(
72
+ "latent_log_var", "per_channel" if double_z else "none"
73
+ )
74
+ use_quant_conv = config.get("use_quant_conv", True)
75
+
76
+ if use_quant_conv and latent_log_var == "uniform":
77
+ raise ValueError("uniform latent_log_var requires use_quant_conv=False")
78
+
79
+ encoder = Encoder(
80
+ dims=config["dims"],
81
+ in_channels=config.get("in_channels", 3),
82
+ out_channels=config["latent_channels"],
83
+ block_out_channels=config["block_out_channels"],
84
+ patch_size=config.get("patch_size", 1),
85
+ latent_log_var=latent_log_var,
86
+ norm_layer=config.get("norm_layer", "group_norm"),
87
+ patch_size_t=config.get("patch_size_t", config.get("patch_size", 1)),
88
+ add_channel_padding=config.get("add_channel_padding", False),
89
+ )
90
+
91
+ decoder = Decoder(
92
+ dims=config["dims"],
93
+ in_channels=config["latent_channels"],
94
+ out_channels=config.get("out_channels", 3),
95
+ block_out_channels=config["block_out_channels"],
96
+ patch_size=config.get("patch_size", 1),
97
+ norm_layer=config.get("norm_layer", "group_norm"),
98
+ patch_size_t=config.get("patch_size_t", config.get("patch_size", 1)),
99
+ add_channel_padding=config.get("add_channel_padding", False),
100
+ )
101
+
102
+ dims = config["dims"]
103
+ return VideoAutoencoder(
104
+ encoder=encoder,
105
+ decoder=decoder,
106
+ latent_channels=config["latent_channels"],
107
+ dims=dims,
108
+ use_quant_conv=use_quant_conv,
109
+ )
110
+
111
+ @property
112
+ def config(self):
113
+ return SimpleNamespace(
114
+ _class_name="VideoAutoencoder",
115
+ dims=self.dims,
116
+ in_channels=self.encoder.conv_in.in_channels
117
+ // (self.encoder.patch_size_t * self.encoder.patch_size**2),
118
+ out_channels=self.decoder.conv_out.out_channels
119
+ // (self.decoder.patch_size_t * self.decoder.patch_size**2),
120
+ latent_channels=self.decoder.conv_in.in_channels,
121
+ block_out_channels=[
122
+ self.encoder.down_blocks[i].res_blocks[-1].conv1.out_channels
123
+ for i in range(len(self.encoder.down_blocks))
124
+ ],
125
+ scaling_factor=1.0,
126
+ norm_layer=self.encoder.norm_layer,
127
+ patch_size=self.encoder.patch_size,
128
+ latent_log_var=self.encoder.latent_log_var,
129
+ use_quant_conv=self.use_quant_conv,
130
+ patch_size_t=self.encoder.patch_size_t,
131
+ add_channel_padding=self.encoder.add_channel_padding,
132
+ )
133
+
134
+ @property
135
+ def is_video_supported(self):
136
+ """
137
+ Check if the model supports video inputs of shape (B, C, F, H, W). Otherwise, the model only supports 2D images.
138
+ """
139
+ return self.dims != 2
140
+
141
+ @property
142
+ def downscale_factor(self):
143
+ return self.encoder.downsample_factor
144
+
145
+ def to_json_string(self) -> str:
146
+ import json
147
+
148
+ return json.dumps(self.config.__dict__)
149
+
150
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
151
+ model_keys = set(name for name, _ in self.named_parameters())
152
+
153
+ key_mapping = {
154
+ ".resnets.": ".res_blocks.",
155
+ "downsamplers.0": "downsample",
156
+ "upsamplers.0": "upsample",
157
+ }
158
+
159
+ converted_state_dict = {}
160
+ for key, value in state_dict.items():
161
+ for k, v in key_mapping.items():
162
+ key = key.replace(k, v)
163
+
164
+ if "norm" in key and key not in model_keys:
165
+ logger.info(
166
+ f"Removing key {key} from state_dict as it is not present in the model"
167
+ )
168
+ continue
169
+
170
+ converted_state_dict[key] = value
171
+
172
+ super().load_state_dict(converted_state_dict, strict=strict)
173
+
174
+ def last_layer(self):
175
+ if hasattr(self.decoder, "conv_out"):
176
+ if isinstance(self.decoder.conv_out, nn.Sequential):
177
+ last_layer = self.decoder.conv_out[-1]
178
+ else:
179
+ last_layer = self.decoder.conv_out
180
+ else:
181
+ last_layer = self.decoder.layers[-1]
182
+ return last_layer
183
+
184
+
185
+ class Encoder(nn.Module):
186
+ r"""
187
+ The `Encoder` layer of a variational autoencoder that encodes its input into a latent representation.
188
+
189
+ Args:
190
+ in_channels (`int`, *optional*, defaults to 3):
191
+ The number of input channels.
192
+ out_channels (`int`, *optional*, defaults to 3):
193
+ The number of output channels.
194
+ block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
195
+ The number of output channels for each block.
196
+ layers_per_block (`int`, *optional*, defaults to 2):
197
+ The number of layers per block.
198
+ norm_num_groups (`int`, *optional*, defaults to 32):
199
+ The number of groups for normalization.
200
+ patch_size (`int`, *optional*, defaults to 1):
201
+ The patch size to use. Should be a power of 2.
202
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
203
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
204
+ latent_log_var (`str`, *optional*, defaults to `per_channel`):
205
+ The number of channels for the log variance. Can be either `per_channel`, `uniform`, or `none`.
206
+ """
207
+
208
+ def __init__(
209
+ self,
210
+ dims: Union[int, Tuple[int, int]] = 3,
211
+ in_channels: int = 3,
212
+ out_channels: int = 3,
213
+ block_out_channels: Tuple[int, ...] = (64,),
214
+ layers_per_block: int = 2,
215
+ norm_num_groups: int = 32,
216
+ patch_size: Union[int, Tuple[int]] = 1,
217
+ norm_layer: str = "group_norm", # group_norm, pixel_norm
218
+ latent_log_var: str = "per_channel",
219
+ patch_size_t: Optional[int] = None,
220
+ add_channel_padding: Optional[bool] = False,
221
+ ):
222
+ super().__init__()
223
+ self.patch_size = patch_size
224
+ self.patch_size_t = patch_size_t if patch_size_t is not None else patch_size
225
+ self.add_channel_padding = add_channel_padding
226
+ self.layers_per_block = layers_per_block
227
+ self.norm_layer = norm_layer
228
+ self.latent_channels = out_channels
229
+ self.latent_log_var = latent_log_var
230
+ if add_channel_padding:
231
+ in_channels = in_channels * self.patch_size**3
232
+ else:
233
+ in_channels = in_channels * self.patch_size_t * self.patch_size**2
234
+ self.in_channels = in_channels
235
+ output_channel = block_out_channels[0]
236
+
237
+ self.conv_in = make_conv_nd(
238
+ dims=dims,
239
+ in_channels=in_channels,
240
+ out_channels=output_channel,
241
+ kernel_size=3,
242
+ stride=1,
243
+ padding=1,
244
+ )
245
+
246
+ self.down_blocks = nn.ModuleList([])
247
+
248
+ for i in range(len(block_out_channels)):
249
+ input_channel = output_channel
250
+ output_channel = block_out_channels[i]
251
+ is_final_block = i == len(block_out_channels) - 1
252
+
253
+ down_block = DownEncoderBlock3D(
254
+ dims=dims,
255
+ in_channels=input_channel,
256
+ out_channels=output_channel,
257
+ num_layers=self.layers_per_block,
258
+ add_downsample=not is_final_block and 2**i >= patch_size,
259
+ resnet_eps=1e-6,
260
+ downsample_padding=0,
261
+ resnet_groups=norm_num_groups,
262
+ norm_layer=norm_layer,
263
+ )
264
+ self.down_blocks.append(down_block)
265
+
266
+ self.mid_block = UNetMidBlock3D(
267
+ dims=dims,
268
+ in_channels=block_out_channels[-1],
269
+ num_layers=self.layers_per_block,
270
+ resnet_eps=1e-6,
271
+ resnet_groups=norm_num_groups,
272
+ norm_layer=norm_layer,
273
+ )
274
+
275
+ # out
276
+ if norm_layer == "group_norm":
277
+ self.conv_norm_out = nn.GroupNorm(
278
+ num_channels=block_out_channels[-1],
279
+ num_groups=norm_num_groups,
280
+ eps=1e-6,
281
+ )
282
+ elif norm_layer == "pixel_norm":
283
+ self.conv_norm_out = PixelNorm()
284
+ self.conv_act = nn.SiLU()
285
+
286
+ conv_out_channels = out_channels
287
+ if latent_log_var == "per_channel":
288
+ conv_out_channels *= 2
289
+ elif latent_log_var == "uniform":
290
+ conv_out_channels += 1
291
+ elif latent_log_var != "none":
292
+ raise ValueError(f"Invalid latent_log_var: {latent_log_var}")
293
+ self.conv_out = make_conv_nd(
294
+ dims, block_out_channels[-1], conv_out_channels, 3, padding=1
295
+ )
296
+
297
+ self.gradient_checkpointing = False
298
+
299
+ @property
300
+ def downscale_factor(self):
301
+ return (
302
+ 2
303
+ ** len(
304
+ [
305
+ block
306
+ for block in self.down_blocks
307
+ if isinstance(block.downsample, Downsample3D)
308
+ ]
309
+ )
310
+ * self.patch_size
311
+ )
312
+
313
+ def forward(
314
+ self, sample: torch.FloatTensor, return_features=False
315
+ ) -> torch.FloatTensor:
316
+ r"""The forward method of the `Encoder` class."""
317
+
318
+ downsample_in_time = sample.shape[2] != 1
319
+
320
+ # patchify
321
+ patch_size_t = self.patch_size_t if downsample_in_time else 1
322
+ sample = patchify(
323
+ sample,
324
+ patch_size_hw=self.patch_size,
325
+ patch_size_t=patch_size_t,
326
+ add_channel_padding=self.add_channel_padding,
327
+ )
328
+
329
+ sample = self.conv_in(sample)
330
+
331
+ checkpoint_fn = (
332
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
333
+ if self.gradient_checkpointing and self.training
334
+ else lambda x: x
335
+ )
336
+
337
+ if return_features:
338
+ features = []
339
+ for down_block in self.down_blocks:
340
+ sample = checkpoint_fn(down_block)(
341
+ sample, downsample_in_time=downsample_in_time
342
+ )
343
+ if return_features:
344
+ features.append(sample)
345
+
346
+ sample = checkpoint_fn(self.mid_block)(sample)
347
+
348
+ # post-process
349
+ sample = self.conv_norm_out(sample)
350
+ sample = self.conv_act(sample)
351
+ sample = self.conv_out(sample)
352
+
353
+ if self.latent_log_var == "uniform":
354
+ last_channel = sample[:, -1:, ...]
355
+ num_dims = sample.dim()
356
+
357
+ if num_dims == 4:
358
+ # For shape (B, C, H, W)
359
+ repeated_last_channel = last_channel.repeat(
360
+ 1, sample.shape[1] - 2, 1, 1
361
+ )
362
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
363
+ elif num_dims == 5:
364
+ # For shape (B, C, F, H, W)
365
+ repeated_last_channel = last_channel.repeat(
366
+ 1, sample.shape[1] - 2, 1, 1, 1
367
+ )
368
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
369
+ else:
370
+ raise ValueError(f"Invalid input shape: {sample.shape}")
371
+
372
+ if return_features:
373
+ features.append(sample[:, : self.latent_channels, ...])
374
+ return sample, features
375
+ return sample
376
+
377
+
378
+ class Decoder(nn.Module):
379
+ r"""
380
+ The `Decoder` layer of a variational autoencoder that decodes its latent representation into an output sample.
381
+
382
+ Args:
383
+ in_channels (`int`, *optional*, defaults to 3):
384
+ The number of input channels.
385
+ out_channels (`int`, *optional*, defaults to 3):
386
+ The number of output channels.
387
+ block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
388
+ The number of output channels for each block.
389
+ layers_per_block (`int`, *optional*, defaults to 2):
390
+ The number of layers per block.
391
+ norm_num_groups (`int`, *optional*, defaults to 32):
392
+ The number of groups for normalization.
393
+ patch_size (`int`, *optional*, defaults to 1):
394
+ The patch size to use. Should be a power of 2.
395
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
396
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
397
+ """
398
+
399
+ def __init__(
400
+ self,
401
+ dims,
402
+ in_channels: int = 3,
403
+ out_channels: int = 3,
404
+ block_out_channels: Tuple[int, ...] = (64,),
405
+ layers_per_block: int = 2,
406
+ norm_num_groups: int = 32,
407
+ patch_size: int = 1,
408
+ norm_layer: str = "group_norm",
409
+ patch_size_t: Optional[int] = None,
410
+ add_channel_padding: Optional[bool] = False,
411
+ ):
412
+ super().__init__()
413
+ self.patch_size = patch_size
414
+ self.patch_size_t = patch_size_t if patch_size_t is not None else patch_size
415
+ self.add_channel_padding = add_channel_padding
416
+ self.layers_per_block = layers_per_block
417
+ if add_channel_padding:
418
+ out_channels = out_channels * self.patch_size**3
419
+ else:
420
+ out_channels = out_channels * self.patch_size_t * self.patch_size**2
421
+ self.out_channels = out_channels
422
+
423
+ self.conv_in = make_conv_nd(
424
+ dims,
425
+ in_channels,
426
+ block_out_channels[-1],
427
+ kernel_size=3,
428
+ stride=1,
429
+ padding=1,
430
+ )
431
+
432
+ self.mid_block = None
433
+ self.up_blocks = nn.ModuleList([])
434
+
435
+ self.mid_block = UNetMidBlock3D(
436
+ dims=dims,
437
+ in_channels=block_out_channels[-1],
438
+ num_layers=self.layers_per_block,
439
+ resnet_eps=1e-6,
440
+ resnet_groups=norm_num_groups,
441
+ norm_layer=norm_layer,
442
+ )
443
+
444
+ reversed_block_out_channels = list(reversed(block_out_channels))
445
+ output_channel = reversed_block_out_channels[0]
446
+ for i in range(len(reversed_block_out_channels)):
447
+ prev_output_channel = output_channel
448
+ output_channel = reversed_block_out_channels[i]
449
+
450
+ is_final_block = i == len(block_out_channels) - 1
451
+
452
+ up_block = UpDecoderBlock3D(
453
+ dims=dims,
454
+ num_layers=self.layers_per_block + 1,
455
+ in_channels=prev_output_channel,
456
+ out_channels=output_channel,
457
+ add_upsample=not is_final_block
458
+ and 2 ** (len(block_out_channels) - i - 1) > patch_size,
459
+ resnet_eps=1e-6,
460
+ resnet_groups=norm_num_groups,
461
+ norm_layer=norm_layer,
462
+ )
463
+ self.up_blocks.append(up_block)
464
+
465
+ if norm_layer == "group_norm":
466
+ self.conv_norm_out = nn.GroupNorm(
467
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=1e-6
468
+ )
469
+ elif norm_layer == "pixel_norm":
470
+ self.conv_norm_out = PixelNorm()
471
+
472
+ self.conv_act = nn.SiLU()
473
+ self.conv_out = make_conv_nd(
474
+ dims, block_out_channels[0], out_channels, 3, padding=1
475
+ )
476
+
477
+ self.gradient_checkpointing = False
478
+
479
+ def forward(self, sample: torch.FloatTensor, target_shape) -> torch.FloatTensor:
480
+ r"""The forward method of the `Decoder` class."""
481
+ assert target_shape is not None, "target_shape must be provided"
482
+ upsample_in_time = sample.shape[2] < target_shape[2]
483
+
484
+ sample = self.conv_in(sample)
485
+
486
+ upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
487
+
488
+ checkpoint_fn = (
489
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
490
+ if self.gradient_checkpointing and self.training
491
+ else lambda x: x
492
+ )
493
+
494
+ sample = checkpoint_fn(self.mid_block)(sample)
495
+ sample = sample.to(upscale_dtype)
496
+
497
+ for up_block in self.up_blocks:
498
+ sample = checkpoint_fn(up_block)(sample, upsample_in_time=upsample_in_time)
499
+
500
+ # post-process
501
+ sample = self.conv_norm_out(sample)
502
+ sample = self.conv_act(sample)
503
+ sample = self.conv_out(sample)
504
+
505
+ # un-patchify
506
+ patch_size_t = self.patch_size_t if upsample_in_time else 1
507
+ sample = unpatchify(
508
+ sample,
509
+ patch_size_hw=self.patch_size,
510
+ patch_size_t=patch_size_t,
511
+ add_channel_padding=self.add_channel_padding,
512
+ )
513
+
514
+ return sample
515
+
516
+
517
+ class DownEncoderBlock3D(nn.Module):
518
+ def __init__(
519
+ self,
520
+ dims: Union[int, Tuple[int, int]],
521
+ in_channels: int,
522
+ out_channels: int,
523
+ dropout: float = 0.0,
524
+ num_layers: int = 1,
525
+ resnet_eps: float = 1e-6,
526
+ resnet_groups: int = 32,
527
+ add_downsample: bool = True,
528
+ downsample_padding: int = 1,
529
+ norm_layer: str = "group_norm",
530
+ ):
531
+ super().__init__()
532
+ res_blocks = []
533
+
534
+ for i in range(num_layers):
535
+ in_channels = in_channels if i == 0 else out_channels
536
+ res_blocks.append(
537
+ ResnetBlock3D(
538
+ dims=dims,
539
+ in_channels=in_channels,
540
+ out_channels=out_channels,
541
+ eps=resnet_eps,
542
+ groups=resnet_groups,
543
+ dropout=dropout,
544
+ norm_layer=norm_layer,
545
+ )
546
+ )
547
+
548
+ self.res_blocks = nn.ModuleList(res_blocks)
549
+
550
+ if add_downsample:
551
+ self.downsample = Downsample3D(
552
+ dims,
553
+ out_channels,
554
+ out_channels=out_channels,
555
+ padding=downsample_padding,
556
+ )
557
+ else:
558
+ self.downsample = Identity()
559
+
560
+ def forward(
561
+ self, hidden_states: torch.FloatTensor, downsample_in_time
562
+ ) -> torch.FloatTensor:
563
+ for resnet in self.res_blocks:
564
+ hidden_states = resnet(hidden_states)
565
+
566
+ hidden_states = self.downsample(
567
+ hidden_states, downsample_in_time=downsample_in_time
568
+ )
569
+
570
+ return hidden_states
571
+
572
+
573
+ class UNetMidBlock3D(nn.Module):
574
+ """
575
+ A 3D UNet mid-block [`UNetMidBlock3D`] with multiple residual blocks.
576
+
577
+ Args:
578
+ in_channels (`int`): The number of input channels.
579
+ dropout (`float`, *optional*, defaults to 0.0): The dropout rate.
580
+ num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.
581
+ resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.
582
+ resnet_groups (`int`, *optional*, defaults to 32):
583
+ The number of groups to use in the group normalization layers of the resnet blocks.
584
+
585
+ Returns:
586
+ `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,
587
+ in_channels, height, width)`.
588
+
589
+ """
590
+
591
+ def __init__(
592
+ self,
593
+ dims: Union[int, Tuple[int, int]],
594
+ in_channels: int,
595
+ dropout: float = 0.0,
596
+ num_layers: int = 1,
597
+ resnet_eps: float = 1e-6,
598
+ resnet_groups: int = 32,
599
+ norm_layer: str = "group_norm",
600
+ ):
601
+ super().__init__()
602
+ resnet_groups = (
603
+ resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
604
+ )
605
+
606
+ self.res_blocks = nn.ModuleList(
607
+ [
608
+ ResnetBlock3D(
609
+ dims=dims,
610
+ in_channels=in_channels,
611
+ out_channels=in_channels,
612
+ eps=resnet_eps,
613
+ groups=resnet_groups,
614
+ dropout=dropout,
615
+ norm_layer=norm_layer,
616
+ )
617
+ for _ in range(num_layers)
618
+ ]
619
+ )
620
+
621
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
622
+ for resnet in self.res_blocks:
623
+ hidden_states = resnet(hidden_states)
624
+
625
+ return hidden_states
626
+
627
+
628
+ class UpDecoderBlock3D(nn.Module):
629
+ def __init__(
630
+ self,
631
+ dims: Union[int, Tuple[int, int]],
632
+ in_channels: int,
633
+ out_channels: int,
634
+ resolution_idx: Optional[int] = None,
635
+ dropout: float = 0.0,
636
+ num_layers: int = 1,
637
+ resnet_eps: float = 1e-6,
638
+ resnet_groups: int = 32,
639
+ add_upsample: bool = True,
640
+ norm_layer: str = "group_norm",
641
+ ):
642
+ super().__init__()
643
+ res_blocks = []
644
+
645
+ for i in range(num_layers):
646
+ input_channels = in_channels if i == 0 else out_channels
647
+
648
+ res_blocks.append(
649
+ ResnetBlock3D(
650
+ dims=dims,
651
+ in_channels=input_channels,
652
+ out_channels=out_channels,
653
+ eps=resnet_eps,
654
+ groups=resnet_groups,
655
+ dropout=dropout,
656
+ norm_layer=norm_layer,
657
+ )
658
+ )
659
+
660
+ self.res_blocks = nn.ModuleList(res_blocks)
661
+
662
+ if add_upsample:
663
+ self.upsample = Upsample3D(
664
+ dims=dims, channels=out_channels, out_channels=out_channels
665
+ )
666
+ else:
667
+ self.upsample = Identity()
668
+
669
+ self.resolution_idx = resolution_idx
670
+
671
+ def forward(
672
+ self, hidden_states: torch.FloatTensor, upsample_in_time=True
673
+ ) -> torch.FloatTensor:
674
+ for resnet in self.res_blocks:
675
+ hidden_states = resnet(hidden_states)
676
+
677
+ hidden_states = self.upsample(hidden_states, upsample_in_time=upsample_in_time)
678
+
679
+ return hidden_states
680
+
681
+
682
+ class ResnetBlock3D(nn.Module):
683
+ r"""
684
+ A Resnet block.
685
+
686
+ Parameters:
687
+ in_channels (`int`): The number of channels in the input.
688
+ out_channels (`int`, *optional*, default to be `None`):
689
+ The number of output channels for the first conv layer. If None, same as `in_channels`.
690
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
691
+ groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
692
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
693
+ """
694
+
695
+ def __init__(
696
+ self,
697
+ dims: Union[int, Tuple[int, int]],
698
+ in_channels: int,
699
+ out_channels: Optional[int] = None,
700
+ conv_shortcut: bool = False,
701
+ dropout: float = 0.0,
702
+ groups: int = 32,
703
+ eps: float = 1e-6,
704
+ norm_layer: str = "group_norm",
705
+ ):
706
+ super().__init__()
707
+ self.in_channels = in_channels
708
+ out_channels = in_channels if out_channels is None else out_channels
709
+ self.out_channels = out_channels
710
+ self.use_conv_shortcut = conv_shortcut
711
+
712
+ if norm_layer == "group_norm":
713
+ self.norm1 = torch.nn.GroupNorm(
714
+ num_groups=groups, num_channels=in_channels, eps=eps, affine=True
715
+ )
716
+ elif norm_layer == "pixel_norm":
717
+ self.norm1 = PixelNorm()
718
+
719
+ self.non_linearity = nn.SiLU()
720
+
721
+ self.conv1 = make_conv_nd(
722
+ dims, in_channels, out_channels, kernel_size=3, stride=1, padding=1
723
+ )
724
+
725
+ if norm_layer == "group_norm":
726
+ self.norm2 = torch.nn.GroupNorm(
727
+ num_groups=groups, num_channels=out_channels, eps=eps, affine=True
728
+ )
729
+ elif norm_layer == "pixel_norm":
730
+ self.norm2 = PixelNorm()
731
+
732
+ self.dropout = torch.nn.Dropout(dropout)
733
+
734
+ self.conv2 = make_conv_nd(
735
+ dims, out_channels, out_channels, kernel_size=3, stride=1, padding=1
736
+ )
737
+
738
+ self.conv_shortcut = (
739
+ make_linear_nd(
740
+ dims=dims, in_channels=in_channels, out_channels=out_channels
741
+ )
742
+ if in_channels != out_channels
743
+ else nn.Identity()
744
+ )
745
+
746
+ def forward(
747
+ self,
748
+ input_tensor: torch.FloatTensor,
749
+ ) -> torch.FloatTensor:
750
+ hidden_states = input_tensor
751
+
752
+ hidden_states = self.norm1(hidden_states)
753
+
754
+ hidden_states = self.non_linearity(hidden_states)
755
+
756
+ hidden_states = self.conv1(hidden_states)
757
+
758
+ hidden_states = self.norm2(hidden_states)
759
+
760
+ hidden_states = self.non_linearity(hidden_states)
761
+
762
+ hidden_states = self.dropout(hidden_states)
763
+
764
+ hidden_states = self.conv2(hidden_states)
765
+
766
+ input_tensor = self.conv_shortcut(input_tensor)
767
+
768
+ output_tensor = input_tensor + hidden_states
769
+
770
+ return output_tensor
771
+
772
+
773
+ class Downsample3D(nn.Module):
774
+ def __init__(
775
+ self,
776
+ dims,
777
+ in_channels: int,
778
+ out_channels: int,
779
+ kernel_size: int = 3,
780
+ padding: int = 1,
781
+ ):
782
+ super().__init__()
783
+ stride: int = 2
784
+ self.padding = padding
785
+ self.in_channels = in_channels
786
+ self.dims = dims
787
+ self.conv = make_conv_nd(
788
+ dims=dims,
789
+ in_channels=in_channels,
790
+ out_channels=out_channels,
791
+ kernel_size=kernel_size,
792
+ stride=stride,
793
+ padding=padding,
794
+ )
795
+
796
+ def forward(self, x, downsample_in_time=True):
797
+ conv = self.conv
798
+ if self.padding == 0:
799
+ if self.dims == 2:
800
+ padding = (0, 1, 0, 1)
801
+ else:
802
+ padding = (0, 1, 0, 1, 0, 1 if downsample_in_time else 0)
803
+
804
+ x = functional.pad(x, padding, mode="constant", value=0)
805
+
806
+ if self.dims == (2, 1) and not downsample_in_time:
807
+ return conv(x, skip_time_conv=True)
808
+
809
+ return conv(x)
810
+
811
+
812
+ class Upsample3D(nn.Module):
813
+ """
814
+ An upsampling layer for 3D tensors of shape (B, C, D, H, W).
815
+
816
+ :param channels: channels in the inputs and outputs.
817
+ """
818
+
819
+ def __init__(self, dims, channels, out_channels=None):
820
+ super().__init__()
821
+ self.dims = dims
822
+ self.channels = channels
823
+ self.out_channels = out_channels or channels
824
+ self.conv = make_conv_nd(
825
+ dims, channels, out_channels, kernel_size=3, padding=1, bias=True
826
+ )
827
+
828
+ def forward(self, x, upsample_in_time):
829
+ if self.dims == 2:
830
+ x = functional.interpolate(
831
+ x, (x.shape[2] * 2, x.shape[3] * 2), mode="nearest"
832
+ )
833
+ else:
834
+ time_scale_factor = 2 if upsample_in_time else 1
835
+ # print("before:", x.shape)
836
+ b, c, d, h, w = x.shape
837
+ x = rearrange(x, "b c d h w -> (b d) c h w")
838
+ # height and width interpolate
839
+ x = functional.interpolate(
840
+ x, (x.shape[2] * 2, x.shape[3] * 2), mode="nearest"
841
+ )
842
+ _, _, h, w = x.shape
843
+
844
+ if not upsample_in_time and self.dims == (2, 1):
845
+ x = rearrange(x, "(b d) c h w -> b c d h w ", b=b, h=h, w=w)
846
+ return self.conv(x, skip_time_conv=True)
847
+
848
+ # Second ** upsampling ** which is essentially treated as a 1D convolution across the 'd' dimension
849
+ x = rearrange(x, "(b d) c h w -> (b h w) c 1 d", b=b)
850
+
851
+ # (b h w) c 1 d
852
+ new_d = x.shape[-1] * time_scale_factor
853
+ x = functional.interpolate(x, (1, new_d), mode="nearest")
854
+ # (b h w) c 1 new_d
855
+ x = rearrange(
856
+ x, "(b h w) c 1 new_d -> b c new_d h w", b=b, h=h, w=w, new_d=new_d
857
+ )
858
+ # b c d h w
859
+
860
+ # x = functional.interpolate(
861
+ # x, (x.shape[2] * time_scale_factor, x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
862
+ # )
863
+ # print("after:", x.shape)
864
+
865
+ return self.conv(x)
866
+
867
+
868
+ def patchify(x, patch_size_hw, patch_size_t=1, add_channel_padding=False):
869
+ if patch_size_hw == 1 and patch_size_t == 1:
870
+ return x
871
+ if x.dim() == 4:
872
+ x = rearrange(
873
+ x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size_hw, r=patch_size_hw
874
+ )
875
+ elif x.dim() == 5:
876
+ x = rearrange(
877
+ x,
878
+ "b c (f p) (h q) (w r) -> b (c p r q) f h w",
879
+ p=patch_size_t,
880
+ q=patch_size_hw,
881
+ r=patch_size_hw,
882
+ )
883
+ else:
884
+ raise ValueError(f"Invalid input shape: {x.shape}")
885
+
886
+ if (
887
+ (x.dim() == 5)
888
+ and (patch_size_hw > patch_size_t)
889
+ and (patch_size_t > 1 or add_channel_padding)
890
+ ):
891
+ channels_to_pad = x.shape[1] * (patch_size_hw // patch_size_t) - x.shape[1]
892
+ padding_zeros = torch.zeros(
893
+ x.shape[0],
894
+ channels_to_pad,
895
+ x.shape[2],
896
+ x.shape[3],
897
+ x.shape[4],
898
+ device=x.device,
899
+ dtype=x.dtype,
900
+ )
901
+ x = torch.cat([padding_zeros, x], dim=1)
902
+
903
+ return x
904
+
905
+
906
+ def unpatchify(x, patch_size_hw, patch_size_t=1, add_channel_padding=False):
907
+ if patch_size_hw == 1 and patch_size_t == 1:
908
+ return x
909
+
910
+ if (
911
+ (x.dim() == 5)
912
+ and (patch_size_hw > patch_size_t)
913
+ and (patch_size_t > 1 or add_channel_padding)
914
+ ):
915
+ channels_to_keep = int(x.shape[1] * (patch_size_t / patch_size_hw))
916
+ x = x[:, :channels_to_keep, :, :, :]
917
+
918
+ if x.dim() == 4:
919
+ x = rearrange(
920
+ x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size_hw, r=patch_size_hw
921
+ )
922
+ elif x.dim() == 5:
923
+ x = rearrange(
924
+ x,
925
+ "b (c p r q) f h w -> b c (f p) (h q) (w r)",
926
+ p=patch_size_t,
927
+ q=patch_size_hw,
928
+ r=patch_size_hw,
929
+ )
930
+
931
+ return x
932
+
933
+
934
+ def create_video_autoencoder_config(
935
+ latent_channels: int = 4,
936
+ ):
937
+ config = {
938
+ "_class_name": "VideoAutoencoder",
939
+ "dims": (
940
+ 2,
941
+ 1,
942
+ ), # 2 for Conv2, 3 for Conv3d, (2, 1) for Conv2d followed by Conv1d
943
+ "in_channels": 3, # Number of input color channels (e.g., RGB)
944
+ "out_channels": 3, # Number of output color channels
945
+ "latent_channels": latent_channels, # Number of channels in the latent space representation
946
+ "block_out_channels": [
947
+ 128,
948
+ 256,
949
+ 512,
950
+ 512,
951
+ ], # Number of output channels of each encoder / decoder inner block
952
+ "patch_size": 1,
953
+ }
954
+
955
+ return config
956
+
957
+
958
+ def create_video_autoencoder_pathify4x4x4_config(
959
+ latent_channels: int = 4,
960
+ ):
961
+ config = {
962
+ "_class_name": "VideoAutoencoder",
963
+ "dims": (
964
+ 2,
965
+ 1,
966
+ ), # 2 for Conv2, 3 for Conv3d, (2, 1) for Conv2d followed by Conv1d
967
+ "in_channels": 3, # Number of input color channels (e.g., RGB)
968
+ "out_channels": 3, # Number of output color channels
969
+ "latent_channels": latent_channels, # Number of channels in the latent space representation
970
+ "block_out_channels": [512]
971
+ * 4, # Number of output channels of each encoder / decoder inner block
972
+ "patch_size": 4,
973
+ "latent_log_var": "uniform",
974
+ }
975
+
976
+ return config
977
+
978
+
979
+ def create_video_autoencoder_pathify4x4_config(
980
+ latent_channels: int = 4,
981
+ ):
982
+ config = {
983
+ "_class_name": "VideoAutoencoder",
984
+ "dims": 2, # 2 for Conv2, 3 for Conv3d, (2, 1) for Conv2d followed by Conv1d
985
+ "in_channels": 3, # Number of input color channels (e.g., RGB)
986
+ "out_channels": 3, # Number of output color channels
987
+ "latent_channels": latent_channels, # Number of channels in the latent space representation
988
+ "block_out_channels": [512]
989
+ * 4, # Number of output channels of each encoder / decoder inner block
990
+ "patch_size": 4,
991
+ "norm_layer": "pixel_norm",
992
+ }
993
+
994
+ return config
995
+
996
+
997
+ def test_vae_patchify_unpatchify():
998
+ import torch
999
+
1000
+ x = torch.randn(2, 3, 8, 64, 64)
1001
+ x_patched = patchify(x, patch_size_hw=4, patch_size_t=4)
1002
+ x_unpatched = unpatchify(x_patched, patch_size_hw=4, patch_size_t=4)
1003
+ assert torch.allclose(x, x_unpatched)
1004
+
1005
+
1006
+ def demo_video_autoencoder_forward_backward():
1007
+ # Configuration for the VideoAutoencoder
1008
+ config = create_video_autoencoder_pathify4x4x4_config()
1009
+
1010
+ # Instantiate the VideoAutoencoder with the specified configuration
1011
+ video_autoencoder = VideoAutoencoder.from_config(config)
1012
+
1013
+ print(video_autoencoder)
1014
+
1015
+ # Print the total number of parameters in the video autoencoder
1016
+ total_params = sum(p.numel() for p in video_autoencoder.parameters())
1017
+ print(f"Total number of parameters in VideoAutoencoder: {total_params:,}")
1018
+
1019
+ # Create a mock input tensor simulating a batch of videos
1020
+ # Shape: (batch_size, channels, depth, height, width)
1021
+ # E.g., 4 videos, each with 3 color channels, 16 frames, and 64x64 pixels per frame
1022
+ input_videos = torch.randn(2, 3, 8, 64, 64)
1023
+
1024
+ # Forward pass: encode and decode the input videos
1025
+ latent = video_autoencoder.encode(input_videos).latent_dist.mode()
1026
+ print(f"input shape={input_videos.shape}")
1027
+ print(f"latent shape={latent.shape}")
1028
+ reconstructed_videos = video_autoencoder.decode(
1029
+ latent, target_shape=input_videos.shape
1030
+ ).sample
1031
+
1032
+ print(f"reconstructed shape={reconstructed_videos.shape}")
1033
+
1034
+ # Calculate the loss (e.g., mean squared error)
1035
+ loss = torch.nn.functional.mse_loss(input_videos, reconstructed_videos)
1036
+
1037
+ # Perform backward pass
1038
+ loss.backward()
1039
+
1040
+ print(f"Demo completed with loss: {loss.item()}")
1041
+
1042
+
1043
+ # Ensure to call the demo function to execute the forward and backward pass
1044
+ if __name__ == "__main__":
1045
+ demo_video_autoencoder_forward_backward()
ltx_video/models/transformers/__init__.py ADDED
File without changes
ltx_video/models/transformers/attention.py ADDED
@@ -0,0 +1,1262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from importlib import import_module
3
+ from typing import Any, Dict, Optional, Tuple
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
8
+ from diffusers.models.attention import _chunked_feed_forward
9
+ from diffusers.models.attention_processor import (
10
+ LoRAAttnAddedKVProcessor,
11
+ LoRAAttnProcessor,
12
+ LoRAAttnProcessor2_0,
13
+ LoRAXFormersAttnProcessor,
14
+ SpatialNorm,
15
+ )
16
+ from diffusers.models.lora import LoRACompatibleLinear
17
+ from diffusers.models.normalization import RMSNorm
18
+ from diffusers.utils import deprecate, logging
19
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
20
+ from einops import rearrange
21
+ from torch import nn
22
+
23
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
24
+
25
+ try:
26
+ # This is a temporary fix until our changes will be merged to torch_xla.
27
+ from ltx_video.models.transformers.custom_kernel_spmd import flash_attention
28
+ from torch_xla.distributed.spmd import Mesh
29
+ except ImportError:
30
+ # workaround for automatic tests. Currently this function is manually patched
31
+ # to the torch_xla lib on setup of container
32
+ Mesh = None
33
+
34
+
35
+ # code adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ @maybe_allow_in_graph
41
+ class BasicTransformerBlock(nn.Module):
42
+ r"""
43
+ A basic Transformer block.
44
+
45
+ Parameters:
46
+ dim (`int`): The number of channels in the input and output.
47
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
48
+ attention_head_dim (`int`): The number of channels in each head.
49
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
50
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
51
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
52
+ num_embeds_ada_norm (:
53
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
54
+ attention_bias (:
55
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
56
+ only_cross_attention (`bool`, *optional*):
57
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
58
+ double_self_attention (`bool`, *optional*):
59
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
60
+ upcast_attention (`bool`, *optional*):
61
+ Whether to upcast the attention computation to float32. This is useful for mixed precision training.
62
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
63
+ Whether to use learnable elementwise affine parameters for normalization.
64
+ qk_norm (`str`, *optional*, defaults to None):
65
+ Set to 'layer_norm' or `rms_norm` to perform query and key normalization.
66
+ adaptive_norm (`str`, *optional*, defaults to `"single_scale_shift"`):
67
+ The type of adaptive norm to use. Can be `"single_scale_shift"`, `"single_scale"` or "none".
68
+ standardization_norm (`str`, *optional*, defaults to `"layer_norm"`):
69
+ The type of pre-normalization to use. Can be `"layer_norm"` or `"rms_norm"`.
70
+ final_dropout (`bool` *optional*, defaults to False):
71
+ Whether to apply a final dropout after the last feed-forward layer.
72
+ attention_type (`str`, *optional*, defaults to `"default"`):
73
+ The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
74
+ positional_embeddings (`str`, *optional*, defaults to `None`):
75
+ The type of positional embeddings to apply to.
76
+ num_positional_embeddings (`int`, *optional*, defaults to `None`):
77
+ The maximum number of positional embeddings to apply.
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ dim: int,
83
+ num_attention_heads: int,
84
+ attention_head_dim: int,
85
+ dropout=0.0,
86
+ cross_attention_dim: Optional[int] = None,
87
+ activation_fn: str = "geglu",
88
+ num_embeds_ada_norm: Optional[int] = None, # pylint: disable=unused-argument
89
+ attention_bias: bool = False,
90
+ only_cross_attention: bool = False,
91
+ double_self_attention: bool = False,
92
+ upcast_attention: bool = False,
93
+ norm_elementwise_affine: bool = True,
94
+ adaptive_norm: str = "single_scale_shift", # 'single_scale_shift', 'single_scale' or 'none'
95
+ standardization_norm: str = "layer_norm", # 'layer_norm' or 'rms_norm'
96
+ norm_eps: float = 1e-5,
97
+ qk_norm: Optional[str] = None,
98
+ final_dropout: bool = False,
99
+ attention_type: str = "default", # pylint: disable=unused-argument
100
+ ff_inner_dim: Optional[int] = None,
101
+ ff_bias: bool = True,
102
+ attention_out_bias: bool = True,
103
+ use_tpu_flash_attention: bool = False,
104
+ use_rope: bool = False,
105
+ ):
106
+ super().__init__()
107
+ self.only_cross_attention = only_cross_attention
108
+ self.use_tpu_flash_attention = use_tpu_flash_attention
109
+ self.adaptive_norm = adaptive_norm
110
+
111
+ assert standardization_norm in ["layer_norm", "rms_norm"]
112
+ assert adaptive_norm in ["single_scale_shift", "single_scale", "none"]
113
+
114
+ make_norm_layer = (
115
+ nn.LayerNorm if standardization_norm == "layer_norm" else RMSNorm
116
+ )
117
+
118
+ # Define 3 blocks. Each block has its own normalization layer.
119
+ # 1. Self-Attn
120
+ self.norm1 = make_norm_layer(
121
+ dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps
122
+ )
123
+
124
+ self.attn1 = Attention(
125
+ query_dim=dim,
126
+ heads=num_attention_heads,
127
+ dim_head=attention_head_dim,
128
+ dropout=dropout,
129
+ bias=attention_bias,
130
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
131
+ upcast_attention=upcast_attention,
132
+ out_bias=attention_out_bias,
133
+ use_tpu_flash_attention=use_tpu_flash_attention,
134
+ qk_norm=qk_norm,
135
+ use_rope=use_rope,
136
+ )
137
+
138
+ # 2. Cross-Attn
139
+ if cross_attention_dim is not None or double_self_attention:
140
+ self.attn2 = Attention(
141
+ query_dim=dim,
142
+ cross_attention_dim=(
143
+ cross_attention_dim if not double_self_attention else None
144
+ ),
145
+ heads=num_attention_heads,
146
+ dim_head=attention_head_dim,
147
+ dropout=dropout,
148
+ bias=attention_bias,
149
+ upcast_attention=upcast_attention,
150
+ out_bias=attention_out_bias,
151
+ use_tpu_flash_attention=use_tpu_flash_attention,
152
+ qk_norm=qk_norm,
153
+ use_rope=use_rope,
154
+ ) # is self-attn if encoder_hidden_states is none
155
+
156
+ if adaptive_norm == "none":
157
+ self.attn2_norm = make_norm_layer(
158
+ dim, norm_eps, norm_elementwise_affine
159
+ )
160
+ else:
161
+ self.attn2 = None
162
+ self.attn2_norm = None
163
+
164
+ self.norm2 = make_norm_layer(dim, norm_eps, norm_elementwise_affine)
165
+
166
+ # 3. Feed-forward
167
+ self.ff = FeedForward(
168
+ dim,
169
+ dropout=dropout,
170
+ activation_fn=activation_fn,
171
+ final_dropout=final_dropout,
172
+ inner_dim=ff_inner_dim,
173
+ bias=ff_bias,
174
+ )
175
+
176
+ # 5. Scale-shift for PixArt-Alpha.
177
+ if adaptive_norm != "none":
178
+ num_ada_params = 4 if adaptive_norm == "single_scale" else 6
179
+ self.scale_shift_table = nn.Parameter(
180
+ torch.randn(num_ada_params, dim) / dim**0.5
181
+ )
182
+
183
+ # let chunk size default to None
184
+ self._chunk_size = None
185
+ self._chunk_dim = 0
186
+
187
+ def set_use_tpu_flash_attention(self):
188
+ r"""
189
+ Function sets the flag in this object and propagates down the children. The flag will enforce the usage of TPU
190
+ attention kernel.
191
+ """
192
+ self.use_tpu_flash_attention = True
193
+ self.attn1.set_use_tpu_flash_attention()
194
+ self.attn2.set_use_tpu_flash_attention()
195
+
196
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
197
+ # Sets chunk feed-forward
198
+ self._chunk_size = chunk_size
199
+ self._chunk_dim = dim
200
+
201
+ def forward(
202
+ self,
203
+ hidden_states: torch.FloatTensor,
204
+ freqs_cis: Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] = None,
205
+ attention_mask: Optional[torch.FloatTensor] = None,
206
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
207
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
208
+ timestep: Optional[torch.LongTensor] = None,
209
+ cross_attention_kwargs: Dict[str, Any] = None,
210
+ class_labels: Optional[torch.LongTensor] = None,
211
+ sharding_mesh: Optional[Mesh] = None,
212
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
213
+ skip_layer_mask: Optional[torch.Tensor] = None,
214
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
215
+ ) -> torch.FloatTensor:
216
+ if cross_attention_kwargs is not None:
217
+ if cross_attention_kwargs.get("scale", None) is not None:
218
+ logger.warning(
219
+ "Passing `scale` to `cross_attention_kwargs` is depcrecated. `scale` will be ignored."
220
+ )
221
+
222
+ # Notice that normalization is always applied before the real computation in the following blocks.
223
+ # 0. Self-Attention
224
+ batch_size = hidden_states.shape[0]
225
+
226
+ norm_hidden_states = self.norm1(hidden_states)
227
+
228
+ # Apply ada_norm_single
229
+ if self.adaptive_norm in ["single_scale_shift", "single_scale"]:
230
+ assert timestep.ndim == 3 # [batch, 1 or num_tokens, embedding_dim]
231
+ num_ada_params = self.scale_shift_table.shape[0]
232
+ ada_values = self.scale_shift_table[None, None] + timestep.reshape(
233
+ batch_size, timestep.shape[1], num_ada_params, -1
234
+ )
235
+ if self.adaptive_norm == "single_scale_shift":
236
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
237
+ ada_values.unbind(dim=2)
238
+ )
239
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
240
+ else:
241
+ scale_msa, gate_msa, scale_mlp, gate_mlp = ada_values.unbind(dim=2)
242
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa)
243
+ elif self.adaptive_norm == "none":
244
+ scale_msa, gate_msa, scale_mlp, gate_mlp = None, None, None, None
245
+ else:
246
+ raise ValueError(f"Unknown adaptive norm type: {self.adaptive_norm}")
247
+
248
+ norm_hidden_states = norm_hidden_states.squeeze(
249
+ 1
250
+ ) # TODO: Check if this is needed
251
+
252
+ # 1. Prepare GLIGEN inputs
253
+ cross_attention_kwargs = (
254
+ cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
255
+ )
256
+
257
+ attn_output = self.attn1(
258
+ norm_hidden_states,
259
+ freqs_cis=freqs_cis,
260
+ encoder_hidden_states=(
261
+ encoder_hidden_states if self.only_cross_attention else None
262
+ ),
263
+ attention_mask=attention_mask,
264
+ sharding_mesh=sharding_mesh,
265
+ skip_layer_mask=skip_layer_mask,
266
+ skip_layer_strategy=skip_layer_strategy,
267
+ **cross_attention_kwargs,
268
+ )
269
+ if gate_msa is not None:
270
+ attn_output = gate_msa * attn_output
271
+
272
+ hidden_states = attn_output + hidden_states
273
+ if hidden_states.ndim == 4:
274
+ hidden_states = hidden_states.squeeze(1)
275
+
276
+ # 3. Cross-Attention
277
+ if self.attn2 is not None:
278
+ if self.adaptive_norm == "none":
279
+ attn_input = self.attn2_norm(hidden_states)
280
+ else:
281
+ attn_input = hidden_states
282
+ attn_output = self.attn2(
283
+ attn_input,
284
+ freqs_cis=freqs_cis,
285
+ encoder_hidden_states=encoder_hidden_states,
286
+ attention_mask=encoder_attention_mask,
287
+ sharding_mesh=sharding_mesh,
288
+ **cross_attention_kwargs,
289
+ )
290
+ hidden_states = attn_output + hidden_states
291
+
292
+ # 4. Feed-forward
293
+ norm_hidden_states = self.norm2(hidden_states)
294
+ if self.adaptive_norm == "single_scale_shift":
295
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
296
+ elif self.adaptive_norm == "single_scale":
297
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp)
298
+ elif self.adaptive_norm == "none":
299
+ pass
300
+ else:
301
+ raise ValueError(f"Unknown adaptive norm type: {self.adaptive_norm}")
302
+
303
+ if self._chunk_size is not None:
304
+ # "feed_forward_chunk_size" can be used to save memory
305
+ ff_output = _chunked_feed_forward(
306
+ self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size
307
+ )
308
+ else:
309
+ ff_output = self.ff(norm_hidden_states)
310
+ if gate_mlp is not None:
311
+ ff_output = gate_mlp * ff_output
312
+
313
+ hidden_states = ff_output + hidden_states
314
+ if hidden_states.ndim == 4:
315
+ hidden_states = hidden_states.squeeze(1)
316
+
317
+ return hidden_states
318
+
319
+
320
+ @maybe_allow_in_graph
321
+ class Attention(nn.Module):
322
+ r"""
323
+ A cross attention layer.
324
+
325
+ Parameters:
326
+ query_dim (`int`):
327
+ The number of channels in the query.
328
+ cross_attention_dim (`int`, *optional*):
329
+ The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`.
330
+ heads (`int`, *optional*, defaults to 8):
331
+ The number of heads to use for multi-head attention.
332
+ dim_head (`int`, *optional*, defaults to 64):
333
+ The number of channels in each head.
334
+ dropout (`float`, *optional*, defaults to 0.0):
335
+ The dropout probability to use.
336
+ bias (`bool`, *optional*, defaults to False):
337
+ Set to `True` for the query, key, and value linear layers to contain a bias parameter.
338
+ upcast_attention (`bool`, *optional*, defaults to False):
339
+ Set to `True` to upcast the attention computation to `float32`.
340
+ upcast_softmax (`bool`, *optional*, defaults to False):
341
+ Set to `True` to upcast the softmax computation to `float32`.
342
+ cross_attention_norm (`str`, *optional*, defaults to `None`):
343
+ The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`.
344
+ cross_attention_norm_num_groups (`int`, *optional*, defaults to 32):
345
+ The number of groups to use for the group norm in the cross attention.
346
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
347
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
348
+ norm_num_groups (`int`, *optional*, defaults to `None`):
349
+ The number of groups to use for the group norm in the attention.
350
+ spatial_norm_dim (`int`, *optional*, defaults to `None`):
351
+ The number of channels to use for the spatial normalization.
352
+ out_bias (`bool`, *optional*, defaults to `True`):
353
+ Set to `True` to use a bias in the output linear layer.
354
+ scale_qk (`bool`, *optional*, defaults to `True`):
355
+ Set to `True` to scale the query and key by `1 / sqrt(dim_head)`.
356
+ qk_norm (`str`, *optional*, defaults to None):
357
+ Set to 'layer_norm' or `rms_norm` to perform query and key normalization.
358
+ only_cross_attention (`bool`, *optional*, defaults to `False`):
359
+ Set to `True` to only use cross attention and not added_kv_proj_dim. Can only be set to `True` if
360
+ `added_kv_proj_dim` is not `None`.
361
+ eps (`float`, *optional*, defaults to 1e-5):
362
+ An additional value added to the denominator in group normalization that is used for numerical stability.
363
+ rescale_output_factor (`float`, *optional*, defaults to 1.0):
364
+ A factor to rescale the output by dividing it with this value.
365
+ residual_connection (`bool`, *optional*, defaults to `False`):
366
+ Set to `True` to add the residual connection to the output.
367
+ _from_deprecated_attn_block (`bool`, *optional*, defaults to `False`):
368
+ Set to `True` if the attention block is loaded from a deprecated state dict.
369
+ processor (`AttnProcessor`, *optional*, defaults to `None`):
370
+ The attention processor to use. If `None`, defaults to `AttnProcessor2_0` if `torch 2.x` is used and
371
+ `AttnProcessor` otherwise.
372
+ """
373
+
374
+ def __init__(
375
+ self,
376
+ query_dim: int,
377
+ cross_attention_dim: Optional[int] = None,
378
+ heads: int = 8,
379
+ dim_head: int = 64,
380
+ dropout: float = 0.0,
381
+ bias: bool = False,
382
+ upcast_attention: bool = False,
383
+ upcast_softmax: bool = False,
384
+ cross_attention_norm: Optional[str] = None,
385
+ cross_attention_norm_num_groups: int = 32,
386
+ added_kv_proj_dim: Optional[int] = None,
387
+ norm_num_groups: Optional[int] = None,
388
+ spatial_norm_dim: Optional[int] = None,
389
+ out_bias: bool = True,
390
+ scale_qk: bool = True,
391
+ qk_norm: Optional[str] = None,
392
+ only_cross_attention: bool = False,
393
+ eps: float = 1e-5,
394
+ rescale_output_factor: float = 1.0,
395
+ residual_connection: bool = False,
396
+ _from_deprecated_attn_block: bool = False,
397
+ processor: Optional["AttnProcessor"] = None,
398
+ out_dim: int = None,
399
+ use_tpu_flash_attention: bool = False,
400
+ use_rope: bool = False,
401
+ ):
402
+ super().__init__()
403
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
404
+ self.query_dim = query_dim
405
+ self.use_bias = bias
406
+ self.is_cross_attention = cross_attention_dim is not None
407
+ self.cross_attention_dim = (
408
+ cross_attention_dim if cross_attention_dim is not None else query_dim
409
+ )
410
+ self.upcast_attention = upcast_attention
411
+ self.upcast_softmax = upcast_softmax
412
+ self.rescale_output_factor = rescale_output_factor
413
+ self.residual_connection = residual_connection
414
+ self.dropout = dropout
415
+ self.fused_projections = False
416
+ self.out_dim = out_dim if out_dim is not None else query_dim
417
+ self.use_tpu_flash_attention = use_tpu_flash_attention
418
+ self.use_rope = use_rope
419
+
420
+ # we make use of this private variable to know whether this class is loaded
421
+ # with an deprecated state dict so that we can convert it on the fly
422
+ self._from_deprecated_attn_block = _from_deprecated_attn_block
423
+
424
+ self.scale_qk = scale_qk
425
+ self.scale = dim_head**-0.5 if self.scale_qk else 1.0
426
+
427
+ if qk_norm is None:
428
+ self.q_norm = nn.Identity()
429
+ self.k_norm = nn.Identity()
430
+ elif qk_norm == "rms_norm":
431
+ self.q_norm = RMSNorm(dim_head * heads, eps=1e-5)
432
+ self.k_norm = RMSNorm(dim_head * heads, eps=1e-5)
433
+ elif qk_norm == "layer_norm":
434
+ self.q_norm = nn.LayerNorm(dim_head * heads, eps=1e-5)
435
+ self.k_norm = nn.LayerNorm(dim_head * heads, eps=1e-5)
436
+ else:
437
+ raise ValueError(f"Unsupported qk_norm method: {qk_norm}")
438
+
439
+ self.heads = out_dim // dim_head if out_dim is not None else heads
440
+ # for slice_size > 0 the attention score computation
441
+ # is split across the batch axis to save memory
442
+ # You can set slice_size with `set_attention_slice`
443
+ self.sliceable_head_dim = heads
444
+
445
+ self.added_kv_proj_dim = added_kv_proj_dim
446
+ self.only_cross_attention = only_cross_attention
447
+
448
+ if self.added_kv_proj_dim is None and self.only_cross_attention:
449
+ raise ValueError(
450
+ "`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
451
+ )
452
+
453
+ if norm_num_groups is not None:
454
+ self.group_norm = nn.GroupNorm(
455
+ num_channels=query_dim, num_groups=norm_num_groups, eps=eps, affine=True
456
+ )
457
+ else:
458
+ self.group_norm = None
459
+
460
+ if spatial_norm_dim is not None:
461
+ self.spatial_norm = SpatialNorm(
462
+ f_channels=query_dim, zq_channels=spatial_norm_dim
463
+ )
464
+ else:
465
+ self.spatial_norm = None
466
+
467
+ if cross_attention_norm is None:
468
+ self.norm_cross = None
469
+ elif cross_attention_norm == "layer_norm":
470
+ self.norm_cross = nn.LayerNorm(self.cross_attention_dim)
471
+ elif cross_attention_norm == "group_norm":
472
+ if self.added_kv_proj_dim is not None:
473
+ # The given `encoder_hidden_states` are initially of shape
474
+ # (batch_size, seq_len, added_kv_proj_dim) before being projected
475
+ # to (batch_size, seq_len, cross_attention_dim). The norm is applied
476
+ # before the projection, so we need to use `added_kv_proj_dim` as
477
+ # the number of channels for the group norm.
478
+ norm_cross_num_channels = added_kv_proj_dim
479
+ else:
480
+ norm_cross_num_channels = self.cross_attention_dim
481
+
482
+ self.norm_cross = nn.GroupNorm(
483
+ num_channels=norm_cross_num_channels,
484
+ num_groups=cross_attention_norm_num_groups,
485
+ eps=1e-5,
486
+ affine=True,
487
+ )
488
+ else:
489
+ raise ValueError(
490
+ f"unknown cross_attention_norm: {cross_attention_norm}. Should be None, 'layer_norm' or 'group_norm'"
491
+ )
492
+
493
+ linear_cls = nn.Linear
494
+
495
+ self.linear_cls = linear_cls
496
+ self.to_q = linear_cls(query_dim, self.inner_dim, bias=bias)
497
+
498
+ if not self.only_cross_attention:
499
+ # only relevant for the `AddedKVProcessor` classes
500
+ self.to_k = linear_cls(self.cross_attention_dim, self.inner_dim, bias=bias)
501
+ self.to_v = linear_cls(self.cross_attention_dim, self.inner_dim, bias=bias)
502
+ else:
503
+ self.to_k = None
504
+ self.to_v = None
505
+
506
+ if self.added_kv_proj_dim is not None:
507
+ self.add_k_proj = linear_cls(added_kv_proj_dim, self.inner_dim)
508
+ self.add_v_proj = linear_cls(added_kv_proj_dim, self.inner_dim)
509
+
510
+ self.to_out = nn.ModuleList([])
511
+ self.to_out.append(linear_cls(self.inner_dim, self.out_dim, bias=out_bias))
512
+ self.to_out.append(nn.Dropout(dropout))
513
+
514
+ # set attention processor
515
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
516
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
517
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
518
+ if processor is None:
519
+ processor = AttnProcessor2_0()
520
+ self.set_processor(processor)
521
+
522
+ def set_use_tpu_flash_attention(self):
523
+ r"""
524
+ Function sets the flag in this object. The flag will enforce the usage of TPU attention kernel.
525
+ """
526
+ self.use_tpu_flash_attention = True
527
+
528
+ def set_processor(self, processor: "AttnProcessor") -> None:
529
+ r"""
530
+ Set the attention processor to use.
531
+
532
+ Args:
533
+ processor (`AttnProcessor`):
534
+ The attention processor to use.
535
+ """
536
+ # if current processor is in `self._modules` and if passed `processor` is not, we need to
537
+ # pop `processor` from `self._modules`
538
+ if (
539
+ hasattr(self, "processor")
540
+ and isinstance(self.processor, torch.nn.Module)
541
+ and not isinstance(processor, torch.nn.Module)
542
+ ):
543
+ logger.info(
544
+ f"You are removing possibly trained weights of {self.processor} with {processor}"
545
+ )
546
+ self._modules.pop("processor")
547
+
548
+ self.processor = processor
549
+
550
+ def get_processor(
551
+ self, return_deprecated_lora: bool = False
552
+ ) -> "AttentionProcessor": # noqa: F821
553
+ r"""
554
+ Get the attention processor in use.
555
+
556
+ Args:
557
+ return_deprecated_lora (`bool`, *optional*, defaults to `False`):
558
+ Set to `True` to return the deprecated LoRA attention processor.
559
+
560
+ Returns:
561
+ "AttentionProcessor": The attention processor in use.
562
+ """
563
+ if not return_deprecated_lora:
564
+ return self.processor
565
+
566
+ # TODO(Sayak, Patrick). The rest of the function is needed to ensure backwards compatible
567
+ # serialization format for LoRA Attention Processors. It should be deleted once the integration
568
+ # with PEFT is completed.
569
+ is_lora_activated = {
570
+ name: module.lora_layer is not None
571
+ for name, module in self.named_modules()
572
+ if hasattr(module, "lora_layer")
573
+ }
574
+
575
+ # 1. if no layer has a LoRA activated we can return the processor as usual
576
+ if not any(is_lora_activated.values()):
577
+ return self.processor
578
+
579
+ # If doesn't apply LoRA do `add_k_proj` or `add_v_proj`
580
+ is_lora_activated.pop("add_k_proj", None)
581
+ is_lora_activated.pop("add_v_proj", None)
582
+ # 2. else it is not posssible that only some layers have LoRA activated
583
+ if not all(is_lora_activated.values()):
584
+ raise ValueError(
585
+ f"Make sure that either all layers or no layers have LoRA activated, but have {is_lora_activated}"
586
+ )
587
+
588
+ # 3. And we need to merge the current LoRA layers into the corresponding LoRA attention processor
589
+ non_lora_processor_cls_name = self.processor.__class__.__name__
590
+ lora_processor_cls = getattr(
591
+ import_module(__name__), "LoRA" + non_lora_processor_cls_name
592
+ )
593
+
594
+ hidden_size = self.inner_dim
595
+
596
+ # now create a LoRA attention processor from the LoRA layers
597
+ if lora_processor_cls in [
598
+ LoRAAttnProcessor,
599
+ LoRAAttnProcessor2_0,
600
+ LoRAXFormersAttnProcessor,
601
+ ]:
602
+ kwargs = {
603
+ "cross_attention_dim": self.cross_attention_dim,
604
+ "rank": self.to_q.lora_layer.rank,
605
+ "network_alpha": self.to_q.lora_layer.network_alpha,
606
+ "q_rank": self.to_q.lora_layer.rank,
607
+ "q_hidden_size": self.to_q.lora_layer.out_features,
608
+ "k_rank": self.to_k.lora_layer.rank,
609
+ "k_hidden_size": self.to_k.lora_layer.out_features,
610
+ "v_rank": self.to_v.lora_layer.rank,
611
+ "v_hidden_size": self.to_v.lora_layer.out_features,
612
+ "out_rank": self.to_out[0].lora_layer.rank,
613
+ "out_hidden_size": self.to_out[0].lora_layer.out_features,
614
+ }
615
+
616
+ if hasattr(self.processor, "attention_op"):
617
+ kwargs["attention_op"] = self.processor.attention_op
618
+
619
+ lora_processor = lora_processor_cls(hidden_size, **kwargs)
620
+ lora_processor.to_q_lora.load_state_dict(self.to_q.lora_layer.state_dict())
621
+ lora_processor.to_k_lora.load_state_dict(self.to_k.lora_layer.state_dict())
622
+ lora_processor.to_v_lora.load_state_dict(self.to_v.lora_layer.state_dict())
623
+ lora_processor.to_out_lora.load_state_dict(
624
+ self.to_out[0].lora_layer.state_dict()
625
+ )
626
+ elif lora_processor_cls == LoRAAttnAddedKVProcessor:
627
+ lora_processor = lora_processor_cls(
628
+ hidden_size,
629
+ cross_attention_dim=self.add_k_proj.weight.shape[0],
630
+ rank=self.to_q.lora_layer.rank,
631
+ network_alpha=self.to_q.lora_layer.network_alpha,
632
+ )
633
+ lora_processor.to_q_lora.load_state_dict(self.to_q.lora_layer.state_dict())
634
+ lora_processor.to_k_lora.load_state_dict(self.to_k.lora_layer.state_dict())
635
+ lora_processor.to_v_lora.load_state_dict(self.to_v.lora_layer.state_dict())
636
+ lora_processor.to_out_lora.load_state_dict(
637
+ self.to_out[0].lora_layer.state_dict()
638
+ )
639
+
640
+ # only save if used
641
+ if self.add_k_proj.lora_layer is not None:
642
+ lora_processor.add_k_proj_lora.load_state_dict(
643
+ self.add_k_proj.lora_layer.state_dict()
644
+ )
645
+ lora_processor.add_v_proj_lora.load_state_dict(
646
+ self.add_v_proj.lora_layer.state_dict()
647
+ )
648
+ else:
649
+ lora_processor.add_k_proj_lora = None
650
+ lora_processor.add_v_proj_lora = None
651
+ else:
652
+ raise ValueError(f"{lora_processor_cls} does not exist.")
653
+
654
+ return lora_processor
655
+
656
+ def forward(
657
+ self,
658
+ hidden_states: torch.FloatTensor,
659
+ freqs_cis: Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] = None,
660
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
661
+ attention_mask: Optional[torch.FloatTensor] = None,
662
+ sharding_mesh: Optional[Mesh] = None,
663
+ skip_layer_mask: Optional[torch.Tensor] = None,
664
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
665
+ **cross_attention_kwargs,
666
+ ) -> torch.Tensor:
667
+ r"""
668
+ The forward method of the `Attention` class.
669
+
670
+ Args:
671
+ hidden_states (`torch.Tensor`):
672
+ The hidden states of the query.
673
+ encoder_hidden_states (`torch.Tensor`, *optional*):
674
+ The hidden states of the encoder.
675
+ attention_mask (`torch.Tensor`, *optional*):
676
+ The attention mask to use. If `None`, no mask is applied.
677
+ skip_layer_mask (`torch.Tensor`, *optional*):
678
+ The skip layer mask to use. If `None`, no mask is applied.
679
+ skip_layer_strategy (`SkipLayerStrategy`, *optional*, defaults to `None`):
680
+ Controls which layers to skip for spatiotemporal guidance.
681
+ **cross_attention_kwargs:
682
+ Additional keyword arguments to pass along to the cross attention.
683
+
684
+ Returns:
685
+ `torch.Tensor`: The output of the attention layer.
686
+ """
687
+ # The `Attention` class can call different attention processors / attention functions
688
+ # here we simply pass along all tensors to the selected processor class
689
+ # For standard processors that are defined here, `**cross_attention_kwargs` is empty
690
+
691
+ attn_parameters = set(
692
+ inspect.signature(self.processor.__call__).parameters.keys()
693
+ )
694
+ unused_kwargs = [
695
+ k for k, _ in cross_attention_kwargs.items() if k not in attn_parameters
696
+ ]
697
+ if len(unused_kwargs) > 0:
698
+ logger.warning(
699
+ f"cross_attention_kwargs {unused_kwargs} are not expected by"
700
+ f" {self.processor.__class__.__name__} and will be ignored."
701
+ )
702
+ cross_attention_kwargs = {
703
+ k: w for k, w in cross_attention_kwargs.items() if k in attn_parameters
704
+ }
705
+
706
+ return self.processor(
707
+ self,
708
+ hidden_states,
709
+ freqs_cis=freqs_cis,
710
+ encoder_hidden_states=encoder_hidden_states,
711
+ attention_mask=attention_mask,
712
+ sharding_mesh=sharding_mesh,
713
+ skip_layer_mask=skip_layer_mask,
714
+ skip_layer_strategy=skip_layer_strategy,
715
+ **cross_attention_kwargs,
716
+ )
717
+
718
+ def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor:
719
+ r"""
720
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
721
+ is the number of heads initialized while constructing the `Attention` class.
722
+
723
+ Args:
724
+ tensor (`torch.Tensor`): The tensor to reshape.
725
+
726
+ Returns:
727
+ `torch.Tensor`: The reshaped tensor.
728
+ """
729
+ head_size = self.heads
730
+ batch_size, seq_len, dim = tensor.shape
731
+ tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
732
+ tensor = tensor.permute(0, 2, 1, 3).reshape(
733
+ batch_size // head_size, seq_len, dim * head_size
734
+ )
735
+ return tensor
736
+
737
+ def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor:
738
+ r"""
739
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
740
+ the number of heads initialized while constructing the `Attention` class.
741
+
742
+ Args:
743
+ tensor (`torch.Tensor`): The tensor to reshape.
744
+ out_dim (`int`, *optional*, defaults to `3`): The output dimension of the tensor. If `3`, the tensor is
745
+ reshaped to `[batch_size * heads, seq_len, dim // heads]`.
746
+
747
+ Returns:
748
+ `torch.Tensor`: The reshaped tensor.
749
+ """
750
+
751
+ head_size = self.heads
752
+ if tensor.ndim == 3:
753
+ batch_size, seq_len, dim = tensor.shape
754
+ extra_dim = 1
755
+ else:
756
+ batch_size, extra_dim, seq_len, dim = tensor.shape
757
+ tensor = tensor.reshape(
758
+ batch_size, seq_len * extra_dim, head_size, dim // head_size
759
+ )
760
+ tensor = tensor.permute(0, 2, 1, 3)
761
+
762
+ if out_dim == 3:
763
+ tensor = tensor.reshape(
764
+ batch_size * head_size, seq_len * extra_dim, dim // head_size
765
+ )
766
+
767
+ return tensor
768
+
769
+ def get_attention_scores(
770
+ self,
771
+ query: torch.Tensor,
772
+ key: torch.Tensor,
773
+ attention_mask: torch.Tensor = None,
774
+ ) -> torch.Tensor:
775
+ r"""
776
+ Compute the attention scores.
777
+
778
+ Args:
779
+ query (`torch.Tensor`): The query tensor.
780
+ key (`torch.Tensor`): The key tensor.
781
+ attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
782
+
783
+ Returns:
784
+ `torch.Tensor`: The attention probabilities/scores.
785
+ """
786
+ dtype = query.dtype
787
+ if self.upcast_attention:
788
+ query = query.float()
789
+ key = key.float()
790
+
791
+ if attention_mask is None:
792
+ baddbmm_input = torch.empty(
793
+ query.shape[0],
794
+ query.shape[1],
795
+ key.shape[1],
796
+ dtype=query.dtype,
797
+ device=query.device,
798
+ )
799
+ beta = 0
800
+ else:
801
+ baddbmm_input = attention_mask
802
+ beta = 1
803
+
804
+ attention_scores = torch.baddbmm(
805
+ baddbmm_input,
806
+ query,
807
+ key.transpose(-1, -2),
808
+ beta=beta,
809
+ alpha=self.scale,
810
+ )
811
+ del baddbmm_input
812
+
813
+ if self.upcast_softmax:
814
+ attention_scores = attention_scores.float()
815
+
816
+ attention_probs = attention_scores.softmax(dim=-1)
817
+ del attention_scores
818
+
819
+ attention_probs = attention_probs.to(dtype)
820
+
821
+ return attention_probs
822
+
823
+ def prepare_attention_mask(
824
+ self,
825
+ attention_mask: torch.Tensor,
826
+ target_length: int,
827
+ batch_size: int,
828
+ out_dim: int = 3,
829
+ ) -> torch.Tensor:
830
+ r"""
831
+ Prepare the attention mask for the attention computation.
832
+
833
+ Args:
834
+ attention_mask (`torch.Tensor`):
835
+ The attention mask to prepare.
836
+ target_length (`int`):
837
+ The target length of the attention mask. This is the length of the attention mask after padding.
838
+ batch_size (`int`):
839
+ The batch size, which is used to repeat the attention mask.
840
+ out_dim (`int`, *optional*, defaults to `3`):
841
+ The output dimension of the attention mask. Can be either `3` or `4`.
842
+
843
+ Returns:
844
+ `torch.Tensor`: The prepared attention mask.
845
+ """
846
+ head_size = self.heads
847
+ if attention_mask is None:
848
+ return attention_mask
849
+
850
+ current_length: int = attention_mask.shape[-1]
851
+ if current_length != target_length:
852
+ if attention_mask.device.type == "mps":
853
+ # HACK: MPS: Does not support padding by greater than dimension of input tensor.
854
+ # Instead, we can manually construct the padding tensor.
855
+ padding_shape = (
856
+ attention_mask.shape[0],
857
+ attention_mask.shape[1],
858
+ target_length,
859
+ )
860
+ padding = torch.zeros(
861
+ padding_shape,
862
+ dtype=attention_mask.dtype,
863
+ device=attention_mask.device,
864
+ )
865
+ attention_mask = torch.cat([attention_mask, padding], dim=2)
866
+ else:
867
+ # TODO: for pipelines such as stable-diffusion, padding cross-attn mask:
868
+ # we want to instead pad by (0, remaining_length), where remaining_length is:
869
+ # remaining_length: int = target_length - current_length
870
+ # TODO: re-enable tests/models/test_models_unet_2d_condition.py#test_model_xattn_padding
871
+ attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
872
+
873
+ if out_dim == 3:
874
+ if attention_mask.shape[0] < batch_size * head_size:
875
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=0)
876
+ elif out_dim == 4:
877
+ attention_mask = attention_mask.unsqueeze(1)
878
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=1)
879
+
880
+ return attention_mask
881
+
882
+ def norm_encoder_hidden_states(
883
+ self, encoder_hidden_states: torch.Tensor
884
+ ) -> torch.Tensor:
885
+ r"""
886
+ Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
887
+ `Attention` class.
888
+
889
+ Args:
890
+ encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder.
891
+
892
+ Returns:
893
+ `torch.Tensor`: The normalized encoder hidden states.
894
+ """
895
+ assert (
896
+ self.norm_cross is not None
897
+ ), "self.norm_cross must be defined to call self.norm_encoder_hidden_states"
898
+
899
+ if isinstance(self.norm_cross, nn.LayerNorm):
900
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
901
+ elif isinstance(self.norm_cross, nn.GroupNorm):
902
+ # Group norm norms along the channels dimension and expects
903
+ # input to be in the shape of (N, C, *). In this case, we want
904
+ # to norm along the hidden dimension, so we need to move
905
+ # (batch_size, sequence_length, hidden_size) ->
906
+ # (batch_size, hidden_size, sequence_length)
907
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
908
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
909
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
910
+ else:
911
+ assert False
912
+
913
+ return encoder_hidden_states
914
+
915
+ @staticmethod
916
+ def apply_rotary_emb(
917
+ input_tensor: torch.Tensor,
918
+ freqs_cis: Tuple[torch.FloatTensor, torch.FloatTensor],
919
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
920
+ cos_freqs = freqs_cis[0]
921
+ sin_freqs = freqs_cis[1]
922
+
923
+ t_dup = rearrange(input_tensor, "... (d r) -> ... d r", r=2)
924
+ t1, t2 = t_dup.unbind(dim=-1)
925
+ t_dup = torch.stack((-t2, t1), dim=-1)
926
+ input_tensor_rot = rearrange(t_dup, "... d r -> ... (d r)")
927
+
928
+ out = input_tensor * cos_freqs + input_tensor_rot * sin_freqs
929
+
930
+ return out
931
+
932
+
933
+ class AttnProcessor2_0:
934
+ r"""
935
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
936
+ """
937
+
938
+ def __init__(self):
939
+ pass
940
+
941
+ def __call__(
942
+ self,
943
+ attn: Attention,
944
+ hidden_states: torch.FloatTensor,
945
+ freqs_cis: Tuple[torch.FloatTensor, torch.FloatTensor],
946
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
947
+ attention_mask: Optional[torch.FloatTensor] = None,
948
+ sharding_mesh: Optional[Mesh] = None,
949
+ temb: Optional[torch.FloatTensor] = None,
950
+ skip_layer_mask: Optional[torch.FloatTensor] = None,
951
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
952
+ *args,
953
+ **kwargs,
954
+ ) -> torch.FloatTensor:
955
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
956
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
957
+ deprecate("scale", "1.0.0", deprecation_message)
958
+
959
+ residual = hidden_states
960
+ if attn.spatial_norm is not None:
961
+ hidden_states = attn.spatial_norm(hidden_states, temb)
962
+
963
+ input_ndim = hidden_states.ndim
964
+
965
+ if input_ndim == 4:
966
+ batch_size, channel, height, width = hidden_states.shape
967
+ hidden_states = hidden_states.view(
968
+ batch_size, channel, height * width
969
+ ).transpose(1, 2)
970
+
971
+ batch_size, sequence_length, _ = (
972
+ hidden_states.shape
973
+ if encoder_hidden_states is None
974
+ else encoder_hidden_states.shape
975
+ )
976
+
977
+ if skip_layer_mask is not None:
978
+ skip_layer_mask = skip_layer_mask.reshape(batch_size, 1, 1)
979
+
980
+ if (attention_mask is not None) and (not attn.use_tpu_flash_attention):
981
+ attention_mask = attn.prepare_attention_mask(
982
+ attention_mask, sequence_length, batch_size
983
+ )
984
+ # scaled_dot_product_attention expects attention_mask shape to be
985
+ # (batch, heads, source_length, target_length)
986
+ attention_mask = attention_mask.view(
987
+ batch_size, attn.heads, -1, attention_mask.shape[-1]
988
+ )
989
+
990
+ if attn.group_norm is not None:
991
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
992
+ 1, 2
993
+ )
994
+
995
+ query = attn.to_q(hidden_states)
996
+ query = attn.q_norm(query)
997
+
998
+ if encoder_hidden_states is not None:
999
+ if attn.norm_cross:
1000
+ encoder_hidden_states = attn.norm_encoder_hidden_states(
1001
+ encoder_hidden_states
1002
+ )
1003
+ key = attn.to_k(encoder_hidden_states)
1004
+ key = attn.k_norm(key)
1005
+ else: # if no context provided do self-attention
1006
+ encoder_hidden_states = hidden_states
1007
+ key = attn.to_k(hidden_states)
1008
+ key = attn.k_norm(key)
1009
+ if attn.use_rope:
1010
+ key = attn.apply_rotary_emb(key, freqs_cis)
1011
+ query = attn.apply_rotary_emb(query, freqs_cis)
1012
+
1013
+ value = attn.to_v(encoder_hidden_states)
1014
+
1015
+ inner_dim = key.shape[-1]
1016
+ head_dim = inner_dim // attn.heads
1017
+
1018
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1019
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1020
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1021
+
1022
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
1023
+
1024
+ if attn.use_tpu_flash_attention: # use tpu attention offload 'flash attention'
1025
+ q_segment_indexes = None
1026
+ if (
1027
+ attention_mask is not None
1028
+ ): # if mask is required need to tune both segmenIds fields
1029
+ # attention_mask = torch.squeeze(attention_mask).to(torch.float32)
1030
+ attention_mask = attention_mask.to(torch.float32)
1031
+ q_segment_indexes = torch.ones(
1032
+ batch_size, query.shape[2], device=query.device, dtype=torch.float32
1033
+ )
1034
+ assert (
1035
+ attention_mask.shape[1] == key.shape[2]
1036
+ ), f"ERROR: KEY SHAPE must be same as attention mask [{key.shape[2]}, {attention_mask.shape[1]}]"
1037
+
1038
+ assert (
1039
+ query.shape[2] % 128 == 0
1040
+ ), f"ERROR: QUERY SHAPE must be divisible by 128 (TPU limitation) [{query.shape[2]}]"
1041
+ assert (
1042
+ key.shape[2] % 128 == 0
1043
+ ), f"ERROR: KEY SHAPE must be divisible by 128 (TPU limitation) [{key.shape[2]}]"
1044
+
1045
+ partition_spec = (
1046
+ (("dcn", "data"), None, None, None)
1047
+ if sharding_mesh is not None
1048
+ else None
1049
+ )
1050
+ # run the TPU kernel implemented in jax with pallas
1051
+ hidden_states_a = flash_attention(
1052
+ q=query,
1053
+ k=key,
1054
+ v=value,
1055
+ q_segment_ids=q_segment_indexes,
1056
+ kv_segment_ids=attention_mask,
1057
+ sm_scale=attn.scale,
1058
+ partition_spec=partition_spec,
1059
+ mesh=sharding_mesh,
1060
+ )
1061
+ else:
1062
+ hidden_states_a = F.scaled_dot_product_attention(
1063
+ query,
1064
+ key,
1065
+ value,
1066
+ attn_mask=attention_mask,
1067
+ dropout_p=0.0,
1068
+ is_causal=False,
1069
+ )
1070
+
1071
+ hidden_states_a = hidden_states_a.transpose(1, 2).reshape(
1072
+ batch_size, -1, attn.heads * head_dim
1073
+ )
1074
+ hidden_states_a = hidden_states_a.to(query.dtype)
1075
+
1076
+ if (
1077
+ skip_layer_mask is not None
1078
+ and skip_layer_strategy == SkipLayerStrategy.Attention
1079
+ ):
1080
+ hidden_states = hidden_states_a * skip_layer_mask + hidden_states * (
1081
+ 1.0 - skip_layer_mask
1082
+ )
1083
+ else:
1084
+ hidden_states = hidden_states_a
1085
+
1086
+ # linear proj
1087
+ hidden_states = attn.to_out[0](hidden_states)
1088
+ # dropout
1089
+ hidden_states = attn.to_out[1](hidden_states)
1090
+
1091
+ if input_ndim == 4:
1092
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
1093
+ batch_size, channel, height, width
1094
+ )
1095
+ if (
1096
+ skip_layer_mask is not None
1097
+ and skip_layer_strategy == SkipLayerStrategy.Residual
1098
+ ):
1099
+ skip_layer_mask = skip_layer_mask.reshape(batch_size, 1, 1, 1)
1100
+
1101
+ if attn.residual_connection:
1102
+ if (
1103
+ skip_layer_mask is not None
1104
+ and skip_layer_strategy == SkipLayerStrategy.Residual
1105
+ ):
1106
+ hidden_states = hidden_states + residual * skip_layer_mask
1107
+ else:
1108
+ hidden_states = hidden_states + residual
1109
+
1110
+ hidden_states = hidden_states / attn.rescale_output_factor
1111
+
1112
+ return hidden_states
1113
+
1114
+
1115
+ class AttnProcessor:
1116
+ r"""
1117
+ Default processor for performing attention-related computations.
1118
+ """
1119
+
1120
+ def __call__(
1121
+ self,
1122
+ attn: Attention,
1123
+ hidden_states: torch.FloatTensor,
1124
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1125
+ attention_mask: Optional[torch.FloatTensor] = None,
1126
+ temb: Optional[torch.FloatTensor] = None,
1127
+ *args,
1128
+ **kwargs,
1129
+ ) -> torch.Tensor:
1130
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
1131
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
1132
+ deprecate("scale", "1.0.0", deprecation_message)
1133
+
1134
+ residual = hidden_states
1135
+
1136
+ if attn.spatial_norm is not None:
1137
+ hidden_states = attn.spatial_norm(hidden_states, temb)
1138
+
1139
+ input_ndim = hidden_states.ndim
1140
+
1141
+ if input_ndim == 4:
1142
+ batch_size, channel, height, width = hidden_states.shape
1143
+ hidden_states = hidden_states.view(
1144
+ batch_size, channel, height * width
1145
+ ).transpose(1, 2)
1146
+
1147
+ batch_size, sequence_length, _ = (
1148
+ hidden_states.shape
1149
+ if encoder_hidden_states is None
1150
+ else encoder_hidden_states.shape
1151
+ )
1152
+ attention_mask = attn.prepare_attention_mask(
1153
+ attention_mask, sequence_length, batch_size
1154
+ )
1155
+
1156
+ if attn.group_norm is not None:
1157
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
1158
+ 1, 2
1159
+ )
1160
+
1161
+ query = attn.to_q(hidden_states)
1162
+
1163
+ if encoder_hidden_states is None:
1164
+ encoder_hidden_states = hidden_states
1165
+ elif attn.norm_cross:
1166
+ encoder_hidden_states = attn.norm_encoder_hidden_states(
1167
+ encoder_hidden_states
1168
+ )
1169
+
1170
+ key = attn.to_k(encoder_hidden_states)
1171
+ value = attn.to_v(encoder_hidden_states)
1172
+
1173
+ query = attn.head_to_batch_dim(query)
1174
+ key = attn.head_to_batch_dim(key)
1175
+ value = attn.head_to_batch_dim(value)
1176
+
1177
+ query = attn.q_norm(query)
1178
+ key = attn.k_norm(key)
1179
+
1180
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
1181
+ hidden_states = torch.bmm(attention_probs, value)
1182
+ hidden_states = attn.batch_to_head_dim(hidden_states)
1183
+
1184
+ # linear proj
1185
+ hidden_states = attn.to_out[0](hidden_states)
1186
+ # dropout
1187
+ hidden_states = attn.to_out[1](hidden_states)
1188
+
1189
+ if input_ndim == 4:
1190
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
1191
+ batch_size, channel, height, width
1192
+ )
1193
+
1194
+ if attn.residual_connection:
1195
+ hidden_states = hidden_states + residual
1196
+
1197
+ hidden_states = hidden_states / attn.rescale_output_factor
1198
+
1199
+ return hidden_states
1200
+
1201
+
1202
+ class FeedForward(nn.Module):
1203
+ r"""
1204
+ A feed-forward layer.
1205
+
1206
+ Parameters:
1207
+ dim (`int`): The number of channels in the input.
1208
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
1209
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
1210
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
1211
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
1212
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
1213
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
1214
+ """
1215
+
1216
+ def __init__(
1217
+ self,
1218
+ dim: int,
1219
+ dim_out: Optional[int] = None,
1220
+ mult: int = 4,
1221
+ dropout: float = 0.0,
1222
+ activation_fn: str = "geglu",
1223
+ final_dropout: bool = False,
1224
+ inner_dim=None,
1225
+ bias: bool = True,
1226
+ ):
1227
+ super().__init__()
1228
+ if inner_dim is None:
1229
+ inner_dim = int(dim * mult)
1230
+ dim_out = dim_out if dim_out is not None else dim
1231
+ linear_cls = nn.Linear
1232
+
1233
+ if activation_fn == "gelu":
1234
+ act_fn = GELU(dim, inner_dim, bias=bias)
1235
+ elif activation_fn == "gelu-approximate":
1236
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
1237
+ elif activation_fn == "geglu":
1238
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
1239
+ elif activation_fn == "geglu-approximate":
1240
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
1241
+ else:
1242
+ raise ValueError(f"Unsupported activation function: {activation_fn}")
1243
+
1244
+ self.net = nn.ModuleList([])
1245
+ # project in
1246
+ self.net.append(act_fn)
1247
+ # project dropout
1248
+ self.net.append(nn.Dropout(dropout))
1249
+ # project out
1250
+ self.net.append(linear_cls(inner_dim, dim_out, bias=bias))
1251
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
1252
+ if final_dropout:
1253
+ self.net.append(nn.Dropout(dropout))
1254
+
1255
+ def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
1256
+ compatible_cls = (GEGLU, LoRACompatibleLinear)
1257
+ for module in self.net:
1258
+ if isinstance(module, compatible_cls):
1259
+ hidden_states = module(hidden_states, scale)
1260
+ else:
1261
+ hidden_states = module(hidden_states)
1262
+ return hidden_states
ltx_video/models/transformers/custom_kernel_spmd.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch_xla
3
+ import torch_xla.distributed.spmd as xs
4
+ import torch_xla.core.xla_model as xm
5
+ import pickle
6
+ import jax
7
+ import os
8
+
9
+
10
+ from torch_xla.experimental.custom_kernel import (
11
+ FlashAttention,
12
+ jax_import_guard,
13
+ trace_pallas,
14
+ )
15
+
16
+
17
+ def flash_attention(
18
+ q, # [batch_size, num_heads, q_seq_len, d_model]
19
+ k, # [batch_size, num_heads, kv_seq_len, d_model]
20
+ v, # [batch_size, num_heads, kv_seq_len, d_model]
21
+ causal=False,
22
+ q_segment_ids=None, # [batch_size, q_seq_len]
23
+ kv_segment_ids=None, # [batch_size, kv_seq_len]
24
+ sm_scale=1.0,
25
+ *,
26
+ ab=None, # [batch_size, num_heads, q_seq_len, kv_seq_len]
27
+ partition_spec=None,
28
+ mesh=None,
29
+ ):
30
+ # TODO: support SPMD and Dynamo with segment_ids.
31
+ return SPMDFlashAttention.apply(
32
+ q,
33
+ k,
34
+ v,
35
+ causal,
36
+ q_segment_ids,
37
+ kv_segment_ids,
38
+ sm_scale,
39
+ ab,
40
+ partition_spec,
41
+ mesh,
42
+ )
43
+
44
+
45
+ class SPMDFlashAttention(FlashAttention):
46
+ """
47
+ This is a simplified wrapper on top of https://github.com/google/jax/blob/b2058d72b7e1693a41303d5411572aabf99b7981/jax/experimental/pallas/ops/tpu/flash_attention.py#L139
48
+ where we only takes q, k, v and causal as input and set block_sizes for the users.
49
+ """
50
+
51
+ @staticmethod
52
+ def forward(
53
+ ctx,
54
+ q,
55
+ k,
56
+ v,
57
+ causal,
58
+ q_segment_ids,
59
+ kv_segment_ids,
60
+ sm_scale,
61
+ ab,
62
+ partition_spec,
63
+ mesh,
64
+ ):
65
+ # Import JAX within the function such that we don't need to call the jax_import_guard()
66
+ # in the global scope which could cause problems for xmp.spawn.
67
+ jax_import_guard()
68
+ import jax # noqa: F401
69
+ from jax.experimental.pallas.ops.tpu.flash_attention import (
70
+ _flash_attention_impl,
71
+ )
72
+
73
+ ctx.causal = causal
74
+ ctx.sm_scale = sm_scale
75
+ ctx.partition_spec = partition_spec
76
+ ctx.mesh = mesh
77
+ ctx.q_full_shape = None
78
+ ctx.kv_full_shape = None
79
+ save_residuals = q.requires_grad or k.requires_grad or v.requires_grad
80
+
81
+ # SPMD integration.
82
+ # mark_sharding is in-placed, and therefore save the full q, k, v for the backward.
83
+ full_q = q
84
+ full_k = k
85
+ full_v = v
86
+ full_ab = ab
87
+
88
+ if partition_spec is not None:
89
+ ctx.q_full_shape = q.shape
90
+ ctx.kv_full_shape = k.shape
91
+ q = xs.enable_manual_sharding(q, partition_spec, mesh=mesh).global_tensor
92
+ k = xs.enable_manual_sharding(k, partition_spec, mesh=mesh).global_tensor
93
+ v = xs.enable_manual_sharding(v, partition_spec, mesh=mesh).global_tensor
94
+ if ab:
95
+ ab = xs.enable_manual_sharding(
96
+ ab, partition_spec, mesh=mesh
97
+ ).global_tensor
98
+
99
+ # It computes the shape and type of o, l, m.
100
+ shapes = [q.shape]
101
+ dtypes = [q.dtype]
102
+ if save_residuals:
103
+ res_shape = list(q.shape)
104
+ res_shape[-1] = FlashAttention.MIN_BLOCK_SIZE
105
+ for _ in range(2):
106
+ shapes.append(res_shape)
107
+ dtypes.append(torch.float32)
108
+
109
+ with torch.no_grad():
110
+ if (
111
+ partition_spec is not None
112
+ and q_segment_ids is not None
113
+ and kv_segment_ids is not None
114
+ ):
115
+ # partition_spec is for q,k,v with shape [batch, num_head, seq_len, head_dim], segment id
116
+ # is of shape [batch, seq_len], hence we need to tweak it a bit
117
+ segment_id_partition_spec = (partition_spec[0], partition_spec[2])
118
+ q_segment_ids = xs.enable_manual_sharding(
119
+ q_segment_ids, (partition_spec[0], partition_spec[2]), mesh=mesh
120
+ ).global_tensor
121
+ kv_segment_ids = xs.enable_manual_sharding(
122
+ kv_segment_ids, segment_id_partition_spec, mesh=mesh
123
+ ).global_tensor
124
+ segment_ids, q_segment_ids_fa, kv_segment_ids_fa = (
125
+ FlashAttention.prepare_segment_ids(q_segment_ids, kv_segment_ids)
126
+ )
127
+ ctx.segment_ids = segment_ids
128
+
129
+ # We can't directly use flash_attention as we need to override the save_residuals flag which returns
130
+ # l and m that is needed for the backward. Then we lose all the shape checks.
131
+ # TODO: replicate the shape checks on flash_attention.
132
+ # Here we seperate the tracing and execution part just to support SegmentIds.
133
+ payload, _ = trace_pallas(
134
+ _flash_attention_impl,
135
+ q,
136
+ k,
137
+ v,
138
+ ab,
139
+ segment_ids,
140
+ save_residuals,
141
+ causal,
142
+ sm_scale,
143
+ min(FlashAttention.DEFAULT_BLOCK_SIZES["block_b"], q.shape[0]),
144
+ min(FlashAttention.DEFAULT_BLOCK_SIZES["block_q"], q.shape[2]),
145
+ min(FlashAttention.DEFAULT_BLOCK_SIZES["block_k_major"], k.shape[2]),
146
+ min(FlashAttention.DEFAULT_BLOCK_SIZES["block_k"], k.shape[2]),
147
+ False,
148
+ static_argnums=range(5, 13),
149
+ use_cache=True,
150
+ )
151
+
152
+ args = [q, k, v]
153
+ if ab is not None:
154
+ args += [ab]
155
+ if segment_ids is not None:
156
+ args += [q_segment_ids_fa, kv_segment_ids_fa]
157
+ o = torch_xla._XLAC._xla_tpu_custom_call(args, payload, shapes, dtypes)
158
+
159
+ if not save_residuals:
160
+ o = o[0]
161
+ # SPMD integration
162
+ if partition_spec is not None:
163
+ o = xs.disable_manual_sharding(
164
+ o, partition_spec, ctx.q_full_shape, mesh=mesh
165
+ ).global_tensor
166
+ return o
167
+ o, *aux = o
168
+ l, m = (v[..., 0] for v in aux[-2:]) # noqa: E741
169
+
170
+ # SPMD integration
171
+ if partition_spec is not None:
172
+ o = xs.disable_manual_sharding(
173
+ o, partition_spec, ctx.q_full_shape, mesh=mesh
174
+ ).global_tensor
175
+ l = xs.disable_manual_sharding( # noqa: E741
176
+ l, partition_spec[0:3], ctx.q_full_shape[0:3], mesh=mesh
177
+ ).global_tensor
178
+ m = xs.disable_manual_sharding(
179
+ m, partition_spec[0:3], ctx.q_full_shape[0:3], mesh=mesh
180
+ ).global_tensor
181
+
182
+ ctx.save_for_backward(
183
+ full_q,
184
+ full_k,
185
+ full_v,
186
+ o,
187
+ l,
188
+ m,
189
+ q_segment_ids_fa,
190
+ kv_segment_ids_fa,
191
+ full_ab,
192
+ )
193
+ return o
194
+
195
+ @staticmethod
196
+ def backward(ctx, grad_output):
197
+ from jax.experimental.pallas.ops.tpu.flash_attention import (
198
+ _flash_attention_bwd_dq,
199
+ _flash_attention_bwd_dkv,
200
+ )
201
+
202
+ q, k, v, o, l, m, q_segment_ids_fa, kv_segment_ids_fa, ab = ( # noqa: E741
203
+ ctx.saved_tensors
204
+ )
205
+ causal = ctx.causal
206
+ sm_scale = ctx.sm_scale
207
+ partition_spec = ctx.partition_spec
208
+ mesh = ctx.mesh
209
+ q_full_shape = ctx.q_full_shape
210
+ kv_full_shape = ctx.kv_full_shape
211
+ segment_ids = ctx.segment_ids
212
+ grad_q = grad_k = grad_v = grad_ab = None
213
+
214
+ grad_i = torch.sum(
215
+ o.to(torch.float32) * grad_output.to(torch.float32), axis=-1
216
+ ) # [batch_size, num_heads, q_seq_len]
217
+
218
+ expanded_l = l.unsqueeze(-1).expand(
219
+ [-1 for _ in l.shape] + [FlashAttention.MIN_BLOCK_SIZE]
220
+ )
221
+ expanded_m = m.unsqueeze(-1).expand(
222
+ [-1 for _ in m.shape] + [FlashAttention.MIN_BLOCK_SIZE]
223
+ )
224
+ expanded_grad_i = grad_i.unsqueeze(-1).expand(
225
+ [-1 for _ in grad_i.shape] + [FlashAttention.MIN_BLOCK_SIZE]
226
+ )
227
+
228
+ # SPMD integration
229
+ if partition_spec is not None:
230
+ q = xs.enable_manual_sharding(q, partition_spec, mesh=mesh).global_tensor
231
+ k = xs.enable_manual_sharding(k, partition_spec, mesh=mesh).global_tensor
232
+ v = xs.enable_manual_sharding(v, partition_spec, mesh=mesh).global_tensor
233
+ expanded_l = xs.enable_manual_sharding(
234
+ expanded_l, partition_spec, mesh=mesh
235
+ ).global_tensor
236
+ expanded_m = xs.enable_manual_sharding(
237
+ expanded_m, partition_spec, mesh=mesh
238
+ ).global_tensor
239
+ grad_output = xs.enable_manual_sharding(
240
+ grad_output, partition_spec, mesh=mesh
241
+ ).global_tensor
242
+ expanded_grad_i = xs.enable_manual_sharding(
243
+ expanded_grad_i, partition_spec, mesh=mesh
244
+ ).global_tensor
245
+ if ab:
246
+ ab = xs.enable_manual_sharding(
247
+ ab, partition_spec, mesh=mesh
248
+ ).global_tensor
249
+
250
+ if ctx.needs_input_grad[0]:
251
+ payload, _ = trace_pallas(
252
+ _flash_attention_bwd_dq,
253
+ q,
254
+ k,
255
+ v,
256
+ ab,
257
+ segment_ids,
258
+ l,
259
+ m,
260
+ grad_output,
261
+ grad_i,
262
+ block_q_major=min(
263
+ FlashAttention.DEFAULT_BLOCK_SIZES["block_q_dq"], q.shape[2]
264
+ ),
265
+ block_k_major=min(
266
+ FlashAttention.DEFAULT_BLOCK_SIZES["block_k_major_dq"], k.shape[2]
267
+ ),
268
+ block_k=min(
269
+ FlashAttention.DEFAULT_BLOCK_SIZES["block_k_dq"], k.shape[2]
270
+ ),
271
+ sm_scale=sm_scale,
272
+ causal=causal,
273
+ mask_value=FlashAttention.DEFAULT_MASK_VALUE,
274
+ debug=False,
275
+ static_argnames=[
276
+ "block_q_major",
277
+ "block_k_major",
278
+ "block_k",
279
+ "sm_scale",
280
+ "causal",
281
+ "mask_value",
282
+ "debug",
283
+ ],
284
+ use_cache=True,
285
+ )
286
+
287
+ args = [q, k, v]
288
+ if ab is not None:
289
+ args += [ab]
290
+ if segment_ids is not None:
291
+ args += [q_segment_ids_fa, kv_segment_ids_fa]
292
+ args += [expanded_l, expanded_m, grad_output, expanded_grad_i]
293
+
294
+ outputs = [q]
295
+ if ab is not None:
296
+ outputs += [ab]
297
+ grads = torch_xla._XLAC._xla_tpu_custom_call(
298
+ args, payload, [i.shape for i in outputs], [i.dtype for i in outputs]
299
+ )
300
+ if ctx.needs_input_grad[0]:
301
+ grad_q = grads[0]
302
+ if ctx.needs_input_grad[-3]:
303
+ grad_ab = grads[1]
304
+
305
+ if ctx.needs_input_grad[1] or ctx.needs_input_grad[2]:
306
+ payload, _ = trace_pallas(
307
+ _flash_attention_bwd_dkv,
308
+ q,
309
+ k,
310
+ v,
311
+ ab,
312
+ segment_ids,
313
+ l,
314
+ m,
315
+ grad_output,
316
+ grad_i,
317
+ block_q_major=min(
318
+ FlashAttention.DEFAULT_BLOCK_SIZES["block_q_major_dkv"], q.shape[2]
319
+ ),
320
+ block_k_major=min(
321
+ FlashAttention.DEFAULT_BLOCK_SIZES["block_k_major_dkv"], k.shape[2]
322
+ ),
323
+ block_k=min(
324
+ FlashAttention.DEFAULT_BLOCK_SIZES["block_k_dkv"], k.shape[2]
325
+ ),
326
+ block_q=min(
327
+ FlashAttention.DEFAULT_BLOCK_SIZES["block_q_dkv"], q.shape[2]
328
+ ),
329
+ sm_scale=sm_scale,
330
+ causal=causal,
331
+ mask_value=FlashAttention.DEFAULT_MASK_VALUE,
332
+ debug=False,
333
+ static_argnames=[
334
+ "block_q_major",
335
+ "block_k_major",
336
+ "block_k",
337
+ "block_q",
338
+ "sm_scale",
339
+ "causal",
340
+ "mask_value",
341
+ "debug",
342
+ ],
343
+ use_cache=True,
344
+ )
345
+
346
+ grads = torch_xla._XLAC._xla_tpu_custom_call(
347
+ args, payload, [k.shape, v.shape], [k.dtype, v.dtype]
348
+ )
349
+
350
+ if ctx.needs_input_grad[1]:
351
+ grad_k = grads[0]
352
+ if ctx.needs_input_grad[2]:
353
+ grad_v = grads[1]
354
+
355
+ # SPMD integration
356
+ if partition_spec is not None:
357
+ grad_q = xs.disable_manual_sharding(
358
+ grad_q, partition_spec, q_full_shape, mesh=mesh
359
+ ).global_tensor
360
+ grad_k = xs.disable_manual_sharding(
361
+ grad_k, partition_spec, kv_full_shape, mesh=mesh
362
+ ).global_tensor
363
+ grad_v = xs.disable_manual_sharding(
364
+ grad_v, partition_spec, kv_full_shape, mesh=mesh
365
+ ).global_tensor
366
+
367
+ return grad_q, grad_k, grad_v, None, None, None, None, grad_ab, None, None
368
+
369
+
370
+ if __name__ == "__main__":
371
+ if len(os.sys.argv) < 2:
372
+ print("Usage: python custom_kernel_spmd.py <use_spmd>")
373
+ os.sys.exit(1)
374
+
375
+ use_spmd = os.sys.argv[1]
376
+ jax.config.update("jax_default_matmul_precision", "highest")
377
+ mesh, attn_spec = None, None
378
+ if use_spmd:
379
+ import torch_xla.runtime as xr
380
+ from torch_xla.distributed.spmd import Mesh
381
+ import numpy as np
382
+
383
+ xr.use_spmd()
384
+ num_devices = xr.global_runtime_device_count()
385
+ mesh_shape = (1, 1, num_devices)
386
+ device_ids = np.array(range(num_devices))
387
+ mesh = Mesh(device_ids, mesh_shape, ("data", "model", "sequence"))
388
+ attn_spec = ("data", None, None, None)
389
+ batch_size = 1000
390
+
391
+ data_path = "data.pkl"
392
+ if os.path.exists(data_path):
393
+ with open(data_path, "rb") as f:
394
+ q, k, v, mask = pickle.load(f)
395
+ else:
396
+ q = torch.randn(batch_size, 2, 128, 4)
397
+ k = torch.randn(batch_size, 2, 128, 4)
398
+ v = torch.randn(batch_size, 2, 128, 4)
399
+ mask = torch.rand(batch_size, 128)
400
+ pickle.dump((q, k, v, mask), open(data_path, "wb"))
401
+
402
+ q, k, v, mask = q.to("xla"), k.to("xla"), v.to("xla"), mask.to("xla")
403
+
404
+ q.requires_grad = True
405
+ k.requires_grad = True
406
+ v.requires_grad = True
407
+ q.retain_grad()
408
+ k.retain_grad()
409
+ v.retain_grad()
410
+
411
+ q_segment_indexes = torch.ones(
412
+ batch_size, q.shape[2], device=q.device, dtype=torch.float32
413
+ )
414
+
415
+ grads_path = "grads.pkl"
416
+ if os.path.exists(grads_path):
417
+ print("loaded output")
418
+ with open(grads_path, "rb") as f:
419
+ o, q_grad, k_grad, v_grad = pickle.load(f)
420
+ o, q_grad, k_grad, v_grad = (
421
+ o.to("xla"),
422
+ q_grad.to("xla"),
423
+ k_grad.to("xla"),
424
+ v_grad.to("xla"),
425
+ )
426
+ else:
427
+ o = SPMDFlashAttention.apply(
428
+ q, k, v, False, q_segment_indexes, mask, 1.0, attn_spec, mesh
429
+ )
430
+ print(f"created output with shape {o.shape}", flush=True)
431
+
432
+ loss = o.sum()
433
+ loss.backward()
434
+ xm.mark_step()
435
+
436
+ q_grad = q.grad
437
+ k_grad = k.grad
438
+ v_grad = v.grad
439
+
440
+ o_cpu = o.cpu()
441
+
442
+ with open("grads.pkl", "wb") as f:
443
+ pickle.dump([o.cpu(), q_grad.cpu(), k_grad.cpu(), v_grad.cpu()], f)
444
+
445
+ q.grad = None
446
+ k.grad = None
447
+ v.grad = None
448
+
449
+ o2 = SPMDFlashAttention.apply(
450
+ q, k, v, False, q_segment_indexes, mask, 1.0, attn_spec, mesh
451
+ )
452
+ loss = o2.sum()
453
+ loss.backward()
454
+ xm.mark_step()
455
+
456
+ print(
457
+ "comparing gradients (loaded / computed) to the gradients after computing the same again:"
458
+ )
459
+ for i, j in [(q_grad, q.grad), (k_grad, k.grad), (v_grad, v.grad)]:
460
+ print(torch.allclose(i, j, rtol=1e-14))
461
+
462
+ print("opposite")
463
+ for i, j in [(q_grad, q.grad), (k_grad, k.grad), (v_grad, v.grad)]:
464
+ print(torch.allclose(j, i, rtol=1e-14))
465
+ print(f"comparing second output with shape: {o2.shape}", flush=True)
466
+ print(torch.allclose(o, o2, rtol=1e-14))
ltx_video/models/transformers/embeddings.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/embeddings.py
2
+ import math
3
+
4
+ import numpy as np
5
+ import torch
6
+ from einops import rearrange
7
+ from torch import nn
8
+
9
+
10
+ def get_timestep_embedding(
11
+ timesteps: torch.Tensor,
12
+ embedding_dim: int,
13
+ flip_sin_to_cos: bool = False,
14
+ downscale_freq_shift: float = 1,
15
+ scale: float = 1,
16
+ max_period: int = 10000,
17
+ ):
18
+ """
19
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
20
+
21
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
22
+ These may be fractional.
23
+ :param embedding_dim: the dimension of the output. :param max_period: controls the minimum frequency of the
24
+ embeddings. :return: an [N x dim] Tensor of positional embeddings.
25
+ """
26
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
27
+
28
+ half_dim = embedding_dim // 2
29
+ exponent = -math.log(max_period) * torch.arange(
30
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
31
+ )
32
+ exponent = exponent / (half_dim - downscale_freq_shift)
33
+
34
+ emb = torch.exp(exponent)
35
+ emb = timesteps[:, None].float() * emb[None, :]
36
+
37
+ # scale embeddings
38
+ emb = scale * emb
39
+
40
+ # concat sine and cosine embeddings
41
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
42
+
43
+ # flip sine and cosine embeddings
44
+ if flip_sin_to_cos:
45
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
46
+
47
+ # zero pad
48
+ if embedding_dim % 2 == 1:
49
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
50
+ return emb
51
+
52
+
53
+ def get_3d_sincos_pos_embed(embed_dim, grid, w, h, f):
54
+ """
55
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
56
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
57
+ """
58
+ grid = rearrange(grid, "c (f h w) -> c f h w", h=h, w=w)
59
+ grid = rearrange(grid, "c f h w -> c h w f", h=h, w=w)
60
+ grid = grid.reshape([3, 1, w, h, f])
61
+ pos_embed = get_3d_sincos_pos_embed_from_grid(embed_dim, grid)
62
+ pos_embed = pos_embed.transpose(1, 0, 2, 3)
63
+ return rearrange(pos_embed, "h w f c -> (f h w) c")
64
+
65
+
66
+ def get_3d_sincos_pos_embed_from_grid(embed_dim, grid):
67
+ if embed_dim % 3 != 0:
68
+ raise ValueError("embed_dim must be divisible by 3")
69
+
70
+ # use half of dimensions to encode grid_h
71
+ emb_f = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[0]) # (H*W*T, D/3)
72
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[1]) # (H*W*T, D/3)
73
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[2]) # (H*W*T, D/3)
74
+
75
+ emb = np.concatenate([emb_h, emb_w, emb_f], axis=-1) # (H*W*T, D)
76
+ return emb
77
+
78
+
79
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
80
+ """
81
+ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
82
+ """
83
+ if embed_dim % 2 != 0:
84
+ raise ValueError("embed_dim must be divisible by 2")
85
+
86
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
87
+ omega /= embed_dim / 2.0
88
+ omega = 1.0 / 10000**omega # (D/2,)
89
+
90
+ pos_shape = pos.shape
91
+
92
+ pos = pos.reshape(-1)
93
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
94
+ out = out.reshape([*pos_shape, -1])[0]
95
+
96
+ emb_sin = np.sin(out) # (M, D/2)
97
+ emb_cos = np.cos(out) # (M, D/2)
98
+
99
+ emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (M, D)
100
+ return emb
101
+
102
+
103
+ class SinusoidalPositionalEmbedding(nn.Module):
104
+ """Apply positional information to a sequence of embeddings.
105
+
106
+ Takes in a sequence of embeddings with shape (batch_size, seq_length, embed_dim) and adds positional embeddings to
107
+ them
108
+
109
+ Args:
110
+ embed_dim: (int): Dimension of the positional embedding.
111
+ max_seq_length: Maximum sequence length to apply positional embeddings
112
+
113
+ """
114
+
115
+ def __init__(self, embed_dim: int, max_seq_length: int = 32):
116
+ super().__init__()
117
+ position = torch.arange(max_seq_length).unsqueeze(1)
118
+ div_term = torch.exp(
119
+ torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim)
120
+ )
121
+ pe = torch.zeros(1, max_seq_length, embed_dim)
122
+ pe[0, :, 0::2] = torch.sin(position * div_term)
123
+ pe[0, :, 1::2] = torch.cos(position * div_term)
124
+ self.register_buffer("pe", pe)
125
+
126
+ def forward(self, x):
127
+ _, seq_length, _ = x.shape
128
+ x = x + self.pe[:, :seq_length]
129
+ return x
ltx_video/models/transformers/symmetric_patchifier.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Tuple
3
+
4
+ import torch
5
+ from diffusers.configuration_utils import ConfigMixin
6
+ from einops import rearrange
7
+ from torch import Tensor
8
+
9
+ from ltx_video.utils.torch_utils import append_dims
10
+
11
+
12
+ class Patchifier(ConfigMixin, ABC):
13
+ def __init__(self, patch_size: int):
14
+ super().__init__()
15
+ self._patch_size = (1, patch_size, patch_size)
16
+
17
+ @abstractmethod
18
+ def patchify(
19
+ self, latents: Tensor, frame_rates: Tensor, scale_grid: bool
20
+ ) -> Tuple[Tensor, Tensor]:
21
+ pass
22
+
23
+ @abstractmethod
24
+ def unpatchify(
25
+ self,
26
+ latents: Tensor,
27
+ output_height: int,
28
+ output_width: int,
29
+ output_num_frames: int,
30
+ out_channels: int,
31
+ ) -> Tuple[Tensor, Tensor]:
32
+ pass
33
+
34
+ @property
35
+ def patch_size(self):
36
+ return self._patch_size
37
+
38
+ def get_grid(
39
+ self, orig_num_frames, orig_height, orig_width, batch_size, scale_grid, device
40
+ ):
41
+ f = orig_num_frames // self._patch_size[0]
42
+ h = orig_height // self._patch_size[1]
43
+ w = orig_width // self._patch_size[2]
44
+ grid_h = torch.arange(h, dtype=torch.float32, device=device)
45
+ grid_w = torch.arange(w, dtype=torch.float32, device=device)
46
+ grid_f = torch.arange(f, dtype=torch.float32, device=device)
47
+ grid = torch.meshgrid(grid_f, grid_h, grid_w)
48
+ grid = torch.stack(grid, dim=0)
49
+ grid = grid.unsqueeze(0).repeat(batch_size, 1, 1, 1, 1)
50
+
51
+ if scale_grid is not None:
52
+ for i in range(3):
53
+ if isinstance(scale_grid[i], Tensor):
54
+ scale = append_dims(scale_grid[i], grid.ndim - 1)
55
+ else:
56
+ scale = scale_grid[i]
57
+ grid[:, i, ...] = grid[:, i, ...] * scale * self._patch_size[i]
58
+
59
+ grid = rearrange(grid, "b c f h w -> b c (f h w)", b=batch_size)
60
+ return grid
61
+
62
+
63
+ class SymmetricPatchifier(Patchifier):
64
+ def patchify(
65
+ self,
66
+ latents: Tensor,
67
+ ) -> Tuple[Tensor, Tensor]:
68
+ latents = rearrange(
69
+ latents,
70
+ "b c (f p1) (h p2) (w p3) -> b (f h w) (c p1 p2 p3)",
71
+ p1=self._patch_size[0],
72
+ p2=self._patch_size[1],
73
+ p3=self._patch_size[2],
74
+ )
75
+ return latents
76
+
77
+ def unpatchify(
78
+ self,
79
+ latents: Tensor,
80
+ output_height: int,
81
+ output_width: int,
82
+ output_num_frames: int,
83
+ out_channels: int,
84
+ ) -> Tuple[Tensor, Tensor]:
85
+ output_height = output_height // self._patch_size[1]
86
+ output_width = output_width // self._patch_size[2]
87
+ latents = rearrange(
88
+ latents,
89
+ "b (f h w) (c p q) -> b c f (h p) (w q) ",
90
+ f=output_num_frames,
91
+ h=output_height,
92
+ w=output_width,
93
+ p=self._patch_size[1],
94
+ q=self._patch_size[2],
95
+ )
96
+ return latents
ltx_video/models/transformers/transformer3d.py ADDED
@@ -0,0 +1,614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from: https://github.com/huggingface/diffusers/blob/v0.26.3/src/diffusers/models/transformers/transformer_2d.py
2
+ import math
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Optional, Literal, Union
5
+ import os
6
+ import json
7
+ import glob
8
+ from pathlib import Path
9
+
10
+ import torch
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.models.embeddings import PixArtAlphaTextProjection
13
+ from diffusers.models.modeling_utils import ModelMixin
14
+ from diffusers.models.normalization import AdaLayerNormSingle
15
+ from diffusers.utils import BaseOutput, is_torch_version
16
+ from diffusers.utils import logging
17
+ from torch import nn
18
+ from safetensors import safe_open
19
+
20
+
21
+ from ltx_video.models.transformers.attention import BasicTransformerBlock
22
+ from ltx_video.models.transformers.embeddings import get_3d_sincos_pos_embed
23
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
24
+
25
+ from ltx_video.utils.diffusers_config_mapping import (
26
+ diffusers_and_ours_config_mapping,
27
+ make_hashable_key,
28
+ TRANSFORMER_KEYS_RENAME_DICT,
29
+ )
30
+
31
+
32
+ try:
33
+ from torch_xla.distributed.spmd import Mesh
34
+ except ImportError:
35
+ Mesh = None
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ @dataclass
41
+ class Transformer3DModelOutput(BaseOutput):
42
+ """
43
+ The output of [`Transformer2DModel`].
44
+
45
+ Args:
46
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
47
+ The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
48
+ distributions for the unnoised latent pixels.
49
+ """
50
+
51
+ sample: torch.FloatTensor
52
+
53
+
54
+ class Transformer3DModel(ModelMixin, ConfigMixin):
55
+ _supports_gradient_checkpointing = True
56
+
57
+ @register_to_config
58
+ def __init__(
59
+ self,
60
+ num_attention_heads: int = 16,
61
+ attention_head_dim: int = 88,
62
+ in_channels: Optional[int] = None,
63
+ out_channels: Optional[int] = None,
64
+ num_layers: int = 1,
65
+ dropout: float = 0.0,
66
+ norm_num_groups: int = 32,
67
+ cross_attention_dim: Optional[int] = None,
68
+ attention_bias: bool = False,
69
+ num_vector_embeds: Optional[int] = None,
70
+ activation_fn: str = "geglu",
71
+ num_embeds_ada_norm: Optional[int] = None,
72
+ use_linear_projection: bool = False,
73
+ only_cross_attention: bool = False,
74
+ double_self_attention: bool = False,
75
+ upcast_attention: bool = False,
76
+ adaptive_norm: str = "single_scale_shift", # 'single_scale_shift' or 'single_scale'
77
+ standardization_norm: str = "layer_norm", # 'layer_norm' or 'rms_norm'
78
+ norm_elementwise_affine: bool = True,
79
+ norm_eps: float = 1e-5,
80
+ attention_type: str = "default",
81
+ caption_channels: int = None,
82
+ project_to_2d_pos: bool = False,
83
+ use_tpu_flash_attention: bool = False, # if True uses the TPU attention offload ('flash attention')
84
+ qk_norm: Optional[str] = None,
85
+ positional_embedding_type: str = "absolute",
86
+ positional_embedding_theta: Optional[float] = None,
87
+ positional_embedding_max_pos: Optional[List[int]] = None,
88
+ timestep_scale_multiplier: Optional[float] = None,
89
+ ):
90
+ super().__init__()
91
+ self.use_tpu_flash_attention = (
92
+ use_tpu_flash_attention # FIXME: push config down to the attention modules
93
+ )
94
+ self.use_linear_projection = use_linear_projection
95
+ self.num_attention_heads = num_attention_heads
96
+ self.attention_head_dim = attention_head_dim
97
+ inner_dim = num_attention_heads * attention_head_dim
98
+ self.inner_dim = inner_dim
99
+
100
+ self.project_to_2d_pos = project_to_2d_pos
101
+
102
+ self.patchify_proj = nn.Linear(in_channels, inner_dim, bias=True)
103
+
104
+ self.positional_embedding_type = positional_embedding_type
105
+ self.positional_embedding_theta = positional_embedding_theta
106
+ self.positional_embedding_max_pos = positional_embedding_max_pos
107
+ self.use_rope = self.positional_embedding_type == "rope"
108
+ self.timestep_scale_multiplier = timestep_scale_multiplier
109
+
110
+ if self.positional_embedding_type == "absolute":
111
+ embed_dim_3d = (
112
+ math.ceil((inner_dim / 2) * 3) if project_to_2d_pos else inner_dim
113
+ )
114
+ if self.project_to_2d_pos:
115
+ self.to_2d_proj = torch.nn.Linear(embed_dim_3d, inner_dim, bias=False)
116
+ self._init_to_2d_proj_weights(self.to_2d_proj)
117
+ elif self.positional_embedding_type == "rope":
118
+ if positional_embedding_theta is None:
119
+ raise ValueError(
120
+ "If `positional_embedding_type` type is rope, `positional_embedding_theta` must also be defined"
121
+ )
122
+ if positional_embedding_max_pos is None:
123
+ raise ValueError(
124
+ "If `positional_embedding_type` type is rope, `positional_embedding_max_pos` must also be defined"
125
+ )
126
+
127
+ # 3. Define transformers blocks
128
+ self.transformer_blocks = nn.ModuleList(
129
+ [
130
+ BasicTransformerBlock(
131
+ inner_dim,
132
+ num_attention_heads,
133
+ attention_head_dim,
134
+ dropout=dropout,
135
+ cross_attention_dim=cross_attention_dim,
136
+ activation_fn=activation_fn,
137
+ num_embeds_ada_norm=num_embeds_ada_norm,
138
+ attention_bias=attention_bias,
139
+ only_cross_attention=only_cross_attention,
140
+ double_self_attention=double_self_attention,
141
+ upcast_attention=upcast_attention,
142
+ adaptive_norm=adaptive_norm,
143
+ standardization_norm=standardization_norm,
144
+ norm_elementwise_affine=norm_elementwise_affine,
145
+ norm_eps=norm_eps,
146
+ attention_type=attention_type,
147
+ use_tpu_flash_attention=use_tpu_flash_attention,
148
+ qk_norm=qk_norm,
149
+ use_rope=self.use_rope,
150
+ )
151
+ for d in range(num_layers)
152
+ ]
153
+ )
154
+
155
+ # 4. Define output layers
156
+ self.out_channels = in_channels if out_channels is None else out_channels
157
+ self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
158
+ self.scale_shift_table = nn.Parameter(
159
+ torch.randn(2, inner_dim) / inner_dim**0.5
160
+ )
161
+ self.proj_out = nn.Linear(inner_dim, self.out_channels)
162
+
163
+ self.adaln_single = AdaLayerNormSingle(
164
+ inner_dim, use_additional_conditions=False
165
+ )
166
+ if adaptive_norm == "single_scale":
167
+ self.adaln_single.linear = nn.Linear(inner_dim, 4 * inner_dim, bias=True)
168
+
169
+ self.caption_projection = None
170
+ if caption_channels is not None:
171
+ self.caption_projection = PixArtAlphaTextProjection(
172
+ in_features=caption_channels, hidden_size=inner_dim
173
+ )
174
+
175
+ self.gradient_checkpointing = False
176
+
177
+ def set_use_tpu_flash_attention(self):
178
+ r"""
179
+ Function sets the flag in this object and propagates down the children. The flag will enforce the usage of TPU
180
+ attention kernel.
181
+ """
182
+ logger.info("ENABLE TPU FLASH ATTENTION -> TRUE")
183
+ self.use_tpu_flash_attention = True
184
+ # push config down to the attention modules
185
+ for block in self.transformer_blocks:
186
+ block.set_use_tpu_flash_attention()
187
+
188
+ def create_skip_layer_mask(
189
+ self,
190
+ skip_block_list: List[int],
191
+ batch_size: int,
192
+ num_conds: int,
193
+ ptb_index: int,
194
+ ):
195
+ num_layers = len(self.transformer_blocks)
196
+ mask = torch.ones(
197
+ (num_layers, batch_size * num_conds), device=self.device, dtype=self.dtype
198
+ )
199
+ for block_idx in skip_block_list:
200
+ mask[block_idx, ptb_index::num_conds] = 0
201
+ return mask
202
+
203
+ def initialize(self, embedding_std: float, mode: Literal["ltx_video", "legacy"]):
204
+ def _basic_init(module):
205
+ if isinstance(module, nn.Linear):
206
+ torch.nn.init.xavier_uniform_(module.weight)
207
+ if module.bias is not None:
208
+ nn.init.constant_(module.bias, 0)
209
+
210
+ self.apply(_basic_init)
211
+
212
+ # Initialize timestep embedding MLP:
213
+ nn.init.normal_(
214
+ self.adaln_single.emb.timestep_embedder.linear_1.weight, std=embedding_std
215
+ )
216
+ nn.init.normal_(
217
+ self.adaln_single.emb.timestep_embedder.linear_2.weight, std=embedding_std
218
+ )
219
+ nn.init.normal_(self.adaln_single.linear.weight, std=embedding_std)
220
+
221
+ if hasattr(self.adaln_single.emb, "resolution_embedder"):
222
+ nn.init.normal_(
223
+ self.adaln_single.emb.resolution_embedder.linear_1.weight,
224
+ std=embedding_std,
225
+ )
226
+ nn.init.normal_(
227
+ self.adaln_single.emb.resolution_embedder.linear_2.weight,
228
+ std=embedding_std,
229
+ )
230
+ if hasattr(self.adaln_single.emb, "aspect_ratio_embedder"):
231
+ nn.init.normal_(
232
+ self.adaln_single.emb.aspect_ratio_embedder.linear_1.weight,
233
+ std=embedding_std,
234
+ )
235
+ nn.init.normal_(
236
+ self.adaln_single.emb.aspect_ratio_embedder.linear_2.weight,
237
+ std=embedding_std,
238
+ )
239
+
240
+ # Initialize caption embedding MLP:
241
+ nn.init.normal_(self.caption_projection.linear_1.weight, std=embedding_std)
242
+ nn.init.normal_(self.caption_projection.linear_1.weight, std=embedding_std)
243
+
244
+ for block in self.transformer_blocks:
245
+ if mode.lower() == "ltx_video":
246
+ nn.init.constant_(block.attn1.to_out[0].weight, 0)
247
+ nn.init.constant_(block.attn1.to_out[0].bias, 0)
248
+
249
+ nn.init.constant_(block.attn2.to_out[0].weight, 0)
250
+ nn.init.constant_(block.attn2.to_out[0].bias, 0)
251
+
252
+ if mode.lower() == "ltx_video":
253
+ nn.init.constant_(block.ff.net[2].weight, 0)
254
+ nn.init.constant_(block.ff.net[2].bias, 0)
255
+
256
+ # Zero-out output layers:
257
+ nn.init.constant_(self.proj_out.weight, 0)
258
+ nn.init.constant_(self.proj_out.bias, 0)
259
+
260
+ def _set_gradient_checkpointing(self, module, value=False):
261
+ if hasattr(module, "gradient_checkpointing"):
262
+ module.gradient_checkpointing = value
263
+
264
+ @staticmethod
265
+ def _init_to_2d_proj_weights(linear_layer):
266
+ input_features = linear_layer.weight.data.size(1)
267
+ output_features = linear_layer.weight.data.size(0)
268
+
269
+ # Start with a zero matrix
270
+ identity_like = torch.zeros((output_features, input_features))
271
+
272
+ # Fill the diagonal with 1's as much as possible
273
+ min_features = min(output_features, input_features)
274
+ identity_like[:min_features, :min_features] = torch.eye(min_features)
275
+ linear_layer.weight.data = identity_like.to(linear_layer.weight.data.device)
276
+
277
+ def get_fractional_positions(self, indices_grid):
278
+ fractional_positions = torch.stack(
279
+ [
280
+ indices_grid[:, i] / self.positional_embedding_max_pos[i]
281
+ for i in range(3)
282
+ ],
283
+ dim=-1,
284
+ )
285
+ return fractional_positions
286
+
287
+ def precompute_freqs_cis(self, indices_grid, spacing="exp"):
288
+ dtype = torch.float32 # We need full precision in the freqs_cis computation.
289
+ dim = self.inner_dim
290
+ theta = self.positional_embedding_theta
291
+
292
+ fractional_positions = self.get_fractional_positions(indices_grid)
293
+
294
+ start = 1
295
+ end = theta
296
+ device = fractional_positions.device
297
+ if spacing == "exp":
298
+ indices = theta ** (
299
+ torch.linspace(
300
+ math.log(start, theta),
301
+ math.log(end, theta),
302
+ dim // 6,
303
+ device=device,
304
+ dtype=dtype,
305
+ )
306
+ )
307
+ indices = indices.to(dtype=dtype)
308
+ elif spacing == "exp_2":
309
+ indices = 1.0 / theta ** (torch.arange(0, dim, 6, device=device) / dim)
310
+ indices = indices.to(dtype=dtype)
311
+ elif spacing == "linear":
312
+ indices = torch.linspace(start, end, dim // 6, device=device, dtype=dtype)
313
+ elif spacing == "sqrt":
314
+ indices = torch.linspace(
315
+ start**2, end**2, dim // 6, device=device, dtype=dtype
316
+ ).sqrt()
317
+
318
+ indices = indices * math.pi / 2
319
+
320
+ if spacing == "exp_2":
321
+ freqs = (
322
+ (indices * fractional_positions.unsqueeze(-1))
323
+ .transpose(-1, -2)
324
+ .flatten(2)
325
+ )
326
+ else:
327
+ freqs = (
328
+ (indices * (fractional_positions.unsqueeze(-1) * 2 - 1))
329
+ .transpose(-1, -2)
330
+ .flatten(2)
331
+ )
332
+
333
+ cos_freq = freqs.cos().repeat_interleave(2, dim=-1)
334
+ sin_freq = freqs.sin().repeat_interleave(2, dim=-1)
335
+ if dim % 6 != 0:
336
+ cos_padding = torch.ones_like(cos_freq[:, :, : dim % 6])
337
+ sin_padding = torch.zeros_like(cos_freq[:, :, : dim % 6])
338
+ cos_freq = torch.cat([cos_padding, cos_freq], dim=-1)
339
+ sin_freq = torch.cat([sin_padding, sin_freq], dim=-1)
340
+ return cos_freq.to(self.dtype), sin_freq.to(self.dtype)
341
+
342
+ def load_state_dict(
343
+ self,
344
+ state_dict: Dict,
345
+ *args,
346
+ **kwargs,
347
+ ):
348
+ if any([key.startswith("model.diffusion_model.") for key in state_dict.keys()]):
349
+ state_dict = {
350
+ key.replace("model.diffusion_model.", ""): value
351
+ for key, value in state_dict.items()
352
+ if key.startswith("model.diffusion_model.")
353
+ }
354
+ super().load_state_dict(state_dict, **kwargs)
355
+
356
+ @classmethod
357
+ def from_pretrained(
358
+ cls,
359
+ pretrained_model_path: Optional[Union[str, os.PathLike]],
360
+ *args,
361
+ **kwargs,
362
+ ):
363
+ pretrained_model_path = Path(pretrained_model_path)
364
+ if pretrained_model_path.is_dir():
365
+ config_path = pretrained_model_path / "transformer" / "config.json"
366
+ with open(config_path, "r") as f:
367
+ config = make_hashable_key(json.load(f))
368
+
369
+ assert config in diffusers_and_ours_config_mapping, (
370
+ "Provided diffusers checkpoint config for transformer is not suppported. "
371
+ "We only support diffusers configs found in Lightricks/LTX-Video."
372
+ )
373
+
374
+ config = diffusers_and_ours_config_mapping[config]
375
+ state_dict = {}
376
+ ckpt_paths = (
377
+ pretrained_model_path
378
+ / "transformer"
379
+ / "diffusion_pytorch_model*.safetensors"
380
+ )
381
+ dict_list = glob.glob(str(ckpt_paths))
382
+ for dict_path in dict_list:
383
+ part_dict = {}
384
+ with safe_open(dict_path, framework="pt", device="cpu") as f:
385
+ for k in f.keys():
386
+ part_dict[k] = f.get_tensor(k)
387
+ state_dict.update(part_dict)
388
+
389
+ for key in list(state_dict.keys()):
390
+ new_key = key
391
+ for replace_key, rename_key in TRANSFORMER_KEYS_RENAME_DICT.items():
392
+ new_key = new_key.replace(replace_key, rename_key)
393
+ state_dict[new_key] = state_dict.pop(key)
394
+
395
+ transformer = cls.from_config(config)
396
+ transformer.load_state_dict(state_dict, strict=True)
397
+ elif pretrained_model_path.is_file() and str(pretrained_model_path).endswith(
398
+ ".safetensors"
399
+ ):
400
+ comfy_single_file_state_dict = {}
401
+ with safe_open(pretrained_model_path, framework="pt", device="cpu") as f:
402
+ metadata = f.metadata()
403
+ for k in f.keys():
404
+ comfy_single_file_state_dict[k] = f.get_tensor(k)
405
+ configs = json.loads(metadata["config"])
406
+ transformer_config = configs["transformer"]
407
+ transformer = Transformer3DModel.from_config(transformer_config)
408
+ transformer.load_state_dict(comfy_single_file_state_dict)
409
+ return transformer
410
+
411
+ def forward(
412
+ self,
413
+ hidden_states: torch.Tensor,
414
+ indices_grid: torch.Tensor,
415
+ encoder_hidden_states: Optional[torch.Tensor] = None,
416
+ timestep: Optional[torch.LongTensor] = None,
417
+ class_labels: Optional[torch.LongTensor] = None,
418
+ cross_attention_kwargs: Dict[str, Any] = None,
419
+ attention_mask: Optional[torch.Tensor] = None,
420
+ encoder_attention_mask: Optional[torch.Tensor] = None,
421
+ skip_layer_mask: Optional[torch.Tensor] = None,
422
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
423
+ sharding_mesh: Optional[Mesh] = None,
424
+ return_dict: bool = True,
425
+ ):
426
+ """
427
+ The [`Transformer2DModel`] forward method.
428
+
429
+ Args:
430
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
431
+ Input `hidden_states`.
432
+ indices_grid (`torch.LongTensor` of shape `(batch size, 3, num latent pixels)`):
433
+ encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
434
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
435
+ self-attention.
436
+ timestep ( `torch.LongTensor`, *optional*):
437
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
438
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
439
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
440
+ `AdaLayerZeroNorm`.
441
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
442
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
443
+ `self.processor` in
444
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
445
+ attention_mask ( `torch.Tensor`, *optional*):
446
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
447
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
448
+ negative values to the attention scores corresponding to "discard" tokens.
449
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
450
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
451
+
452
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
453
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
454
+
455
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
456
+ above. This bias will be added to the cross-attention scores.
457
+ skip_layer_mask ( `torch.Tensor`, *optional*):
458
+ A mask of shape `(num_layers, batch)` that indicates which layers to skip. `0` at position
459
+ `layer, batch_idx` indicates that the layer should be skipped for the corresponding batch index.
460
+ skip_layer_strategy ( `SkipLayerStrategy`, *optional*, defaults to `None`):
461
+ Controls which layers are skipped when calculating a perturbed latent for spatiotemporal guidance.
462
+ sharding_mesh (xs.Mesh, *optional*, defaults to 'None')
463
+ return_dict (`bool`, *optional*, defaults to `True`):
464
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
465
+ tuple.
466
+
467
+ Returns:
468
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
469
+ `tuple` where the first element is the sample tensor.
470
+ """
471
+ # for tpu attention offload 2d token masks are used. No need to transform.
472
+ if not self.use_tpu_flash_attention:
473
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
474
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
475
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
476
+ # expects mask of shape:
477
+ # [batch, key_tokens]
478
+ # adds singleton query_tokens dimension:
479
+ # [batch, 1, key_tokens]
480
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
481
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
482
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
483
+ if attention_mask is not None and attention_mask.ndim == 2:
484
+ # assume that mask is expressed as:
485
+ # (1 = keep, 0 = discard)
486
+ # convert mask into a bias that can be added to attention scores:
487
+ # (keep = +0, discard = -10000.0)
488
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
489
+ attention_mask = attention_mask.unsqueeze(1)
490
+
491
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
492
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
493
+ encoder_attention_mask = (
494
+ 1 - encoder_attention_mask.to(hidden_states.dtype)
495
+ ) * -10000.0
496
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
497
+
498
+ # 1. Input
499
+ hidden_states = self.patchify_proj(hidden_states)
500
+
501
+ if self.timestep_scale_multiplier:
502
+ timestep = self.timestep_scale_multiplier * timestep
503
+
504
+ if self.positional_embedding_type == "absolute":
505
+ pos_embed_3d = self.get_absolute_pos_embed(indices_grid).to(
506
+ hidden_states.device
507
+ )
508
+ if self.project_to_2d_pos:
509
+ pos_embed = self.to_2d_proj(pos_embed_3d)
510
+ hidden_states = (hidden_states + pos_embed).to(hidden_states.dtype)
511
+ freqs_cis = None
512
+ elif self.positional_embedding_type == "rope":
513
+ freqs_cis = self.precompute_freqs_cis(indices_grid)
514
+
515
+ batch_size = hidden_states.shape[0]
516
+ timestep, embedded_timestep = self.adaln_single(
517
+ timestep.flatten(),
518
+ {"resolution": None, "aspect_ratio": None},
519
+ batch_size=batch_size,
520
+ hidden_dtype=hidden_states.dtype,
521
+ )
522
+ # Second dimension is 1 or number of tokens (if timestep_per_token)
523
+ timestep = timestep.view(batch_size, -1, timestep.shape[-1])
524
+ embedded_timestep = embedded_timestep.view(
525
+ batch_size, -1, embedded_timestep.shape[-1]
526
+ )
527
+
528
+ if skip_layer_mask is None:
529
+ skip_layer_mask = torch.ones(
530
+ len(self.transformer_blocks), batch_size, device=hidden_states.device
531
+ )
532
+
533
+ # 2. Blocks
534
+ if self.caption_projection is not None:
535
+ batch_size = hidden_states.shape[0]
536
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
537
+ encoder_hidden_states = encoder_hidden_states.view(
538
+ batch_size, -1, hidden_states.shape[-1]
539
+ )
540
+
541
+ for block_idx, block in enumerate(self.transformer_blocks):
542
+ if self.training and self.gradient_checkpointing:
543
+
544
+ def create_custom_forward(module, return_dict=None):
545
+ def custom_forward(*inputs):
546
+ if return_dict is not None:
547
+ return module(*inputs, return_dict=return_dict)
548
+ else:
549
+ return module(*inputs)
550
+
551
+ return custom_forward
552
+
553
+ ckpt_kwargs: Dict[str, Any] = (
554
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
555
+ )
556
+ hidden_states = torch.utils.checkpoint.checkpoint(
557
+ create_custom_forward(block),
558
+ hidden_states,
559
+ freqs_cis,
560
+ attention_mask,
561
+ encoder_hidden_states,
562
+ encoder_attention_mask,
563
+ timestep,
564
+ cross_attention_kwargs,
565
+ class_labels,
566
+ sharding_mesh,
567
+ skip_layer_mask[block_idx],
568
+ skip_layer_strategy,
569
+ **ckpt_kwargs,
570
+ )
571
+ else:
572
+ hidden_states = block(
573
+ hidden_states,
574
+ freqs_cis=freqs_cis,
575
+ attention_mask=attention_mask,
576
+ encoder_hidden_states=encoder_hidden_states,
577
+ encoder_attention_mask=encoder_attention_mask,
578
+ timestep=timestep,
579
+ cross_attention_kwargs=cross_attention_kwargs,
580
+ class_labels=class_labels,
581
+ sharding_mesh=sharding_mesh,
582
+ skip_layer_mask=skip_layer_mask[block_idx],
583
+ skip_layer_strategy=skip_layer_strategy,
584
+ )
585
+
586
+ # 3. Output
587
+ scale_shift_values = (
588
+ self.scale_shift_table[None, None] + embedded_timestep[:, :, None]
589
+ )
590
+ shift, scale = scale_shift_values[:, :, 0], scale_shift_values[:, :, 1]
591
+ hidden_states = self.norm_out(hidden_states)
592
+ # Modulation
593
+ hidden_states = hidden_states * (1 + scale) + shift
594
+ hidden_states = self.proj_out(hidden_states)
595
+ if not return_dict:
596
+ return (hidden_states,)
597
+
598
+ return Transformer3DModelOutput(sample=hidden_states)
599
+
600
+ def get_absolute_pos_embed(self, grid):
601
+ grid_np = grid[0].cpu().numpy()
602
+ embed_dim_3d = (
603
+ math.ceil((self.inner_dim / 2) * 3)
604
+ if self.project_to_2d_pos
605
+ else self.inner_dim
606
+ )
607
+ pos_embed = get_3d_sincos_pos_embed( # (f h w)
608
+ embed_dim_3d,
609
+ grid_np,
610
+ h=int(max(grid_np[1]) + 1),
611
+ w=int(max(grid_np[2]) + 1),
612
+ f=int(max(grid_np[0] + 1)),
613
+ )
614
+ return torch.from_numpy(pos_embed).float().unsqueeze(0)
ltx_video/pipelines/__init__.py ADDED
File without changes
ltx_video/pipelines/pipeline_ltx_video.py ADDED
@@ -0,0 +1,1286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py
2
+ import html
3
+ import inspect
4
+ import math
5
+ import re
6
+ import urllib.parse as ul
7
+ from typing import Callable, Dict, List, Optional, Tuple, Union
8
+
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from contextlib import nullcontext
13
+ from diffusers.image_processor import VaeImageProcessor
14
+ from diffusers.models import AutoencoderKL
15
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
16
+ from diffusers.schedulers import DPMSolverMultistepScheduler
17
+ from diffusers.utils import (
18
+ BACKENDS_MAPPING,
19
+ deprecate,
20
+ is_bs4_available,
21
+ is_ftfy_available,
22
+ logging,
23
+ )
24
+ from diffusers.utils.torch_utils import randn_tensor
25
+ from einops import rearrange
26
+ from transformers import T5EncoderModel, T5Tokenizer
27
+
28
+ from ltx_video.models.transformers.transformer3d import Transformer3DModel
29
+ from ltx_video.models.transformers.symmetric_patchifier import Patchifier
30
+ from ltx_video.models.autoencoders.vae_encode import (
31
+ get_vae_size_scale_factor,
32
+ vae_decode,
33
+ vae_encode,
34
+ )
35
+ from ltx_video.models.autoencoders.causal_video_autoencoder import (
36
+ CausalVideoAutoencoder,
37
+ )
38
+ from ltx_video.schedulers.rf import TimestepShifter
39
+ from ltx_video.utils.conditioning_method import ConditioningMethod
40
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
41
+
42
+ try:
43
+ import torch_xla.distributed.spmd as xs
44
+ except ImportError:
45
+ xs = None
46
+
47
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
48
+
49
+ if is_bs4_available():
50
+ from bs4 import BeautifulSoup
51
+
52
+ if is_ftfy_available():
53
+ import ftfy
54
+
55
+ ASPECT_RATIO_1024_BIN = {
56
+ "0.25": [512.0, 2048.0],
57
+ "0.28": [512.0, 1856.0],
58
+ "0.32": [576.0, 1792.0],
59
+ "0.33": [576.0, 1728.0],
60
+ "0.35": [576.0, 1664.0],
61
+ "0.4": [640.0, 1600.0],
62
+ "0.42": [640.0, 1536.0],
63
+ "0.48": [704.0, 1472.0],
64
+ "0.5": [704.0, 1408.0],
65
+ "0.52": [704.0, 1344.0],
66
+ "0.57": [768.0, 1344.0],
67
+ "0.6": [768.0, 1280.0],
68
+ "0.68": [832.0, 1216.0],
69
+ "0.72": [832.0, 1152.0],
70
+ "0.78": [896.0, 1152.0],
71
+ "0.82": [896.0, 1088.0],
72
+ "0.88": [960.0, 1088.0],
73
+ "0.94": [960.0, 1024.0],
74
+ "1.0": [1024.0, 1024.0],
75
+ "1.07": [1024.0, 960.0],
76
+ "1.13": [1088.0, 960.0],
77
+ "1.21": [1088.0, 896.0],
78
+ "1.29": [1152.0, 896.0],
79
+ "1.38": [1152.0, 832.0],
80
+ "1.46": [1216.0, 832.0],
81
+ "1.67": [1280.0, 768.0],
82
+ "1.75": [1344.0, 768.0],
83
+ "2.0": [1408.0, 704.0],
84
+ "2.09": [1472.0, 704.0],
85
+ "2.4": [1536.0, 640.0],
86
+ "2.5": [1600.0, 640.0],
87
+ "3.0": [1728.0, 576.0],
88
+ "4.0": [2048.0, 512.0],
89
+ }
90
+
91
+ ASPECT_RATIO_512_BIN = {
92
+ "0.25": [256.0, 1024.0],
93
+ "0.28": [256.0, 928.0],
94
+ "0.32": [288.0, 896.0],
95
+ "0.33": [288.0, 864.0],
96
+ "0.35": [288.0, 832.0],
97
+ "0.4": [320.0, 800.0],
98
+ "0.42": [320.0, 768.0],
99
+ "0.48": [352.0, 736.0],
100
+ "0.5": [352.0, 704.0],
101
+ "0.52": [352.0, 672.0],
102
+ "0.57": [384.0, 672.0],
103
+ "0.6": [384.0, 640.0],
104
+ "0.68": [416.0, 608.0],
105
+ "0.72": [416.0, 576.0],
106
+ "0.78": [448.0, 576.0],
107
+ "0.82": [448.0, 544.0],
108
+ "0.88": [480.0, 544.0],
109
+ "0.94": [480.0, 512.0],
110
+ "1.0": [512.0, 512.0],
111
+ "1.07": [512.0, 480.0],
112
+ "1.13": [544.0, 480.0],
113
+ "1.21": [544.0, 448.0],
114
+ "1.29": [576.0, 448.0],
115
+ "1.38": [576.0, 416.0],
116
+ "1.46": [608.0, 416.0],
117
+ "1.67": [640.0, 384.0],
118
+ "1.75": [672.0, 384.0],
119
+ "2.0": [704.0, 352.0],
120
+ "2.09": [736.0, 352.0],
121
+ "2.4": [768.0, 320.0],
122
+ "2.5": [800.0, 320.0],
123
+ "3.0": [864.0, 288.0],
124
+ "4.0": [1024.0, 256.0],
125
+ }
126
+
127
+
128
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
129
+ def retrieve_timesteps(
130
+ scheduler,
131
+ num_inference_steps: Optional[int] = None,
132
+ device: Optional[Union[str, torch.device]] = None,
133
+ timesteps: Optional[List[int]] = None,
134
+ **kwargs,
135
+ ):
136
+ """
137
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
138
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
139
+
140
+ Args:
141
+ scheduler (`SchedulerMixin`):
142
+ The scheduler to get timesteps from.
143
+ num_inference_steps (`int`):
144
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
145
+ `timesteps` must be `None`.
146
+ device (`str` or `torch.device`, *optional*):
147
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
148
+ timesteps (`List[int]`, *optional*):
149
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
150
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
151
+ must be `None`.
152
+
153
+ Returns:
154
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
155
+ second element is the number of inference steps.
156
+ """
157
+ if timesteps is not None:
158
+ accepts_timesteps = "timesteps" in set(
159
+ inspect.signature(scheduler.set_timesteps).parameters.keys()
160
+ )
161
+ if not accepts_timesteps:
162
+ raise ValueError(
163
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
164
+ f" timestep schedules. Please check whether you are using the correct scheduler."
165
+ )
166
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
167
+ timesteps = scheduler.timesteps
168
+ num_inference_steps = len(timesteps)
169
+ else:
170
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
171
+ timesteps = scheduler.timesteps
172
+ return timesteps, num_inference_steps
173
+
174
+
175
+ class LTXVideoPipeline(DiffusionPipeline):
176
+ r"""
177
+ Pipeline for text-to-image generation using LTX-Video.
178
+
179
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
180
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
181
+
182
+ Args:
183
+ vae ([`AutoencoderKL`]):
184
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
185
+ text_encoder ([`T5EncoderModel`]):
186
+ Frozen text-encoder. This uses
187
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
188
+ [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
189
+ tokenizer (`T5Tokenizer`):
190
+ Tokenizer of class
191
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
192
+ transformer ([`Transformer2DModel`]):
193
+ A text conditioned `Transformer2DModel` to denoise the encoded image latents.
194
+ scheduler ([`SchedulerMixin`]):
195
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
196
+ """
197
+
198
+ bad_punct_regex = re.compile(
199
+ r"["
200
+ + "#®•©™&@·º½¾¿¡§~"
201
+ + r"\)"
202
+ + r"\("
203
+ + r"\]"
204
+ + r"\["
205
+ + r"\}"
206
+ + r"\{"
207
+ + r"\|"
208
+ + "\\"
209
+ + r"\/"
210
+ + r"\*"
211
+ + r"]{1,}"
212
+ ) # noqa
213
+
214
+ _optional_components = ["tokenizer", "text_encoder"]
215
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
216
+
217
+ def __init__(
218
+ self,
219
+ tokenizer: T5Tokenizer,
220
+ text_encoder: T5EncoderModel,
221
+ vae: AutoencoderKL,
222
+ transformer: Transformer3DModel,
223
+ scheduler: DPMSolverMultistepScheduler,
224
+ patchifier: Patchifier,
225
+ ):
226
+ super().__init__()
227
+
228
+ self.register_modules(
229
+ tokenizer=tokenizer,
230
+ text_encoder=text_encoder,
231
+ vae=vae,
232
+ transformer=transformer,
233
+ scheduler=scheduler,
234
+ patchifier=patchifier,
235
+ )
236
+
237
+ self.video_scale_factor, self.vae_scale_factor, _ = get_vae_size_scale_factor(
238
+ self.vae
239
+ )
240
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
241
+
242
+ def mask_text_embeddings(self, emb, mask):
243
+ if emb.shape[0] == 1:
244
+ keep_index = mask.sum().item()
245
+ return emb[:, :, :keep_index, :], keep_index
246
+ else:
247
+ masked_feature = emb * mask[:, None, :, None]
248
+ return masked_feature, emb.shape[2]
249
+
250
+ # Adapted from diffusers.pipelines.deepfloyd_if.pipeline_if.encode_prompt
251
+ def encode_prompt(
252
+ self,
253
+ prompt: Union[str, List[str]],
254
+ do_classifier_free_guidance: bool = True,
255
+ negative_prompt: str = "",
256
+ num_images_per_prompt: int = 1,
257
+ device: Optional[torch.device] = None,
258
+ prompt_embeds: Optional[torch.FloatTensor] = None,
259
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
260
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
261
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
262
+ clean_caption: bool = False,
263
+ **kwargs,
264
+ ):
265
+ r"""
266
+ Encodes the prompt into text encoder hidden states.
267
+
268
+ Args:
269
+ prompt (`str` or `List[str]`, *optional*):
270
+ prompt to be encoded
271
+ negative_prompt (`str` or `List[str]`, *optional*):
272
+ The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
273
+ instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). For
274
+ This should be "".
275
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
276
+ whether to use classifier free guidance or not
277
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
278
+ number of images that should be generated per prompt
279
+ device: (`torch.device`, *optional*):
280
+ torch device to place the resulting embeddings on
281
+ prompt_embeds (`torch.FloatTensor`, *optional*):
282
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
283
+ provided, text embeddings will be generated from `prompt` input argument.
284
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
285
+ Pre-generated negative text embeddings.
286
+ clean_caption (bool, defaults to `False`):
287
+ If `True`, the function will preprocess and clean the provided caption before encoding.
288
+ """
289
+
290
+ if "mask_feature" in kwargs:
291
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
292
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
293
+
294
+ if device is None:
295
+ device = self._execution_device
296
+
297
+ if prompt is not None and isinstance(prompt, str):
298
+ batch_size = 1
299
+ elif prompt is not None and isinstance(prompt, list):
300
+ batch_size = len(prompt)
301
+ else:
302
+ batch_size = prompt_embeds.shape[0]
303
+
304
+ # See Section 3.1. of the paper.
305
+ # FIXME: to be configured in config not hardecoded. Fix in separate PR with rest of config
306
+ max_length = 128 # TPU supports only lengths multiple of 128
307
+ text_enc_device = next(self.text_encoder.parameters()).device
308
+ if prompt_embeds is None:
309
+ prompt = self._text_preprocessing(prompt, clean_caption=clean_caption)
310
+ text_inputs = self.tokenizer(
311
+ prompt,
312
+ padding="max_length",
313
+ max_length=max_length,
314
+ truncation=True,
315
+ add_special_tokens=True,
316
+ return_tensors="pt",
317
+ )
318
+ text_input_ids = text_inputs.input_ids
319
+ untruncated_ids = self.tokenizer(
320
+ prompt, padding="longest", return_tensors="pt"
321
+ ).input_ids
322
+
323
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[
324
+ -1
325
+ ] and not torch.equal(text_input_ids, untruncated_ids):
326
+ removed_text = self.tokenizer.batch_decode(
327
+ untruncated_ids[:, max_length - 1 : -1]
328
+ )
329
+ logger.warning(
330
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
331
+ f" {max_length} tokens: {removed_text}"
332
+ )
333
+
334
+ prompt_attention_mask = text_inputs.attention_mask
335
+ prompt_attention_mask = prompt_attention_mask.to(text_enc_device)
336
+ prompt_attention_mask = prompt_attention_mask.to(device)
337
+
338
+ prompt_embeds = self.text_encoder(
339
+ text_input_ids.to(text_enc_device), attention_mask=prompt_attention_mask
340
+ )
341
+ prompt_embeds = prompt_embeds[0]
342
+
343
+ if self.text_encoder is not None:
344
+ dtype = self.text_encoder.dtype
345
+ elif self.transformer is not None:
346
+ dtype = self.transformer.dtype
347
+ else:
348
+ dtype = None
349
+
350
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
351
+
352
+ bs_embed, seq_len, _ = prompt_embeds.shape
353
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
354
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
355
+ prompt_embeds = prompt_embeds.view(
356
+ bs_embed * num_images_per_prompt, seq_len, -1
357
+ )
358
+ prompt_attention_mask = prompt_attention_mask.repeat(1, num_images_per_prompt)
359
+ prompt_attention_mask = prompt_attention_mask.view(
360
+ bs_embed * num_images_per_prompt, -1
361
+ )
362
+
363
+ # get unconditional embeddings for classifier free guidance
364
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
365
+ uncond_tokens = [negative_prompt] * batch_size
366
+ uncond_tokens = self._text_preprocessing(
367
+ uncond_tokens, clean_caption=clean_caption
368
+ )
369
+ max_length = prompt_embeds.shape[1]
370
+ uncond_input = self.tokenizer(
371
+ uncond_tokens,
372
+ padding="max_length",
373
+ max_length=max_length,
374
+ truncation=True,
375
+ return_attention_mask=True,
376
+ add_special_tokens=True,
377
+ return_tensors="pt",
378
+ )
379
+ negative_prompt_attention_mask = uncond_input.attention_mask
380
+ negative_prompt_attention_mask = negative_prompt_attention_mask.to(
381
+ text_enc_device
382
+ )
383
+
384
+ negative_prompt_embeds = self.text_encoder(
385
+ uncond_input.input_ids.to(text_enc_device),
386
+ attention_mask=negative_prompt_attention_mask,
387
+ )
388
+ negative_prompt_embeds = negative_prompt_embeds[0]
389
+
390
+ if do_classifier_free_guidance:
391
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
392
+ seq_len = negative_prompt_embeds.shape[1]
393
+
394
+ negative_prompt_embeds = negative_prompt_embeds.to(
395
+ dtype=dtype, device=device
396
+ )
397
+
398
+ negative_prompt_embeds = negative_prompt_embeds.repeat(
399
+ 1, num_images_per_prompt, 1
400
+ )
401
+ negative_prompt_embeds = negative_prompt_embeds.view(
402
+ batch_size * num_images_per_prompt, seq_len, -1
403
+ )
404
+
405
+ negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(
406
+ 1, num_images_per_prompt
407
+ )
408
+ negative_prompt_attention_mask = negative_prompt_attention_mask.view(
409
+ bs_embed * num_images_per_prompt, -1
410
+ )
411
+ else:
412
+ negative_prompt_embeds = None
413
+ negative_prompt_attention_mask = None
414
+
415
+ return (
416
+ prompt_embeds,
417
+ prompt_attention_mask,
418
+ negative_prompt_embeds,
419
+ negative_prompt_attention_mask,
420
+ )
421
+
422
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
423
+ def prepare_extra_step_kwargs(self, generator, eta):
424
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
425
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
426
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
427
+ # and should be between [0, 1]
428
+
429
+ accepts_eta = "eta" in set(
430
+ inspect.signature(self.scheduler.step).parameters.keys()
431
+ )
432
+ extra_step_kwargs = {}
433
+ if accepts_eta:
434
+ extra_step_kwargs["eta"] = eta
435
+
436
+ # check if the scheduler accepts generator
437
+ accepts_generator = "generator" in set(
438
+ inspect.signature(self.scheduler.step).parameters.keys()
439
+ )
440
+ if accepts_generator:
441
+ extra_step_kwargs["generator"] = generator
442
+ return extra_step_kwargs
443
+
444
+ def check_inputs(
445
+ self,
446
+ prompt,
447
+ height,
448
+ width,
449
+ negative_prompt,
450
+ prompt_embeds=None,
451
+ negative_prompt_embeds=None,
452
+ prompt_attention_mask=None,
453
+ negative_prompt_attention_mask=None,
454
+ ):
455
+ if height % 8 != 0 or width % 8 != 0:
456
+ raise ValueError(
457
+ f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
458
+ )
459
+
460
+ if prompt is not None and prompt_embeds is not None:
461
+ raise ValueError(
462
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
463
+ " only forward one of the two."
464
+ )
465
+ elif prompt is None and prompt_embeds is None:
466
+ raise ValueError(
467
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
468
+ )
469
+ elif prompt is not None and (
470
+ not isinstance(prompt, str) and not isinstance(prompt, list)
471
+ ):
472
+ raise ValueError(
473
+ f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
474
+ )
475
+
476
+ if prompt is not None and negative_prompt_embeds is not None:
477
+ raise ValueError(
478
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
479
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
480
+ )
481
+
482
+ if negative_prompt is not None and negative_prompt_embeds is not None:
483
+ raise ValueError(
484
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
485
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
486
+ )
487
+
488
+ if prompt_embeds is not None and prompt_attention_mask is None:
489
+ raise ValueError(
490
+ "Must provide `prompt_attention_mask` when specifying `prompt_embeds`."
491
+ )
492
+
493
+ if (
494
+ negative_prompt_embeds is not None
495
+ and negative_prompt_attention_mask is None
496
+ ):
497
+ raise ValueError(
498
+ "Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`."
499
+ )
500
+
501
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
502
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
503
+ raise ValueError(
504
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
505
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
506
+ f" {negative_prompt_embeds.shape}."
507
+ )
508
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
509
+ raise ValueError(
510
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
511
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
512
+ f" {negative_prompt_attention_mask.shape}."
513
+ )
514
+
515
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessing
516
+ def _text_preprocessing(self, text, clean_caption=False):
517
+ if clean_caption and not is_bs4_available():
518
+ logger.warn(
519
+ BACKENDS_MAPPING["bs4"][-1].format("Setting `clean_caption=True`")
520
+ )
521
+ logger.warn("Setting `clean_caption` to False...")
522
+ clean_caption = False
523
+
524
+ if clean_caption and not is_ftfy_available():
525
+ logger.warn(
526
+ BACKENDS_MAPPING["ftfy"][-1].format("Setting `clean_caption=True`")
527
+ )
528
+ logger.warn("Setting `clean_caption` to False...")
529
+ clean_caption = False
530
+
531
+ if not isinstance(text, (tuple, list)):
532
+ text = [text]
533
+
534
+ def process(text: str):
535
+ if clean_caption:
536
+ text = self._clean_caption(text)
537
+ text = self._clean_caption(text)
538
+ else:
539
+ text = text.lower().strip()
540
+ return text
541
+
542
+ return [process(t) for t in text]
543
+
544
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._clean_caption
545
+ def _clean_caption(self, caption):
546
+ caption = str(caption)
547
+ caption = ul.unquote_plus(caption)
548
+ caption = caption.strip().lower()
549
+ caption = re.sub("<person>", "person", caption)
550
+ # urls:
551
+ caption = re.sub(
552
+ r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
553
+ "",
554
+ caption,
555
+ ) # regex for urls
556
+ caption = re.sub(
557
+ r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
558
+ "",
559
+ caption,
560
+ ) # regex for urls
561
+ # html:
562
+ caption = BeautifulSoup(caption, features="html.parser").text
563
+
564
+ # @<nickname>
565
+ caption = re.sub(r"@[\w\d]+\b", "", caption)
566
+
567
+ # 31C0—31EF CJK Strokes
568
+ # 31F0—31FF Katakana Phonetic Extensions
569
+ # 3200—32FF Enclosed CJK Letters and Months
570
+ # 3300—33FF CJK Compatibility
571
+ # 3400—4DBF CJK Unified Ideographs Extension A
572
+ # 4DC0—4DFF Yijing Hexagram Symbols
573
+ # 4E00—9FFF CJK Unified Ideographs
574
+ caption = re.sub(r"[\u31c0-\u31ef]+", "", caption)
575
+ caption = re.sub(r"[\u31f0-\u31ff]+", "", caption)
576
+ caption = re.sub(r"[\u3200-\u32ff]+", "", caption)
577
+ caption = re.sub(r"[\u3300-\u33ff]+", "", caption)
578
+ caption = re.sub(r"[\u3400-\u4dbf]+", "", caption)
579
+ caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption)
580
+ caption = re.sub(r"[\u4e00-\u9fff]+", "", caption)
581
+ #######################################################
582
+
583
+ # все виды тире / all types of dash --> "-"
584
+ caption = re.sub(
585
+ r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa
586
+ "-",
587
+ caption,
588
+ )
589
+
590
+ # кавычки к одному стандарту
591
+ caption = re.sub(r"[`´«»“”¨]", '"', caption)
592
+ caption = re.sub(r"[‘’]", "'", caption)
593
+
594
+ # &quot;
595
+ caption = re.sub(r"&quot;?", "", caption)
596
+ # &amp
597
+ caption = re.sub(r"&amp", "", caption)
598
+
599
+ # ip adresses:
600
+ caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption)
601
+
602
+ # article ids:
603
+ caption = re.sub(r"\d:\d\d\s+$", "", caption)
604
+
605
+ # \n
606
+ caption = re.sub(r"\\n", " ", caption)
607
+
608
+ # "#123"
609
+ caption = re.sub(r"#\d{1,3}\b", "", caption)
610
+ # "#12345.."
611
+ caption = re.sub(r"#\d{5,}\b", "", caption)
612
+ # "123456.."
613
+ caption = re.sub(r"\b\d{6,}\b", "", caption)
614
+ # filenames:
615
+ caption = re.sub(
616
+ r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption
617
+ )
618
+
619
+ #
620
+ caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT"""
621
+ caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT"""
622
+
623
+ caption = re.sub(
624
+ self.bad_punct_regex, r" ", caption
625
+ ) # ***AUSVERKAUFT***, #AUSVERKAUFT
626
+ caption = re.sub(r"\s+\.\s+", r" ", caption) # " . "
627
+
628
+ # this-is-my-cute-cat / this_is_my_cute_cat
629
+ regex2 = re.compile(r"(?:\-|\_)")
630
+ if len(re.findall(regex2, caption)) > 3:
631
+ caption = re.sub(regex2, " ", caption)
632
+
633
+ caption = ftfy.fix_text(caption)
634
+ caption = html.unescape(html.unescape(caption))
635
+
636
+ caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640
637
+ caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc
638
+ caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231
639
+
640
+ caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption)
641
+ caption = re.sub(r"(free\s)?download(\sfree)?", "", caption)
642
+ caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption)
643
+ caption = re.sub(
644
+ r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption
645
+ )
646
+ caption = re.sub(r"\bpage\s+\d+\b", "", caption)
647
+
648
+ caption = re.sub(
649
+ r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption
650
+ ) # j2d1a2a...
651
+
652
+ caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption)
653
+
654
+ caption = re.sub(r"\b\s+\:\s+", r": ", caption)
655
+ caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption)
656
+ caption = re.sub(r"\s+", " ", caption)
657
+
658
+ caption.strip()
659
+
660
+ caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption)
661
+ caption = re.sub(r"^[\'\_,\-\:;]", r"", caption)
662
+ caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption)
663
+ caption = re.sub(r"^\.\S+$", "", caption)
664
+
665
+ return caption.strip()
666
+
667
+ def image_cond_noise_update(
668
+ self,
669
+ t,
670
+ init_latents,
671
+ latents,
672
+ noise_scale,
673
+ conditiong_mask,
674
+ generator,
675
+ ):
676
+ noise = randn_tensor(
677
+ latents.shape,
678
+ generator=generator,
679
+ device=latents.device,
680
+ dtype=latents.dtype,
681
+ )
682
+ latents = (init_latents + noise_scale * noise * (t**2)) * conditiong_mask[
683
+ ..., None
684
+ ] + latents * (1 - conditiong_mask[..., None])
685
+ return latents
686
+
687
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
688
+ def prepare_latents(
689
+ self,
690
+ batch_size,
691
+ num_latent_channels,
692
+ num_patches,
693
+ dtype,
694
+ device,
695
+ generator,
696
+ latents=None,
697
+ latents_mask=None,
698
+ ):
699
+ shape = (
700
+ batch_size,
701
+ num_patches // math.prod(self.patchifier.patch_size),
702
+ num_latent_channels,
703
+ )
704
+
705
+ if isinstance(generator, list) and len(generator) != batch_size:
706
+ raise ValueError(
707
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
708
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
709
+ )
710
+
711
+ if latents is None:
712
+ latents = randn_tensor(
713
+ shape, generator=generator, device=generator.device, dtype=dtype
714
+ )
715
+ elif latents_mask is not None:
716
+ noise = randn_tensor(
717
+ shape, generator=generator, device=generator.device, dtype=dtype
718
+ )
719
+ latents = latents * latents_mask[..., None] + noise * (
720
+ 1 - latents_mask[..., None]
721
+ )
722
+ else:
723
+ latents = latents.to(device)
724
+
725
+ # scale the initial noise by the standard deviation required by the scheduler
726
+ latents = latents * self.scheduler.init_noise_sigma
727
+ return latents
728
+
729
+ @staticmethod
730
+ def classify_height_width_bin(
731
+ height: int, width: int, ratios: dict
732
+ ) -> Tuple[int, int]:
733
+ """Returns binned height and width."""
734
+ ar = float(height / width)
735
+ closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
736
+ default_hw = ratios[closest_ratio]
737
+ return int(default_hw[0]), int(default_hw[1])
738
+
739
+ @staticmethod
740
+ def resize_and_crop_tensor(
741
+ samples: torch.Tensor, new_width: int, new_height: int
742
+ ) -> torch.Tensor:
743
+ n_frames, orig_height, orig_width = samples.shape[-3:]
744
+
745
+ # Check if resizing is needed
746
+ if orig_height != new_height or orig_width != new_width:
747
+ ratio = max(new_height / orig_height, new_width / orig_width)
748
+ resized_width = int(orig_width * ratio)
749
+ resized_height = int(orig_height * ratio)
750
+
751
+ # Resize
752
+ samples = rearrange(samples, "b c n h w -> (b n) c h w")
753
+ samples = F.interpolate(
754
+ samples,
755
+ size=(resized_height, resized_width),
756
+ mode="bilinear",
757
+ align_corners=False,
758
+ )
759
+ samples = rearrange(samples, "(b n) c h w -> b c n h w", n=n_frames)
760
+
761
+ # Center Crop
762
+ start_x = (resized_width - new_width) // 2
763
+ end_x = start_x + new_width
764
+ start_y = (resized_height - new_height) // 2
765
+ end_y = start_y + new_height
766
+ samples = samples[..., start_y:end_y, start_x:end_x]
767
+
768
+ return samples
769
+
770
+ @torch.no_grad()
771
+ def __call__(
772
+ self,
773
+ height: int,
774
+ width: int,
775
+ num_frames: int,
776
+ frame_rate: float,
777
+ prompt: Union[str, List[str]] = None,
778
+ negative_prompt: str = "",
779
+ num_inference_steps: int = 20,
780
+ timesteps: List[int] = None,
781
+ guidance_scale: float = 4.5,
782
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
783
+ skip_block_list: List[int] = None,
784
+ stg_scale: float = 1.0,
785
+ do_rescaling: bool = True,
786
+ rescaling_scale: float = 0.7,
787
+ num_images_per_prompt: Optional[int] = 1,
788
+ eta: float = 0.0,
789
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
790
+ latents: Optional[torch.FloatTensor] = None,
791
+ prompt_embeds: Optional[torch.FloatTensor] = None,
792
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
793
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
794
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
795
+ output_type: Optional[str] = "pil",
796
+ return_dict: bool = True,
797
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
798
+ clean_caption: bool = True,
799
+ media_items: Optional[torch.FloatTensor] = None,
800
+ decode_timestep: Union[List[float], float] = 0.0,
801
+ decode_noise_scale: Optional[List[float]] = None,
802
+ mixed_precision: bool = False,
803
+ offload_to_cpu: bool = False,
804
+ **kwargs,
805
+ ) -> Union[ImagePipelineOutput, Tuple]:
806
+ """
807
+ Function invoked when calling the pipeline for generation.
808
+
809
+ Args:
810
+ prompt (`str` or `List[str]`, *optional*):
811
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
812
+ instead.
813
+ negative_prompt (`str` or `List[str]`, *optional*):
814
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
815
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
816
+ less than `1`).
817
+ num_inference_steps (`int`, *optional*, defaults to 100):
818
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
819
+ expense of slower inference.
820
+ timesteps (`List[int]`, *optional*):
821
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
822
+ timesteps are used. Must be in descending order.
823
+ guidance_scale (`float`, *optional*, defaults to 4.5):
824
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
825
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
826
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
827
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
828
+ usually at the expense of lower image quality.
829
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
830
+ The number of images to generate per prompt.
831
+ height (`int`, *optional*, defaults to self.unet.config.sample_size):
832
+ The height in pixels of the generated image.
833
+ width (`int`, *optional*, defaults to self.unet.config.sample_size):
834
+ The width in pixels of the generated image.
835
+ eta (`float`, *optional*, defaults to 0.0):
836
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
837
+ [`schedulers.DDIMScheduler`], will be ignored for others.
838
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
839
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
840
+ to make generation deterministic.
841
+ latents (`torch.FloatTensor`, *optional*):
842
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
843
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
844
+ tensor will ge generated by sampling using the supplied random `generator`.
845
+ prompt_embeds (`torch.FloatTensor`, *optional*):
846
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
847
+ provided, text embeddings will be generated from `prompt` input argument.
848
+ prompt_attention_mask (`torch.FloatTensor`, *optional*): Pre-generated attention mask for text embeddings.
849
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
850
+ Pre-generated negative text embeddings. This negative prompt should be "". If not
851
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
852
+ negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
853
+ Pre-generated attention mask for negative text embeddings.
854
+ output_type (`str`, *optional*, defaults to `"pil"`):
855
+ The output format of the generate image. Choose between
856
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
857
+ return_dict (`bool`, *optional*, defaults to `True`):
858
+ Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
859
+ callback_on_step_end (`Callable`, *optional*):
860
+ A function that calls at the end of each denoising steps during the inference. The function is called
861
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
862
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
863
+ `callback_on_step_end_tensor_inputs`.
864
+ clean_caption (`bool`, *optional*, defaults to `True`):
865
+ Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
866
+ be installed. If the dependencies are not installed, the embeddings will be created from the raw
867
+ prompt.
868
+ use_resolution_binning (`bool` defaults to `True`):
869
+ If set to `True`, the requested height and width are first mapped to the closest resolutions using
870
+ `ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
871
+ the requested resolution. Useful for generating non-square images.
872
+
873
+ Examples:
874
+
875
+ Returns:
876
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
877
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
878
+ returned where the first element is a list with the generated images
879
+ """
880
+ if "mask_feature" in kwargs:
881
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
882
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
883
+
884
+ is_video = kwargs.get("is_video", False)
885
+ self.check_inputs(
886
+ prompt,
887
+ height,
888
+ width,
889
+ negative_prompt,
890
+ prompt_embeds,
891
+ negative_prompt_embeds,
892
+ prompt_attention_mask,
893
+ negative_prompt_attention_mask,
894
+ )
895
+
896
+ # 2. Default height and width to transformer
897
+ if prompt is not None and isinstance(prompt, str):
898
+ batch_size = 1
899
+ elif prompt is not None and isinstance(prompt, list):
900
+ batch_size = len(prompt)
901
+ else:
902
+ batch_size = prompt_embeds.shape[0]
903
+
904
+ device = self._execution_device
905
+
906
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
907
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
908
+ # corresponds to doing no classifier free guidance.
909
+ do_classifier_free_guidance = guidance_scale > 1.0
910
+ do_spatio_temporal_guidance = stg_scale > 0.0
911
+
912
+ num_conds = 1
913
+ if do_classifier_free_guidance:
914
+ num_conds += 1
915
+ if do_spatio_temporal_guidance:
916
+ num_conds += 1
917
+
918
+ skip_layer_mask = None
919
+ if do_spatio_temporal_guidance:
920
+ skip_layer_mask = self.transformer.create_skip_layer_mask(
921
+ skip_block_list, batch_size, num_conds, 2
922
+ )
923
+
924
+ # 3. Encode input prompt
925
+ self.text_encoder = self.text_encoder.to(self._execution_device)
926
+
927
+ (
928
+ prompt_embeds,
929
+ prompt_attention_mask,
930
+ negative_prompt_embeds,
931
+ negative_prompt_attention_mask,
932
+ ) = self.encode_prompt(
933
+ prompt,
934
+ do_classifier_free_guidance,
935
+ negative_prompt=negative_prompt,
936
+ num_images_per_prompt=num_images_per_prompt,
937
+ device=device,
938
+ prompt_embeds=prompt_embeds,
939
+ negative_prompt_embeds=negative_prompt_embeds,
940
+ prompt_attention_mask=prompt_attention_mask,
941
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
942
+ clean_caption=clean_caption,
943
+ )
944
+
945
+ if offload_to_cpu:
946
+ self.text_encoder = self.text_encoder.cpu()
947
+
948
+ self.transformer = self.transformer.to(self._execution_device)
949
+
950
+ prompt_embeds_batch = prompt_embeds
951
+ prompt_attention_mask_batch = prompt_attention_mask
952
+ if do_classifier_free_guidance:
953
+ prompt_embeds_batch = torch.cat(
954
+ [negative_prompt_embeds, prompt_embeds], dim=0
955
+ )
956
+ prompt_attention_mask_batch = torch.cat(
957
+ [negative_prompt_attention_mask, prompt_attention_mask], dim=0
958
+ )
959
+ if do_spatio_temporal_guidance:
960
+ prompt_embeds_batch = torch.cat([prompt_embeds_batch, prompt_embeds], dim=0)
961
+ prompt_attention_mask_batch = torch.cat(
962
+ [
963
+ prompt_attention_mask_batch,
964
+ prompt_attention_mask,
965
+ ],
966
+ dim=0,
967
+ )
968
+
969
+ # 3b. Encode and prepare conditioning data
970
+ self.video_scale_factor = self.video_scale_factor if is_video else 1
971
+ conditioning_method = kwargs.get("conditioning_method", None)
972
+ vae_per_channel_normalize = kwargs.get("vae_per_channel_normalize", False)
973
+ image_cond_noise_scale = kwargs.get("image_cond_noise_scale", 0.0)
974
+ init_latents, conditioning_mask = self.prepare_conditioning(
975
+ media_items,
976
+ num_frames,
977
+ height,
978
+ width,
979
+ conditioning_method,
980
+ vae_per_channel_normalize,
981
+ )
982
+
983
+ # 4. Prepare latents.
984
+ latent_height = height // self.vae_scale_factor
985
+ latent_width = width // self.vae_scale_factor
986
+ latent_num_frames = num_frames // self.video_scale_factor
987
+ if isinstance(self.vae, CausalVideoAutoencoder) and is_video:
988
+ latent_num_frames += 1
989
+ latent_frame_rate = frame_rate / self.video_scale_factor
990
+ num_latent_patches = latent_height * latent_width * latent_num_frames
991
+ latents = self.prepare_latents(
992
+ batch_size=batch_size * num_images_per_prompt,
993
+ num_latent_channels=self.transformer.config.in_channels,
994
+ num_patches=num_latent_patches,
995
+ dtype=prompt_embeds_batch.dtype,
996
+ device=device,
997
+ generator=generator,
998
+ latents=init_latents,
999
+ latents_mask=conditioning_mask,
1000
+ )
1001
+ orig_conditiong_mask = conditioning_mask
1002
+ if conditioning_mask is not None and is_video:
1003
+ assert num_images_per_prompt == 1
1004
+ conditioning_mask = (
1005
+ torch.cat([conditioning_mask] * num_conds)
1006
+ if num_conds > 1
1007
+ else conditioning_mask
1008
+ )
1009
+
1010
+ # 5. Prepare timesteps
1011
+ retrieve_timesteps_kwargs = {}
1012
+ if isinstance(self.scheduler, TimestepShifter):
1013
+ retrieve_timesteps_kwargs["samples"] = latents
1014
+ timesteps, num_inference_steps = retrieve_timesteps(
1015
+ self.scheduler,
1016
+ num_inference_steps,
1017
+ device,
1018
+ timesteps,
1019
+ **retrieve_timesteps_kwargs,
1020
+ )
1021
+
1022
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1023
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1024
+
1025
+ # 7. Denoising loop
1026
+ num_warmup_steps = max(
1027
+ len(timesteps) - num_inference_steps * self.scheduler.order, 0
1028
+ )
1029
+
1030
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1031
+ for i, t in enumerate(timesteps):
1032
+ if conditioning_method == ConditioningMethod.FIRST_FRAME:
1033
+ latents = self.image_cond_noise_update(
1034
+ t,
1035
+ init_latents,
1036
+ latents,
1037
+ image_cond_noise_scale,
1038
+ orig_conditiong_mask,
1039
+ generator,
1040
+ )
1041
+
1042
+ latent_model_input = (
1043
+ torch.cat([latents] * num_conds) if num_conds > 1 else latents
1044
+ )
1045
+ latent_model_input = self.scheduler.scale_model_input(
1046
+ latent_model_input, t
1047
+ )
1048
+
1049
+ latent_frame_rates = (
1050
+ torch.ones(
1051
+ latent_model_input.shape[0], 1, device=latent_model_input.device
1052
+ )
1053
+ * latent_frame_rate
1054
+ )
1055
+
1056
+ current_timestep = t
1057
+ if not torch.is_tensor(current_timestep):
1058
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
1059
+ # This would be a good case for the `match` statement (Python 3.10+)
1060
+ is_mps = latent_model_input.device.type == "mps"
1061
+ if isinstance(current_timestep, float):
1062
+ dtype = torch.float32 if is_mps else torch.float64
1063
+ else:
1064
+ dtype = torch.int32 if is_mps else torch.int64
1065
+ current_timestep = torch.tensor(
1066
+ [current_timestep],
1067
+ dtype=dtype,
1068
+ device=latent_model_input.device,
1069
+ )
1070
+ elif len(current_timestep.shape) == 0:
1071
+ current_timestep = current_timestep[None].to(
1072
+ latent_model_input.device
1073
+ )
1074
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1075
+ current_timestep = current_timestep.expand(
1076
+ latent_model_input.shape[0]
1077
+ ).unsqueeze(-1)
1078
+ scale_grid = (
1079
+ (
1080
+ 1 / latent_frame_rates,
1081
+ self.vae_scale_factor,
1082
+ self.vae_scale_factor,
1083
+ )
1084
+ if self.transformer.use_rope
1085
+ else None
1086
+ )
1087
+ indices_grid = self.patchifier.get_grid(
1088
+ orig_num_frames=latent_num_frames,
1089
+ orig_height=latent_height,
1090
+ orig_width=latent_width,
1091
+ batch_size=latent_model_input.shape[0],
1092
+ scale_grid=scale_grid,
1093
+ device=latents.device,
1094
+ )
1095
+
1096
+ if conditioning_mask is not None:
1097
+ current_timestep = current_timestep * (1 - conditioning_mask)
1098
+ # Choose the appropriate context manager based on `mixed_precision`
1099
+ if mixed_precision:
1100
+ if "xla" in device.type:
1101
+ raise NotImplementedError(
1102
+ "Mixed precision is not supported yet on XLA devices."
1103
+ )
1104
+
1105
+ context_manager = torch.autocast(device.type, dtype=torch.bfloat16)
1106
+ else:
1107
+ context_manager = nullcontext() # Dummy context manager
1108
+
1109
+ mesh = kwargs.get("mesh", None)
1110
+ if xs is not None and mesh is not None:
1111
+ xs.mark_sharding(
1112
+ latent_model_input, mesh, (("dcn", "data"), "sequence", None)
1113
+ )
1114
+
1115
+ # predict noise model_output
1116
+ with context_manager:
1117
+ noise_pred = self.transformer(
1118
+ latent_model_input.to(self.transformer.dtype),
1119
+ indices_grid,
1120
+ encoder_hidden_states=prompt_embeds_batch.to(
1121
+ self.transformer.dtype
1122
+ ),
1123
+ encoder_attention_mask=prompt_attention_mask_batch,
1124
+ timestep=current_timestep,
1125
+ sharding_mesh=mesh,
1126
+ skip_layer_mask=skip_layer_mask,
1127
+ skip_layer_strategy=skip_layer_strategy,
1128
+ return_dict=False,
1129
+ )[0]
1130
+
1131
+ # perform guidance
1132
+ if do_spatio_temporal_guidance:
1133
+ noise_pred_text_perturb = noise_pred[-1:]
1134
+ if do_classifier_free_guidance:
1135
+ noise_pred_uncond, noise_pred_text = noise_pred[:2].chunk(2)
1136
+ noise_pred = noise_pred_uncond + guidance_scale * (
1137
+ noise_pred_text - noise_pred_uncond
1138
+ )
1139
+ if do_spatio_temporal_guidance:
1140
+ noise_pred = noise_pred + stg_scale * (
1141
+ noise_pred_text - noise_pred_text_perturb
1142
+ )
1143
+ if do_rescaling:
1144
+ factor = noise_pred_text.std() / noise_pred.std()
1145
+ factor = rescaling_scale * factor + (1 - rescaling_scale)
1146
+ noise_pred = noise_pred * factor
1147
+
1148
+ current_timestep = current_timestep[:1]
1149
+ # learned sigma
1150
+ if (
1151
+ self.transformer.config.out_channels // 2
1152
+ == self.transformer.config.in_channels
1153
+ ):
1154
+ noise_pred = noise_pred.chunk(2, dim=1)[0]
1155
+
1156
+ # compute previous image: x_t -> x_t-1
1157
+ latents = self.scheduler.step(
1158
+ noise_pred,
1159
+ t if current_timestep is None else current_timestep,
1160
+ latents,
1161
+ **extra_step_kwargs,
1162
+ return_dict=False,
1163
+ )[0]
1164
+
1165
+ # call the callback, if provided
1166
+ if i == len(timesteps) - 1 or (
1167
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
1168
+ ):
1169
+ progress_bar.update()
1170
+
1171
+ if callback_on_step_end is not None:
1172
+ callback_on_step_end(self, i, t, {})
1173
+
1174
+ if offload_to_cpu:
1175
+ self.transformer = self.transformer.cpu()
1176
+ if self._execution_device == "cuda":
1177
+ torch.cuda.empty_cache()
1178
+
1179
+ latents = self.patchifier.unpatchify(
1180
+ latents=latents,
1181
+ output_height=latent_height,
1182
+ output_width=latent_width,
1183
+ output_num_frames=latent_num_frames,
1184
+ out_channels=self.transformer.in_channels
1185
+ // math.prod(self.patchifier.patch_size),
1186
+ )
1187
+ if output_type != "latent":
1188
+ if self.vae.decoder.timestep_conditioning:
1189
+ noise = torch.randn_like(latents)
1190
+ if not isinstance(decode_timestep, list):
1191
+ decode_timestep = [decode_timestep] * latents.shape[0]
1192
+ if decode_noise_scale is None:
1193
+ decode_noise_scale = decode_timestep
1194
+ elif not isinstance(decode_noise_scale, list):
1195
+ decode_noise_scale = [decode_noise_scale] * latents.shape[0]
1196
+
1197
+ decode_timestep = torch.tensor(decode_timestep).to(latents.device)
1198
+ decode_noise_scale = torch.tensor(decode_noise_scale).to(
1199
+ latents.device
1200
+ )[:, None, None, None, None]
1201
+ latents = (
1202
+ latents * (1 - decode_noise_scale) + noise * decode_noise_scale
1203
+ )
1204
+ else:
1205
+ decode_timestep = None
1206
+ image = vae_decode(
1207
+ latents,
1208
+ self.vae,
1209
+ is_video,
1210
+ vae_per_channel_normalize=kwargs["vae_per_channel_normalize"],
1211
+ timestep=decode_timestep,
1212
+ )
1213
+ image = self.image_processor.postprocess(image, output_type=output_type)
1214
+
1215
+ else:
1216
+ image = latents
1217
+
1218
+ # Offload all models
1219
+ self.maybe_free_model_hooks()
1220
+
1221
+ if not return_dict:
1222
+ return (image,)
1223
+
1224
+ return ImagePipelineOutput(images=image)
1225
+
1226
+ def prepare_conditioning(
1227
+ self,
1228
+ media_items: torch.Tensor,
1229
+ num_frames: int,
1230
+ height: int,
1231
+ width: int,
1232
+ method: ConditioningMethod = ConditioningMethod.UNCONDITIONAL,
1233
+ vae_per_channel_normalize: bool = False,
1234
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
1235
+ """
1236
+ Prepare the conditioning data for the video generation. If an input media item is provided, encode it
1237
+ and set the conditioning_mask to indicate which tokens to condition on. Input media item should have
1238
+ the same height and width as the generated video.
1239
+
1240
+ Args:
1241
+ media_items (torch.Tensor): media items to condition on (images or videos)
1242
+ num_frames (int): number of frames to generate
1243
+ height (int): height of the generated video
1244
+ width (int): width of the generated video
1245
+ method (ConditioningMethod, optional): conditioning method to use. Defaults to ConditioningMethod.UNCONDITIONAL.
1246
+ vae_per_channel_normalize (bool, optional): whether to normalize the input to the VAE per channel. Defaults to False.
1247
+
1248
+ Returns:
1249
+ Tuple[torch.Tensor, torch.Tensor]: the conditioning latents and the conditioning mask
1250
+ """
1251
+ if media_items is None or method == ConditioningMethod.UNCONDITIONAL:
1252
+ return None, None
1253
+
1254
+ assert media_items.ndim == 5
1255
+ assert height == media_items.shape[-2] and width == media_items.shape[-1]
1256
+
1257
+ # Encode the input video and repeat to the required number of frame-tokens
1258
+ init_latents = vae_encode(
1259
+ media_items.to(dtype=self.vae.dtype, device=self.vae.device),
1260
+ self.vae,
1261
+ vae_per_channel_normalize=vae_per_channel_normalize,
1262
+ ).float()
1263
+
1264
+ init_len, target_len = (
1265
+ init_latents.shape[2],
1266
+ num_frames // self.video_scale_factor,
1267
+ )
1268
+ if isinstance(self.vae, CausalVideoAutoencoder):
1269
+ target_len += 1
1270
+ init_latents = init_latents[:, :, :target_len]
1271
+ if target_len > init_len:
1272
+ repeat_factor = (target_len + init_len - 1) // init_len # Ceiling division
1273
+ init_latents = init_latents.repeat(1, 1, repeat_factor, 1, 1)[
1274
+ :, :, :target_len
1275
+ ]
1276
+
1277
+ # Prepare the conditioning mask (1.0 = condition on this token)
1278
+ b, n, f, h, w = init_latents.shape
1279
+ conditioning_mask = torch.zeros([b, 1, f, h, w], device=init_latents.device)
1280
+ if method == ConditioningMethod.FIRST_FRAME:
1281
+ conditioning_mask[:, :, 0] = 1.0
1282
+
1283
+ # Patchify the init latents and the mask
1284
+ conditioning_mask = self.patchifier.patchify(conditioning_mask).squeeze(-1)
1285
+ init_latents = self.patchifier.patchify(latents=init_latents)
1286
+ return init_latents, conditioning_mask
ltx_video/schedulers/__init__.py ADDED
File without changes
ltx_video/schedulers/rf.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from abc import ABC, abstractmethod
3
+ from dataclasses import dataclass
4
+ from typing import Callable, Optional, Tuple, Union
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import torch
10
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
11
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
12
+ from diffusers.utils import BaseOutput
13
+ from torch import Tensor
14
+ from safetensors import safe_open
15
+
16
+
17
+ from ltx_video.utils.torch_utils import append_dims
18
+
19
+ from ltx_video.utils.diffusers_config_mapping import (
20
+ diffusers_and_ours_config_mapping,
21
+ make_hashable_key,
22
+ )
23
+
24
+
25
+ def simple_diffusion_resolution_dependent_timestep_shift(
26
+ samples: Tensor,
27
+ timesteps: Tensor,
28
+ n: int = 32 * 32,
29
+ ) -> Tensor:
30
+ if len(samples.shape) == 3:
31
+ _, m, _ = samples.shape
32
+ elif len(samples.shape) in [4, 5]:
33
+ m = math.prod(samples.shape[2:])
34
+ else:
35
+ raise ValueError(
36
+ "Samples must have shape (b, t, c), (b, c, h, w) or (b, c, f, h, w)"
37
+ )
38
+ snr = (timesteps / (1 - timesteps)) ** 2
39
+ shift_snr = torch.log(snr) + 2 * math.log(m / n)
40
+ shifted_timesteps = torch.sigmoid(0.5 * shift_snr)
41
+
42
+ return shifted_timesteps
43
+
44
+
45
+ def time_shift(mu: float, sigma: float, t: Tensor):
46
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
47
+
48
+
49
+ def get_normal_shift(
50
+ n_tokens: int,
51
+ min_tokens: int = 1024,
52
+ max_tokens: int = 4096,
53
+ min_shift: float = 0.95,
54
+ max_shift: float = 2.05,
55
+ ) -> Callable[[float], float]:
56
+ m = (max_shift - min_shift) / (max_tokens - min_tokens)
57
+ b = min_shift - m * min_tokens
58
+ return m * n_tokens + b
59
+
60
+
61
+ def strech_shifts_to_terminal(shifts: Tensor, terminal=0.1):
62
+ """
63
+ Stretch a function (given as sampled shifts) so that its final value matches the given terminal value
64
+ using the provided formula.
65
+
66
+ Parameters:
67
+ - shifts (Tensor): The samples of the function to be stretched (PyTorch Tensor).
68
+ - terminal (float): The desired terminal value (value at the last sample).
69
+
70
+ Returns:
71
+ - Tensor: The stretched shifts such that the final value equals `terminal`.
72
+ """
73
+ if shifts.numel() == 0:
74
+ raise ValueError("The 'shifts' tensor must not be empty.")
75
+
76
+ # Ensure terminal value is valid
77
+ if terminal <= 0 or terminal >= 1:
78
+ raise ValueError("The terminal value must be between 0 and 1 (exclusive).")
79
+
80
+ # Transform the shifts using the given formula
81
+ one_minus_z = 1 - shifts
82
+ scale_factor = one_minus_z[-1] / (1 - terminal)
83
+ stretched_shifts = 1 - (one_minus_z / scale_factor)
84
+
85
+ return stretched_shifts
86
+
87
+
88
+ def sd3_resolution_dependent_timestep_shift(
89
+ samples: Tensor, timesteps: Tensor, target_shift_terminal: Optional[float] = None
90
+ ) -> Tensor:
91
+ """
92
+ Shifts the timestep schedule as a function of the generated resolution.
93
+
94
+ In the SD3 paper, the authors empirically how to shift the timesteps based on the resolution of the target images.
95
+ For more details: https://arxiv.org/pdf/2403.03206
96
+
97
+ In Flux they later propose a more dynamic resolution dependent timestep shift, see:
98
+ https://github.com/black-forest-labs/flux/blob/87f6fff727a377ea1c378af692afb41ae84cbe04/src/flux/sampling.py#L66
99
+
100
+
101
+ Args:
102
+ samples (Tensor): A batch of samples with shape (batch_size, channels, height, width) or
103
+ (batch_size, channels, frame, height, width).
104
+ timesteps (Tensor): A batch of timesteps with shape (batch_size,).
105
+ target_shift_terminal (float): The target terminal value for the shifted timesteps.
106
+
107
+ Returns:
108
+ Tensor: The shifted timesteps.
109
+ """
110
+ if len(samples.shape) == 3:
111
+ _, m, _ = samples.shape
112
+ elif len(samples.shape) in [4, 5]:
113
+ m = math.prod(samples.shape[2:])
114
+ else:
115
+ raise ValueError(
116
+ "Samples must have shape (b, t, c), (b, c, h, w) or (b, c, f, h, w)"
117
+ )
118
+
119
+ shift = get_normal_shift(m)
120
+ time_shifts = time_shift(shift, 1, timesteps)
121
+ if target_shift_terminal is not None: # Stretch the shifts to the target terminal
122
+ time_shifts = strech_shifts_to_terminal(time_shifts, target_shift_terminal)
123
+ return time_shifts
124
+
125
+
126
+ class TimestepShifter(ABC):
127
+ @abstractmethod
128
+ def shift_timesteps(self, samples: Tensor, timesteps: Tensor) -> Tensor:
129
+ pass
130
+
131
+
132
+ @dataclass
133
+ class RectifiedFlowSchedulerOutput(BaseOutput):
134
+ """
135
+ Output class for the scheduler's step function output.
136
+
137
+ Args:
138
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
139
+ Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the
140
+ denoising loop.
141
+ pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
142
+ The predicted denoised sample (x_{0}) based on the model output from the current timestep.
143
+ `pred_original_sample` can be used to preview progress or for guidance.
144
+ """
145
+
146
+ prev_sample: torch.FloatTensor
147
+ pred_original_sample: Optional[torch.FloatTensor] = None
148
+
149
+
150
+ class RectifiedFlowScheduler(SchedulerMixin, ConfigMixin, TimestepShifter):
151
+ order = 1
152
+
153
+ @register_to_config
154
+ def __init__(
155
+ self,
156
+ num_train_timesteps=1000,
157
+ shifting: Optional[str] = None,
158
+ base_resolution: int = 32**2,
159
+ target_shift_terminal: Optional[float] = None,
160
+ ):
161
+ super().__init__()
162
+ self.init_noise_sigma = 1.0
163
+ self.num_inference_steps = None
164
+ self.timesteps = self.sigmas = torch.linspace(
165
+ 1, 1 / num_train_timesteps, num_train_timesteps
166
+ )
167
+ self.delta_timesteps = self.timesteps - torch.cat(
168
+ [self.timesteps[1:], torch.zeros_like(self.timesteps[-1:])]
169
+ )
170
+ self.shifting = shifting
171
+ self.base_resolution = base_resolution
172
+ self.target_shift_terminal = target_shift_terminal
173
+
174
+ def shift_timesteps(self, samples: Tensor, timesteps: Tensor) -> Tensor:
175
+ if self.shifting == "SD3":
176
+ return sd3_resolution_dependent_timestep_shift(
177
+ samples, timesteps, self.target_shift_terminal
178
+ )
179
+ elif self.shifting == "SimpleDiffusion":
180
+ return simple_diffusion_resolution_dependent_timestep_shift(
181
+ samples, timesteps, self.base_resolution
182
+ )
183
+ return timesteps
184
+
185
+ def set_timesteps(
186
+ self,
187
+ num_inference_steps: int,
188
+ samples: Tensor,
189
+ device: Union[str, torch.device] = None,
190
+ ):
191
+ """
192
+ Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.
193
+
194
+ Args:
195
+ num_inference_steps (`int`): The number of diffusion steps used when generating samples.
196
+ samples (`Tensor`): A batch of samples with shape.
197
+ device (`Union[str, torch.device]`, *optional*): The device to which the timesteps tensor will be moved.
198
+ """
199
+ num_inference_steps = min(self.config.num_train_timesteps, num_inference_steps)
200
+ timesteps = torch.linspace(1, 1 / num_inference_steps, num_inference_steps).to(
201
+ device
202
+ )
203
+ self.timesteps = self.shift_timesteps(samples, timesteps)
204
+ self.delta_timesteps = self.timesteps - torch.cat(
205
+ [self.timesteps[1:], torch.zeros_like(self.timesteps[-1:])]
206
+ )
207
+ self.num_inference_steps = num_inference_steps
208
+ self.sigmas = self.timesteps
209
+
210
+ @staticmethod
211
+ def from_pretrained(pretrained_model_path: Union[str, os.PathLike]):
212
+ pretrained_model_path = Path(pretrained_model_path)
213
+ if pretrained_model_path.is_file():
214
+ comfy_single_file_state_dict = {}
215
+ with safe_open(pretrained_model_path, framework="pt", device="cpu") as f:
216
+ metadata = f.metadata()
217
+ for k in f.keys():
218
+ comfy_single_file_state_dict[k] = f.get_tensor(k)
219
+ configs = json.loads(metadata["config"])
220
+ config = configs["scheduler"]
221
+ del comfy_single_file_state_dict
222
+
223
+ elif pretrained_model_path.is_dir():
224
+ diffusers_noise_scheduler_config_path = (
225
+ pretrained_model_path / "scheduler" / "scheduler_config.json"
226
+ )
227
+
228
+ with open(diffusers_noise_scheduler_config_path, "r") as f:
229
+ scheduler_config = json.load(f)
230
+ hashable_config = make_hashable_key(scheduler_config)
231
+ if hashable_config in diffusers_and_ours_config_mapping:
232
+ config = diffusers_and_ours_config_mapping[hashable_config]
233
+ return RectifiedFlowScheduler.from_config(config)
234
+
235
+ def scale_model_input(
236
+ self, sample: torch.FloatTensor, timestep: Optional[int] = None
237
+ ) -> torch.FloatTensor:
238
+ # pylint: disable=unused-argument
239
+ """
240
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
241
+ current timestep.
242
+
243
+ Args:
244
+ sample (`torch.FloatTensor`): input sample
245
+ timestep (`int`, optional): current timestep
246
+
247
+ Returns:
248
+ `torch.FloatTensor`: scaled input sample
249
+ """
250
+ return sample
251
+
252
+ def step(
253
+ self,
254
+ model_output: torch.FloatTensor,
255
+ timestep: torch.FloatTensor,
256
+ sample: torch.FloatTensor,
257
+ eta: float = 0.0,
258
+ use_clipped_model_output: bool = False,
259
+ generator=None,
260
+ variance_noise: Optional[torch.FloatTensor] = None,
261
+ return_dict: bool = True,
262
+ ) -> Union[RectifiedFlowSchedulerOutput, Tuple]:
263
+ # pylint: disable=unused-argument
264
+ """
265
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
266
+ process from the learned model outputs (most often the predicted noise).
267
+
268
+ Args:
269
+ model_output (`torch.FloatTensor`):
270
+ The direct output from learned diffusion model.
271
+ timestep (`float`):
272
+ The current discrete timestep in the diffusion chain.
273
+ sample (`torch.FloatTensor`):
274
+ A current instance of a sample created by the diffusion process.
275
+ eta (`float`):
276
+ The weight of noise for added noise in diffusion step.
277
+ use_clipped_model_output (`bool`, defaults to `False`):
278
+ If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary
279
+ because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no
280
+ clipping has happened, "corrected" `model_output` would coincide with the one provided as input and
281
+ `use_clipped_model_output` has no effect.
282
+ generator (`torch.Generator`, *optional*):
283
+ A random number generator.
284
+ variance_noise (`torch.FloatTensor`):
285
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
286
+ itself. Useful for methods such as [`CycleDiffusion`].
287
+ return_dict (`bool`, *optional*, defaults to `True`):
288
+ Whether or not to return a [`~schedulers.scheduling_ddim.DDIMSchedulerOutput`] or `tuple`.
289
+
290
+ Returns:
291
+ [`~schedulers.scheduling_utils.RectifiedFlowSchedulerOutput`] or `tuple`:
292
+ If return_dict is `True`, [`~schedulers.rf_scheduler.RectifiedFlowSchedulerOutput`] is returned,
293
+ otherwise a tuple is returned where the first element is the sample tensor.
294
+ """
295
+ if self.num_inference_steps is None:
296
+ raise ValueError(
297
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
298
+ )
299
+
300
+ if timestep.ndim == 0:
301
+ # Global timestep
302
+ current_index = (self.timesteps - timestep).abs().argmin()
303
+ dt = self.delta_timesteps.gather(0, current_index.unsqueeze(0))
304
+ else:
305
+ # Timestep per token
306
+ assert timestep.ndim == 2
307
+ current_index = (
308
+ (self.timesteps[:, None, None] - timestep[None]).abs().argmin(dim=0)
309
+ )
310
+ dt = self.delta_timesteps[current_index]
311
+ # Special treatment for zero timestep tokens - set dt to 0 so prev_sample = sample
312
+ dt = torch.where(timestep == 0.0, torch.zeros_like(dt), dt)[..., None]
313
+
314
+ prev_sample = sample - dt * model_output
315
+
316
+ if not return_dict:
317
+ return (prev_sample,)
318
+
319
+ return RectifiedFlowSchedulerOutput(prev_sample=prev_sample)
320
+
321
+ def add_noise(
322
+ self,
323
+ original_samples: torch.FloatTensor,
324
+ noise: torch.FloatTensor,
325
+ timesteps: torch.FloatTensor,
326
+ ) -> torch.FloatTensor:
327
+ sigmas = timesteps
328
+ sigmas = append_dims(sigmas, original_samples.ndim)
329
+ alphas = 1 - sigmas
330
+ noisy_samples = alphas * original_samples + sigmas * noise
331
+ return noisy_samples
ltx_video/utils/__init__.py ADDED
File without changes
ltx_video/utils/conditioning_method.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+
3
+
4
+ class ConditioningMethod(Enum):
5
+ UNCONDITIONAL = "unconditional"
6
+ FIRST_FRAME = "first_frame"
ltx_video/utils/diffusers_config_mapping.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def make_hashable_key(dict_key):
2
+ def convert_value(value):
3
+ if isinstance(value, list):
4
+ return tuple(value)
5
+ elif isinstance(value, dict):
6
+ return tuple(sorted((k, convert_value(v)) for k, v in value.items()))
7
+ else:
8
+ return value
9
+
10
+ return tuple(sorted((k, convert_value(v)) for k, v in dict_key.items()))
11
+
12
+
13
+ DIFFUSERS_SCHEDULER_CONFIG = {
14
+ "_class_name": "FlowMatchEulerDiscreteScheduler",
15
+ "_diffusers_version": "0.32.0.dev0",
16
+ "base_image_seq_len": 1024,
17
+ "base_shift": 0.95,
18
+ "invert_sigmas": False,
19
+ "max_image_seq_len": 4096,
20
+ "max_shift": 2.05,
21
+ "num_train_timesteps": 1000,
22
+ "shift": 1.0,
23
+ "shift_terminal": 0.1,
24
+ "use_beta_sigmas": False,
25
+ "use_dynamic_shifting": True,
26
+ "use_exponential_sigmas": False,
27
+ "use_karras_sigmas": False,
28
+ }
29
+ DIFFUSERS_TRANSFORMER_CONFIG = {
30
+ "_class_name": "LTXVideoTransformer3DModel",
31
+ "_diffusers_version": "0.32.0.dev0",
32
+ "activation_fn": "gelu-approximate",
33
+ "attention_bias": True,
34
+ "attention_head_dim": 64,
35
+ "attention_out_bias": True,
36
+ "caption_channels": 4096,
37
+ "cross_attention_dim": 2048,
38
+ "in_channels": 128,
39
+ "norm_elementwise_affine": False,
40
+ "norm_eps": 1e-06,
41
+ "num_attention_heads": 32,
42
+ "num_layers": 28,
43
+ "out_channels": 128,
44
+ "patch_size": 1,
45
+ "patch_size_t": 1,
46
+ "qk_norm": "rms_norm_across_heads",
47
+ }
48
+ DIFFUSERS_VAE_CONFIG = {
49
+ "_class_name": "AutoencoderKLLTXVideo",
50
+ "_diffusers_version": "0.32.0.dev0",
51
+ "block_out_channels": [128, 256, 512, 512],
52
+ "decoder_causal": False,
53
+ "encoder_causal": True,
54
+ "in_channels": 3,
55
+ "latent_channels": 128,
56
+ "layers_per_block": [4, 3, 3, 3, 4],
57
+ "out_channels": 3,
58
+ "patch_size": 4,
59
+ "patch_size_t": 1,
60
+ "resnet_norm_eps": 1e-06,
61
+ "scaling_factor": 1.0,
62
+ "spatio_temporal_scaling": [True, True, True, False],
63
+ }
64
+
65
+ OURS_SCHEDULER_CONFIG = {
66
+ "_class_name": "RectifiedFlowScheduler",
67
+ "_diffusers_version": "0.25.1",
68
+ "num_train_timesteps": 1000,
69
+ "shifting": "SD3",
70
+ "base_resolution": None,
71
+ "target_shift_terminal": 0.1,
72
+ }
73
+
74
+ OURS_TRANSFORMER_CONFIG = {
75
+ "_class_name": "Transformer3DModel",
76
+ "_diffusers_version": "0.25.1",
77
+ "_name_or_path": "PixArt-alpha/PixArt-XL-2-256x256",
78
+ "activation_fn": "gelu-approximate",
79
+ "attention_bias": True,
80
+ "attention_head_dim": 64,
81
+ "attention_type": "default",
82
+ "caption_channels": 4096,
83
+ "cross_attention_dim": 2048,
84
+ "double_self_attention": False,
85
+ "dropout": 0.0,
86
+ "in_channels": 128,
87
+ "norm_elementwise_affine": False,
88
+ "norm_eps": 1e-06,
89
+ "norm_num_groups": 32,
90
+ "num_attention_heads": 32,
91
+ "num_embeds_ada_norm": 1000,
92
+ "num_layers": 28,
93
+ "num_vector_embeds": None,
94
+ "only_cross_attention": False,
95
+ "out_channels": 128,
96
+ "project_to_2d_pos": True,
97
+ "upcast_attention": False,
98
+ "use_linear_projection": False,
99
+ "qk_norm": "rms_norm",
100
+ "standardization_norm": "rms_norm",
101
+ "positional_embedding_type": "rope",
102
+ "positional_embedding_theta": 10000.0,
103
+ "positional_embedding_max_pos": [20, 2048, 2048],
104
+ "timestep_scale_multiplier": 1000,
105
+ }
106
+ OURS_VAE_CONFIG = {
107
+ "_class_name": "CausalVideoAutoencoder",
108
+ "dims": 3,
109
+ "in_channels": 3,
110
+ "out_channels": 3,
111
+ "latent_channels": 128,
112
+ "blocks": [
113
+ ["res_x", 4],
114
+ ["compress_all", 1],
115
+ ["res_x_y", 1],
116
+ ["res_x", 3],
117
+ ["compress_all", 1],
118
+ ["res_x_y", 1],
119
+ ["res_x", 3],
120
+ ["compress_all", 1],
121
+ ["res_x", 3],
122
+ ["res_x", 4],
123
+ ],
124
+ "scaling_factor": 1.0,
125
+ "norm_layer": "pixel_norm",
126
+ "patch_size": 4,
127
+ "latent_log_var": "uniform",
128
+ "use_quant_conv": False,
129
+ "causal_decoder": False,
130
+ }
131
+
132
+
133
+ diffusers_and_ours_config_mapping = {
134
+ make_hashable_key(DIFFUSERS_SCHEDULER_CONFIG): OURS_SCHEDULER_CONFIG,
135
+ make_hashable_key(DIFFUSERS_TRANSFORMER_CONFIG): OURS_TRANSFORMER_CONFIG,
136
+ make_hashable_key(DIFFUSERS_VAE_CONFIG): OURS_VAE_CONFIG,
137
+ }
138
+
139
+
140
+ TRANSFORMER_KEYS_RENAME_DICT = {
141
+ "proj_in": "patchify_proj",
142
+ "time_embed": "adaln_single",
143
+ "norm_q": "q_norm",
144
+ "norm_k": "k_norm",
145
+ }
146
+
147
+
148
+ VAE_KEYS_RENAME_DICT = {
149
+ "decoder.up_blocks.3.conv_in": "decoder.up_blocks.7",
150
+ "decoder.up_blocks.3.upsamplers.0": "decoder.up_blocks.8",
151
+ "decoder.up_blocks.3": "decoder.up_blocks.9",
152
+ "decoder.up_blocks.2.upsamplers.0": "decoder.up_blocks.5",
153
+ "decoder.up_blocks.2.conv_in": "decoder.up_blocks.4",
154
+ "decoder.up_blocks.2": "decoder.up_blocks.6",
155
+ "decoder.up_blocks.1.upsamplers.0": "decoder.up_blocks.2",
156
+ "decoder.up_blocks.1": "decoder.up_blocks.3",
157
+ "decoder.up_blocks.0": "decoder.up_blocks.1",
158
+ "decoder.mid_block": "decoder.up_blocks.0",
159
+ "encoder.down_blocks.3": "encoder.down_blocks.8",
160
+ "encoder.down_blocks.2.downsamplers.0": "encoder.down_blocks.7",
161
+ "encoder.down_blocks.2": "encoder.down_blocks.6",
162
+ "encoder.down_blocks.1.downsamplers.0": "encoder.down_blocks.4",
163
+ "encoder.down_blocks.1.conv_out": "encoder.down_blocks.5",
164
+ "encoder.down_blocks.1": "encoder.down_blocks.3",
165
+ "encoder.down_blocks.0.conv_out": "encoder.down_blocks.2",
166
+ "encoder.down_blocks.0.downsamplers.0": "encoder.down_blocks.1",
167
+ "encoder.down_blocks.0": "encoder.down_blocks.0",
168
+ "encoder.mid_block": "encoder.down_blocks.9",
169
+ "conv_shortcut.conv": "conv_shortcut",
170
+ "resnets": "res_blocks",
171
+ "norm3": "norm3.norm",
172
+ "latents_mean": "per_channel_statistics.mean-of-means",
173
+ "latents_std": "per_channel_statistics.std-of-means",
174
+ }
ltx_video/utils/skip_layer_strategy.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from enum import Enum, auto
2
+
3
+
4
+ class SkipLayerStrategy(Enum):
5
+ Attention = auto()
6
+ Residual = auto()
ltx_video/utils/torch_utils.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ def append_dims(x: torch.Tensor, target_dims: int) -> torch.Tensor:
6
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
7
+ dims_to_append = target_dims - x.ndim
8
+ if dims_to_append < 0:
9
+ raise ValueError(
10
+ f"input has {x.ndim} dims but target_dims is {target_dims}, which is less"
11
+ )
12
+ elif dims_to_append == 0:
13
+ return x
14
+ return x[(...,) + (None,) * dims_to_append]
15
+
16
+
17
+ class Identity(nn.Module):
18
+ """A placeholder identity operator that is argument-insensitive."""
19
+
20
+ def __init__(self, *args, **kwargs) -> None: # pylint: disable=unused-argument
21
+ super().__init__()
22
+
23
+ # pylint: disable=unused-argument
24
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
25
+ return x