-
Notifications
You must be signed in to change notification settings - Fork 236
combine hunyuan #1227
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
combine hunyuan #1227
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| { | ||
| "infer_steps": 50, | ||
| "sample_guide_scale": 5.0, | ||
| "flow_shift": 1.0, | ||
| "use_meanflow": false, | ||
| "guidance_rescale": 0.0, | ||
| "image_size": "auto", | ||
| "enable_auto_image_size": false, | ||
| "hunyuan_image_size": "", | ||
| "attn_impl": "sdpa", | ||
| "moe_impl": "eager", | ||
| "rewrite": false, | ||
| "sys_deepseek_prompt": "universal", | ||
| "reproduce": false, | ||
| "feature_caching": "NoCaching", | ||
| "enable_kv_cache": true, | ||
| "enable_text_kv_cache": true, | ||
| "use_taylor_cache": false, | ||
| "taylor_cache_interval": 5, | ||
| "taylor_cache_order": 2, | ||
| "taylor_cache_enable_first_enhance": false, | ||
| "taylor_cache_first_enhance_steps": 3, | ||
| "taylor_cache_enable_tailing_enhance": false, | ||
| "taylor_cache_tailing_enhance_steps": 1, | ||
| "taylor_cache_low_freqs_order": 2, | ||
| "taylor_cache_high_freqs_order": 2, | ||
| "pipeline_parallel": true, | ||
| "enable_cfg": true, | ||
| "infer_align_image_size": true, | ||
| "bot_task": "think_recaption", | ||
| "use_system_prompt": "en_unified", | ||
| "max_new_tokens": 2048, | ||
| "text_do_sample": true, | ||
| "text_top_k": 1024, | ||
| "text_top_p": 0.95, | ||
| "text_temperature": 0.6 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| { | ||
| "infer_steps": 50, | ||
| "sample_guide_scale": 5.0, | ||
| "flow_shift": 1.0, | ||
| "use_meanflow": false, | ||
| "guidance_rescale": 0.0, | ||
| "target_height": 1024, | ||
| "target_width": 1024, | ||
| "enable_auto_image_size": false, | ||
| "hunyuan_image_size": "", | ||
| "attn_impl": "sdpa", | ||
| "moe_impl": "eager", | ||
| "rewrite": false, | ||
| "sys_deepseek_prompt": "universal", | ||
| "reproduce": false, | ||
| "feature_caching": "NoCaching", | ||
| "enable_kv_cache": true, | ||
| "enable_text_kv_cache": true, | ||
| "use_taylor_cache": false, | ||
| "taylor_cache_interval": 5, | ||
| "taylor_cache_order": 2, | ||
| "taylor_cache_enable_first_enhance": false, | ||
| "taylor_cache_first_enhance_steps": 3, | ||
| "taylor_cache_enable_tailing_enhance": false, | ||
| "taylor_cache_tailing_enhance_steps": 1, | ||
| "taylor_cache_low_freqs_order": 2, | ||
| "taylor_cache_high_freqs_order": 2, | ||
| "pipeline_parallel": true, | ||
| "enable_cfg": true, | ||
| "bot_task": "think_recaption", | ||
| "use_system_prompt": "en_unified", | ||
| "max_new_tokens": 2048, | ||
| "text_do_sample": true, | ||
| "text_top_k": 1024, | ||
| "text_top_p": 0.95, | ||
| "text_temperature": 0.6 | ||
| } |
45 changes: 45 additions & 0 deletions
45
docs/superpowers/plans/2026-07-02-hunyuan-image3-think-recaption.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| # Hunyuan Image3 Think Recaption Implementation Plan | ||
|
|
||
| > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. | ||
|
|
||
| **Goal:** Add a native LightX2V text-generation pre-stage for Hunyuan Image3 `recaption` and `think_recaption`, then feed generated COT text into the existing native image generation path. | ||
|
|
||
| **Architecture:** Keep the DiT path native. Add small runner-level helpers for text input preparation, autoregressive token generation without KV cache, stage transitions from `</think>` to `<recaption>`, and generated COT injection via tokenizer `batch_cot_text` for `gen_image`. | ||
|
|
||
| **Tech Stack:** Python, PyTorch, Hunyuan tokenizer/image processor helpers, LightX2V native HunyuanImage3 model/infer/weights. | ||
|
|
||
| --- | ||
|
|
||
| ### Task 1: Regression Tests | ||
|
|
||
| **Files:** | ||
| - Modify: `tests/test_hunyuan_image3_integration.py` | ||
|
|
||
| - [ ] Add tests for resolving bot task, generating COT before image inputs, and stage transition token forcing. | ||
| - [ ] Run targeted pytest and verify failures before implementation. | ||
|
|
||
| ### Task 2: Runner Text Generation Helpers | ||
|
|
||
| **Files:** | ||
| - Modify: `lightx2v/models/runners/hunyuan_image3/hunyuan_image3_runner.py` | ||
|
|
||
| - [ ] Add helpers for system prompt resolution, text template creation, next-token selection, and COT text generation. | ||
| - [ ] Preserve existing `bot_task=image` behavior. | ||
| - [ ] For `think_recaption`, force `<recaption>` after `</think>` and stop after `</recaption>`. | ||
|
|
||
| ### Task 3: Feed COT Into Image Generation | ||
|
|
||
| **Files:** | ||
| - Modify: `lightx2v/models/runners/hunyuan_image3/hunyuan_image3_runner.py` | ||
| - Modify: `configs/hunyuan_image3/hunyuan_image3_t2i.json` | ||
|
|
||
| - [ ] Pass `batch_cot_text` into `apply_chat_template(..., mode="gen_image")`. | ||
| - [ ] Add config keys for `bot_task`, `use_system_prompt`, `max_new_tokens`, and deterministic text generation. | ||
|
|
||
| ### Task 4: Verification | ||
|
|
||
| **Files:** | ||
| - Test: `tests/test_hunyuan_image3_integration.py` | ||
|
|
||
| - [ ] Run full Hunyuan integration tests. | ||
| - [ ] Run ruff and py_compile on touched files. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -12,6 +12,7 @@ | |||||||||||||||||||||||
| from lightx2v.models.runners.flux2.flux2_runner import Flux2DevRunner, Flux2KleinRunner # noqa: F401 | ||||||||||||||||||||||||
| from lightx2v.models.runners.hidream_o1_image.hidream_o1_image_runner import HidreamO1ImageRunner # noqa: F401 | ||||||||||||||||||||||||
| from lightx2v.models.runners.hunyuan3d.hunyuan3d_shape_runner import Hunyuan3DShapeRunner # noqa: F401 | ||||||||||||||||||||||||
| from lightx2v.models.runners.hunyuan_image3.hunyuan_image3_runner import HunyuanImage3Runner # noqa: F401 | ||||||||||||||||||||||||
| from lightx2v.models.runners.hunyuan_video.hunyuan_video_15_distill_runner import HunyuanVideo15DistillRunner # noqa: F401 | ||||||||||||||||||||||||
| from lightx2v.models.runners.hunyuan_video.hunyuan_video_15_runner import HunyuanVideo15Runner # noqa: F401 | ||||||||||||||||||||||||
| from lightx2v.models.runners.longcat_image.longcat_image_runner import LongCatImageRunner # noqa: F401 | ||||||||||||||||||||||||
|
|
@@ -47,6 +48,35 @@ | |||||||||||||||||||||||
| from lightx2v_platform.registry_factory import PLATFORM_DEVICE_REGISTER | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def _str2bool(value): | ||||||||||||||||||||||||
| if isinstance(value, bool): | ||||||||||||||||||||||||
| return value | ||||||||||||||||||||||||
| lowered = value.lower() | ||||||||||||||||||||||||
| if lowered in ("1", "true", "yes", "y", "on"): | ||||||||||||||||||||||||
| return True | ||||||||||||||||||||||||
| if lowered in ("0", "false", "no", "n", "off"): | ||||||||||||||||||||||||
| return False | ||||||||||||||||||||||||
| raise argparse.ArgumentTypeError(f"Expected a boolean value, got {value!r}") | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def _set_reproducibility(enable, global_seed=None, benchmark=None): | ||||||||||||||||||||||||
| if not enable: | ||||||||||||||||||||||||
| return | ||||||||||||||||||||||||
| import random | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| import numpy as np | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| random.seed(global_seed) | ||||||||||||||||||||||||
| np.random.seed(global_seed) | ||||||||||||||||||||||||
| torch.manual_seed(global_seed) | ||||||||||||||||||||||||
| if torch.cuda.is_available(): | ||||||||||||||||||||||||
| torch.cuda.manual_seed_all(global_seed) | ||||||||||||||||||||||||
|
Comment on lines
+69
to
+73
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If
Suggested change
|
||||||||||||||||||||||||
| os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" | ||||||||||||||||||||||||
| torch.backends.cudnn.benchmark = benchmark if benchmark is not None else False | ||||||||||||||||||||||||
| torch.backends.cudnn.deterministic = True | ||||||||||||||||||||||||
| torch.use_deterministic_algorithms(True) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def init_runner(config): | ||||||||||||||||||||||||
| torch.set_grad_enabled(False) | ||||||||||||||||||||||||
| runner = RUNNER_REGISTER[config["model_cls"]](config) | ||||||||||||||||||||||||
|
|
@@ -88,6 +118,7 @@ def main(): | |||||||||||||||||||||||
| "wan2.2_s2v", | ||||||||||||||||||||||||
| "hunyuan_video_1.5", | ||||||||||||||||||||||||
| "hunyuan_video_1.5_distill", | ||||||||||||||||||||||||
| "hunyuan_image3", | ||||||||||||||||||||||||
| "hunyuan3d", | ||||||||||||||||||||||||
| "worldplay_distill", | ||||||||||||||||||||||||
| "worldplay_ar", | ||||||||||||||||||||||||
|
|
@@ -116,6 +147,46 @@ def main(): | |||||||||||||||||||||||
| parser.add_argument("--support_tasks", type=str, nargs="+", default=[], help="Set supported tasks for the model") | ||||||||||||||||||||||||
| parser.add_argument("--model_path", type=str, required=True) | ||||||||||||||||||||||||
| parser.add_argument("--config_json", type=str, required=True) | ||||||||||||||||||||||||
| hunyuan_cache_args = parser.add_argument_group("HunyuanImage3 cache options") | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument("--enable_kv_cache", "--enable-kv-cache", dest="enable_kv_cache", type=_str2bool, nargs="?", const=True, default=None) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument("--enable_text_kv_cache", "--enable-text-kv-cache", dest="enable_text_kv_cache", type=_str2bool, nargs="?", const=True, default=None) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument("--use_taylor_cache", "--use-taylor-cache", dest="use_taylor_cache", type=_str2bool, nargs="?", const=True, default=None) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument("--taylor_cache_interval", "--taylor-cache-interval", dest="taylor_cache_interval", type=int, default=None) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument("--taylor_cache_order", "--taylor-cache-order", dest="taylor_cache_order", type=int, default=None) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument( | ||||||||||||||||||||||||
| "--taylor_cache_enable_first_enhance", | ||||||||||||||||||||||||
| "--taylor-cache-enable-first-enhance", | ||||||||||||||||||||||||
| dest="taylor_cache_enable_first_enhance", | ||||||||||||||||||||||||
| type=_str2bool, | ||||||||||||||||||||||||
| nargs="?", | ||||||||||||||||||||||||
| const=True, | ||||||||||||||||||||||||
| default=None, | ||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument("--taylor_cache_first_enhance_steps", "--taylor-cache-first-enhance-steps", dest="taylor_cache_first_enhance_steps", type=int, default=None) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument( | ||||||||||||||||||||||||
| "--taylor_cache_enable_tailing_enhance", | ||||||||||||||||||||||||
| "--taylor-cache-enable-tailing-enhance", | ||||||||||||||||||||||||
| dest="taylor_cache_enable_tailing_enhance", | ||||||||||||||||||||||||
| type=_str2bool, | ||||||||||||||||||||||||
| nargs="?", | ||||||||||||||||||||||||
| const=True, | ||||||||||||||||||||||||
| default=None, | ||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument("--taylor_cache_tailing_enhance_steps", "--taylor-cache-tailing-enhance-steps", dest="taylor_cache_tailing_enhance_steps", type=int, default=None) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument("--taylor_cache_low_freqs_order", "--taylor-cache-low-freqs-order", dest="taylor_cache_low_freqs_order", type=int, default=None) | ||||||||||||||||||||||||
| hunyuan_cache_args.add_argument("--taylor_cache_high_freqs_order", "--taylor-cache-high-freqs-order", dest="taylor_cache_high_freqs_order", type=int, default=None) | ||||||||||||||||||||||||
| hunyuan_native_args = parser.add_argument_group("HunyuanImage3 native generation options") | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--use_meanflow", "--use-meanflow", dest="use_meanflow", type=_str2bool, nargs="?", const=True, default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--guidance_rescale", "--guidance-rescale", dest="guidance_rescale", type=float, default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--enable_auto_image_size", "--enable-auto-image-size", dest="enable_auto_image_size", type=_str2bool, nargs="?", const=True, default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--hunyuan_image_size", "--hunyuan-image-size", dest="hunyuan_image_size", type=str, default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--hunyuan_timesteps", "--hunyuan-timesteps", dest="hunyuan_timesteps", type=str, default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--hunyuan_sigmas", "--hunyuan-sigmas", dest="hunyuan_sigmas", type=str, default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--attn_impl", "--attn-impl", dest="attn_impl", type=str, choices=["sdpa", "flash_attention_2"], default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--moe_impl", "--moe-impl", dest="moe_impl", type=str, choices=["eager", "flashinfer"], default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--rewrite", dest="rewrite", type=_str2bool, nargs="?", const=True, default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--sys_deepseek_prompt", "--sys-deepseek-prompt", dest="sys_deepseek_prompt", type=str, choices=["universal", "text_rendering"], default=None) | ||||||||||||||||||||||||
| hunyuan_native_args.add_argument("--reproduce", dest="reproduce", type=_str2bool, nargs="?", const=True, default=None) | ||||||||||||||||||||||||
| parser.add_argument("--use_prompt_enhancer", action="store_true") | ||||||||||||||||||||||||
| parser.add_argument("--prompt", type=str, default="", help="The input prompt for text-to-video generation") | ||||||||||||||||||||||||
| parser.add_argument("--negative_prompt", type=str, default="") | ||||||||||||||||||||||||
|
|
@@ -258,6 +329,7 @@ def main(): | |||||||||||||||||||||||
| args = parser.parse_args() | ||||||||||||||||||||||||
| # validate_task_arguments(args) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| _set_reproducibility(bool(args.reproduce), global_seed=args.seed) | ||||||||||||||||||||||||
| seed_all(args.seed) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| # set config | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from .model import HunyuanImage3Model | ||
|
|
||
| __all__ = ["HunyuanImage3Model"] |
130 changes: 130 additions & 0 deletions
130
lightx2v/models/networks/hunyuan_image3/infer/kv_cache.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| from dataclasses import dataclass | ||
| import math | ||
|
|
||
| import torch | ||
|
|
||
|
|
||
| @dataclass | ||
| class HunyuanImage3KVCacheLayer: | ||
| key: torch.Tensor | None = None | ||
| value: torch.Tensor | None = None | ||
|
|
||
|
|
||
| class HunyuanImage3StaticKVCache: | ||
| """Per-layer KV cache matching HunyuanImage3 gen_text/gen_image inference.""" | ||
|
|
||
| def __init__(self, num_layers, max_cache_len, dynamic=False): | ||
| self.num_layers = int(num_layers) | ||
| self.max_cache_len = int(max_cache_len) | ||
| self.dynamic = bool(dynamic) | ||
| self.layers = [HunyuanImage3KVCacheLayer() for _ in range(self.num_layers)] | ||
|
|
||
| def _ensure_layer(self, layer_idx, key_states, value_states): | ||
| layer = self.layers[layer_idx] | ||
| if layer.key is None: | ||
| key_shape = (*key_states.shape[:2], self.max_cache_len, key_states.shape[-1]) | ||
| value_shape = (*value_states.shape[:2], self.max_cache_len, value_states.shape[-1]) | ||
| layer.key = torch.zeros(key_shape, device=key_states.device, dtype=key_states.dtype) | ||
| layer.value = torch.zeros(value_shape, device=value_states.device, dtype=value_states.dtype) | ||
| return layer | ||
|
|
||
| def update(self, key_states, value_states, layer_idx, cache_position=None): | ||
| layer = self._ensure_layer(layer_idx, key_states, value_states) | ||
| if cache_position is None: | ||
| layer.key[:, :, : key_states.shape[2]].copy_(key_states) | ||
| layer.value[:, :, : value_states.shape[2]].copy_(value_states) | ||
| return self._slice_dynamic(layer, key_states.shape[2]) | ||
|
|
||
| cache_position = cache_position.to(device=key_states.device, dtype=torch.long) | ||
| if cache_position.dim() == 1: | ||
| layer.key.index_copy_(2, cache_position, key_states) | ||
| layer.value.index_copy_(2, cache_position, value_states) | ||
| return self._slice_dynamic(layer, int(cache_position[-1].item()) + 1) | ||
|
|
||
| if cache_position.dim() != 2: | ||
| raise ValueError(f"HunyuanImage3 cache_position must be 1D or 2D, got {cache_position.shape}.") | ||
| if cache_position.shape[0] != key_states.shape[0]: | ||
| raise ValueError( | ||
| f"HunyuanImage3 cache batch mismatch: cache_position={cache_position.shape}, key_states={key_states.shape}." | ||
| ) | ||
|
|
||
| for batch_idx in range(cache_position.shape[0]): | ||
| layer.key[batch_idx].index_copy_(1, cache_position[batch_idx], key_states[batch_idx]) | ||
| layer.value[batch_idx].index_copy_(1, cache_position[batch_idx], value_states[batch_idx]) | ||
| return self._slice_dynamic(layer, int(cache_position.max().item()) + 1) | ||
|
|
||
| def _slice_dynamic(self, layer, end): | ||
| if not self.dynamic: | ||
| return layer.key, layer.value | ||
| end = min(int(end), self.max_cache_len) | ||
| return layer.key[:, :, :end], layer.value[:, :, :end] | ||
|
|
||
|
|
||
| def _decompose_freqs(x, cutoff_ratio=0.1): | ||
| original_dtype = x.dtype | ||
| x_fp32 = x.float() | ||
| freq = torch.fft.fft(x_fp32, dim=1) | ||
| freqs = torch.fft.fftfreq(x_fp32.shape[1], d=1.0, device=x.device) | ||
| cutoff = cutoff_ratio * freqs.abs().max() | ||
| low_mask = (freqs.abs() <= cutoff)[None, :, None] | ||
| high_mask = ~low_mask | ||
| low = torch.fft.ifft(freq * low_mask, dim=1).real.to(dtype=original_dtype) | ||
| high = torch.fft.ifft(freq * high_mask, dim=1).real.to(dtype=original_dtype) | ||
| return low, high | ||
|
|
||
|
|
||
| class HunyuanImage3TaylorCache: | ||
| """Frequency-split Taylor hidden-state cache used by HunyuanImage3 sampling.""" | ||
|
|
||
| def __init__(self, max_order): | ||
| self.max_order = int(max_order) | ||
| self.low_derivatives = [None for _ in range(self.max_order + 1)] | ||
| self.high_derivatives = [None for _ in range(self.max_order + 1)] | ||
| self.last_past_key_values = None | ||
|
|
||
| def taylor_formula(self, distance): | ||
| low_output = None | ||
| high_output = None | ||
| for order, derivative in enumerate(self.low_derivatives): | ||
| if derivative is None: | ||
| break | ||
| term = (distance**order / math.factorial(order)) * derivative | ||
| low_output = term if low_output is None else low_output + term | ||
| for order, derivative in enumerate(self.high_derivatives): | ||
| if derivative is None: | ||
| break | ||
| term = (distance**order / math.factorial(order)) * derivative | ||
| high_output = term if high_output is None else high_output + term | ||
| if low_output is None and high_output is None: | ||
| raise RuntimeError("HunyuanImage3 Taylor cache has no derivatives to extrapolate from.") | ||
| if low_output is None: | ||
| return high_output | ||
| if high_output is None: | ||
| return low_output | ||
| return low_output + high_output | ||
|
|
||
| def derivatives_computation(self, hidden_states, distance, low_freqs_order, high_freqs_order): | ||
| low, high = _decompose_freqs(hidden_states) | ||
| new_low = [None for _ in range(self.max_order + 1)] | ||
| new_high = [None for _ in range(self.max_order + 1)] | ||
| new_low[0] = low | ||
| new_high[0] = high | ||
| safe_distance = max(int(distance), 1) | ||
|
|
||
| for order in range(min(int(low_freqs_order), self.max_order)): | ||
| if self.low_derivatives[order] is None: | ||
| break | ||
| new_low[order + 1] = (new_low[order] - self.low_derivatives[order]) / safe_distance | ||
|
|
||
| for order in range(min(int(high_freqs_order), self.max_order)): | ||
| if self.high_derivatives[order] is None: | ||
| break | ||
| new_high[order + 1] = (new_high[order] - self.high_derivatives[order]) / safe_distance | ||
|
|
||
| self.low_derivatives = new_low | ||
| self.high_derivatives = new_high | ||
|
|
||
| def clear_derivatives(self): | ||
| self.low_derivatives = [None for _ in range(self.max_order + 1)] | ||
| self.high_derivatives = [None for _ in range(self.max_order + 1)] | ||
| self.last_past_key_values = None |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
self.has_diffattribute is not initialized in__init__. If_get_actual_weightis called beforeregister_diff(or ifregister_diffis called butself.weight_diff_nameis not inweight_dict), this will raise anAttributeError. Usinggetattr(self, "has_diff", False)is safer and avoids this potential runtime crash.