{"repo_name": "FramePack", "file_name": "/FramePack/diffusers_helper/thread_utils.py", "inference_info": {"prefix_code": "import time\n\nfrom threading import Thread, Lock\n\n\n", "suffix_code": "\n\n\ndef async_run(func, *args, **kwargs):\n Listener.add_task(func, *args, **kwargs)\n\n\nclass FIFOQueue:\n def __init__(self):\n self.queue = []\n self.lock = Lock()\n\n def push(self, item):\n with self.lock:\n self.queue.append(item)\n\n def pop(self):\n with self.lock:\n if self.queue:\n return self.queue.pop(0)\n return None\n\n def top(self):\n with self.lock:\n if self.queue:\n return self.queue[0]\n return None\n\n def next(self):\n while True:\n with self.lock:\n if self.queue:\n return self.queue.pop(0)\n\n time.sleep(0.001)\n\n\nclass AsyncStream:\n def __init__(self):\n self.input_queue = FIFOQueue()\n self.output_queue = FIFOQueue()\n", "middle_code": "class Listener:\n task_queue = []\n lock = Lock()\n thread = None\n @classmethod\n def _process_tasks(cls):\n while True:\n task = None\n with cls.lock:\n if cls.task_queue:\n task = cls.task_queue.pop(0)\n if task is None:\n time.sleep(0.001)\n continue\n func, args, kwargs = task\n try:\n func(*args, **kwargs)\n except Exception as e:\n print(f\"Error in listener thread: {e}\")\n @classmethod\n def add_task(cls, func, *args, **kwargs):\n with cls.lock:\n cls.task_queue.append((func, args, kwargs))\n if cls.thread is None:\n cls.thread = Thread(target=cls._process_tasks, daemon=True)\n cls.thread.start()", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "python", "sub_task_type": null}, "context_code": [["/FramePack/diffusers_helper/models/hunyuan_video_packed.py", "from typing import Any, Dict, List, Optional, Tuple, Union\n\nimport torch\nimport einops\nimport torch.nn as nn\nimport numpy as np\n\nfrom diffusers.loaders import FromOriginalModelMixin\nfrom diffusers.configuration_utils import ConfigMixin, register_to_config\nfrom diffusers.loaders import PeftAdapterMixin\nfrom diffusers.utils import logging\nfrom diffusers.models.attention import FeedForward\nfrom diffusers.models.attention_processor import Attention\nfrom diffusers.models.embeddings import TimestepEmbedding, Timesteps, PixArtAlphaTextProjection\nfrom diffusers.models.modeling_outputs import Transformer2DModelOutput\nfrom diffusers.models.modeling_utils import ModelMixin\nfrom diffusers_helper.dit_common import LayerNorm\nfrom diffusers_helper.utils import zero_module\n\n\nenabled_backends = []\n\nif torch.backends.cuda.flash_sdp_enabled():\n enabled_backends.append(\"flash\")\nif torch.backends.cuda.math_sdp_enabled():\n enabled_backends.append(\"math\")\nif torch.backends.cuda.mem_efficient_sdp_enabled():\n enabled_backends.append(\"mem_efficient\")\nif torch.backends.cuda.cudnn_sdp_enabled():\n enabled_backends.append(\"cudnn\")\n\nprint(\"Currently enabled native sdp backends:\", enabled_backends)\n\ntry:\n # raise NotImplementedError\n from xformers.ops import memory_efficient_attention as xformers_attn_func\n print('Xformers is installed!')\nexcept:\n print('Xformers is not installed!')\n xformers_attn_func = None\n\ntry:\n # raise NotImplementedError\n from flash_attn import flash_attn_varlen_func, flash_attn_func\n print('Flash Attn is installed!')\nexcept:\n print('Flash Attn is not installed!')\n flash_attn_varlen_func = None\n flash_attn_func = None\n\ntry:\n # raise NotImplementedError\n from sageattention import sageattn_varlen, sageattn\n print('Sage Attn is installed!')\nexcept:\n print('Sage Attn is not installed!')\n sageattn_varlen = None\n sageattn = None\n\n\nlogger = logging.get_logger(__name__) # pylint: disable=invalid-name\n\n\ndef pad_for_3d_conv(x, kernel_size):\n b, c, t, h, w = x.shape\n pt, ph, pw = kernel_size\n pad_t = (pt - (t % pt)) % pt\n pad_h = (ph - (h % ph)) % ph\n pad_w = (pw - (w % pw)) % pw\n return torch.nn.functional.pad(x, (0, pad_w, 0, pad_h, 0, pad_t), mode='replicate')\n\n\ndef center_down_sample_3d(x, kernel_size):\n # pt, ph, pw = kernel_size\n # cp = (pt * ph * pw) // 2\n # xp = einops.rearrange(x, 'b c (t pt) (h ph) (w pw) -> (pt ph pw) b c t h w', pt=pt, ph=ph, pw=pw)\n # xc = xp[cp]\n # return xc\n return torch.nn.functional.avg_pool3d(x, kernel_size, stride=kernel_size)\n\n\ndef get_cu_seqlens(text_mask, img_len):\n batch_size = text_mask.shape[0]\n text_len = text_mask.sum(dim=1)\n max_len = text_mask.shape[1] + img_len\n\n cu_seqlens = torch.zeros([2 * batch_size + 1], dtype=torch.int32, device=\"cuda\")\n\n for i in range(batch_size):\n s = text_len[i] + img_len\n s1 = i * max_len + s\n s2 = (i + 1) * max_len\n cu_seqlens[2 * i + 1] = s1\n cu_seqlens[2 * i + 2] = s2\n\n return cu_seqlens\n\n\ndef apply_rotary_emb_transposed(x, freqs_cis):\n cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1)\n x_real, x_imag = x.unflatten(-1, (-1, 2)).unbind(-1)\n x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)\n out = x.float() * cos + x_rotated.float() * sin\n out = out.to(x)\n return out\n\n\ndef attn_varlen_func(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv):\n if cu_seqlens_q is None and cu_seqlens_kv is None and max_seqlen_q is None and max_seqlen_kv is None:\n if sageattn is not None:\n x = sageattn(q, k, v, tensor_layout='NHD')\n return x\n\n if flash_attn_func is not None:\n x = flash_attn_func(q, k, v)\n return x\n\n if xformers_attn_func is not None:\n x = xformers_attn_func(q, k, v)\n return x\n\n x = torch.nn.functional.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)).transpose(1, 2)\n return x\n\n B, L, H, C = q.shape\n\n q = q.flatten(0, 1)\n k = k.flatten(0, 1)\n v = v.flatten(0, 1)\n\n if sageattn_varlen is not None:\n x = sageattn_varlen(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)\n elif flash_attn_varlen_func is not None:\n x = flash_attn_varlen_func(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)\n else:\n raise NotImplementedError('No Attn Installed!')\n\n x = x.unflatten(0, (B, L))\n\n return x\n\n\nclass HunyuanAttnProcessorFlashAttnDouble:\n def __call__(self, attn, hidden_states, encoder_hidden_states, attention_mask, image_rotary_emb):\n cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv = attention_mask\n\n query = attn.to_q(hidden_states)\n key = attn.to_k(hidden_states)\n value = attn.to_v(hidden_states)\n\n query = query.unflatten(2, (attn.heads, -1))\n key = key.unflatten(2, (attn.heads, -1))\n value = value.unflatten(2, (attn.heads, -1))\n\n query = attn.norm_q(query)\n key = attn.norm_k(key)\n\n query = apply_rotary_emb_transposed(query, image_rotary_emb)\n key = apply_rotary_emb_transposed(key, image_rotary_emb)\n\n encoder_query = attn.add_q_proj(encoder_hidden_states)\n encoder_key = attn.add_k_proj(encoder_hidden_states)\n encoder_value = attn.add_v_proj(encoder_hidden_states)\n\n encoder_query = encoder_query.unflatten(2, (attn.heads, -1))\n encoder_key = encoder_key.unflatten(2, (attn.heads, -1))\n encoder_value = encoder_value.unflatten(2, (attn.heads, -1))\n\n encoder_query = attn.norm_added_q(encoder_query)\n encoder_key = attn.norm_added_k(encoder_key)\n\n query = torch.cat([query, encoder_query], dim=1)\n key = torch.cat([key, encoder_key], dim=1)\n value = torch.cat([value, encoder_value], dim=1)\n\n hidden_states = attn_varlen_func(query, key, value, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)\n hidden_states = hidden_states.flatten(-2)\n\n txt_length = encoder_hidden_states.shape[1]\n hidden_states, encoder_hidden_states = hidden_states[:, :-txt_length], hidden_states[:, -txt_length:]\n\n hidden_states = attn.to_out[0](hidden_states)\n hidden_states = attn.to_out[1](hidden_states)\n encoder_hidden_states = attn.to_add_out(encoder_hidden_states)\n\n return hidden_states, encoder_hidden_states\n\n\nclass HunyuanAttnProcessorFlashAttnSingle:\n def __call__(self, attn, hidden_states, encoder_hidden_states, attention_mask, image_rotary_emb):\n cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv = attention_mask\n\n hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)\n\n query = attn.to_q(hidden_states)\n key = attn.to_k(hidden_states)\n value = attn.to_v(hidden_states)\n\n query = query.unflatten(2, (attn.heads, -1))\n key = key.unflatten(2, (attn.heads, -1))\n value = value.unflatten(2, (attn.heads, -1))\n\n query = attn.norm_q(query)\n key = attn.norm_k(key)\n\n txt_length = encoder_hidden_states.shape[1]\n\n query = torch.cat([apply_rotary_emb_transposed(query[:, :-txt_length], image_rotary_emb), query[:, -txt_length:]], dim=1)\n key = torch.cat([apply_rotary_emb_transposed(key[:, :-txt_length], image_rotary_emb), key[:, -txt_length:]], dim=1)\n\n hidden_states = attn_varlen_func(query, key, value, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)\n hidden_states = hidden_states.flatten(-2)\n\n hidden_states, encoder_hidden_states = hidden_states[:, :-txt_length], hidden_states[:, -txt_length:]\n\n return hidden_states, encoder_hidden_states\n\n\nclass CombinedTimestepGuidanceTextProjEmbeddings(nn.Module):\n def __init__(self, embedding_dim, pooled_projection_dim):\n super().__init__()\n\n self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)\n self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)\n self.guidance_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)\n self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn=\"silu\")\n\n def forward(self, timestep, guidance, pooled_projection):\n timesteps_proj = self.time_proj(timestep)\n timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype))\n\n guidance_proj = self.time_proj(guidance)\n guidance_emb = self.guidance_embedder(guidance_proj.to(dtype=pooled_projection.dtype))\n\n time_guidance_emb = timesteps_emb + guidance_emb\n\n pooled_projections = self.text_embedder(pooled_projection)\n conditioning = time_guidance_emb + pooled_projections\n\n return conditioning\n\n\nclass CombinedTimestepTextProjEmbeddings(nn.Module):\n def __init__(self, embedding_dim, pooled_projection_dim):\n super().__init__()\n\n self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)\n self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)\n self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn=\"silu\")\n\n def forward(self, timestep, pooled_projection):\n timesteps_proj = self.time_proj(timestep)\n timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype))\n\n pooled_projections = self.text_embedder(pooled_projection)\n\n conditioning = timesteps_emb + pooled_projections\n\n return conditioning\n\n\nclass HunyuanVideoAdaNorm(nn.Module):\n def __init__(self, in_features: int, out_features: Optional[int] = None) -> None:\n super().__init__()\n\n out_features = out_features or 2 * in_features\n self.linear = nn.Linear(in_features, out_features)\n self.nonlinearity = nn.SiLU()\n\n def forward(\n self, temb: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:\n temb = self.linear(self.nonlinearity(temb))\n gate_msa, gate_mlp = temb.chunk(2, dim=-1)\n gate_msa, gate_mlp = gate_msa.unsqueeze(1), gate_mlp.unsqueeze(1)\n return gate_msa, gate_mlp\n\n\nclass HunyuanVideoIndividualTokenRefinerBlock(nn.Module):\n def __init__(\n self,\n num_attention_heads: int,\n attention_head_dim: int,\n mlp_width_ratio: str = 4.0,\n mlp_drop_rate: float = 0.0,\n attention_bias: bool = True,\n ) -> None:\n super().__init__()\n\n hidden_size = num_attention_heads * attention_head_dim\n\n self.norm1 = LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)\n self.attn = Attention(\n query_dim=hidden_size,\n cross_attention_dim=None,\n heads=num_attention_heads,\n dim_head=attention_head_dim,\n bias=attention_bias,\n )\n\n self.norm2 = LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)\n self.ff = FeedForward(hidden_size, mult=mlp_width_ratio, activation_fn=\"linear-silu\", dropout=mlp_drop_rate)\n\n self.norm_out = HunyuanVideoAdaNorm(hidden_size, 2 * hidden_size)\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n temb: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n ) -> torch.Tensor:\n norm_hidden_states = self.norm1(hidden_states)\n\n attn_output = self.attn(\n hidden_states=norm_hidden_states,\n encoder_hidden_states=None,\n attention_mask=attention_mask,\n )\n\n gate_msa, gate_mlp = self.norm_out(temb)\n hidden_states = hidden_states + attn_output * gate_msa\n\n ff_output = self.ff(self.norm2(hidden_states))\n hidden_states = hidden_states + ff_output * gate_mlp\n\n return hidden_states\n\n\nclass HunyuanVideoIndividualTokenRefiner(nn.Module):\n def __init__(\n self,\n num_attention_heads: int,\n attention_head_dim: int,\n num_layers: int,\n mlp_width_ratio: float = 4.0,\n mlp_drop_rate: float = 0.0,\n attention_bias: bool = True,\n ) -> None:\n super().__init__()\n\n self.refiner_blocks = nn.ModuleList(\n [\n HunyuanVideoIndividualTokenRefinerBlock(\n num_attention_heads=num_attention_heads,\n attention_head_dim=attention_head_dim,\n mlp_width_ratio=mlp_width_ratio,\n mlp_drop_rate=mlp_drop_rate,\n attention_bias=attention_bias,\n )\n for _ in range(num_layers)\n ]\n )\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n temb: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n ) -> None:\n self_attn_mask = None\n if attention_mask is not None:\n batch_size = attention_mask.shape[0]\n seq_len = attention_mask.shape[1]\n attention_mask = attention_mask.to(hidden_states.device).bool()\n self_attn_mask_1 = attention_mask.view(batch_size, 1, 1, seq_len).repeat(1, 1, seq_len, 1)\n self_attn_mask_2 = self_attn_mask_1.transpose(2, 3)\n self_attn_mask = (self_attn_mask_1 & self_attn_mask_2).bool()\n self_attn_mask[:, :, :, 0] = True\n\n for block in self.refiner_blocks:\n hidden_states = block(hidden_states, temb, self_attn_mask)\n\n return hidden_states\n\n\nclass HunyuanVideoTokenRefiner(nn.Module):\n def __init__(\n self,\n in_channels: int,\n num_attention_heads: int,\n attention_head_dim: int,\n num_layers: int,\n mlp_ratio: float = 4.0,\n mlp_drop_rate: float = 0.0,\n attention_bias: bool = True,\n ) -> None:\n super().__init__()\n\n hidden_size = num_attention_heads * attention_head_dim\n\n self.time_text_embed = CombinedTimestepTextProjEmbeddings(\n embedding_dim=hidden_size, pooled_projection_dim=in_channels\n )\n self.proj_in = nn.Linear(in_channels, hidden_size, bias=True)\n self.token_refiner = HunyuanVideoIndividualTokenRefiner(\n num_attention_heads=num_attention_heads,\n attention_head_dim=attention_head_dim,\n num_layers=num_layers,\n mlp_width_ratio=mlp_ratio,\n mlp_drop_rate=mlp_drop_rate,\n attention_bias=attention_bias,\n )\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n timestep: torch.LongTensor,\n attention_mask: Optional[torch.LongTensor] = None,\n ) -> torch.Tensor:\n if attention_mask is None:\n pooled_projections = hidden_states.mean(dim=1)\n else:\n original_dtype = hidden_states.dtype\n mask_float = attention_mask.float().unsqueeze(-1)\n pooled_projections = (hidden_states * mask_float).sum(dim=1) / mask_float.sum(dim=1)\n pooled_projections = pooled_projections.to(original_dtype)\n\n temb = self.time_text_embed(timestep, pooled_projections)\n hidden_states = self.proj_in(hidden_states)\n hidden_states = self.token_refiner(hidden_states, temb, attention_mask)\n\n return hidden_states\n\n\nclass HunyuanVideoRotaryPosEmbed(nn.Module):\n def __init__(self, rope_dim, theta):\n super().__init__()\n self.DT, self.DY, self.DX = rope_dim\n self.theta = theta\n\n @torch.no_grad()\n def get_frequency(self, dim, pos):\n T, H, W = pos.shape\n freqs = 1.0 / (self.theta ** (torch.arange(0, dim, 2, dtype=torch.float32, device=pos.device)[: (dim // 2)] / dim))\n freqs = torch.outer(freqs, pos.reshape(-1)).unflatten(-1, (T, H, W)).repeat_interleave(2, dim=0)\n return freqs.cos(), freqs.sin()\n\n @torch.no_grad()\n def forward_inner(self, frame_indices, height, width, device):\n GT, GY, GX = torch.meshgrid(\n frame_indices.to(device=device, dtype=torch.float32),\n torch.arange(0, height, device=device, dtype=torch.float32),\n torch.arange(0, width, device=device, dtype=torch.float32),\n indexing=\"ij\"\n )\n\n FCT, FST = self.get_frequency(self.DT, GT)\n FCY, FSY = self.get_frequency(self.DY, GY)\n FCX, FSX = self.get_frequency(self.DX, GX)\n\n result = torch.cat([FCT, FCY, FCX, FST, FSY, FSX], dim=0)\n\n return result.to(device)\n\n @torch.no_grad()\n def forward(self, frame_indices, height, width, device):\n frame_indices = frame_indices.unbind(0)\n results = [self.forward_inner(f, height, width, device) for f in frame_indices]\n results = torch.stack(results, dim=0)\n return results\n\n\nclass AdaLayerNormZero(nn.Module):\n def __init__(self, embedding_dim: int, norm_type=\"layer_norm\", bias=True):\n super().__init__()\n self.silu = nn.SiLU()\n self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=bias)\n if norm_type == \"layer_norm\":\n self.norm = LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)\n else:\n raise ValueError(f\"unknown norm_type {norm_type}\")\n\n def forward(\n self,\n x: torch.Tensor,\n emb: Optional[torch.Tensor] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:\n emb = emb.unsqueeze(-2)\n emb = self.linear(self.silu(emb))\n shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=-1)\n x = self.norm(x) * (1 + scale_msa) + shift_msa\n return x, gate_msa, shift_mlp, scale_mlp, gate_mlp\n\n\nclass AdaLayerNormZeroSingle(nn.Module):\n def __init__(self, embedding_dim: int, norm_type=\"layer_norm\", bias=True):\n super().__init__()\n\n self.silu = nn.SiLU()\n self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)\n if norm_type == \"layer_norm\":\n self.norm = LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)\n else:\n raise ValueError(f\"unknown norm_type {norm_type}\")\n\n def forward(\n self,\n x: torch.Tensor,\n emb: Optional[torch.Tensor] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:\n emb = emb.unsqueeze(-2)\n emb = self.linear(self.silu(emb))\n shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=-1)\n x = self.norm(x) * (1 + scale_msa) + shift_msa\n return x, gate_msa\n\n\nclass AdaLayerNormContinuous(nn.Module):\n def __init__(\n self,\n embedding_dim: int,\n conditioning_embedding_dim: int,\n elementwise_affine=True,\n eps=1e-5,\n bias=True,\n norm_type=\"layer_norm\",\n ):\n super().__init__()\n self.silu = nn.SiLU()\n self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)\n if norm_type == \"layer_norm\":\n self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)\n else:\n raise ValueError(f\"unknown norm_type {norm_type}\")\n\n def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:\n emb = emb.unsqueeze(-2)\n emb = self.linear(self.silu(emb))\n scale, shift = emb.chunk(2, dim=-1)\n x = self.norm(x) * (1 + scale) + shift\n return x\n\n\nclass HunyuanVideoSingleTransformerBlock(nn.Module):\n def __init__(\n self,\n num_attention_heads: int,\n attention_head_dim: int,\n mlp_ratio: float = 4.0,\n qk_norm: str = \"rms_norm\",\n ) -> None:\n super().__init__()\n\n hidden_size = num_attention_heads * attention_head_dim\n mlp_dim = int(hidden_size * mlp_ratio)\n\n self.attn = Attention(\n query_dim=hidden_size,\n cross_attention_dim=None,\n dim_head=attention_head_dim,\n heads=num_attention_heads,\n out_dim=hidden_size,\n bias=True,\n processor=HunyuanAttnProcessorFlashAttnSingle(),\n qk_norm=qk_norm,\n eps=1e-6,\n pre_only=True,\n )\n\n self.norm = AdaLayerNormZeroSingle(hidden_size, norm_type=\"layer_norm\")\n self.proj_mlp = nn.Linear(hidden_size, mlp_dim)\n self.act_mlp = nn.GELU(approximate=\"tanh\")\n self.proj_out = nn.Linear(hidden_size + mlp_dim, hidden_size)\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n encoder_hidden_states: torch.Tensor,\n temb: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,\n ) -> torch.Tensor:\n text_seq_length = encoder_hidden_states.shape[1]\n hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)\n\n residual = hidden_states\n\n # 1. Input normalization\n norm_hidden_states, gate = self.norm(hidden_states, emb=temb)\n mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))\n\n norm_hidden_states, norm_encoder_hidden_states = (\n norm_hidden_states[:, :-text_seq_length, :],\n norm_hidden_states[:, -text_seq_length:, :],\n )\n\n # 2. Attention\n attn_output, context_attn_output = self.attn(\n hidden_states=norm_hidden_states,\n encoder_hidden_states=norm_encoder_hidden_states,\n attention_mask=attention_mask,\n image_rotary_emb=image_rotary_emb,\n )\n attn_output = torch.cat([attn_output, context_attn_output], dim=1)\n\n # 3. Modulation and residual connection\n hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)\n hidden_states = gate * self.proj_out(hidden_states)\n hidden_states = hidden_states + residual\n\n hidden_states, encoder_hidden_states = (\n hidden_states[:, :-text_seq_length, :],\n hidden_states[:, -text_seq_length:, :],\n )\n return hidden_states, encoder_hidden_states\n\n\nclass HunyuanVideoTransformerBlock(nn.Module):\n def __init__(\n self,\n num_attention_heads: int,\n attention_head_dim: int,\n mlp_ratio: float,\n qk_norm: str = \"rms_norm\",\n ) -> None:\n super().__init__()\n\n hidden_size = num_attention_heads * attention_head_dim\n\n self.norm1 = AdaLayerNormZero(hidden_size, norm_type=\"layer_norm\")\n self.norm1_context = AdaLayerNormZero(hidden_size, norm_type=\"layer_norm\")\n\n self.attn = Attention(\n query_dim=hidden_size,\n cross_attention_dim=None,\n added_kv_proj_dim=hidden_size,\n dim_head=attention_head_dim,\n heads=num_attention_heads,\n out_dim=hidden_size,\n context_pre_only=False,\n bias=True,\n processor=HunyuanAttnProcessorFlashAttnDouble(),\n qk_norm=qk_norm,\n eps=1e-6,\n )\n\n self.norm2 = LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n self.ff = FeedForward(hidden_size, mult=mlp_ratio, activation_fn=\"gelu-approximate\")\n\n self.norm2_context = LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n self.ff_context = FeedForward(hidden_size, mult=mlp_ratio, activation_fn=\"gelu-approximate\")\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n encoder_hidden_states: torch.Tensor,\n temb: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n freqs_cis: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n # 1. Input normalization\n norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)\n norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(encoder_hidden_states, emb=temb)\n\n # 2. Joint attention\n attn_output, context_attn_output = self.attn(\n hidden_states=norm_hidden_states,\n encoder_hidden_states=norm_encoder_hidden_states,\n attention_mask=attention_mask,\n image_rotary_emb=freqs_cis,\n )\n\n # 3. Modulation and residual connection\n hidden_states = hidden_states + attn_output * gate_msa\n encoder_hidden_states = encoder_hidden_states + context_attn_output * c_gate_msa\n\n norm_hidden_states = self.norm2(hidden_states)\n norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)\n\n norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp\n norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp) + c_shift_mlp\n\n # 4. Feed-forward\n ff_output = self.ff(norm_hidden_states)\n context_ff_output = self.ff_context(norm_encoder_hidden_states)\n\n hidden_states = hidden_states + gate_mlp * ff_output\n encoder_hidden_states = encoder_hidden_states + c_gate_mlp * context_ff_output\n\n return hidden_states, encoder_hidden_states\n\n\nclass ClipVisionProjection(nn.Module):\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.up = nn.Linear(in_channels, out_channels * 3)\n self.down = nn.Linear(out_channels * 3, out_channels)\n\n def forward(self, x):\n projected_x = self.down(nn.functional.silu(self.up(x)))\n return projected_x\n\n\nclass HunyuanVideoPatchEmbed(nn.Module):\n def __init__(self, patch_size, in_chans, embed_dim):\n super().__init__()\n self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)\n\n\nclass HunyuanVideoPatchEmbedForCleanLatents(nn.Module):\n def __init__(self, inner_dim):\n super().__init__()\n self.proj = nn.Conv3d(16, inner_dim, kernel_size=(1, 2, 2), stride=(1, 2, 2))\n self.proj_2x = nn.Conv3d(16, inner_dim, kernel_size=(2, 4, 4), stride=(2, 4, 4))\n self.proj_4x = nn.Conv3d(16, inner_dim, kernel_size=(4, 8, 8), stride=(4, 8, 8))\n\n @torch.no_grad()\n def initialize_weight_from_another_conv3d(self, another_layer):\n weight = another_layer.weight.detach().clone()\n bias = another_layer.bias.detach().clone()\n\n sd = {\n 'proj.weight': weight.clone(),\n 'proj.bias': bias.clone(),\n 'proj_2x.weight': einops.repeat(weight, 'b c t h w -> b c (t tk) (h hk) (w wk)', tk=2, hk=2, wk=2) / 8.0,\n 'proj_2x.bias': bias.clone(),\n 'proj_4x.weight': einops.repeat(weight, 'b c t h w -> b c (t tk) (h hk) (w wk)', tk=4, hk=4, wk=4) / 64.0,\n 'proj_4x.bias': bias.clone(),\n }\n\n sd = {k: v.clone() for k, v in sd.items()}\n\n self.load_state_dict(sd)\n return\n\n\nclass HunyuanVideoTransformer3DModelPacked(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):\n @register_to_config\n def __init__(\n self,\n in_channels: int = 16,\n out_channels: int = 16,\n num_attention_heads: int = 24,\n attention_head_dim: int = 128,\n num_layers: int = 20,\n num_single_layers: int = 40,\n num_refiner_layers: int = 2,\n mlp_ratio: float = 4.0,\n patch_size: int = 2,\n patch_size_t: int = 1,\n qk_norm: str = \"rms_norm\",\n guidance_embeds: bool = True,\n text_embed_dim: int = 4096,\n pooled_projection_dim: int = 768,\n rope_theta: float = 256.0,\n rope_axes_dim: Tuple[int] = (16, 56, 56),\n has_image_proj=False,\n image_proj_dim=1152,\n has_clean_x_embedder=False,\n ) -> None:\n super().__init__()\n\n inner_dim = num_attention_heads * attention_head_dim\n out_channels = out_channels or in_channels\n\n # 1. Latent and condition embedders\n self.x_embedder = HunyuanVideoPatchEmbed((patch_size_t, patch_size, patch_size), in_channels, inner_dim)\n self.context_embedder = HunyuanVideoTokenRefiner(\n text_embed_dim, num_attention_heads, attention_head_dim, num_layers=num_refiner_layers\n )\n self.time_text_embed = CombinedTimestepGuidanceTextProjEmbeddings(inner_dim, pooled_projection_dim)\n\n self.clean_x_embedder = None\n self.image_projection = None\n\n # 2. RoPE\n self.rope = HunyuanVideoRotaryPosEmbed(rope_axes_dim, rope_theta)\n\n # 3. Dual stream transformer blocks\n self.transformer_blocks = nn.ModuleList(\n [\n HunyuanVideoTransformerBlock(\n num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm\n )\n for _ in range(num_layers)\n ]\n )\n\n # 4. Single stream transformer blocks\n self.single_transformer_blocks = nn.ModuleList(\n [\n HunyuanVideoSingleTransformerBlock(\n num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm\n )\n for _ in range(num_single_layers)\n ]\n )\n\n # 5. Output projection\n self.norm_out = AdaLayerNormContinuous(inner_dim, inner_dim, elementwise_affine=False, eps=1e-6)\n self.proj_out = nn.Linear(inner_dim, patch_size_t * patch_size * patch_size * out_channels)\n\n self.inner_dim = inner_dim\n self.use_gradient_checkpointing = False\n self.enable_teacache = False\n\n if has_image_proj:\n self.install_image_projection(image_proj_dim)\n\n if has_clean_x_embedder:\n self.install_clean_x_embedder()\n\n self.high_quality_fp32_output_for_inference = False\n\n def install_image_projection(self, in_channels):\n self.image_projection = ClipVisionProjection(in_channels=in_channels, out_channels=self.inner_dim)\n self.config['has_image_proj'] = True\n self.config['image_proj_dim'] = in_channels\n\n def install_clean_x_embedder(self):\n self.clean_x_embedder = HunyuanVideoPatchEmbedForCleanLatents(self.inner_dim)\n self.config['has_clean_x_embedder'] = True\n\n def enable_gradient_checkpointing(self):\n self.use_gradient_checkpointing = True\n print('self.use_gradient_checkpointing = True')\n\n def disable_gradient_checkpointing(self):\n self.use_gradient_checkpointing = False\n print('self.use_gradient_checkpointing = False')\n\n def initialize_teacache(self, enable_teacache=True, num_steps=25, rel_l1_thresh=0.15):\n self.enable_teacache = enable_teacache\n self.cnt = 0\n self.num_steps = num_steps\n self.rel_l1_thresh = rel_l1_thresh # 0.1 for 1.6x speedup, 0.15 for 2.1x speedup\n self.accumulated_rel_l1_distance = 0\n self.previous_modulated_input = None\n self.previous_residual = None\n self.teacache_rescale_func = np.poly1d([7.33226126e+02, -4.01131952e+02, 6.75869174e+01, -3.14987800e+00, 9.61237896e-02])\n\n def gradient_checkpointing_method(self, block, *args):\n if self.use_gradient_checkpointing:\n result = torch.utils.checkpoint.checkpoint(block, *args, use_reentrant=False)\n else:\n result = block(*args)\n return result\n\n def process_input_hidden_states(\n self,\n latents, latent_indices=None,\n clean_latents=None, clean_latent_indices=None,\n clean_latents_2x=None, clean_latent_2x_indices=None,\n clean_latents_4x=None, clean_latent_4x_indices=None\n ):\n hidden_states = self.gradient_checkpointing_method(self.x_embedder.proj, latents)\n B, C, T, H, W = hidden_states.shape\n\n if latent_indices is None:\n latent_indices = torch.arange(0, T).unsqueeze(0).expand(B, -1)\n\n hidden_states = hidden_states.flatten(2).transpose(1, 2)\n\n rope_freqs = self.rope(frame_indices=latent_indices, height=H, width=W, device=hidden_states.device)\n rope_freqs = rope_freqs.flatten(2).transpose(1, 2)\n\n if clean_latents is not None and clean_latent_indices is not None:\n clean_latents = clean_latents.to(hidden_states)\n clean_latents = self.gradient_checkpointing_method(self.clean_x_embedder.proj, clean_latents)\n clean_latents = clean_latents.flatten(2).transpose(1, 2)\n\n clean_latent_rope_freqs = self.rope(frame_indices=clean_latent_indices, height=H, width=W, device=clean_latents.device)\n clean_latent_rope_freqs = clean_latent_rope_freqs.flatten(2).transpose(1, 2)\n\n hidden_states = torch.cat([clean_latents, hidden_states], dim=1)\n rope_freqs = torch.cat([clean_latent_rope_freqs, rope_freqs], dim=1)\n\n if clean_latents_2x is not None and clean_latent_2x_indices is not None:\n clean_latents_2x = clean_latents_2x.to(hidden_states)\n clean_latents_2x = pad_for_3d_conv(clean_latents_2x, (2, 4, 4))\n clean_latents_2x = self.gradient_checkpointing_method(self.clean_x_embedder.proj_2x, clean_latents_2x)\n clean_latents_2x = clean_latents_2x.flatten(2).transpose(1, 2)\n\n clean_latent_2x_rope_freqs = self.rope(frame_indices=clean_latent_2x_indices, height=H, width=W, device=clean_latents_2x.device)\n clean_latent_2x_rope_freqs = pad_for_3d_conv(clean_latent_2x_rope_freqs, (2, 2, 2))\n clean_latent_2x_rope_freqs = center_down_sample_3d(clean_latent_2x_rope_freqs, (2, 2, 2))\n clean_latent_2x_rope_freqs = clean_latent_2x_rope_freqs.flatten(2).transpose(1, 2)\n\n hidden_states = torch.cat([clean_latents_2x, hidden_states], dim=1)\n rope_freqs = torch.cat([clean_latent_2x_rope_freqs, rope_freqs], dim=1)\n\n if clean_latents_4x is not None and clean_latent_4x_indices is not None:\n clean_latents_4x = clean_latents_4x.to(hidden_states)\n clean_latents_4x = pad_for_3d_conv(clean_latents_4x, (4, 8, 8))\n clean_latents_4x = self.gradient_checkpointing_method(self.clean_x_embedder.proj_4x, clean_latents_4x)\n clean_latents_4x = clean_latents_4x.flatten(2).transpose(1, 2)\n\n clean_latent_4x_rope_freqs = self.rope(frame_indices=clean_latent_4x_indices, height=H, width=W, device=clean_latents_4x.device)\n clean_latent_4x_rope_freqs = pad_for_3d_conv(clean_latent_4x_rope_freqs, (4, 4, 4))\n clean_latent_4x_rope_freqs = center_down_sample_3d(clean_latent_4x_rope_freqs, (4, 4, 4))\n clean_latent_4x_rope_freqs = clean_latent_4x_rope_freqs.flatten(2).transpose(1, 2)\n\n hidden_states = torch.cat([clean_latents_4x, hidden_states], dim=1)\n rope_freqs = torch.cat([clean_latent_4x_rope_freqs, rope_freqs], dim=1)\n\n return hidden_states, rope_freqs\n\n def forward(\n self,\n hidden_states, timestep, encoder_hidden_states, encoder_attention_mask, pooled_projections, guidance,\n latent_indices=None,\n clean_latents=None, clean_latent_indices=None,\n clean_latents_2x=None, clean_latent_2x_indices=None,\n clean_latents_4x=None, clean_latent_4x_indices=None,\n image_embeddings=None,\n attention_kwargs=None, return_dict=True\n ):\n\n if attention_kwargs is None:\n attention_kwargs = {}\n\n batch_size, num_channels, num_frames, height, width = hidden_states.shape\n p, p_t = self.config['patch_size'], self.config['patch_size_t']\n post_patch_num_frames = num_frames // p_t\n post_patch_height = height // p\n post_patch_width = width // p\n original_context_length = post_patch_num_frames * post_patch_height * post_patch_width\n\n hidden_states, rope_freqs = self.process_input_hidden_states(hidden_states, latent_indices, clean_latents, clean_latent_indices, clean_latents_2x, clean_latent_2x_indices, clean_latents_4x, clean_latent_4x_indices)\n\n temb = self.gradient_checkpointing_method(self.time_text_embed, timestep, guidance, pooled_projections)\n encoder_hidden_states = self.gradient_checkpointing_method(self.context_embedder, encoder_hidden_states, timestep, encoder_attention_mask)\n\n if self.image_projection is not None:\n assert image_embeddings is not None, 'You must use image embeddings!'\n extra_encoder_hidden_states = self.gradient_checkpointing_method(self.image_projection, image_embeddings)\n extra_attention_mask = torch.ones((batch_size, extra_encoder_hidden_states.shape[1]), dtype=encoder_attention_mask.dtype, device=encoder_attention_mask.device)\n\n # must cat before (not after) encoder_hidden_states, due to attn masking\n encoder_hidden_states = torch.cat([extra_encoder_hidden_states, encoder_hidden_states], dim=1)\n encoder_attention_mask = torch.cat([extra_attention_mask, encoder_attention_mask], dim=1)\n\n if batch_size == 1:\n # When batch size is 1, we do not need any masks or var-len funcs since cropping is mathematically same to what we want\n # If they are not same, then their impls are wrong. Ours are always the correct one.\n text_len = encoder_attention_mask.sum().item()\n encoder_hidden_states = encoder_hidden_states[:, :text_len]\n attention_mask = None, None, None, None\n else:\n img_seq_len = hidden_states.shape[1]\n txt_seq_len = encoder_hidden_states.shape[1]\n\n cu_seqlens_q = get_cu_seqlens(encoder_attention_mask, img_seq_len)\n cu_seqlens_kv = cu_seqlens_q\n max_seqlen_q = img_seq_len + txt_seq_len\n max_seqlen_kv = max_seqlen_q\n\n attention_mask = cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv\n\n if self.enable_teacache:\n modulated_inp = self.transformer_blocks[0].norm1(hidden_states, emb=temb)[0]\n\n if self.cnt == 0 or self.cnt == self.num_steps-1:\n should_calc = True\n self.accumulated_rel_l1_distance = 0\n else:\n curr_rel_l1 = ((modulated_inp - self.previous_modulated_input).abs().mean() / self.previous_modulated_input.abs().mean()).cpu().item()\n self.accumulated_rel_l1_distance += self.teacache_rescale_func(curr_rel_l1)\n should_calc = self.accumulated_rel_l1_distance >= self.rel_l1_thresh\n\n if should_calc:\n self.accumulated_rel_l1_distance = 0\n\n self.previous_modulated_input = modulated_inp\n self.cnt += 1\n\n if self.cnt == self.num_steps:\n self.cnt = 0\n\n if not should_calc:\n hidden_states = hidden_states + self.previous_residual\n else:\n ori_hidden_states = hidden_states.clone()\n\n for block_id, block in enumerate(self.transformer_blocks):\n hidden_states, encoder_hidden_states = self.gradient_checkpointing_method(\n block,\n hidden_states,\n encoder_hidden_states,\n temb,\n attention_mask,\n rope_freqs\n )\n\n for block_id, block in enumerate(self.single_transformer_blocks):\n hidden_states, encoder_hidden_states = self.gradient_checkpointing_method(\n block,\n hidden_states,\n encoder_hidden_states,\n temb,\n attention_mask,\n rope_freqs\n )\n\n self.previous_residual = hidden_states - ori_hidden_states\n else:\n for block_id, block in enumerate(self.transformer_blocks):\n hidden_states, encoder_hidden_states = self.gradient_checkpointing_method(\n block,\n hidden_states,\n encoder_hidden_states,\n temb,\n attention_mask,\n rope_freqs\n )\n\n for block_id, block in enumerate(self.single_transformer_blocks):\n hidden_states, encoder_hidden_states = self.gradient_checkpointing_method(\n block,\n hidden_states,\n encoder_hidden_states,\n temb,\n attention_mask,\n rope_freqs\n )\n\n hidden_states = self.gradient_checkpointing_method(self.norm_out, hidden_states, temb)\n\n hidden_states = hidden_states[:, -original_context_length:, :]\n\n if self.high_quality_fp32_output_for_inference:\n hidden_states = hidden_states.to(dtype=torch.float32)\n if self.proj_out.weight.dtype != torch.float32:\n self.proj_out.to(dtype=torch.float32)\n\n hidden_states = self.gradient_checkpointing_method(self.proj_out, hidden_states)\n\n hidden_states = einops.rearrange(hidden_states, 'b (t h w) (c pt ph pw) -> b c (t pt) (h ph) (w pw)',\n t=post_patch_num_frames, h=post_patch_height, w=post_patch_width,\n pt=p_t, ph=p, pw=p)\n\n if return_dict:\n return Transformer2DModelOutput(sample=hidden_states)\n\n return hidden_states,\n"], ["/FramePack/diffusers_helper/memory.py", "# By lllyasviel\n\n\nimport torch\n\n\ncpu = torch.device('cpu')\ngpu = torch.device(f'cuda:{torch.cuda.current_device()}')\ngpu_complete_modules = []\n\n\nclass DynamicSwapInstaller:\n @staticmethod\n def _install_module(module: torch.nn.Module, **kwargs):\n original_class = module.__class__\n module.__dict__['forge_backup_original_class'] = original_class\n\n def hacked_get_attr(self, name: str):\n if '_parameters' in self.__dict__:\n _parameters = self.__dict__['_parameters']\n if name in _parameters:\n p = _parameters[name]\n if p is None:\n return None\n if p.__class__ == torch.nn.Parameter:\n return torch.nn.Parameter(p.to(**kwargs), requires_grad=p.requires_grad)\n else:\n return p.to(**kwargs)\n if '_buffers' in self.__dict__:\n _buffers = self.__dict__['_buffers']\n if name in _buffers:\n return _buffers[name].to(**kwargs)\n return super(original_class, self).__getattr__(name)\n\n module.__class__ = type('DynamicSwap_' + original_class.__name__, (original_class,), {\n '__getattr__': hacked_get_attr,\n })\n\n return\n\n @staticmethod\n def _uninstall_module(module: torch.nn.Module):\n if 'forge_backup_original_class' in module.__dict__:\n module.__class__ = module.__dict__.pop('forge_backup_original_class')\n return\n\n @staticmethod\n def install_model(model: torch.nn.Module, **kwargs):\n for m in model.modules():\n DynamicSwapInstaller._install_module(m, **kwargs)\n return\n\n @staticmethod\n def uninstall_model(model: torch.nn.Module):\n for m in model.modules():\n DynamicSwapInstaller._uninstall_module(m)\n return\n\n\ndef fake_diffusers_current_device(model: torch.nn.Module, target_device: torch.device):\n if hasattr(model, 'scale_shift_table'):\n model.scale_shift_table.data = model.scale_shift_table.data.to(target_device)\n return\n\n for k, p in model.named_modules():\n if hasattr(p, 'weight'):\n p.to(target_device)\n return\n\n\ndef get_cuda_free_memory_gb(device=None):\n if device is None:\n device = gpu\n\n memory_stats = torch.cuda.memory_stats(device)\n bytes_active = memory_stats['active_bytes.all.current']\n bytes_reserved = memory_stats['reserved_bytes.all.current']\n bytes_free_cuda, _ = torch.cuda.mem_get_info(device)\n bytes_inactive_reserved = bytes_reserved - bytes_active\n bytes_total_available = bytes_free_cuda + bytes_inactive_reserved\n return bytes_total_available / (1024 ** 3)\n\n\ndef move_model_to_device_with_memory_preservation(model, target_device, preserved_memory_gb=0):\n print(f'Moving {model.__class__.__name__} to {target_device} with preserved memory: {preserved_memory_gb} GB')\n\n for m in model.modules():\n if get_cuda_free_memory_gb(target_device) <= preserved_memory_gb:\n torch.cuda.empty_cache()\n return\n\n if hasattr(m, 'weight'):\n m.to(device=target_device)\n\n model.to(device=target_device)\n torch.cuda.empty_cache()\n return\n\n\ndef offload_model_from_device_for_memory_preservation(model, target_device, preserved_memory_gb=0):\n print(f'Offloading {model.__class__.__name__} from {target_device} to preserve memory: {preserved_memory_gb} GB')\n\n for m in model.modules():\n if get_cuda_free_memory_gb(target_device) >= preserved_memory_gb:\n torch.cuda.empty_cache()\n return\n\n if hasattr(m, 'weight'):\n m.to(device=cpu)\n\n model.to(device=cpu)\n torch.cuda.empty_cache()\n return\n\n\ndef unload_complete_models(*args):\n for m in gpu_complete_modules + list(args):\n m.to(device=cpu)\n print(f'Unloaded {m.__class__.__name__} as complete.')\n\n gpu_complete_modules.clear()\n torch.cuda.empty_cache()\n return\n\n\ndef load_model_as_complete(model, target_device, unload=True):\n if unload:\n unload_complete_models()\n\n model.to(device=target_device)\n print(f'Loaded {model.__class__.__name__} to {target_device} as complete.')\n\n gpu_complete_modules.append(model)\n return\n"], ["/FramePack/diffusers_helper/k_diffusion/uni_pc_fm.py", "# Better Flow Matching UniPC by Lvmin Zhang\n# (c) 2025\n# CC BY-SA 4.0\n# Attribution-ShareAlike 4.0 International Licence\n\n\nimport torch\n\nfrom tqdm.auto import trange\n\n\ndef expand_dims(v, dims):\n return v[(...,) + (None,) * (dims - 1)]\n\n\nclass FlowMatchUniPC:\n def __init__(self, model, extra_args, variant='bh1'):\n self.model = model\n self.variant = variant\n self.extra_args = extra_args\n\n def model_fn(self, x, t):\n return self.model(x, t, **self.extra_args)\n\n def update_fn(self, x, model_prev_list, t_prev_list, t, order):\n assert order <= len(model_prev_list)\n dims = x.dim()\n\n t_prev_0 = t_prev_list[-1]\n lambda_prev_0 = - torch.log(t_prev_0)\n lambda_t = - torch.log(t)\n model_prev_0 = model_prev_list[-1]\n\n h = lambda_t - lambda_prev_0\n\n rks = []\n D1s = []\n for i in range(1, order):\n t_prev_i = t_prev_list[-(i + 1)]\n model_prev_i = model_prev_list[-(i + 1)]\n lambda_prev_i = - torch.log(t_prev_i)\n rk = ((lambda_prev_i - lambda_prev_0) / h)[0]\n rks.append(rk)\n D1s.append((model_prev_i - model_prev_0) / rk)\n\n rks.append(1.)\n rks = torch.tensor(rks, device=x.device)\n\n R = []\n b = []\n\n hh = -h[0]\n h_phi_1 = torch.expm1(hh)\n h_phi_k = h_phi_1 / hh - 1\n\n factorial_i = 1\n\n if self.variant == 'bh1':\n B_h = hh\n elif self.variant == 'bh2':\n B_h = torch.expm1(hh)\n else:\n raise NotImplementedError('Bad variant!')\n\n for i in range(1, order + 1):\n R.append(torch.pow(rks, i - 1))\n b.append(h_phi_k * factorial_i / B_h)\n factorial_i *= (i + 1)\n h_phi_k = h_phi_k / hh - 1 / factorial_i\n\n R = torch.stack(R)\n b = torch.tensor(b, device=x.device)\n\n use_predictor = len(D1s) > 0\n\n if use_predictor:\n D1s = torch.stack(D1s, dim=1)\n if order == 2:\n rhos_p = torch.tensor([0.5], device=b.device)\n else:\n rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1])\n else:\n D1s = None\n rhos_p = None\n\n if order == 1:\n rhos_c = torch.tensor([0.5], device=b.device)\n else:\n rhos_c = torch.linalg.solve(R, b)\n\n x_t_ = expand_dims(t / t_prev_0, dims) * x - expand_dims(h_phi_1, dims) * model_prev_0\n\n if use_predictor:\n pred_res = torch.tensordot(D1s, rhos_p, dims=([1], [0]))\n else:\n pred_res = 0\n\n x_t = x_t_ - expand_dims(B_h, dims) * pred_res\n model_t = self.model_fn(x_t, t)\n\n if D1s is not None:\n corr_res = torch.tensordot(D1s, rhos_c[:-1], dims=([1], [0]))\n else:\n corr_res = 0\n\n D1_t = (model_t - model_prev_0)\n x_t = x_t_ - expand_dims(B_h, dims) * (corr_res + rhos_c[-1] * D1_t)\n\n return x_t, model_t\n\n def sample(self, x, sigmas, callback=None, disable_pbar=False):\n order = min(3, len(sigmas) - 2)\n model_prev_list, t_prev_list = [], []\n for i in trange(len(sigmas) - 1, disable=disable_pbar):\n vec_t = sigmas[i].expand(x.shape[0])\n\n if i == 0:\n model_prev_list = [self.model_fn(x, vec_t)]\n t_prev_list = [vec_t]\n elif i < order:\n init_order = i\n x, model_x = self.update_fn(x, model_prev_list, t_prev_list, vec_t, init_order)\n model_prev_list.append(model_x)\n t_prev_list.append(vec_t)\n else:\n x, model_x = self.update_fn(x, model_prev_list, t_prev_list, vec_t, order)\n model_prev_list.append(model_x)\n t_prev_list.append(vec_t)\n\n model_prev_list = model_prev_list[-order:]\n t_prev_list = t_prev_list[-order:]\n\n if callback is not None:\n callback({'x': x, 'i': i, 'denoised': model_prev_list[-1]})\n\n return model_prev_list[-1]\n\n\ndef sample_unipc(model, noise, sigmas, extra_args=None, callback=None, disable=False, variant='bh1'):\n assert variant in ['bh1', 'bh2']\n return FlowMatchUniPC(model, extra_args=extra_args, variant=variant).sample(noise, sigmas=sigmas, callback=callback, disable_pbar=disable)\n"], ["/FramePack/demo_gradio_f1.py", "from diffusers_helper.hf_login import login\n\nimport os\n\nos.environ['HF_HOME'] = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download')))\n\nimport gradio as gr\nimport torch\nimport traceback\nimport einops\nimport safetensors.torch as sf\nimport numpy as np\nimport argparse\nimport math\n\nfrom PIL import Image\nfrom diffusers import AutoencoderKLHunyuanVideo\nfrom transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer\nfrom diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake\nfrom diffusers_helper.utils import save_bcthw_as_mp4, crop_or_pad_yield_mask, soft_append_bcthw, resize_and_center_crop, state_dict_weighted_merge, state_dict_offset_merge, generate_timestamp\nfrom diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked\nfrom diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan\nfrom diffusers_helper.memory import cpu, gpu, get_cuda_free_memory_gb, move_model_to_device_with_memory_preservation, offload_model_from_device_for_memory_preservation, fake_diffusers_current_device, DynamicSwapInstaller, unload_complete_models, load_model_as_complete\nfrom diffusers_helper.thread_utils import AsyncStream, async_run\nfrom diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html\nfrom transformers import SiglipImageProcessor, SiglipVisionModel\nfrom diffusers_helper.clip_vision import hf_clip_vision_encode\nfrom diffusers_helper.bucket_tools import find_nearest_bucket\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--share', action='store_true')\nparser.add_argument(\"--server\", type=str, default='0.0.0.0')\nparser.add_argument(\"--port\", type=int, required=False)\nparser.add_argument(\"--inbrowser\", action='store_true')\nargs = parser.parse_args()\n\n# for win desktop probably use --server 127.0.0.1 --inbrowser\n# For linux server probably use --server 127.0.0.1 or do not use any cmd flags\n\nprint(args)\n\nfree_mem_gb = get_cuda_free_memory_gb(gpu)\nhigh_vram = free_mem_gb > 60\n\nprint(f'Free VRAM {free_mem_gb} GB')\nprint(f'High-VRAM Mode: {high_vram}')\n\ntext_encoder = LlamaModel.from_pretrained(\"hunyuanvideo-community/HunyuanVideo\", subfolder='text_encoder', torch_dtype=torch.float16).cpu()\ntext_encoder_2 = CLIPTextModel.from_pretrained(\"hunyuanvideo-community/HunyuanVideo\", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu()\ntokenizer = LlamaTokenizerFast.from_pretrained(\"hunyuanvideo-community/HunyuanVideo\", subfolder='tokenizer')\ntokenizer_2 = CLIPTokenizer.from_pretrained(\"hunyuanvideo-community/HunyuanVideo\", subfolder='tokenizer_2')\nvae = AutoencoderKLHunyuanVideo.from_pretrained(\"hunyuanvideo-community/HunyuanVideo\", subfolder='vae', torch_dtype=torch.float16).cpu()\n\nfeature_extractor = SiglipImageProcessor.from_pretrained(\"lllyasviel/flux_redux_bfl\", subfolder='feature_extractor')\nimage_encoder = SiglipVisionModel.from_pretrained(\"lllyasviel/flux_redux_bfl\", subfolder='image_encoder', torch_dtype=torch.float16).cpu()\n\ntransformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('lllyasviel/FramePack_F1_I2V_HY_20250503', torch_dtype=torch.bfloat16).cpu()\n\nvae.eval()\ntext_encoder.eval()\ntext_encoder_2.eval()\nimage_encoder.eval()\ntransformer.eval()\n\nif not high_vram:\n vae.enable_slicing()\n vae.enable_tiling()\n\ntransformer.high_quality_fp32_output_for_inference = True\nprint('transformer.high_quality_fp32_output_for_inference = True')\n\ntransformer.to(dtype=torch.bfloat16)\nvae.to(dtype=torch.float16)\nimage_encoder.to(dtype=torch.float16)\ntext_encoder.to(dtype=torch.float16)\ntext_encoder_2.to(dtype=torch.float16)\n\nvae.requires_grad_(False)\ntext_encoder.requires_grad_(False)\ntext_encoder_2.requires_grad_(False)\nimage_encoder.requires_grad_(False)\ntransformer.requires_grad_(False)\n\nif not high_vram:\n # DynamicSwapInstaller is same as huggingface's enable_sequential_offload but 3x faster\n DynamicSwapInstaller.install_model(transformer, device=gpu)\n DynamicSwapInstaller.install_model(text_encoder, device=gpu)\nelse:\n text_encoder.to(gpu)\n text_encoder_2.to(gpu)\n image_encoder.to(gpu)\n vae.to(gpu)\n transformer.to(gpu)\n\nstream = AsyncStream()\n\noutputs_folder = './outputs/'\nos.makedirs(outputs_folder, exist_ok=True)\n\n\n@torch.no_grad()\ndef worker(input_image, prompt, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf):\n total_latent_sections = (total_second_length * 30) / (latent_window_size * 4)\n total_latent_sections = int(max(round(total_latent_sections), 1))\n\n job_id = generate_timestamp()\n\n stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))\n\n try:\n # Clean GPU\n if not high_vram:\n unload_complete_models(\n text_encoder, text_encoder_2, image_encoder, vae, transformer\n )\n\n # Text encoding\n\n stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))\n\n if not high_vram:\n fake_diffusers_current_device(text_encoder, gpu) # since we only encode one text - that is one model move and one encode, offload is same time consumption since it is also one load and one encode.\n load_model_as_complete(text_encoder_2, target_device=gpu)\n\n llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)\n\n if cfg == 1:\n llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)\n else:\n llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)\n\n llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)\n llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)\n\n # Processing input image\n\n stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Image processing ...'))))\n\n H, W, C = input_image.shape\n height, width = find_nearest_bucket(H, W, resolution=640)\n input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height)\n\n Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))\n\n input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1\n input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None]\n\n # VAE encoding\n\n stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...'))))\n\n if not high_vram:\n load_model_as_complete(vae, target_device=gpu)\n\n start_latent = vae_encode(input_image_pt, vae)\n\n # CLIP Vision\n\n stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))\n\n if not high_vram:\n load_model_as_complete(image_encoder, target_device=gpu)\n\n image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)\n image_encoder_last_hidden_state = image_encoder_output.last_hidden_state\n\n # Dtype\n\n llama_vec = llama_vec.to(transformer.dtype)\n llama_vec_n = llama_vec_n.to(transformer.dtype)\n clip_l_pooler = clip_l_pooler.to(transformer.dtype)\n clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)\n image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)\n\n # Sampling\n\n stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))\n\n rnd = torch.Generator(\"cpu\").manual_seed(seed)\n\n history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32).cpu()\n history_pixels = None\n\n history_latents = torch.cat([history_latents, start_latent.to(history_latents)], dim=2)\n total_generated_latent_frames = 1\n\n for section_index in range(total_latent_sections):\n if stream.input_queue.top() == 'end':\n stream.output_queue.push(('end', None))\n return\n\n print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')\n\n if not high_vram:\n unload_complete_models()\n move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)\n\n if use_teacache:\n transformer.initialize_teacache(enable_teacache=True, num_steps=steps)\n else:\n transformer.initialize_teacache(enable_teacache=False)\n\n def callback(d):\n preview = d['denoised']\n preview = vae_decode_fake(preview)\n\n preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)\n preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')\n\n if stream.input_queue.top() == 'end':\n stream.output_queue.push(('end', None))\n raise KeyboardInterrupt('User ends the task.')\n\n current_step = d['i'] + 1\n percentage = int(100.0 * current_step / steps)\n hint = f'Sampling {current_step}/{steps}'\n desc = f'Total generated frames: {int(max(0, total_generated_latent_frames * 4 - 3))}, Video length: {max(0, (total_generated_latent_frames * 4 - 3) / 30) :.2f} seconds (FPS-30). The video is being extended now ...'\n stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))\n return\n\n indices = torch.arange(0, sum([1, 16, 2, 1, latent_window_size])).unsqueeze(0)\n clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split([1, 16, 2, 1, latent_window_size], dim=1)\n clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)\n\n clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents[:, :, -sum([16, 2, 1]):, :, :].split([16, 2, 1], dim=2)\n clean_latents = torch.cat([start_latent.to(history_latents), clean_latents_1x], dim=2)\n\n generated_latents = sample_hunyuan(\n transformer=transformer,\n sampler='unipc',\n width=width,\n height=height,\n frames=latent_window_size * 4 - 3,\n real_guidance_scale=cfg,\n distilled_guidance_scale=gs,\n guidance_rescale=rs,\n # shift=3.0,\n num_inference_steps=steps,\n generator=rnd,\n prompt_embeds=llama_vec,\n prompt_embeds_mask=llama_attention_mask,\n prompt_poolers=clip_l_pooler,\n negative_prompt_embeds=llama_vec_n,\n negative_prompt_embeds_mask=llama_attention_mask_n,\n negative_prompt_poolers=clip_l_pooler_n,\n device=gpu,\n dtype=torch.bfloat16,\n image_embeddings=image_encoder_last_hidden_state,\n latent_indices=latent_indices,\n clean_latents=clean_latents,\n clean_latent_indices=clean_latent_indices,\n clean_latents_2x=clean_latents_2x,\n clean_latent_2x_indices=clean_latent_2x_indices,\n clean_latents_4x=clean_latents_4x,\n clean_latent_4x_indices=clean_latent_4x_indices,\n callback=callback,\n )\n\n total_generated_latent_frames += int(generated_latents.shape[2])\n history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)\n\n if not high_vram:\n offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)\n load_model_as_complete(vae, target_device=gpu)\n\n real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]\n\n if history_pixels is None:\n history_pixels = vae_decode(real_history_latents, vae).cpu()\n else:\n section_latent_frames = latent_window_size * 2\n overlapped_frames = latent_window_size * 4 - 3\n\n current_pixels = vae_decode(real_history_latents[:, :, -section_latent_frames:], vae).cpu()\n history_pixels = soft_append_bcthw(history_pixels, current_pixels, overlapped_frames)\n\n if not high_vram:\n unload_complete_models()\n\n output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')\n\n save_bcthw_as_mp4(history_pixels, output_filename, fps=30, crf=mp4_crf)\n\n print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')\n\n stream.output_queue.push(('file', output_filename))\n except:\n traceback.print_exc()\n\n if not high_vram:\n unload_complete_models(\n text_encoder, text_encoder_2, image_encoder, vae, transformer\n )\n\n stream.output_queue.push(('end', None))\n return\n\n\ndef process(input_image, prompt, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf):\n global stream\n assert input_image is not None, 'No input image!'\n\n yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)\n\n stream = AsyncStream()\n\n async_run(worker, input_image, prompt, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf)\n\n output_filename = None\n\n while True:\n flag, data = stream.output_queue.next()\n\n if flag == 'file':\n output_filename = data\n yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)\n\n if flag == 'progress':\n preview, desc, html = data\n yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)\n\n if flag == 'end':\n yield output_filename, gr.update(visible=False), gr.update(), '', gr.update(interactive=True), gr.update(interactive=False)\n break\n\n\ndef end_process():\n stream.input_queue.push('end')\n\n\nquick_prompts = [\n 'The girl dances gracefully, with clear movements, full of charm.',\n 'A character doing some simple body movements.',\n]\nquick_prompts = [[x] for x in quick_prompts]\n\n\ncss = make_progress_bar_css()\nblock = gr.Blocks(css=css).queue()\nwith block:\n gr.Markdown('# FramePack-F1')\n with gr.Row():\n with gr.Column():\n input_image = gr.Image(sources='upload', type=\"numpy\", label=\"Image\", height=320)\n prompt = gr.Textbox(label=\"Prompt\", value='')\n example_quick_prompts = gr.Dataset(samples=quick_prompts, label='Quick List', samples_per_page=1000, components=[prompt])\n example_quick_prompts.click(lambda x: x[0], inputs=[example_quick_prompts], outputs=prompt, show_progress=False, queue=False)\n\n with gr.Row():\n start_button = gr.Button(value=\"Start Generation\")\n end_button = gr.Button(value=\"End Generation\", interactive=False)\n\n with gr.Group():\n use_teacache = gr.Checkbox(label='Use TeaCache', value=True, info='Faster speed, but often makes hands and fingers slightly worse.')\n\n n_prompt = gr.Textbox(label=\"Negative Prompt\", value=\"\", visible=False) # Not used\n seed = gr.Number(label=\"Seed\", value=31337, precision=0)\n\n total_second_length = gr.Slider(label=\"Total Video Length (Seconds)\", minimum=1, maximum=120, value=5, step=0.1)\n latent_window_size = gr.Slider(label=\"Latent Window Size\", minimum=1, maximum=33, value=9, step=1, visible=False) # Should not change\n steps = gr.Slider(label=\"Steps\", minimum=1, maximum=100, value=25, step=1, info='Changing this value is not recommended.')\n\n cfg = gr.Slider(label=\"CFG Scale\", minimum=1.0, maximum=32.0, value=1.0, step=0.01, visible=False) # Should not change\n gs = gr.Slider(label=\"Distilled CFG Scale\", minimum=1.0, maximum=32.0, value=10.0, step=0.01, info='Changing this value is not recommended.')\n rs = gr.Slider(label=\"CFG Re-Scale\", minimum=0.0, maximum=1.0, value=0.0, step=0.01, visible=False) # Should not change\n\n gpu_memory_preservation = gr.Slider(label=\"GPU Inference Preserved Memory (GB) (larger means slower)\", minimum=6, maximum=128, value=6, step=0.1, info=\"Set this number to a larger value if you encounter OOM. Larger value causes slower speed.\")\n\n mp4_crf = gr.Slider(label=\"MP4 Compression\", minimum=0, maximum=100, value=16, step=1, info=\"Lower means better quality. 0 is uncompressed. Change to 16 if you get black outputs. \")\n\n with gr.Column():\n preview_image = gr.Image(label=\"Next Latents\", height=200, visible=False)\n result_video = gr.Video(label=\"Finished Frames\", autoplay=True, show_share_button=False, height=512, loop=True)\n progress_desc = gr.Markdown('', elem_classes='no-generating-animation')\n progress_bar = gr.HTML('', elem_classes='no-generating-animation')\n\n gr.HTML('