Skip to content
Python

added text encoder cache

DeepBeepMeepb2cd56b265aa
diff --git a/README.md b/README.md
index 7418372..aa04efc 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@ WanGP supports the Wan (and derived models), Hunyuan Video, Flux, Qwen, Z-Image,
## 🔥 Latest Updates :
-### January 17th 2026: WanGP v10.41, The Cost Saver
+### January 19th 2026: WanGP v10.41, The Cost Saver
*GPUs are expensive, RAM is expensive, SSD are expensive, sadly we live now in a GPU & RAM poor.*
WanGP comes again to the rescue:
@@ -44,7 +44,12 @@ WanGP comes again to the rescue:
- **Flux 2 Klein 4B & 9B**: try these distilled models as fast as Z_Image if not faster but with out of the box image edition capabiltities
-*update 10.41*: added Flux 2 klein
+- **RAM Optimizations for multi minutes Videos**: processing, saving, spatial & Temporal upsampling very long videos should require much less RAM.
+
+- **Text Encoder Cache**: if you are using a Text prompt already used recently with the current model, it will be taken straight from a cache. The cache is optimized to consume little RAM. It wont work with certain models such as Qwen where the Text Pormpt is combined internally with an Image.
+
+*update 10.41*: added Flux 2 klein\
+*update 10.42*: added RAM optimizations & Text Encoder Cache
### January 15th 2026: WanGP v10.30, The Need for Speed ...
diff --git a/icons/bottom.svg b/icons/bottom.svg
deleted file mode 100644
index 1aeccc4..0000000
--- a/icons/bottom.svg
+++ /dev/null
@@ -1,14 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" fill="#000000" viewBox="0 0 512 512">
- <g>
- <g>
- <g>
- <path d="M256,0C114.618,0,0,114.618,0,256s114.618,256,256,256s256-114.618,256-256S397.382,0,256,0z M256,469.333
- c-117.818,0-213.333-95.515-213.333-213.333S138.182,42.667,256,42.667S469.333,138.182,469.333,256S373.818,469.333,256,469.333
- z"/>
- <path d="M347.582,198.248L256,289.83l-91.582-91.582c-8.331-8.331-21.839-8.331-30.17,0c-8.331,8.331-8.331,21.839,0,30.17
- l106.667,106.667c8.331,8.331,21.839,8.331,30.17,0l106.667-106.667c8.331-8.331,8.331-21.839,0-30.17
- C369.42,189.917,355.913,189.917,347.582,198.248z"/>
- </g>
- </g>
- </g>
-</svg>
\ No newline at end of file
diff --git a/icons/edit.svg b/icons/edit.svg
deleted file mode 100644
index 7910c6e..0000000
--- a/icons/edit.svg
+++ /dev/null
@@ -1,5 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
-<path d="M0 0 C1.11826172 0.00322266 2.23652344 0.00644531 3.38867188 0.00976562 C4.55591797 0.01814453 5.72316406 0.02652344 6.92578125 0.03515625 C8.10462891 0.03966797 9.28347656 0.04417969 10.49804688 0.04882812 C13.41150914 0.06062352 16.32486988 0.07708355 19.23828125 0.09765625 C19.89828125 1.41765625 20.55828125 2.73765625 21.23828125 4.09765625 C20.57828125 5.08765625 19.91828125 6.07765625 19.23828125 7.09765625 C16.71630859 7.43823242 16.71630859 7.43823242 13.57421875 7.390625 C12.56407715 7.38313232 11.55393555 7.37563965 10.51318359 7.36791992 C9.22621582 7.34060791 7.93924805 7.3132959 6.61328125 7.28515625 C2.52953125 7.22328125 -1.55421875 7.16140625 -5.76171875 7.09765625 C-5.76171875 20.62765625 -5.76171875 34.15765625 -5.76171875 48.09765625 C7.76828125 48.09765625 21.29828125 48.09765625 35.23828125 48.09765625 C35.11973183 40.33403423 35.11973183 40.33403423 34.96801758 32.57104492 C34.9605249 31.60400635 34.95303223 30.63696777 34.9453125 29.640625 C34.92960205 28.6508667 34.9138916 27.6611084 34.89770508 26.64135742 C35.28781002 23.72773495 35.95836413 22.87267823 38.23828125 21.09765625 C39.55828125 21.75765625 40.87828125 22.41765625 42.23828125 23.09765625 C42.35462058 27.32659093 42.42558077 31.55511299 42.48828125 35.78515625 C42.53855469 37.58243164 42.53855469 37.58243164 42.58984375 39.41601562 C42.60273437 40.57294922 42.615625 41.72988281 42.62890625 42.921875 C42.64985352 43.98494873 42.67080078 45.04802246 42.69238281 46.14331055 C42.08668997 50.08389607 41.33970543 51.54877801 38.23828125 54.09765625 C34.80064189 54.82978838 31.42929782 54.77430179 27.92578125 54.7265625 C26.41697388 54.73018044 26.41697388 54.73018044 24.87768555 54.73387146 C22.75272679 54.73289272 20.62774263 54.71949279 18.50292969 54.69458008 C15.2497702 54.66027739 11.99932742 54.67391872 8.74609375 54.69335938 C6.68097802 54.68646084 4.6158693 54.67678839 2.55078125 54.6640625 C1.57778076 54.66902237 0.60478027 54.67398224 -0.39770508 54.67909241 C-4.22696801 54.61228762 -6.97272175 54.52167304 -10.37524414 52.69311523 C-12.57503646 48.57513809 -12.31211348 44.60130827 -12.2578125 40.00390625 C-12.25926773 39.02023071 -12.26072296 38.03655518 -12.26222229 37.02307129 C-12.26056374 34.94520096 -12.24900737 32.8673183 -12.22827148 30.78955078 C-12.19932355 27.60916966 -12.20766242 24.43045611 -12.22070312 21.25 C-12.21446541 19.23046065 -12.20607421 17.21092656 -12.1953125 15.19140625 C-12.19824814 14.24027954 -12.20118378 13.28915283 -12.20420837 12.3092041 C-12.1915242 11.42148315 -12.17884003 10.53376221 -12.16577148 9.61914062 C-12.1603685 8.84066772 -12.15496552 8.06219482 -12.1493988 7.26013184 C-11.65561813 4.50582801 -10.66022148 3.13054266 -8.76171875 1.09765625 C-5.58384334 0.03836445 -3.33582932 -0.01693314 0 0 Z " fill="#5F7D8B" transform="translate(11.76171875,9.90234375)"/>
-<path d="M0 0 C3.18086518 1.50946511 5.29869906 3.07941825 7.75 5.625 C8.67039062 6.57246094 8.67039062 6.57246094 9.609375 7.5390625 C10.29773437 8.26222656 10.29773437 8.26222656 11 9 C8.59523682 14.54812095 4.06412729 18.38524881 -0.125 22.625 C-0.95515625 23.49640625 -1.7853125 24.3678125 -2.640625 25.265625 C-7.55981439 30.24649701 -10.9212929 33.32655006 -18 34 C-19.67421842 33.70694442 -21.34358949 33.38104214 -23 33 C-22.73322255 23.701482 -19.99207397 18.8860205 -13.359375 12.48046875 C-12.36512148 11.56972466 -11.37032304 10.65957512 -10.375 9.75 C-9.37010113 8.79537851 -8.3674748 7.83835883 -7.3671875 6.87890625 C-4.93268233 4.56144459 -2.47807311 2.27066292 0 0 Z " fill="#42A5F5" transform="translate(45,8)"/>
-<path d="M0 0 C1.9375 1 1.9375 1 3 3 C3.73574144 8.06844106 3.73574144 8.06844106 3 11 C1.18277145 13.20174358 -0.58687091 14.39124727 -3 16 C-6.3 12.7 -9.6 9.4 -13 6 C-8.2454497 0.05681213 -7.32417654 -0.5139773 0 0 Z " fill="#42A5F5" transform="translate(61,0)"/>
-</svg>
\ No newline at end of file
diff --git a/icons/remove.svg b/icons/remove.svg
deleted file mode 100644
index af13a6d..0000000
--- a/icons/remove.svg
+++ /dev/null
@@ -1,3 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
-<path d="M0 0 C0.91974609 -0.01224609 1.83949219 -0.02449219 2.78710938 -0.03710938 C3.67076172 -0.03904297 4.55441406 -0.04097656 5.46484375 -0.04296875 C6.27429443 -0.04707764 7.08374512 -0.05118652 7.91772461 -0.05541992 C10.0625 0.1875 10.0625 0.1875 13.0625 2.1875 C13.75 4.8125 13.75 4.8125 14.0625 7.1875 C15.42375 7.06375 15.42375 7.06375 16.8125 6.9375 C20.0625 7.1875 20.0625 7.1875 22.5 8.875 C24.0625 11.1875 24.0625 11.1875 23.9375 13.5625 C23.0625 16.1875 23.0625 16.1875 22.04296875 18.640625 C20.67104278 23.60360819 20.63408506 28.43456418 20.5 33.5625 C20.38290046 37.43924233 20.24089926 41.31308782 20.0625 45.1875 C20.02600342 46.35974121 20.02600342 46.35974121 19.98876953 47.55566406 C19.75385703 51.06553322 19.41343427 52.82998048 16.91577148 55.37451172 C13.52950324 57.5261698 11.60953176 57.70262762 7.625 57.71875 C5.78808594 57.72648437 5.78808594 57.72648437 3.9140625 57.734375 C2.64304687 57.71890625 1.37203125 57.7034375 0.0625 57.6875 C-1.84402344 57.71070312 -1.84402344 57.71070312 -3.7890625 57.734375 C-5.01367188 57.72921875 -6.23828125 57.7240625 -7.5 57.71875 C-8.61503906 57.71423828 -9.73007812 57.70972656 -10.87890625 57.70507812 C-14.62316268 57.07147151 -16.29526355 55.87931783 -18.9375 53.1875 C-19.5718301 50.34090421 -19.84799189 48.06242942 -19.9375 45.1875 C-19.97858887 44.29514648 -20.01967773 43.40279297 -20.06201172 42.48339844 C-20.22958856 38.48982026 -20.35059881 34.49569673 -20.45507812 30.5 C-20.63368241 25.36428436 -20.93861234 20.9970841 -22.9375 16.1875 C-23.8125 13.5625 -23.8125 13.5625 -23.9375 11.1875 C-22.375 8.875 -22.375 8.875 -19.9375 7.1875 C-16.6875 6.9375 -16.6875 6.9375 -13.9375 7.1875 C-13.64875 6.218125 -13.36 5.24875 -13.0625 4.25 C-10.91276671 -1.60205174 -5.44118975 0.00379706 0 0 Z M-9.9375 4.1875 C-9.6075 5.5075 -9.2775 6.8275 -8.9375 8.1875 C-2.6675 8.1875 3.6025 8.1875 10.0625 8.1875 C10.0625 6.8675 10.0625 5.5475 10.0625 4.1875 C3.4625 4.1875 -3.1375 4.1875 -9.9375 4.1875 Z M-19.9375 16.1875 C-19.9375 16.5175 -19.9375 16.8475 -19.9375 17.1875 C-6.7375 17.1875 6.4625 17.1875 20.0625 17.1875 C20.0625 16.8575 20.0625 16.5275 20.0625 16.1875 C6.8625 16.1875 -6.3375 16.1875 -19.9375 16.1875 Z M-9.9375 29.1875 C-9.9375 34.7975 -9.9375 40.4075 -9.9375 46.1875 C-9.6075 46.1875 -9.2775 46.1875 -8.9375 46.1875 C-8.9375 40.5775 -8.9375 34.9675 -8.9375 29.1875 C-9.2675 29.1875 -9.5975 29.1875 -9.9375 29.1875 Z M9.0625 29.1875 C9.0625 34.7975 9.0625 40.4075 9.0625 46.1875 C9.3925 46.1875 9.7225 46.1875 10.0625 46.1875 C10.0625 40.5775 10.0625 34.9675 10.0625 29.1875 C9.7325 29.1875 9.4025 29.1875 9.0625 29.1875 Z " fill="#2A8BFF" transform="translate(31.9375,3.8125)"/>
-</svg>
\ No newline at end of file
diff --git a/icons/top.svg b/icons/top.svg
deleted file mode 100644
index b327527..0000000
--- a/icons/top.svg
+++ /dev/null
@@ -1,14 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" fill="#000000" viewBox="0 0 512 512">
- <g>
- <g>
- <g>
- <path d="M256,0C114.618,0,0,114.618,0,256s114.618,256,256,256s256-114.618,256-256S397.382,0,256,0z M256,469.333
- c-117.818,0-213.333-95.515-213.333-213.333S138.182,42.667,256,42.667S469.333,138.182,469.333,256S373.818,469.333,256,469.333
- z"/>
- <path d="M271.085,176.915c-8.331-8.331-21.839-8.331-30.17,0L134.248,283.582c-8.331,8.331-8.331,21.839,0,30.17
- c8.331,8.331,21.839,8.331,30.17,0L256,222.17l91.582,91.582c8.331,8.331,21.839,8.331,30.17,0c8.331-8.331,8.331-21.839,0-30.17
- L271.085,176.915z"/>
- </g>
- </g>
- </g>
-</svg>
\ No newline at end of file
diff --git a/models/flux/flux_main.py b/models/flux/flux_main.py
index e19577a..ae5e530 100644
--- a/models/flux/flux_main.py
+++ b/models/flux/flux_main.py
@@ -16,6 +16,7 @@ from shared.utils import files_locator as fl
from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2VLProcessor
from .modules.autoencoder_flux2 import AutoencoderKLFlux2, AutoEncoderParamsFlux2
from shared.qtypes import nunchaku_int4 as _nunchaku_int4
+from shared.utils.text_encoder_cache import TextEncoderCache
from .util import load_ae, load_clip, load_flow_model, load_t5, preprocess_flux_state_dict
from .flux2_adapter import (
@@ -94,6 +95,7 @@ class model_factory:
self.name = model_def.get("flux-model", "flux-dev")
self.is_piflux2 = self.name == "pi-flux2"
self.is_flux2 = self.name.startswith("flux2") or self.is_piflux2
+ self.text_encoder_cache = TextEncoderCache()
# model_filename = ["c:/temp/flux1-schnell.safetensors"]
source = model_def.get("source", None)
@@ -108,7 +110,9 @@ class model_factory:
text_encoder_type = model_def.get("text_encoder_type", "mistral3")
if text_encoder_type == "qwen3":
from .modules.text_encoder_qwen3 import Qwen3Embedder
- tokenizer_path = model_def.get("text_encoder_folder")
+ text_encoder_folder = model_def.get("text_encoder_folder")
+ tokenizer_path = os.path.dirname(fl.locate_file(os.path.join(text_encoder_folder, "tokenizer_config.json")))
+
self.mistral = Qwen3Embedder(
model_spec=text_encoder_filename,
tokenizer_path=tokenizer_path,
@@ -283,14 +287,13 @@ class model_factory:
generator = torch.Generator(device="cuda").manual_seed(seed)
randn = torch.randn(shape, generator=generator, dtype=torch.bfloat16, device="cuda")
img, img_ids = batched_prc_img(randn)
- ctx = self.mistral([input_prompt]).to(torch.bfloat16)
- txt_embeds, txt_ids = batched_prc_txt(ctx)
+ encode_fn = lambda prompts: list(zip(*batched_prc_txt(self.mistral(prompts).to(torch.bfloat16))))
+ txt_embeds, txt_ids = self.text_encoder_cache.encode(encode_fn, [input_prompt], device=self.device)[0]
txt_embeds, txt_ids = txt_embeds.expand(batch_size, -1, -1), txt_ids.expand(batch_size, -1, -1)
vec = torch.zeros(batch_size, 1, device=device, dtype=self.dtype)
inp = { "img": img, "img_ids": img_ids, "txt": txt_embeds.to(device), "txt_ids": txt_ids.to(device), "vec": vec }
if guide_scale != 1:
- ctx = self.mistral([n_prompt]).to(torch.bfloat16)
- txt_embeds, txt_ids = batched_prc_txt(ctx)
+ txt_embeds, txt_ids = self.text_encoder_cache.encode(encode_fn, [n_prompt], device=self.device)[0]
txt_embeds, txt_ids = txt_embeds.expand(batch_size, -1, -1), txt_ids.expand(batch_size, -1, -1)
inp.update({ "neg_txt": txt_embeds.to(device), "neg_txt_ids": txt_ids.to(device), "neg_vec": vec })
@@ -389,9 +392,28 @@ class model_factory:
noise_channels=noise_channels,
)
- inp.update(prepare_prompt(self.t5, self.clip, batch_size, input_prompt))
+ encode_fn = lambda prompts: [prepare_prompt(self.t5, self.clip, 1, prompt, device=device) for prompt in prompts]
+ prompt_list = [input_prompt] if isinstance(input_prompt, str) else input_prompt
+ prompt_bs = len(prompt_list) if batch_size == 1 and not isinstance(input_prompt, str) else batch_size
+ prompt_contexts = self.text_encoder_cache.encode(encode_fn, prompt_list, device=device)
+ txt = torch.cat([ctx["txt"] for ctx in prompt_contexts], dim=0)
+ vec = torch.cat([ctx["vec"] for ctx in prompt_contexts], dim=0)
+ if txt.shape[0] == 1 and prompt_bs > 1:
+ txt = txt.repeat(prompt_bs, 1, 1)
+ vec = vec.repeat(prompt_bs, 1)
+ txt_ids = torch.zeros(prompt_bs, txt.shape[1], 3, device=device)
+ inp.update({"txt": txt.to(device), "txt_ids": txt_ids.to(device), "vec": vec.to(device)})
if guide_scale != 1:
- inp.update(prepare_prompt(self.t5, self.clip, batch_size, n_prompt, neg = True, device=device))
+ neg_list = [n_prompt] if isinstance(n_prompt, str) else n_prompt
+ neg_bs = len(neg_list) if batch_size == 1 and not isinstance(n_prompt, str) else batch_size
+ neg_contexts = self.text_encoder_cache.encode(encode_fn, neg_list, device=device)
+ neg_txt = torch.cat([ctx["txt"] for ctx in neg_contexts], dim=0)
+ neg_vec = torch.cat([ctx["vec"] for ctx in neg_contexts], dim=0)
+ if neg_txt.shape[0] == 1 and neg_bs > 1:
+ neg_txt = neg_txt.repeat(neg_bs, 1, 1)
+ neg_vec = neg_vec.repeat(neg_bs, 1)
+ neg_txt_ids = torch.zeros(neg_bs, neg_txt.shape[1], 3, device=device)
+ inp.update({"neg_txt": neg_txt.to(device), "neg_txt_ids": neg_txt_ids.to(device), "neg_vec": neg_vec.to(device)})
timesteps = get_schedule(sampling_steps, inp["img"].shape[1], shift=(self.name != "flux-schnell"))
diff --git a/models/flux/modules/text_encoder_qwen3.py b/models/flux/modules/text_encoder_qwen3.py
index b3da3ae..bded77c 100644
--- a/models/flux/modules/text_encoder_qwen3.py
+++ b/models/flux/modules/text_encoder_qwen3.py
@@ -31,8 +31,6 @@ class Qwen3Embedder(nn.Module):
)
tokenizer_root = tokenizer_path or os.path.dirname(file_path)
- if tokenizer_root and not os.path.isabs(tokenizer_root):
- tokenizer_root = fl.locate_folder(tokenizer_root)
tokenizer_subdir = os.path.join(tokenizer_root, "tokenizer")
if os.path.isdir(tokenizer_subdir):
tokenizer_root = tokenizer_subdir
diff --git a/models/hyvideo/diffusion/pipelines/pipeline_hunyuan_video.py b/models/hyvideo/diffusion/pipelines/pipeline_hunyuan_video.py
index 86a741a..cb6c0d5 100644
--- a/models/hyvideo/diffusion/pipelines/pipeline_hunyuan_video.py
+++ b/models/hyvideo/diffusion/pipelines/pipeline_hunyuan_video.py
@@ -51,6 +51,7 @@ from ...modules import HYVideoDiffusionTransformer
from mmgp import offload
from ...utils.data_utils import black_image
from einops import rearrange
+from shared.utils.text_encoder_cache import TextEncoderCache
EXAMPLE_DOC_STRING = """"""
@@ -252,6 +253,7 @@ class HunyuanVideoPipeline(DiffusionPipeline):
self.noise_pertub = 0
self.hunyuan_1_5 = hunyuan_1_5
self.target_dtype = torch.bfloat16
+ self.text_encoder_cache = TextEncoderCache()
def encode_prompt_1_5(
self,
@@ -319,39 +321,32 @@ class HunyuanVideoPipeline(DiffusionPipeline):
if prompt_embeds is None:
- text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, max_length=text_encoder.max_length)
- if clip_skip is None:
- prompt_outputs = text_encoder.encode(
- text_inputs, data_type=data_type, device=device
- )
- prompt_embeds = prompt_outputs.hidden_state
- else:
- prompt_outputs = text_encoder.encode(
- text_inputs,
- output_hidden_states=True,
- data_type=data_type,
- device=device,
- )
- # Access the `hidden_states` first, that contains a tuple of
- # all the hidden states from the encoder layers. Then index into
- # the tuple to access the hidden states from the desired layer.
- prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
- # We also need to apply the final LayerNorm here to not mess with the
- # representations. The `last_hidden_states` that we typically use for
- # obtaining the final prompt representations passes through the LayerNorm
- # layer.
- prompt_embeds = text_encoder.model.text_model.final_layer_norm(
- prompt_embeds
- )
-
- attention_mask = prompt_outputs.attention_mask
+ def encode_fn(prompts):
+ text_inputs = text_encoder.text2tokens(prompts, data_type=data_type, max_length=text_encoder.max_length)
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type, device=device)
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type, device=device)
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)
+ attention_mask = prompt_outputs.attention_mask
+ if attention_mask is None:
+ return [(prompt_embeds[i], None) for i in range(prompt_embeds.shape[0])]
+ return list(zip(prompt_embeds, attention_mask))
+
+ prompt_list = prompt if isinstance(prompt, list) else [prompt]
+ cache_keys = [(id(text_encoder), name, data_type, clip_skip, text_encoder.max_length, text) for text in prompt_list]
+ prompt_contexts = self.text_encoder_cache.encode(encode_fn, prompt_list, device=device, cache_keys=cache_keys)
+ prompt_embeds = torch.stack([ctx[0] for ctx in prompt_contexts], dim=0)
+ attention_mask = prompt_contexts[0][1]
+ if attention_mask is not None:
+ attention_mask = torch.stack([ctx[1] for ctx in prompt_contexts], dim=0)
if attention_mask is not None:
attention_mask = attention_mask.to(device)
bs_embed, seq_len = attention_mask.shape
attention_mask = attention_mask.repeat(1, num_videos_per_prompt)
- attention_mask = attention_mask.view(
- bs_embed * num_videos_per_prompt, seq_len
- )
+ attention_mask = attention_mask.view(bs_embed * num_videos_per_prompt, seq_len)
if text_encoder is not None:
prompt_embeds_dtype = text_encoder.dtype
@@ -396,12 +391,21 @@ class HunyuanVideoPipeline(DiffusionPipeline):
else:
uncond_tokens = negative_prompt
- uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type, max_length=text_encoder.max_length)
-
- negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type, is_uncond=True)
- negative_prompt_embeds = negative_prompt_outputs.hidden_state
-
- negative_attention_mask = negative_prompt_outputs.attention_mask
+ def encode_uncond_fn(prompts):
+ uncond_input = text_encoder.text2tokens(prompts, data_type=data_type, max_length=text_encoder.max_length)
+ negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type, is_uncond=True)
+ negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ negative_attention_mask = negative_prompt_outputs.attention_mask
+ if negative_attention_mask is None:
+ return [(negative_prompt_embeds[i], None) for i in range(negative_prompt_embeds.shape[0])]
+ return list(zip(negative_prompt_embeds, negative_attention_mask))
+
+ cache_keys = [("uncond", id(text_encoder), name, data_type, text_encoder.max_length, text) for text in uncond_tokens]
+ negative_contexts = self.text_encoder_cache.encode(encode_uncond_fn, uncond_tokens, device=device, cache_keys=cache_keys)
+ negative_prompt_embeds = torch.stack([ctx[0] for ctx in negative_contexts], dim=0)
+ negative_attention_mask = negative_contexts[0][1]
+ if negative_attention_mask is not None:
+ negative_attention_mask = torch.stack([ctx[1] for ctx in negative_contexts], dim=0)
if negative_attention_mask is not None:
negative_attention_mask = negative_attention_mask.to(device)
_, seq_len = negative_attention_mask.shape
@@ -513,45 +517,51 @@ class HunyuanVideoPipeline(DiffusionPipeline):
if isinstance(self, TextualInversionLoaderMixin):
prompt = self.maybe_convert_prompt(prompt, text_encoder.tokenizer)
- text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, name = name)
+ use_cache = pixel_value_llava is None and semantic_images is None
+ if use_cache:
+ def encode_fn(prompts):
+ text_inputs = text_encoder.text2tokens(prompts, data_type=data_type, name=name)
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type, semantic_images=None, device=device)
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type, semantic_images=None, device=device)
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)
+ attention_mask = prompt_outputs.attention_mask
+ if attention_mask is None:
+ return [(prompt_embeds[i], None) for i in range(prompt_embeds.shape[0])]
+ return list(zip(prompt_embeds, attention_mask))
+
+ prompt_list = prompt if isinstance(prompt, list) else [prompt]
+ cache_keys = [(id(text_encoder), name, data_type, clip_skip, lora_scale, text) for text in prompt_list]
+ prompt_contexts = self.text_encoder_cache.encode(encode_fn, prompt_list, device=device, cache_keys=cache_keys)
+ prompt_embeds = torch.stack([ctx[0] for ctx in prompt_contexts], dim=0)
+ attention_mask = prompt_contexts[0][1]
+ if attention_mask is not None:
+ attention_mask = torch.stack([ctx[1] for ctx in prompt_contexts], dim=0)
+ else:
+ text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, name=name)
- if pixel_value_llava is not None:
- text_inputs['pixel_value_llava'] = pixel_value_llava
- text_inputs['attention_mask'] = torch.cat([text_inputs['attention_mask'], torch.ones((1, 575 * len(pixel_value_llava))).to(text_inputs['attention_mask'])], dim=1)
+ if pixel_value_llava is not None:
+ text_inputs['pixel_value_llava'] = pixel_value_llava
+ text_inputs['attention_mask'] = torch.cat([text_inputs['attention_mask'], torch.ones((1, 575 * len(pixel_value_llava))).to(text_inputs['attention_mask'])], dim=1)
- if clip_skip is None:
- prompt_outputs = text_encoder.encode(
- text_inputs, data_type=data_type, semantic_images=semantic_images, device=device
- )
- prompt_embeds = prompt_outputs.hidden_state
- else:
- prompt_outputs = text_encoder.encode(
- text_inputs,
- output_hidden_states=True,
- data_type=data_type,
- semantic_images=semantic_images,
- device=device,
- )
- # Access the `hidden_states` first, that contains a tuple of
- # all the hidden states from the encoder layers. Then index into
- # the tuple to access the hidden states from the desired layer.
- prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
- # We also need to apply the final LayerNorm here to not mess with the
- # representations. The `last_hidden_states` that we typically use for
- # obtaining the final prompt representations passes through the LayerNorm
- # layer.
- prompt_embeds = text_encoder.model.text_model.final_layer_norm(
- prompt_embeds
- )
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type, semantic_images=semantic_images, device=device)
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type, semantic_images=semantic_images, device=device)
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)
+
+ attention_mask = prompt_outputs.attention_mask
- attention_mask = prompt_outputs.attention_mask
if attention_mask is not None:
attention_mask = attention_mask.to(device)
bs_embed, seq_len = attention_mask.shape
attention_mask = attention_mask.repeat(1, num_videos_per_prompt)
- attention_mask = attention_mask.view(
- bs_embed * num_videos_per_prompt, seq_len
- )
+ attention_mask = attention_mask.view(bs_embed * num_videos_per_prompt, seq_len)
if text_encoder is not None:
prompt_embeds_dtype = text_encoder.dtype
@@ -602,33 +612,44 @@ class HunyuanVideoPipeline(DiffusionPipeline):
uncond_tokens, text_encoder.tokenizer
)
- # max_length = prompt_embeds.shape[1]
- uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type, name = name)
-
- if semantic_images is not None:
- uncond_image = [black_image(img.size[0], img.size[1]) for img in semantic_images]
+ use_cache = uncond_pixel_value_llava is None and semantic_images is None
+ if use_cache:
+ def encode_uncond_fn(prompts):
+ uncond_input = text_encoder.text2tokens(prompts, data_type=data_type, name=name)
+ negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type, semantic_images=None, device=device)
+ negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ negative_attention_mask = negative_prompt_outputs.attention_mask
+ if negative_attention_mask is None:
+ return [(negative_prompt_embeds[i], None) for i in range(negative_prompt_embeds.shape[0])]
+ return list(zip(negative_prompt_embeds, negative_attention_mask))
+
+ cache_keys = [("uncond", id(text_encoder), name, data_type, lora_scale, text) for text in uncond_tokens]
+ negative_contexts = self.text_encoder_cache.encode(encode_uncond_fn, uncond_tokens, device=device, cache_keys=cache_keys)
+ negative_prompt_embeds = torch.stack([ctx[0] for ctx in negative_contexts], dim=0)
+ negative_attention_mask = negative_contexts[0][1]
+ if negative_attention_mask is not None:
+ negative_attention_mask = torch.stack([ctx[1] for ctx in negative_contexts], dim=0)
else:
- uncond_image = None
-
- if uncond_pixel_value_llava is not None:
- uncond_input['pixel_value_llava'] = uncond_pixel_value_llava
- uncond_input['attention_mask'] = torch.cat([uncond_input['attention_mask'], torch.ones((1, 575 * len(uncond_pixel_value_llava))).to(uncond_input['attention_mask'])], dim=1)
+ uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type, name=name)
- negative_prompt_outputs = text_encoder.encode(
- uncond_input, data_type=data_type, semantic_images=uncond_image, device=device
- )
- negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ if semantic_images is not None:
+ uncond_image = [black_image(img.size[0], img.size[1]) for img in semantic_images]
+ else:
+ uncond_image = None
+
+ if uncond_pixel_value_llava is not None:
+ uncond_input['pixel_value_llava'] = uncond_pixel_value_llava
+ uncond_input['attention_mask'] = torch.cat([uncond_input['attention_mask'], torch.ones((1, 575 * len(uncond_pixel_value_llava))).to(uncond_input['attention_mask'])], dim=1)
+
+ negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type, semantic_images=uncond_image, device=device)
+ negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ negative_attention_mask = negative_prompt_outputs.attention_mask
- negative_attention_mask = negative_prompt_outputs.attention_mask
if negative_attention_mask is not None:
negative_attention_mask = negative_attention_mask.to(device)
_, seq_len = negative_attention_mask.shape
- negative_attention_mask = negative_attention_mask.repeat(
- 1, num_videos_per_prompt
- )
- negative_attention_mask = negative_attention_mask.view(
- batch_size * num_videos_per_prompt, seq_len
- )
+ negative_attention_mask = negative_attention_mask.repeat(1, num_videos_per_prompt)
+ negative_attention_mask = negative_attention_mask.view(batch_size * num_videos_per_prompt, seq_len)
if do_classifier_free_guidance:
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
diff --git a/models/hyvideo/diffusion/pipelines/pipeline_hunyuan_video_audio.py b/models/hyvideo/diffusion/pipelines/pipeline_hunyuan_video_audio.py
index c043a12..44b4521 100644
--- a/models/hyvideo/diffusion/pipelines/pipeline_hunyuan_video_audio.py
+++ b/models/hyvideo/diffusion/pipelines/pipeline_hunyuan_video_audio.py
@@ -46,6 +46,7 @@ from ...vae.autoencoder_kl_causal_3d import AutoencoderKLCausal3D
from ...text_encoder import TextEncoder
from einops import rearrange
from ...modules import HYVideoDiffusionTransformer
+from shared.utils.text_encoder_cache import TextEncoderCache
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@@ -212,6 +213,7 @@ class HunyuanVideoAudioPipeline(DiffusionPipeline):
)
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
+ self.text_encoder_cache = TextEncoderCache()
def encode_prompt(
self,
@@ -294,28 +296,47 @@ class HunyuanVideoAudioPipeline(DiffusionPipeline):
# textual inversion: process multi-vector tokens if necessary
if isinstance(self, TextualInversionLoaderMixin):
prompt = self.maybe_convert_prompt(prompt, text_encoder.tokenizer)
- text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, name=name)
- if pixel_value_llava is not None:
- text_inputs['pixel_value_llava'] = pixel_value_llava
- text_inputs['attention_mask'] = torch.cat([text_inputs['attention_mask'], torch.ones((1, 575 * len(pixel_value_llava))).to(text_inputs['attention_mask'])], dim=1)
-
- if clip_skip is None:
- prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type)
- prompt_embeds = prompt_outputs.hidden_state
+ use_cache = pixel_value_llava is None
+ if use_cache:
+ def encode_fn(prompts):
+ text_inputs = text_encoder.text2tokens(prompts, data_type=data_type, name=name)
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type)
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type)
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)
+ attention_mask = prompt_outputs.attention_mask
+ if attention_mask is None:
+ return [(prompt_embeds[i], None) for i in range(prompt_embeds.shape[0])]
+ return list(zip(prompt_embeds, attention_mask))
+
+ prompt_list = prompt if isinstance(prompt, list) else [prompt]
+ cache_keys = [(id(text_encoder), name, data_type, clip_skip, lora_scale, text) for text in prompt_list]
+ prompt_contexts = self.text_encoder_cache.encode(encode_fn, prompt_list, device=device, cache_keys=cache_keys)
+ prompt_embeds = torch.stack([ctx[0] for ctx in prompt_contexts], dim=0)
+ attention_mask = prompt_contexts[0][1]
+ if attention_mask is not None:
+ attention_mask = torch.stack([ctx[1] for ctx in prompt_contexts], dim=0)
else:
- prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type)
- # Access the `hidden_states` first, that contains a tuple of
- # all the hidden states from the encoder layers. Then index into
- # the tuple to access the hidden states from the desired layer.
- prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
- # We also need to apply the final LayerNorm here to not mess with the
- # representations. The `last_hidden_states` that we typically use for
- # obtaining the final prompt representations passes through the LayerNorm
- # layer.
- prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)
-
- attention_mask = prompt_outputs.attention_mask
+ text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, name=name)
+
+ if pixel_value_llava is not None:
+ text_inputs['pixel_value_llava'] = pixel_value_llava
+ text_inputs['attention_mask'] = torch.cat([text_inputs['attention_mask'], torch.ones((1, 575 * len(pixel_value_llava))).to(text_inputs['attention_mask'])], dim=1)
+
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type)
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type)
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)
+
+ attention_mask = prompt_outputs.attention_mask
+
if attention_mask is not None:
attention_mask = attention_mask.to(device)
bs_embed, seq_len = attention_mask.shape
@@ -366,15 +387,34 @@ class HunyuanVideoAudioPipeline(DiffusionPipeline):
# textual inversion: process multi-vector tokens if necessary
if isinstance(self, TextualInversionLoaderMixin):
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, text_encoder.tokenizer)
- uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type)
- if uncond_pixel_value_llava is not None:
- uncond_input['pixel_value_llava'] = uncond_pixel_value_llava
- uncond_input['attention_mask'] = torch.cat([uncond_input['attention_mask'], torch.ones((1, 575 * len(uncond_pixel_value_llava))).to(uncond_input['attention_mask'])], dim=1)
- negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type)
- negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ use_cache = uncond_pixel_value_llava is None
+ if use_cache:
+ def encode_uncond_fn(prompts):
+ uncond_input = text_encoder.text2tokens(prompts, data_type=data_type)
+ negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type)
+ negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ negative_attention_mask = negative_prompt_outputs.attention_mask
+ if negative_attention_mask is None:
+ return [(negative_prompt_embeds[i], None) for i in range(negative_prompt_embeds.shape[0])]
+ return list(zip(negative_prompt_embeds, negative_attention_mask))
+
+ cache_keys = [("uncond", id(text_encoder), name, data_type, lora_scale, text) for text in uncond_tokens]
+ negative_contexts = self.text_encoder_cache.encode(encode_uncond_fn, uncond_tokens, device=device, cache_keys=cache_keys)
+ negative_prompt_embeds = torch.stack([ctx[0] for ctx in negative_contexts], dim=0)
+ negative_attention_mask = negative_contexts[0][1]
+ if negative_attention_mask is not None:
+ negative_attention_mask = torch.stack([ctx[1] for ctx in negative_contexts], dim=0)
+ else:
+ uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type)
+ if uncond_pixel_value_llava is not None:
+ uncond_input['pixel_value_llava'] = uncond_pixel_value_llava
+ uncond_input['attention_mask'] = torch.cat([uncond_input['attention_mask'], torch.ones((1, 575 * len(uncond_pixel_value_llava))).to(uncond_input['attention_mask'])], dim=1)
+
+ negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type)
+ negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ negative_attention_mask = negative_prompt_outputs.attention_mask
- negative_attention_mask = negative_prompt_outputs.attention_mask
if negative_attention_mask is not None:
negative_attention_mask = negative_attention_mask.to(device)
_, seq_len = negative_attention_mask.shape
@@ -446,31 +486,49 @@ class HunyuanVideoAudioPipeline(DiffusionPipeline):
# textual inversion: process multi-vector tokens if necessary
if isinstance(self, TextualInversionLoaderMixin):
prompt = self.maybe_convert_prompt(prompt, text_encoder.tokenizer)
- text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, name=name) # data_type: video, text_inputs: {'input_ids', 'attention_mask'}
-
- text_keys = ['input_ids', 'attention_mask']
-
- if pixel_value_llava is not None:
- text_inputs['pixel_value_llava'] = pixel_value_llava
- text_inputs['attention_mask'] = torch.cat([text_inputs['attention_mask'], torch.ones((1, 575)).to(text_inputs['attention_mask'])], dim=1)
-
- if clip_skip is None:
- prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type)
- prompt_embeds = prompt_outputs.hidden_state
+ use_cache = pixel_value_llava is None
+ if use_cache:
+ def encode_fn(prompts):
+ text_inputs = text_encoder.text2tokens(prompts, data_type=data_type, name=name)
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type)
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type)
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)
+ attention_mask = prompt_outputs.attention_mask
+ if attention_mask is None:
+ return [(prompt_embeds[i], None) for i in range(prompt_embeds.shape[0])]
+ return list(zip(prompt_embeds, attention_mask))
+
+ prompt_list = prompt if isinstance(prompt, list) else [prompt]
+ cache_keys = [(id(text_encoder), name, data_type, clip_skip, lora_scale, text) for text in prompt_list]
+ prompt_contexts = self.text_encoder_cache.encode(encode_fn, prompt_list, device=device, cache_keys=cache_keys)
+ prompt_embeds = torch.stack([ctx[0] for ctx in prompt_contexts], dim=0)
+ attention_mask = prompt_contexts[0][1]
+ if attention_mask is not None:
+ attention_mask = torch.stack([ctx[1] for ctx in prompt_contexts], dim=0)
else:
- prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type)
- # Access the `hidden_states` first, that contains a tuple of
- # all the hidden states from the encoder layers. Then index into
- # the tuple to access the hidden states from the desired layer.
- prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
- # We also need to apply the final LayerNorm here to not mess with the
- # representations. The `last_hidden_states` that we typically use for
- # obtaining the final prompt representations passes through the LayerNorm
- # layer.
- prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)
-
- attention_mask = prompt_outputs.attention_mask
+ text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, name=name) # data_type: video, text_inputs: {'input_ids', 'attention_mask'}
+
+ text_keys = ['input_ids', 'attention_mask']
+
+ if pixel_value_llava is not None:
+ text_inputs['pixel_value_llava'] = pixel_value_llava
+ text_inputs['attention_mask'] = torch.cat([text_inputs['attention_mask'], torch.ones((1, 575)).to(text_inputs['attention_mask'])], dim=1)
+
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type)
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type)
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)
+
+ attention_mask = prompt_outputs.attention_mask
+
if attention_mask is not None:
attention_mask = attention_mask.to(device)
bs_embed, seq_len = attention_mask.shape
@@ -521,21 +579,35 @@ class HunyuanVideoAudioPipeline(DiffusionPipeline):
# textual inversion: process multi-vector tokens if necessary
if isinstance(self, TextualInversionLoaderMixin):
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, text_encoder.tokenizer)
- # max_length = prompt_embeds.shape[1]
- uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type, name=name)
- # if hasattr(text_encoder.model.config, "use_attention_mask") and text_encoder.model.config.use_attention_mask:
- # attention_mask = uncond_input.attention_mask.to(device)
- # else:
- # attention_mask = None
- if uncond_pixel_value_llava is not None:
- uncond_input['pixel_value_llava'] = uncond_pixel_value_llava
- uncond_input['attention_mask'] = torch.cat([uncond_input['attention_mask'], torch.ones((1, 575)).to(uncond_input['attention_mask'])], dim=1)
+ use_cache = uncond_pixel_value_llava is None
+ if use_cache:
+ def encode_uncond_fn(prompts):
+ uncond_input = text_encoder.text2tokens(prompts, data_type=data_type, name=name)
+ negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type)
+ negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ negative_attention_mask = negative_prompt_outputs.attention_mask
+ if negative_attention_mask is None:
+ return [(negative_prompt_embeds[i], None) for i in range(negative_prompt_embeds.shape[0])]
+ return list(zip(negative_prompt_embeds, negative_attention_mask))
+
+ cache_keys = [("uncond", id(text_encoder), name, data_type, lora_scale, text) for text in uncond_tokens]
+ negative_contexts = self.text_encoder_cache.encode(encode_uncond_fn, uncond_tokens, device=device, cache_keys=cache_keys)
+ negative_prompt_embeds = torch.stack([ctx[0] for ctx in negative_contexts], dim=0)
+ negative_attention_mask = negative_contexts[0][1]
+ if negative_attention_mask is not None:
+ negative_attention_mask = torch.stack([ctx[1] for ctx in negative_contexts], dim=0)
+ else:
+ uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type, name=name)
+
+ if uncond_pixel_value_llava is not None:
+ uncond_input['pixel_value_llava'] = uncond_pixel_value_llava
+ uncond_input['attention_mask'] = torch.cat([uncond_input['attention_mask'], torch.ones((1, 575)).to(uncond_input['attention_mask'])], dim=1)
- negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type)
- negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type)
+ negative_prompt_embeds = negative_prompt_outputs.hidden_state
+ negative_attention_mask = negative_prompt_outputs.attention_mask
- negative_attention_mask = negative_prompt_outputs.attention_mask
if negative_attention_mask is not None:
negative_attention_mask = negative_attention_mask.to(device)
_, seq_len = negative_attention_mask.shape
diff --git a/models/hyvideo/hunyuan.py b/models/hyvideo/hunyuan.py
index 07a71aa..2b49982 100644
--- a/models/hyvideo/hunyuan.py
+++ b/models/hyvideo/hunyuan.py
@@ -406,7 +406,7 @@ class Inference(object):
text_encoder_folder = model_def.get("text_encoder_folder")
if text_encoder_folder:
- tokenizer_path = fl.locate_folder(text_encoder_folder)
+ tokenizer_path = os.path.dirname(fl.locate_file(os.path.join(text_encoder_folder, "tokenizer_config.json")))
elif text_encoder_filepath:
tokenizer_path = os.path.dirname(text_encoder_filepath)
else:
diff --git a/models/hyvideo/text_encoder/text_encoder_1_5.py b/models/hyvideo/text_encoder/text_encoder_1_5.py
index a680c8b..cc355ac 100644
--- a/models/hyvideo/text_encoder/text_encoder_1_5.py
+++ b/models/hyvideo/text_encoder/text_encoder_1_5.py
@@ -14,6 +14,7 @@
# of rights and permissions under this agreement.
# See the License for the specific language governing permissions and limitations under the License.
+import json
import os
from copy import deepcopy
from dataclasses import dataclass
@@ -126,15 +127,30 @@ def load_tokenizer(
tokenizer_path = TOKENIZER_PATH[tokenizer_type]
tokenizer = AutoTokenizer.from_pretrained(
- os.path.dirname(tokenizer_path), padding_side=padding_side
+ tokenizer_path, padding_side=padding_side
)
# If the checkpoint ships a chat template separately, load it when missing.
if getattr(tokenizer, "chat_template", None) in (None, ""):
- jinja_path = os.path.join(os.path.dirname(tokenizer_path), "chat_template.json")
- if os.path.exists(jinja_path):
- with open(jinja_path, "r", encoding="utf-8") as f:
- tokenizer.chat_template = f.read()
+ tokenizer_root = tokenizer_path if os.path.isdir(tokenizer_path) else os.path.dirname(tokenizer_path)
+ json_path = os.path.join(tokenizer_root, "chat_template.json")
+ jinja_path = os.path.join(tokenizer_root, "chat_template.jinja")
+ template_path = json_path if os.path.exists(json_path) else jinja_path
+ if os.path.exists(template_path):
+ with open(template_path, "r", encoding="utf-8") as f:
+ template_raw = f.read()
+ if template_path.endswith(".json"):
+ try:
+ template_data = json.loads(template_raw)
+ except json.JSONDecodeError:
+ template_data = None
+ tokenizer.chat_template = (
+ template_data.get("chat_template", template_raw)
+ if isinstance(template_data, dict)
+ else template_raw
+ )
+ else:
+ tokenizer.chat_template = template_raw
return tokenizer, tokenizer_path, processor
diff --git a/models/kandinsky5/kandinsky/models/text_embedders.py b/models/kandinsky5/kandinsky/models/text_embedders.py
index c781122..80d798b 100644
--- a/models/kandinsky5/kandinsky/models/text_embedders.py
+++ b/models/kandinsky5/kandinsky/models/text_embedders.py
@@ -11,6 +11,7 @@ from transformers import (
from .utils import freeze
from mmgp import offload
import torchvision.transforms.functional as F
+from shared.utils.text_encoder_cache import TextEncoderCache
class ClipTextEmbedder:
@@ -224,12 +225,51 @@ class Kandinsky5TextEmbedder:
self.embedder = Qwen2_5_VLTextEmbedder(conf.qwen, device, quantized_qwen, text_token_padding)
self.clip_embedder = ClipTextEmbedder(conf.clip, device)
self.conf = conf
+ self.text_encoder_cache = TextEncoderCache()
def encode(self, texts, images=None, type_of_content="image"):
- text_embeds, cu_seqlens, attention_mask = self.embedder(texts, images=images, type_of_content=type_of_content)
- pooled_embed = self.clip_embedder(texts)
- if attention_mask is not None:
- attention_mask = attention_mask.to(torch.bool)
+ if isinstance(texts, str):
+ texts = [texts]
+ if images is not None:
+ text_embeds, cu_seqlens, attention_mask = self.embedder(texts, images=images, type_of_content=type_of_content)
+ pooled_embed = self.clip_embedder(texts)
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(torch.bool)
+ return {"text_embeds": text_embeds, "pooled_embed": pooled_embed}, cu_seqlens, attention_mask
+
+ def encode_fn(prompts):
+ text_embeds, cu_seqlens, attention_mask = self.embedder(prompts, images=None, type_of_content=type_of_content)
+ pooled_embed = self.clip_embedder(prompts)
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(torch.bool)
+ return [
+ {"text_embeds": text_embeds[i : i + 1], "pooled_embed": pooled_embed[i : i + 1], "attention_mask": attention_mask[i : i + 1]}
+ for i in range(text_embeds.shape[0])
+ ]
+ lengths = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
+ split_embeds = torch.split(text_embeds.squeeze(0), lengths, dim=0)
+ return [
+ {"text_embeds": emb.unsqueeze(0), "pooled_embed": pooled_embed[i : i + 1], "attention_mask": None}
+ for i, emb in enumerate(split_embeds)
+ ]
+
+ cache_keys = [(type_of_content, text) for text in texts]
+ contexts = self.text_encoder_cache.encode(encode_fn, texts, device=self.embedder.model.device, cache_keys=cache_keys)
+ if contexts and contexts[0]["attention_mask"] is None:
+ text_embeds = torch.cat([ctx["text_embeds"] for ctx in contexts], dim=1)
+ pooled_embed = torch.cat([ctx["pooled_embed"] for ctx in contexts], dim=0)
+ lengths = [ctx["text_embeds"].shape[1] for ctx in contexts]
+ cu = [0]
+ for length in lengths:
+ cu.append(cu[-1] + length)
+ cu_seqlens = torch.tensor(cu, dtype=torch.int32)
+ attention_mask = None
+ else:
+ text_embeds = torch.cat([ctx["text_embeds"] for ctx in contexts], dim=0)
+ pooled_embed = torch.cat([ctx["pooled_embed"] for ctx in contexts], dim=0)
+ attention_mask = torch.cat([ctx["attention_mask"] for ctx in contexts], dim=0)
+ seq_len = text_embeds.shape[1]
+ cu_seqlens = torch.tensor([0, seq_len], dtype=torch.int32)
return {"text_embeds": text_embeds, "pooled_embed": pooled_embed}, cu_seqlens, attention_mask
def to(self, device):
diff --git a/models/longcat/longcat_main.py b/models/longcat/longcat_main.py
index d707f7f..cd2c762 100644
--- a/models/longcat/longcat_main.py
+++ b/models/longcat/longcat_main.py
@@ -22,6 +22,7 @@ from .modules.autoencoder_kl_wan import AutoencoderKLWan
from .modules.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
from .audio_process.wav2vec2 import Wav2Vec2ModelWrapper
from ..qwen.convert_diffusers_qwen_vae import convert_state_dict
+from shared.utils.text_encoder_cache import TextEncoderCache
def _load_json_config(path):
@@ -94,6 +95,7 @@ class LongCatModel:
tokenizer_path=tokenizer_path,
shard_fn=None,
)
+ self.text_encoder_cache = TextEncoderCache()
transformer_config_path = (
"models/longcat/configs/longcat_avatar.json"
@@ -260,16 +262,25 @@ class LongCatModel:
):
device = device or self.device
dtype = dtype or self.dtype
+ def encode_fn(prompts):
+ ids, mask = self.text_encoder.tokenizer(
+ prompts,
+ return_mask=True,
+ add_special_tokens=True,
+ )
+ ids = ids.to(device)
+ mask = mask.to(device)
+ prompt_embeds = self.text_encoder.model(ids, mask).to(dtype)
+ return list(zip(prompt_embeds, mask))
prompt_list = [prompt] if isinstance(prompt, str) else prompt
batch_size = len(prompt_list)
- ids, mask = self.text_encoder.tokenizer(
+ prompt_contexts = self.text_encoder_cache.encode(
+ encode_fn,
prompt_list,
- return_mask=True,
- add_special_tokens=True,
+ device=device,
)
- ids = ids.to(device)
- mask = mask.to(device)
- prompt_embeds = self.text_encoder.model(ids, mask).to(dtype)
+ prompt_embeds = torch.stack([ctx[0] for ctx in prompt_contexts], dim=0)
+ mask = torch.stack([ctx[1] for ctx in prompt_contexts], dim=0)
seq_len = prompt_embeds.shape[1]
prompt_embeds = prompt_embeds.unsqueeze(1)
if num_videos_per_prompt > 1:
@@ -283,14 +294,13 @@ class LongCatModel:
neg_list = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
if len(neg_list) == 1 and batch_size > 1:
neg_list = neg_list * batch_size
- ids, neg_mask = self.text_encoder.tokenizer(
+ neg_contexts = self.text_encoder_cache.encode(
+ encode_fn,
neg_list,
- return_mask=True,
- add_special_tokens=True,
+ device=device,
)
- ids = ids.to(device)
- neg_mask = neg_mask.to(device)
- neg_embeds = self.text_encoder.model(ids, neg_mask).to(dtype)
+ neg_embeds = torch.stack([ctx[0] for ctx in neg_contexts], dim=0)
+ neg_mask = torch.stack([ctx[1] for ctx in neg_contexts], dim=0)
neg_embeds = neg_embeds.unsqueeze(1)
if num_videos_per_prompt > 1:
neg_embeds = neg_embeds.repeat(1, num_videos_per_prompt, 1, 1)
diff --git a/models/ltx2/ltx_core/model/video_vae/video_vae.py b/models/ltx2/ltx_core/model/video_vae/video_vae.py
index 9575306..0683cb7 100644
--- a/models/ltx2/ltx_core/model/video_vae/video_vae.py
+++ b/models/ltx2/ltx_core/model/video_vae/video_vae.py
@@ -724,11 +724,8 @@ class VideoDecoder(nn.Module):
total_frames=total_frames,
)
if chunk_device != blend_device:
- buffer_cpu = buffer.to(device=blend_device)
- curr_weights_cpu = curr_weights.to(device=blend_device)
- del buffer, curr_weights
- buffer = buffer_cpu
- curr_weights = curr_weights_cpu
+ buffer = buffer.to(device=blend_device)
+ curr_weights = curr_weights.to(device=blend_device)
# Blend with previous temporal chunk if it exists
if previous_chunk is not None:
diff --git a/models/ltx2/ltx_pipelines/distilled.py b/models/ltx2/ltx_pipelines/distilled.py
index 9eddb27..f3b8fa4 100644
--- a/models/ltx2/ltx_pipelines/distilled.py
+++ b/models/ltx2/ltx_pipelines/distilled.py
@@ -38,6 +38,7 @@ from .utils.helpers import (
from .utils.media_io import encode_video
from .utils.types import PipelineComponents
from shared.utils.loras_mutipliers import update_loras_slists
+from shared.utils.text_encoder_cache import TextEncoderCache
device = get_device()
@@ -83,6 +84,7 @@ class DistilledPipeline:
dtype=self.dtype,
device=device,
)
+ self.text_encoder_cache = TextEncoderCache()
def _get_model(self, name: str):
if self.models is not None:
@@ -124,20 +126,21 @@ class DistilledPipeline:
text_encoder = self._get_model("text_encoder")
if enhance_prompt:
prompt = generate_enhanced_prompt(text_encoder, prompt, images[0][0] if len(images) > 0 else None)
- raw_contexts = encode_text(text_encoder, prompts=[prompt])
feature_extractor, video_connector, audio_connector = resolve_text_connectors(
text_encoder, text_connectors
)
+ encode_fn = lambda prompts: postprocess_text_embeddings(
+ encode_text(text_encoder, prompts=prompts),
+ feature_extractor,
+ video_connector,
+ audio_connector,
+ )
+ contexts = self.text_encoder_cache.encode(encode_fn, [prompt], device=self.device, parallel=True)
torch.cuda.synchronize()
del text_encoder
cleanup_memory()
- video_context, audio_context = postprocess_text_embeddings(
- raw_contexts,
- feature_extractor,
- video_connector,
- audio_connector,
- )[0]
+ video_context, audio_context = contexts[0]
# Stage 1: Initial low resolution video generation.
video_encoder = self._get_model("video_encoder")
diff --git a/models/ltx2/ltx_pipelines/ic_lora.py b/models/ltx2/ltx_pipelines/ic_lora.py
index 5e307ac..885750f 100644
--- a/models/ltx2/ltx_pipelines/ic_lora.py
+++ b/models/ltx2/ltx_pipelines/ic_lora.py
@@ -38,6 +38,7 @@ from .utils.helpers import (
from .utils.media_io import encode_video
from .utils.types import PipelineComponents
from shared.utils.loras_mutipliers import update_loras_slists
+from shared.utils.text_encoder_cache import TextEncoderCache
device = get_device()
@@ -85,6 +86,7 @@ class ICLoraPipeline:
device=device,
)
self.device = device
+ self.text_encoder_cache = TextEncoderCache()
@torch.inference_mode()
def __call__(
@@ -121,20 +123,26 @@ class ICLoraPipeline:
prompt = generate_enhanced_prompt(
text_encoder, prompt, images[0][0] if len(images) > 0 else None, seed=seed
)
- raw_contexts = encode_text(text_encoder, prompts=[prompt])
feature_extractor, video_connector, audio_connector = resolve_text_connectors(
text_encoder, text_connectors
)
+ encode_fn = lambda prompts: postprocess_text_embeddings(
+ encode_text(text_encoder, prompts=prompts),
+ feature_extractor,
+ video_connector,
+ audio_connector,
+ )
+ contexts = self.text_encoder_cache.encode(
+ encode_fn,
+ [prompt],
+ device=self.device,
+ parallel=True,
+ )
torch.cuda.synchronize()
del text_encoder
cleanup_memory()
- video_context, audio_context = postprocess_text_embeddings(
- raw_contexts,
- feature_extractor,
- video_connector,
- audio_connector,
- )[0]
+ video_context, audio_context = contexts[0]
# Stage 1: Initial low resolution video generation.
video_encoder = self.stage_1_model_ledger.video_encoder()
diff --git a/models/ltx2/ltx_pipelines/keyframe_interpolation.py b/models/ltx2/ltx_pipelines/keyframe_interpolation.py
index 466e557..9e3989f 100644
--- a/models/ltx2/ltx_pipelines/keyframe_interpolation.py
+++ b/models/ltx2/ltx_pipelines/keyframe_interpolation.py
@@ -38,6 +38,7 @@ from .utils.helpers import (
from .utils.media_io import encode_video
from .utils.types import PipelineComponents
from shared.utils.loras_mutipliers import update_loras_slists
+from shared.utils.text_encoder_cache import TextEncoderCache
device = get_device()
@@ -78,6 +79,7 @@ class KeyframeInterpolationPipeline:
dtype=self.dtype,
device=device,
)
+ self.text_encoder_cache = TextEncoderCache()
@torch.inference_mode()
def __call__( # noqa: PLR0913
@@ -116,20 +118,26 @@ class KeyframeInterpolationPipeline:
prompt = generate_enhanced_prompt(
text_encoder, prompt, images[0][0] if len(images) > 0 else None, seed=seed
)
- raw_contexts = encode_text(text_encoder, prompts=[prompt, negative_prompt])
feature_extractor, video_connector, audio_connector = resolve_text_connectors(
text_encoder, text_connectors
)
-
- torch.cuda.synchronize()
- del text_encoder
- cleanup_memory()
- context_p, context_n = postprocess_text_embeddings(
- raw_contexts,
+ encode_fn = lambda prompts: postprocess_text_embeddings(
+ encode_text(text_encoder, prompts=prompts),
feature_extractor,
video_connector,
audio_connector,
)
+ contexts = self.text_encoder_cache.encode(
+ encode_fn,
+ [prompt, negative_prompt],
+ device=self.device,
+ parallel=True,
+ )
+
+ torch.cuda.synchronize()
+ del text_encoder
+ cleanup_memory()
+ context_p, context_n = contexts
v_context_p, a_context_p = context_p
v_context_n, a_context_n = context_n
diff --git a/models/ltx2/ltx_pipelines/ti2vid_one_stage.py b/models/ltx2/ltx_pipelines/ti2vid_one_stage.py
index f575517..e16614b 100644
--- a/models/ltx2/ltx_pipelines/ti2vid_one_stage.py
+++ b/models/ltx2/ltx_pipelines/ti2vid_one_stage.py
@@ -32,6 +32,7 @@ from .utils.helpers import (
from .utils.media_io import encode_video
from .utils.types import PipelineComponents
from shared.utils.loras_mutipliers import update_loras_slists
+from shared.utils.text_encoder_cache import TextEncoderCache
device = get_device()
@@ -66,6 +67,7 @@ class TI2VidOneStagePipeline:
dtype=self.dtype,
device=device,
)
+ self.text_encoder_cache = TextEncoderCache()
def __call__( # noqa: PLR0913
self,
@@ -102,20 +104,26 @@ class TI2VidOneStagePipeline:
prompt = generate_enhanced_prompt(
text_encoder, prompt, images[0][0] if len(images) > 0 else None, seed=seed
)
- raw_contexts = encode_text(text_encoder, prompts=[prompt, negative_prompt])
feature_extractor, video_connector, audio_connector = resolve_text_connectors(
text_encoder, text_connectors
)
-
- torch.cuda.synchronize()
- del text_encoder
- cleanup_memory()
- context_p, context_n = postprocess_text_embeddings(
- raw_contexts,
+ encode_fn = lambda prompts: postprocess_text_embeddings(
+ encode_text(text_encoder, prompts=prompts),
feature_extractor,
video_connector,
audio_connector,
)
+ contexts = self.text_encoder_cache.encode(
+ encode_fn,
+ [prompt, negative_prompt],
+ device=self.device,
+ parallel=True,
+ )
+
+ torch.cuda.synchronize()
+ del text_encoder
+ cleanup_memory()
+ context_p, context_n = contexts
v_context_p, a_context_p = context_p
v_context_n, a_context_n = context_n
diff --git a/models/ltx2/ltx_pipelines/ti2vid_two_stages.py b/models/ltx2/ltx_pipelines/ti2vid_two_stages.py
index 6a2239e..c2a5fd8 100644
--- a/models/ltx2/ltx_pipelines/ti2vid_two_stages.py
+++ b/models/ltx2/ltx_pipelines/ti2vid_two_stages.py
@@ -41,6 +41,7 @@ from .utils.helpers import (
from .utils.media_io import encode_video
from .utils.types import PipelineComponents
from shared.utils.loras_mutipliers import update_loras_slists
+from shared.utils.text_encoder_cache import TextEncoderCache
device = get_device()
@@ -99,6 +100,7 @@ class TI2VidTwoStagesPipeline:
dtype=self.dtype,
device=device,
)
+ self.text_encoder_cache = TextEncoderCache()
def _get_stage_model(self, stage: int, name: str):
if stage == 1:
@@ -156,10 +158,21 @@ class TI2VidTwoStagesPipeline:
text_encoder, prompt, images[0][0] if len(images) > 0 else None, seed=seed
)
# Codex: needs to return only the text embeddings from the text encoder for all the prompts
- raw_contexts = encode_text(text_encoder, prompts=[prompt, negative_prompt])
feature_extractor, video_connector, audio_connector = resolve_text_connectors(
text_encoder, text_connectors
)
+ encode_fn = lambda prompts: postprocess_text_embeddings(
+ encode_text(text_encoder, prompts=prompts),
+ feature_extractor,
+ video_connector,
+ audio_connector,
+ )
+ contexts = self.text_encoder_cache.encode(
+ encode_fn,
+ [prompt, negative_prompt],
+ device=self.device,
+ parallel=True,
+ )
torch.cuda.synchronize()
del text_encoder
@@ -167,12 +180,7 @@ class TI2VidTwoStagesPipeline:
# Codex: now that the text encoder has been released, compute the text_embedding_projection,
# audio_embeddings_connector, video_embeddings_connector in order to get v_context_p, a_context_p
# and v_context_n, a_context_n
- context_p, context_n = postprocess_text_embeddings(
- raw_contexts,
- feature_extractor,
- video_connector,
- audio_connector,
- )
+ context_p, context_n = contexts
v_context_p, a_context_p = context_p
v_context_n, a_context_n = context_n
diff --git a/models/ltx_video/pipelines/pipeline_ltx_video.py b/models/ltx_video/pipelines/pipeline_ltx_video.py
index f98eb13..39d9128 100644
--- a/models/ltx_video/pipelines/pipeline_ltx_video.py
+++ b/models/ltx_video/pipelines/pipeline_ltx_video.py
@@ -23,6 +23,7 @@ from transformers import (
AutoProcessor,
AutoTokenizer,
)
+from shared.utils.text_encoder_cache import TextEncoderCache
from ..models.autoencoders.causal_video_autoencoder import (
CausalVideoAutoencoder,
@@ -346,6 +347,7 @@ class LTXVideoPipeline(DiffusionPipeline):
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
self.allowed_inference_steps = allowed_inference_steps
+ self.text_encoder_cache = TextEncoderCache()
def mask_text_embeddings(self, emb, mask):
if emb.shape[0] == 1:
@@ -411,14 +413,11 @@ class LTXVideoPipeline(DiffusionPipeline):
max_length = (
text_encoder_max_tokens # TPU supports only lengths multiple of 128
)
- if prompt_embeds is None:
- assert (
- self.text_encoder is not None
- ), "You should provide either prompt_embeds or self.text_encoder should not be None,"
- text_enc_device = next(self.text_encoder.parameters()).device
- prompt = self._text_preprocessing(prompt)
+ text_enc_device = next(self.text_encoder.parameters()).device
+ emit_warning = True
+ def encode_fn(prompts):
text_inputs = self.tokenizer(
- prompt,
+ prompts,
padding="max_length",
max_length=max_length,
truncation=True,
@@ -426,29 +425,36 @@ class LTXVideoPipeline(DiffusionPipeline):
return_tensors="pt",
)
text_input_ids = text_inputs.input_ids
- untruncated_ids = self.tokenizer(
- prompt, padding="longest", return_tensors="pt"
- ).input_ids
-
- if untruncated_ids.shape[-1] >= text_input_ids.shape[
- -1
- ] and not torch.equal(text_input_ids, untruncated_ids):
- removed_text = self.tokenizer.batch_decode(
- untruncated_ids[:, max_length - 1 : -1]
- )
- logger.warning(
- "The following part of your input was truncated because CLIP can only handle sequences up to"
- f" {max_length} tokens: {removed_text}"
- )
-
+ if emit_warning:
+ untruncated_ids = self.tokenizer(
+ prompts, padding="longest", return_tensors="pt"
+ ).input_ids
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[
+ -1
+ ] and not torch.equal(text_input_ids, untruncated_ids):
+ removed_text = self.tokenizer.batch_decode(
+ untruncated_ids[:, max_length - 1 : -1]
+ )
+ logger.warning(
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
+ f" {max_length} tokens: {removed_text}"
+ )
prompt_attention_mask = text_inputs.attention_mask
prompt_attention_mask = prompt_attention_mask.to(text_enc_device)
prompt_attention_mask = prompt_attention_mask.to(device)
-
- prompt_embeds = self.text_encoder(
- text_input_ids.to(text_enc_device), attention_mask=prompt_attention_mask
+ prompt_embeds = self.text_encoder(text_input_ids.to(text_enc_device), attention_mask=prompt_attention_mask)[0]
+ return list(zip(prompt_embeds, prompt_attention_mask))
+ if prompt_embeds is None:
+ assert (
+ self.text_encoder is not None
+ ), "You should provide either prompt_embeds or self.text_encoder should not be None,"
+ prompt_list = self._text_preprocessing(prompt)
+ cache_keys = [(max_length, p) for p in prompt_list]
+ prompt_contexts = self.text_encoder_cache.encode(
+ encode_fn, prompt_list, device=device, cache_keys=cache_keys
)
- prompt_embeds = prompt_embeds[0]
+ prompt_embeds = torch.stack([ctx[0] for ctx in prompt_contexts], dim=0)
+ prompt_attention_mask = torch.stack([ctx[1] for ctx in prompt_contexts], dim=0)
if self.text_encoder is not None:
dtype = self.text_encoder.dtype
@@ -475,25 +481,13 @@ class LTXVideoPipeline(DiffusionPipeline):
uncond_tokens = self._text_preprocessing(negative_prompt)
uncond_tokens = uncond_tokens * batch_size
max_length = prompt_embeds.shape[1]
- uncond_input = self.tokenizer(
- uncond_tokens,
- padding="max_length",
- max_length=max_length,
- truncation=True,
- return_attention_mask=True,
- add_special_tokens=True,
- return_tensors="pt",
- )
- negative_prompt_attention_mask = uncond_input.attention_mask
- negative_prompt_attention_mask = negative_prompt_attention_mask.to(
- text_enc_device
- )
-
- negative_prompt_embeds = self.text_encoder(
- uncond_input.input_ids.to(text_enc_device),
- attention_mask=negative_prompt_attention_mask,
+ emit_warning = False
+ cache_keys = [(max_length, token) for token in uncond_tokens]
+ negative_contexts = self.text_encoder_cache.encode(
+ encode_fn, uncond_tokens, device=device, cache_keys=cache_keys
)
- negative_prompt_embeds = negative_prompt_embeds[0]
+ negative_prompt_embeds = torch.stack([ctx[0] for ctx in negative_contexts], dim=0)
+ negative_prompt_attention_mask = torch.stack([ctx[1] for ctx in negative_contexts], dim=0)
if do_classifier_free_guidance:
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
diff --git a/models/qwen/pipeline_qwenimage.py b/models/qwen/pipeline_qwenimage.py
index 8a20050..4ad13ce 100644
--- a/models/qwen/pipeline_qwenimage.py
+++ b/models/qwen/pipeline_qwenimage.py
@@ -28,6 +28,7 @@ from .autoencoder_kl_qwenimage import AutoencoderKLQwenImage
from diffusers import FlowMatchEulerDiscreteScheduler
from PIL import Image
from shared.utils.utils import calculate_new_dimensions, convert_image_to_tensor, convert_tensor_to_image
+from shared.utils.text_encoder_cache import TextEncoderCache
XLA_AVAILABLE = False
@@ -183,6 +184,7 @@ class QwenImagePipeline(): #DiffusionPipeline
# by the patch size. So the vae scale factor is multiplied by the patch size to account for this
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
self.tokenizer_max_length = 1024
+ self.text_encoder_cache = TextEncoderCache()
if processor is not None:
# self.prompt_template_encode = "<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>{}<|im_end|>\n<|im_start|>assistant\n"
self.prompt_template_encode = "<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n"
@@ -214,7 +216,6 @@ class QwenImagePipeline(): #DiffusionPipeline
template = self.prompt_template_encode
drop_idx = self.prompt_template_encode_start_idx
- txt = [template.format(e) for e in prompt]
if self.processor is not None and image is not None and len(image) > 0:
img_prompt_template = "Picture {}: <|vision_start|><|image_pad|><|vision_end|>"
@@ -239,29 +240,29 @@ class QwenImagePipeline(): #DiffusionPipeline
return_tensors="pt",
).to(device)
- outputs = self.text_encoder(
- input_ids=model_inputs.input_ids,
- attention_mask=model_inputs.attention_mask,
- pixel_values=model_inputs.pixel_values,
- image_grid_thw=model_inputs.image_grid_thw,
- output_hidden_states=True,
- )
+ outputs = self.text_encoder(input_ids=model_inputs.input_ids, attention_mask=model_inputs.attention_mask, pixel_values=model_inputs.pixel_values, image_grid_thw=model_inputs.image_grid_thw, output_hidden_states=True)
hidden_states = outputs.hidden_states[-1]
split_hidden_states = self._extract_masked_hidden(hidden_states, model_inputs.attention_mask)
+ split_hidden_states = [e[drop_idx:] for e in split_hidden_states]
+ attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]
else:
- txt_tokens = self.tokenizer(
- txt, max_length=self.tokenizer_max_length + drop_idx, padding=True, truncation=True, return_tensors="pt"
- ).to(device)
- encoder_hidden_states = self.text_encoder(
- input_ids=txt_tokens.input_ids,
- attention_mask=txt_tokens.attention_mask,
- output_hidden_states=True,
- )
- hidden_states = encoder_hidden_states.hidden_states[-1]
- split_hidden_states = self._extract_masked_hidden(hidden_states, txt_tokens.attention_mask)
-
- split_hidden_states = [e[drop_idx:] for e in split_hidden_states]
- attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]
+ def encode_fn(prompts):
+ txt = [template.format(p) for p in prompts]
+ txt_tokens = self.tokenizer(
+ txt,
+ max_length=self.tokenizer_max_length + drop_idx,
+ padding=True,
+ truncation=True,
+ return_tensors="pt",
+ ).to(device)
+ hidden_states = self.text_encoder(input_ids=txt_tokens.input_ids, attention_mask=txt_tokens.attention_mask, output_hidden_states=True).hidden_states[-1]
+ split_hidden_states = self._extract_masked_hidden(hidden_states, txt_tokens.attention_mask)
+ split_hidden_states = [e[drop_idx:] for e in split_hidden_states]
+ attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]
+ return list(zip(split_hidden_states, attn_mask_list))
+ contexts = self.text_encoder_cache.encode(encode_fn, prompt, device=device)
+ split_hidden_states = [ctx[0] for ctx in contexts]
+ attn_mask_list = [ctx[1] for ctx in contexts]
max_seq_len = max([e.size(0) for e in split_hidden_states])
prompt_embeds = torch.stack(
[torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states]
diff --git a/models/wan/any2video.py b/models/wan/any2video.py
index c116357..ee54f86 100644
--- a/models/wan/any2video.py
+++ b/models/wan/any2video.py
@@ -44,6 +44,7 @@ from .multitalk.multitalk_utils import MomentumBuffer, adaptive_projected_guidan
from .wanmove.trajectory import replace_feature, create_pos_feature_map
from .alpha.utils import load_gauss_mask, apply_alpha_shift
from shared.utils.audio_video import save_video
+from shared.utils.text_encoder_cache import TextEncoderCache
from mmgp import safetensors2
from shared.utils import files_locator as fl
@@ -101,7 +102,7 @@ class WanAny2V:
self.is_mocha = model_def.get("mocha_mode", False)
text_encoder_folder = model_def.get("text_encoder_folder")
if text_encoder_folder:
- tokenizer_path = fl.locate_folder(text_encoder_folder)
+ tokenizer_path = os.path.dirname(fl.locate_file(os.path.join(text_encoder_folder, "tokenizer_config.json")))
else:
tokenizer_path = os.path.dirname(text_encoder_filename)
self.text_encoder = T5EncoderModel(
@@ -111,6 +112,7 @@ class WanAny2V:
checkpoint_path=text_encoder_filename,
tokenizer_path=tokenizer_path,
shard_fn= None)
+ self.text_encoder_cache = TextEncoderCache()
if hasattr(config, "clip_checkpoint") and not model_def.get("i2v_2_2", False) or base_model_type in ["animate"]:
self.clip = CLIPModel(
dtype=config.clip_dtype,
@@ -336,7 +338,8 @@ class WanAny2V:
if any_guidance:
vae_feat_uncond = self.vae.encode([ref_images[0] * 0], tile_size = tile_size) * len(ref_images)
vae_feat_uncond = torch.cat( vae_feat_uncond, dim=1).unsqueeze(0)
- context = self.text_encoder([ref_prompt], self.device)[0].to(self.dtype)
+ encode_fn = lambda prompts: self.text_encoder(prompts, self.device)
+ context = self.text_encoder_cache.encode(encode_fn, [ref_prompt], device=self.device)[0].to(self.dtype)
context = torch.cat([context, context.new_zeros(self.model.text_len -context.size(0), context.size(1)) ]).unsqueeze(0)
clear_caches()
get_cache("lynx_ref_buffer").update({ 0: {}, 1: {} })
@@ -523,11 +526,12 @@ class WanAny2V:
n_prompt = self.sample_neg_prompt
text_len = self.model.text_len
any_guidance_at_all = guide_scale > 1 or guide2_scale > 1 and guide_phases >=2 or guide3_scale > 1 and guide_phases >=3
- context = self.text_encoder([input_prompt], self.device)[0].to(self.dtype)
+ encode_fn = lambda prompts: self.text_encoder(prompts, self.device)
+ context = self.text_encoder_cache.encode(encode_fn, [input_prompt], device=self.device)[0].to(self.dtype)
context = torch.cat([context, context.new_zeros(text_len -context.size(0), context.size(1)) ]).unsqueeze(0)
if NAG_scale > 1 or any_guidance_at_all:
- context_null = self.text_encoder([n_prompt], self.device)[0].to(self.dtype)
- context_null = torch.cat([context_null, context_null.new_zeros(text_len -context_null.size(0), context_null.size(1)) ]).unsqueeze(0)
+ context_null = self.text_encoder_cache.encode(encode_fn, [n_prompt], device=self.device)[0].to(self.dtype)
+ context_null = torch.cat([context_null, context_null.new_zeros(text_len -context_null.size(0), context_null.size(1)) ]).unsqueeze(0)
else:
context_null = None
if input_video is not None: height, width = input_video.shape[-2:]
diff --git a/models/z_image/pipeline_z_image.py b/models/z_image/pipeline_z_image.py
index 9f5e768..f106237 100644
--- a/models/z_image/pipeline_z_image.py
+++ b/models/z_image/pipeline_z_image.py
@@ -31,6 +31,7 @@ from .unified_sampler import UnifiedSampler
from .pipeline_output import ZImagePipelineOutput
from shared.utils.utils import get_outpainting_frame_location, resize_lanczos, calculate_new_dimensions, convert_image_to_tensor, fit_image_into_canvas
from shared.utils.loras_mutipliers import update_loras_slists
+from shared.utils.text_encoder_cache import TextEncoderCache
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@@ -218,6 +219,7 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
)
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
+ self.text_encoder_cache = TextEncoderCache()
def encode_prompt(
self,
@@ -278,41 +280,37 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
if isinstance(prompt, str):
prompt = [prompt]
- for i, prompt_item in enumerate(prompt):
- messages = [
- {"role": "user", "content": prompt_item},
- ]
- prompt_item = self.tokenizer.apply_chat_template(
- messages,
- tokenize=False,
- add_generation_prompt=True,
- enable_thinking=True,
+ def encode_fn(prompts):
+ formatted_prompts = []
+ for prompt_item in prompts:
+ messages = [
+ {"role": "user", "content": prompt_item},
+ ]
+ formatted_prompts.append(
+ self.tokenizer.apply_chat_template(
+ messages,
+ tokenize=False,
+ add_generation_prompt=True,
+ enable_thinking=True,
+ )
+ )
+ text_inputs = self.tokenizer(
+ formatted_prompts,
+ padding="max_length",
+ max_length=max_sequence_length,
+ truncation=True,
+ return_tensors="pt",
)
- prompt[i] = prompt_item
-
- text_inputs = self.tokenizer(
- prompt,
- padding="max_length",
- max_length=max_sequence_length,
- truncation=True,
- return_tensors="pt",
- )
-
- text_input_ids = text_inputs.input_ids.to(device)
- prompt_masks = text_inputs.attention_mask.to(device).bool()
-
- prompt_embeds = self.text_encoder(
- input_ids=text_input_ids,
- attention_mask=prompt_masks,
- output_hidden_states=True,
- ).hidden_states[-2]
-
- embeddings_list = []
-
- for i in range(len(prompt_embeds)):
- embeddings_list.append(prompt_embeds[i][prompt_masks[i]])
-
- return embeddings_list
+ text_input_ids = text_inputs.input_ids.to(device)
+ prompt_masks = text_inputs.attention_mask.to(device).bool()
+ prompt_embeds = self.text_encoder(input_ids=text_input_ids, attention_mask=prompt_masks, output_hidden_states=True).hidden_states[-2]
+ embeddings_list = []
+ for i in range(len(prompt_embeds)):
+ embeddings_list.append(prompt_embeds[i][prompt_masks[i]])
+ return embeddings_list
+
+ cache_keys = [(max_sequence_length, p) for p in prompt]
+ return self.text_encoder_cache.encode(encode_fn, prompt, device=device, cache_keys=cache_keys)
def prepare_latents(
self,
diff --git a/models/z_image/z_image_main.py b/models/z_image/z_image_main.py
index 435fbf7..2f311fd 100644
--- a/models/z_image/z_image_main.py
+++ b/models/z_image/z_image_main.py
@@ -133,7 +133,7 @@ class model_factory:
# Tokenizer
text_encoder_folder = model_def.get("text_encoder_folder")
if text_encoder_folder:
- tokenizer_path = fl.locate_folder(text_encoder_folder)
+ tokenizer_path = os.path.dirname(fl.locate_file(os.path.join(text_encoder_folder, "tokenizer_config.json")))
else:
tokenizer_path = os.path.dirname(text_encoder_filename)
tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, trust_remote_code=True)
diff --git a/requirements.txt b/requirements.txt
index 2d83938..eb92bff 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -57,7 +57,7 @@ pydantic==2.10.6
# Math & modeling
torchdiffeq>=0.2.5
tensordict>=0.6.1
-mmgp==3.6.16
+mmgp==3.7.0
peft==0.15.0
matplotlib
gguf==0.17.1
diff --git a/shared/utils/text_encoder_cache.py b/shared/utils/text_encoder_cache.py
new file mode 100644
index 0000000..9bbb60d
--- /dev/null
+++ b/shared/utils/text_encoder_cache.py
@@ -0,0 +1,151 @@
+from __future__ import annotations
+
+from collections import OrderedDict
+from dataclasses import dataclass
+from typing import Any, Callable, Iterable, Hashable
+
+import torch
+
+
+@dataclass
+class _CacheEntry:
+ value: Any
+ size_bytes: int
+
+
+class TextEncoderCache:
+ def __init__(self, max_size_mb: float = 100) -> None:
+ self.max_size_bytes = int(max_size_mb * 1024 * 1024)
+ self._entries: "OrderedDict[Hashable, _CacheEntry]" = OrderedDict()
+ self._size_bytes = 0
+
+ def encode(
+ self,
+ encode_fn: Callable[[list[str]], list[Any]],
+ prompts: Iterable[str] | str,
+ device: torch.device | str | None = None,
+ parallel: bool = False,
+ cache_keys: Iterable[Hashable] | Hashable | None = None,
+ ) -> list[Any]:
+ if isinstance(prompts, str):
+ prompts_list = [prompts]
+ else:
+ prompts_list = list(prompts)
+ if not prompts_list:
+ return []
+ if cache_keys is None:
+ keys_list = prompts_list
+ else:
+ if len(prompts_list) == 1 and not isinstance(cache_keys, list):
+ keys_list = [cache_keys]
+ else:
+ keys_list = list(cache_keys)
+ if len(keys_list) != len(prompts_list):
+ raise ValueError("cache_keys must match the number of prompts.")
+
+ if not parallel:
+ results: list[Any] = []
+ for prompt, cache_key in zip(prompts_list, keys_list):
+ cached = self._entries.get(cache_key)
+ if cached is not None:
+ self._entries.move_to_end(cache_key)
+ results.append(self._to_device(cached.value, device))
+ continue
+ encoded = encode_fn([prompt])
+ if isinstance(encoded, (list, tuple)):
+ if not encoded:
+ raise ValueError("encode_fn returned empty embeddings.")
+ encoded_item = encoded[0]
+ else:
+ encoded_item = encoded
+ results.append(self._store(cache_key, encoded_item, device))
+ return results
+
+ results = [None] * len(prompts_list)
+ missing_prompts: list[str] = []
+ missing_indices: list[int] = []
+ missing_keys: list[Hashable] = []
+
+ for idx, (prompt, cache_key) in enumerate(zip(prompts_list, keys_list)):
+ cached = self._entries.get(cache_key)
+ if cached is None:
+ missing_prompts.append(prompt)
+ missing_indices.append(idx)
+ missing_keys.append(cache_key)
+ continue
+ self._entries.move_to_end(cache_key)
+ results[idx] = self._to_device(cached.value, device)
+
+ if missing_prompts:
+ encoded_batch = encode_fn(missing_prompts)
+ if not isinstance(encoded_batch, list):
+ encoded_batch = list(encoded_batch)
+ if len(encoded_batch) != len(missing_prompts):
+ raise ValueError("encode_fn returned unexpected number of embeddings.")
+ for cache_key, idx, encoded in zip(missing_keys, missing_indices, encoded_batch):
+ results[idx] = self._store(cache_key, encoded, device)
+
+ return results
+
+ def _store(self, cache_key: Hashable, encoded: Any, device: torch.device | str | None) -> Any:
+ cached_value = self._detach_to_cpu(encoded)
+ size_bytes = self._estimate_size_bytes(cached_value)
+ if size_bytes <= self.max_size_bytes:
+ existing = self._entries.pop(cache_key, None)
+ if existing is not None:
+ self._size_bytes -= existing.size_bytes
+ self._entries[cache_key] = _CacheEntry(cached_value, size_bytes)
+ self._size_bytes += size_bytes
+ self._purge_if_needed()
+ else:
+ if cache_key in self._entries:
+ self._entries.move_to_end(cache_key)
+ return self._to_device(encoded, device)
+
+ def _purge_if_needed(self) -> None:
+ if self._size_bytes <= self.max_size_bytes:
+ return
+ while self._entries and self._size_bytes > self.max_size_bytes:
+ _, entry = self._entries.popitem(last=False)
+ self._size_bytes -= entry.size_bytes
+
+ def _estimate_size_bytes(self, value: Any) -> int:
+ if torch.is_tensor(value):
+ return int(value.numel() * value.element_size())
+ if isinstance(value, dict):
+ return sum(self._estimate_size_bytes(v) for v in value.values())
+ if isinstance(value, (list, tuple)):
+ return sum(self._estimate_size_bytes(v) for v in value)
+ return 0
+
+ def _detach_to_cpu(self, value: Any) -> Any:
+ if torch.is_tensor(value):
+ if value.device.type == "cpu":
+ return value.detach()
+ return value.detach().to("cpu")
+ if isinstance(value, dict):
+ return {k: self._detach_to_cpu(v) for k, v in value.items()}
+ if isinstance(value, tuple):
+ items = [self._detach_to_cpu(v) for v in value]
+ if hasattr(value, "_fields"):
+ return value.__class__(*items)
+ return tuple(items)
+ if isinstance(value, list):
+ return [self._detach_to_cpu(v) for v in value]
+ return value
+
+ def _to_device(self, value: Any, device: torch.device | str | None) -> Any:
+ if device is None:
+ return value
+ if torch.is_tensor(value):
+ return value.to(device)
+ if isinstance(value, dict):
+ return {k: self._to_device(v, device) for k, v in value.items()}
+ if isinstance(value, tuple):
+ items = [self._to_device(v, device) for v in value]
+ if hasattr(value, "_fields"):
+ return value.__class__(*items)
+ return tuple(items)
+ if isinstance(value, list):
+ return [self._to_device(v, device) for v in value]
+ return value
diff --git a/wgp.py b/wgp.py
index 6cc209e..27f61fe 100644
--- a/wgp.py
+++ b/wgp.py
@@ -84,8 +84,8 @@ AUTOSAVE_PATH = AUTOSAVE_FILENAME
AUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAME
CONFIG_FILENAME = "wgp_config.json"
PROMPT_VARS_MAX = 10
-target_mmgp_version = "3.6.16"
-WanGP_version = "10.41"
+target_mmgp_version = "3.7.0"
+WanGP_version = "10.42"
settings_version = 2.43
max_source_video_frames = 3000
prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None