Skip to content
Python

enabled refiners for all wan models

DeepBeepMeepf8a6937388a8
diff --git a/models/_settings.json b/models/_settings.json
index a97ec01..08bea2b 100644
--- a/models/_settings.json
+++ b/models/_settings.json
@@ -71,6 +71,8 @@
"cfg_zero_step": -1,
"self_refiner_setting": 0,
"self_refiner_plan": "",
+ "self_refiner_f_uncertainty": 0.1,
+ "self_refiner_certain_percentage":0.999,
"min_frames_if_references": 1,
"motion_amplitude": 1.0,
"sliding_window_size": 129,
diff --git a/models/wan/any2video.py b/models/wan/any2video.py
index b03710c..9c240d2 100644
--- a/models/wan/any2video.py
+++ b/models/wan/any2video.py
@@ -38,6 +38,7 @@ from .modules.posemb_layers import (
)
from shared.utils.vace_preprocessor import VaceVideoProcessor
from shared.utils.basic_flowmatch import FlowMatchScheduler
+from shared.utils.euler_scheduler import EulerScheduler
from shared.utils.lcm_scheduler import LCMScheduler
from shared.utils.utils import get_outpainting_frame_location, resize_lanczos, calculate_new_dimensions, convert_image_to_tensor, fit_image_into_canvas
from .multitalk.multitalk_utils import MomentumBuffer, adaptive_projected_guidance, match_and_blend_colors, match_and_blend_colors_with_mask
@@ -466,11 +467,9 @@ class WanAny2V:
control_scale_alt = 1.,
motion_amplitude = 1.,
window_start_frame_no = 0,
- enable_self_refine = False,
self_refiner_setting=0,
self_refiner_plan="",
- self_refiner_f_uncertainty = 0.0,
- self_refiner_p_norm = 1,
+ self_refiner_f_uncertainty = 0.1,
self_refiner_certain_percentage = 0.999,
**bbargs
):
@@ -478,14 +477,12 @@ class WanAny2V:
model_def = self.model_def
if sample_solver =="euler":
- # prepare timesteps
- timesteps = list(np.linspace(self.num_timesteps, 1, sampling_steps, dtype=np.float32))
- timesteps.append(0.)
- timesteps = [torch.tensor([t], device=self.device) for t in timesteps]
- if self.use_timestep_transform:
- timesteps = [timestep_transform(t, shift=shift, num_timesteps=self.num_timesteps) for t in timesteps][:-1]
- timesteps = torch.tensor(timesteps)
- sample_scheduler = None
+ sample_scheduler = EulerScheduler(
+ num_train_timesteps=self.num_timesteps,
+ use_timestep_transform=self.use_timestep_transform,
+ )
+ sample_scheduler.set_timesteps(sampling_steps, device=self.device, shift=shift)
+ timesteps = sample_scheduler.timesteps
elif sample_solver == 'causvid':
sample_scheduler = FlowMatchScheduler(num_inference_steps=sampling_steps, shift=shift, sigma_min=0, extra_one_step=True)
timesteps = torch.tensor([1000, 934, 862, 756, 603, 410, 250, 140, 74])[:sampling_steps].to(self.device)
@@ -1160,202 +1157,195 @@ class WanAny2V:
kwargs.update({"t": timestep, "current_step_no": i, "real_step_no": start_step_no + i })
kwargs["slg_layers"] = slg_layers if int(slg_start * sampling_steps) <= i < int(slg_end * sampling_steps) else None
- if denoising_strength < 1 and i <= injection_denoising_step:
- sigma = t / 1000
- if inject_from_start:
- noisy_image = latents.clone()
- noisy_image[:,:, :source_latents.shape[2] ] = randn[:, :, :source_latents.shape[2] ] * sigma + (1 - sigma) * source_latents
- for latent_no, keep_latent in enumerate(latent_keep_frames):
- if not keep_latent:
- noisy_image[:, :, latent_no:latent_no+1 ] = latents[:, :, latent_no:latent_no+1]
- latents = noisy_image
- noisy_image = None
- else:
- latents = randn * sigma + (1 - sigma) * source_latents
+ def denoise_with_cfg_fn(latents):
+ if denoising_strength < 1 and i <= injection_denoising_step:
+ sigma = t / 1000
+ if inject_from_start:
+ noisy_image = latents.clone()
+ noisy_image[:,:, :source_latents.shape[2] ] = randn[:, :, :source_latents.shape[2] ] * sigma + (1 - sigma) * source_latents
+ for latent_no, keep_latent in enumerate(latent_keep_frames):
+ if not keep_latent:
+ noisy_image[:, :, latent_no:latent_no+1 ] = latents[:, :, latent_no:latent_no+1]
+ latents = noisy_image
+ noisy_image = None
+ else:
+ latents = randn * sigma + (1 - sigma) * source_latents
+
+ if extended_overlapped_latents != None:
+ if no_noise_latents_injection:
+ latents[:, :, :extended_overlapped_latents.shape[2]] = extended_overlapped_latents
+ else:
+ latent_noise_factor = t / 1000
+ latents[:, :, :extended_overlapped_latents.shape[2]] = extended_overlapped_latents * (1.0 - latent_noise_factor) + torch.randn_like(extended_overlapped_latents ) * latent_noise_factor
+ if vace:
+ overlap_noise_factor = overlap_noise / 1000
+ for zz in z:
+ zz[0:16, ref_images_count:extended_overlapped_latents.shape[2] ] = extended_overlapped_latents[0, :, ref_images_count:] * (1.0 - overlap_noise_factor) + torch.randn_like(extended_overlapped_latents[0, :, ref_images_count:] ) * overlap_noise_factor
- if extended_overlapped_latents != None:
- if no_noise_latents_injection:
- latents[:, :, :extended_overlapped_latents.shape[2]] = extended_overlapped_latents
+ if extended_input_dim > 0:
+ latent_model_input = torch.cat([latents, extended_latents.expand(*expand_shape)], dim=extended_input_dim)
else:
- latent_noise_factor = t / 1000
- latents[:, :, :extended_overlapped_latents.shape[2]] = extended_overlapped_latents * (1.0 - latent_noise_factor) + torch.randn_like(extended_overlapped_latents ) * latent_noise_factor
- if vace:
- overlap_noise_factor = overlap_noise / 1000
- for zz in z:
- zz[0:16, ref_images_count:extended_overlapped_latents.shape[2] ] = extended_overlapped_latents[0, :, ref_images_count:] * (1.0 - overlap_noise_factor) + torch.randn_like(extended_overlapped_latents[0, :, ref_images_count:] ) * overlap_noise_factor
-
- if extended_input_dim > 0:
- latent_model_input = torch.cat([latents, extended_latents.expand(*expand_shape)], dim=extended_input_dim)
- else:
- latent_model_input = latents
-
- any_guidance = guide_scale != 1
- if phantom:
- gen_args = {
- "x" : ([ torch.cat([latent_model_input[:,:, :-ref_images_count], lat_input_ref_images.unsqueeze(0).expand(*expand_shape)], dim=2) ] * 2 +
- [ torch.cat([latent_model_input[:,:, :-ref_images_count], lat_input_ref_images_neg.unsqueeze(0).expand(*expand_shape)], dim=2)]),
- "context": [context, context_null, context_null] ,
- }
- elif fantasy:
- gen_args = {
- "x" : [latent_model_input, latent_model_input, latent_model_input],
- "context" : [context, context_null, context_null],
- "audio_scale": [audio_scale, None, None ]
- }
- elif animate:
- gen_args = {
- "x" : [latent_model_input, latent_model_input],
- "context" : [context, context_null],
- # "face_pixel_values": [face_pixel_values, None]
- "face_pixel_values": [face_pixel_values, face_pixel_values] # seems to look better this way
- }
- elif wanmove:
- gen_args = {
- "x" : [latent_model_input, latent_model_input],
- "context" : [context, context_null],
- "y" : [y_cond, y_uncond],
- }
- elif lynx:
- gen_args = {
- "x" : [latent_model_input, latent_model_input],
- "context" : [context, context_null],
- "lynx_ip_embeds": [ip_hidden_states, ip_hidden_states_uncond]
- }
- if model_type in ["lynx", "vace_lynx_14B"]:
- gen_args["lynx_ref_buffer"] = [lynx_ref_buffer, lynx_ref_buffer_uncond]
-
- elif steadydancer:
- # DC-CFG: pose guidance only in [10%, 50%] of denoising steps
- apply_cond_cfg = 0.1 <= i / sampling_steps < 0.5 and condition_guide_scale != 1
- x_list, ctx_list, cond_list = [latent_model_input], [context], [conditions]
- if guide_scale != 1:
- x_list.append(latent_model_input); ctx_list.append(context_null); cond_list.append(conditions)
- if apply_cond_cfg:
- x_list.append(latent_model_input); ctx_list.append(context); cond_list.append(conditions_null)
- gen_args = {"x": x_list, "context": ctx_list, "steadydancer_condition": cond_list}
- any_guidance = len(x_list) > 1
- elif multitalk and audio_proj != None:
- if guide_scale == 1:
+ latent_model_input = latents
+
+ any_guidance = guide_scale != 1
+ if phantom:
gen_args = {
- "x" : [latent_model_input, latent_model_input],
- "context" : [context, context],
- "multitalk_audio": [audio_proj, [torch.zeros_like(audio_proj[0][-1:]), torch.zeros_like(audio_proj[1][-1:])]],
- "multitalk_masks": [token_ref_target_masks, None]
+ "x" : ([ torch.cat([latent_model_input[:,:, :-ref_images_count], lat_input_ref_images.unsqueeze(0).expand(*expand_shape)], dim=2) ] * 2 +
+ [ torch.cat([latent_model_input[:,:, :-ref_images_count], lat_input_ref_images_neg.unsqueeze(0).expand(*expand_shape)], dim=2)]),
+ "context": [context, context_null, context_null] ,
}
- any_guidance = audio_cfg_scale != 1
- else:
+ elif fantasy:
gen_args = {
"x" : [latent_model_input, latent_model_input, latent_model_input],
"context" : [context, context_null, context_null],
- "multitalk_audio": [audio_proj, audio_proj, [torch.zeros_like(audio_proj[0][-1:]), torch.zeros_like(audio_proj[1][-1:])]],
- "multitalk_masks": [token_ref_target_masks, token_ref_target_masks, None]
+ "audio_scale": [audio_scale, None, None ]
}
- else:
- gen_args = {
- "x" : [latent_model_input, latent_model_input],
- "context": [context, context_null]
- }
-
- if joint_pass and any_guidance:
- ret_values = trans( **gen_args , **kwargs)
- if self._interrupt:
- return clear()
- else:
- size = len(gen_args["x"]) if any_guidance else 1
- ret_values = [None] * size
- for x_id in range(size):
- sub_gen_args = {k : [v[x_id]] for k, v in gen_args.items() }
- ret_values[x_id] = trans( **sub_gen_args, x_id= x_id , **kwargs)[0]
- if self._interrupt:
- return clear()
- sub_gen_args = None
- if not any_guidance:
- noise_pred = ret_values[0]
- elif phantom:
- guide_scale_img= 5.0
- guide_scale_text= guide_scale #7.5
- pos_it, pos_i, neg = ret_values
- noise_pred = neg + guide_scale_img * (pos_i - neg) + guide_scale_text * (pos_it - pos_i)
- pos_it = pos_i = neg = None
- elif fantasy:
- noise_pred_cond, noise_pred_noaudio, noise_pred_uncond = ret_values
- noise_pred = noise_pred_uncond + guide_scale * (noise_pred_noaudio - noise_pred_uncond) + audio_cfg_scale * (noise_pred_cond - noise_pred_noaudio)
- noise_pred_noaudio = None
- elif steadydancer:
- noise_pred_cond = ret_values[0]
- if guide_scale == 1: # only condition CFG (ret_values[1] = uncond_condition)
- noise_pred = ret_values[1] + condition_guide_scale * (noise_pred_cond - ret_values[1])
- else: # text CFG + optionally condition CFG (ret_values[1] = uncond_context)
- noise_pred = ret_values[1] + guide_scale * (noise_pred_cond - ret_values[1])
+ elif animate:
+ gen_args = {
+ "x" : [latent_model_input, latent_model_input],
+ "context" : [context, context_null],
+ # "face_pixel_values": [face_pixel_values, None]
+ "face_pixel_values": [face_pixel_values, face_pixel_values] # seems to look better this way
+ }
+ elif wanmove:
+ gen_args = {
+ "x" : [latent_model_input, latent_model_input],
+ "context" : [context, context_null],
+ "y" : [y_cond, y_uncond],
+ }
+ elif lynx:
+ gen_args = {
+ "x" : [latent_model_input, latent_model_input],
+ "context" : [context, context_null],
+ "lynx_ip_embeds": [ip_hidden_states, ip_hidden_states_uncond]
+ }
+ if model_type in ["lynx", "vace_lynx_14B"]:
+ gen_args["lynx_ref_buffer"] = [lynx_ref_buffer, lynx_ref_buffer_uncond]
+
+ elif steadydancer:
+ # DC-CFG: pose guidance only in [10%, 50%] of denoising steps
+ apply_cond_cfg = 0.1 <= i / sampling_steps < 0.5 and condition_guide_scale != 1
+ x_list, ctx_list, cond_list = [latent_model_input], [context], [conditions]
+ if guide_scale != 1:
+ x_list.append(latent_model_input); ctx_list.append(context_null); cond_list.append(conditions)
if apply_cond_cfg:
- noise_pred = noise_pred + condition_guide_scale * (noise_pred_cond - ret_values[2])
- noise_pred_cond = None
-
- elif multitalk and audio_proj != None:
- if apg_switch != 0:
- if guide_scale == 1:
- noise_pred_cond, noise_pred_drop_audio = ret_values
- noise_pred = noise_pred_cond + (audio_cfg_scale - 1)* adaptive_projected_guidance(noise_pred_cond - noise_pred_drop_audio,
- noise_pred_cond,
- momentum_buffer=audio_momentumbuffer,
- norm_threshold=apg_norm_threshold)
-
- else:
- noise_pred_cond, noise_pred_drop_text, noise_pred_uncond = ret_values
- noise_pred = noise_pred_cond + (guide_scale - 1) * adaptive_projected_guidance(noise_pred_cond - noise_pred_drop_text,
- noise_pred_cond,
- momentum_buffer=text_momentumbuffer,
- norm_threshold=apg_norm_threshold) \
- + (audio_cfg_scale - 1) * adaptive_projected_guidance(noise_pred_drop_text - noise_pred_uncond,
- noise_pred_cond,
- momentum_buffer=audio_momentumbuffer,
- norm_threshold=apg_norm_threshold)
- else:
+ x_list.append(latent_model_input); ctx_list.append(context); cond_list.append(conditions_null)
+ gen_args = {"x": x_list, "context": ctx_list, "steadydancer_condition": cond_list}
+ any_guidance = len(x_list) > 1
+ elif multitalk and audio_proj != None:
if guide_scale == 1:
- noise_pred_cond, noise_pred_drop_audio = ret_values
- noise_pred = noise_pred_drop_audio + audio_cfg_scale* (noise_pred_cond - noise_pred_drop_audio)
+ gen_args = {
+ "x" : [latent_model_input, latent_model_input],
+ "context" : [context, context],
+ "multitalk_audio": [audio_proj, [torch.zeros_like(audio_proj[0][-1:]), torch.zeros_like(audio_proj[1][-1:])]],
+ "multitalk_masks": [token_ref_target_masks, None]
+ }
+ any_guidance = audio_cfg_scale != 1
else:
- noise_pred_cond, noise_pred_drop_text, noise_pred_uncond = ret_values
- noise_pred = noise_pred_uncond + guide_scale * (noise_pred_cond - noise_pred_drop_text) + audio_cfg_scale * (noise_pred_drop_text - noise_pred_uncond)
- noise_pred_uncond = noise_pred_cond = noise_pred_drop_text = noise_pred_drop_audio = None
- else:
- noise_pred_cond, noise_pred_uncond = ret_values
- if apg_switch != 0:
- noise_pred = noise_pred_cond + (guide_scale - 1) * adaptive_projected_guidance(noise_pred_cond - noise_pred_uncond,
- noise_pred_cond,
- momentum_buffer=text_momentumbuffer,
- norm_threshold=apg_norm_threshold)
+ gen_args = {
+ "x" : [latent_model_input, latent_model_input, latent_model_input],
+ "context" : [context, context_null, context_null],
+ "multitalk_audio": [audio_proj, audio_proj, [torch.zeros_like(audio_proj[0][-1:]), torch.zeros_like(audio_proj[1][-1:])]],
+ "multitalk_masks": [token_ref_target_masks, token_ref_target_masks, None]
+ }
else:
- noise_pred_text = noise_pred_cond
- if cfg_star_switch:
- # CFG Zero *. Thanks to https://github.com/WeichenFan/CFG-Zero-star/
- positive_flat = noise_pred_text.view(batch_size, -1)
- negative_flat = noise_pred_uncond.view(batch_size, -1)
+ gen_args = {
+ "x" : [latent_model_input, latent_model_input],
+ "context": [context, context_null]
+ }
- alpha = optimized_scale(positive_flat,negative_flat)
- alpha = alpha.view(batch_size, 1, 1, 1)
+ if joint_pass and any_guidance:
+ ret_values = trans( **gen_args , **kwargs)
+ if self._interrupt:
+ return clear()
+ else:
+ size = len(gen_args["x"]) if any_guidance else 1
+ ret_values = [None] * size
+ for x_id in range(size):
+ sub_gen_args = {k : [v[x_id]] for k, v in gen_args.items() }
+ ret_values[x_id] = trans( **sub_gen_args, x_id= x_id , **kwargs)[0]
+ if self._interrupt:
+ return clear()
+ sub_gen_args = None
+ if not any_guidance:
+ noise_pred = ret_values[0]
+ elif phantom:
+ guide_scale_img= 5.0
+ guide_scale_text= guide_scale #7.5
+ pos_it, pos_i, neg = ret_values
+ noise_pred = neg + guide_scale_img * (pos_i - neg) + guide_scale_text * (pos_it - pos_i)
+ pos_it = pos_i = neg = None
+ elif fantasy:
+ noise_pred_cond, noise_pred_noaudio, noise_pred_uncond = ret_values
+ noise_pred = noise_pred_uncond + guide_scale * (noise_pred_noaudio - noise_pred_uncond) + audio_cfg_scale * (noise_pred_cond - noise_pred_noaudio)
+ noise_pred_noaudio = None
+ elif steadydancer:
+ noise_pred_cond = ret_values[0]
+ if guide_scale == 1: # only condition CFG (ret_values[1] = uncond_condition)
+ noise_pred = ret_values[1] + condition_guide_scale * (noise_pred_cond - ret_values[1])
+ else: # text CFG + optionally condition CFG (ret_values[1] = uncond_context)
+ noise_pred = ret_values[1] + guide_scale * (noise_pred_cond - ret_values[1])
+ if apply_cond_cfg:
+ noise_pred = noise_pred + condition_guide_scale * (noise_pred_cond - ret_values[2])
+ noise_pred_cond = None
+
+ elif multitalk and audio_proj != None:
+ if apg_switch != 0:
+ if guide_scale == 1:
+ noise_pred_cond, noise_pred_drop_audio = ret_values
+ noise_pred = noise_pred_cond + (audio_cfg_scale - 1)* adaptive_projected_guidance(noise_pred_cond - noise_pred_drop_audio,
+ noise_pred_cond,
+ momentum_buffer=audio_momentumbuffer,
+ norm_threshold=apg_norm_threshold)
- if (i <= cfg_zero_step):
- noise_pred = noise_pred_text*0. # it would be faster not to compute noise_pred...
else:
- noise_pred_uncond *= alpha
- noise_pred = noise_pred_uncond + guide_scale * (noise_pred_text - noise_pred_uncond)
- ret_values = noise_pred_uncond = noise_pred_cond = noise_pred_text = neg = None
-
-
+ noise_pred_cond, noise_pred_drop_text, noise_pred_uncond = ret_values
+ noise_pred = noise_pred_cond + (guide_scale - 1) * adaptive_projected_guidance(noise_pred_cond - noise_pred_drop_text,
+ noise_pred_cond,
+ momentum_buffer=text_momentumbuffer,
+ norm_threshold=apg_norm_threshold) \
+ + (audio_cfg_scale - 1) * adaptive_projected_guidance(noise_pred_drop_text - noise_pred_uncond,
+ noise_pred_cond,
+ momentum_buffer=audio_momentumbuffer,
+ norm_threshold=apg_norm_threshold)
+ else:
+ if guide_scale == 1:
+ noise_pred_cond, noise_pred_drop_audio = ret_values
+ noise_pred = noise_pred_drop_audio + audio_cfg_scale* (noise_pred_cond - noise_pred_drop_audio)
+ else:
+ noise_pred_cond, noise_pred_drop_text, noise_pred_uncond = ret_values
+ noise_pred = noise_pred_uncond + guide_scale * (noise_pred_cond - noise_pred_drop_text) + audio_cfg_scale * (noise_pred_drop_text - noise_pred_uncond)
+ noise_pred_uncond = noise_pred_cond = noise_pred_drop_text = noise_pred_drop_audio = None
+ else:
+ noise_pred_cond, noise_pred_uncond = ret_values
+ if apg_switch != 0:
+ noise_pred = noise_pred_cond + (guide_scale - 1) * adaptive_projected_guidance(noise_pred_cond - noise_pred_uncond,
+ noise_pred_cond,
+ momentum_buffer=text_momentumbuffer,
+ norm_threshold=apg_norm_threshold)
+ else:
+ noise_pred_text = noise_pred_cond
+ if cfg_star_switch:
+ # CFG Zero *. Thanks to https://github.com/WeichenFan/CFG-Zero-star/
+ positive_flat = noise_pred_text.view(batch_size, -1)
+ negative_flat = noise_pred_uncond.view(batch_size, -1)
+
+ alpha = optimized_scale(positive_flat,negative_flat)
+ alpha = alpha.view(batch_size, 1, 1, 1)
+
+ if (i <= cfg_zero_step):
+ noise_pred = noise_pred_text*0. # it would be faster not to compute noise_pred...
+ else:
+ noise_pred_uncond *= alpha
+ noise_pred = noise_pred_uncond + guide_scale * (noise_pred_text - noise_pred_uncond)
+ ret_values = noise_pred_uncond = noise_pred_cond = noise_pred_text = neg = None
+ return noise_pred
+
+ noise_pred = denoise_with_cfg_fn(latents)
if self_refiner_handler:
- latents, sample_scheduler = self_refiner_handler.step(i, latents, noise_pred, locals(), phantom or scail or steadydancer or fantasy)
+ latents, sample_scheduler = self_refiner_handler.step(i, latents, noise_pred, t, timesteps, target_shape, seed_g, sample_scheduler, scheduler_kwargs, denoise_with_cfg_fn)
else:
- if sample_solver == "euler":
- dt = timesteps[i] if i == len(timesteps)-1 else (timesteps[i] - timesteps[i + 1])
- dt = dt.item() / self.num_timesteps
- latents = latents - noise_pred * dt
- else:
- latents = sample_scheduler.step(
- noise_pred[:, :, :target_shape[1]],
- t,
- latents,
- **scheduler_kwargs)[0]
+ latents = sample_scheduler.step( noise_pred[:, :, :target_shape[1]], t, latents, **scheduler_kwargs)[0]
if image_mask_latents is not None and i< masked_steps:
diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.py
index f308386..e31c54b 100644
--- a/models/wan/wan_handler.py
+++ b/models/wan/wan_handler.py
@@ -277,7 +277,7 @@ class family_handler():
("lcm + ltx", "lcm"), ]
})
- extra_model_def["self_refiner"] = base_model_type in ["t2v_2_2", "i2v_2_2", "i2v", "t2v", "flf2v_720p"]
+ extra_model_def["self_refiner"] = True
if i2v:
extra_model_def["motion_amplitude"] = True
@@ -866,8 +866,9 @@ class family_handler():
if model_def.get("self_refiner",False) and settings_version < 2.47:
ui_defaults["self_refiner_setting"] = 0
ui_defaults["self_refiner_plan"] = ""
- # ui_defaults["self_refiner_f_uncertainty"] = 0.2
- # ui_defaults["self_refiner_certain_percentage"] = 0.999
+ if model_def.get("self_refiner",False) and settings_version < 2.48:
+ ui_defaults["self_refiner_f_uncertainty"] = 0.1
+ ui_defaults["self_refiner_certain_percentage"] = 0.999
@staticmethod
def update_default_settings(base_model_type, model_def, ui_defaults):
diff --git a/shared/utils/basic_flowmatch.py b/shared/utils/basic_flowmatch.py
index ceb4657..d9e6b82 100644
--- a/shared/utils/basic_flowmatch.py
+++ b/shared/utils/basic_flowmatch.py
@@ -5,6 +5,7 @@ import torch
class FlowMatchScheduler():
+ is_stateful = False
def __init__(self, num_inference_steps=100, num_train_timesteps=1000, shift=3.0, sigma_max=1.0, sigma_min=0.003 / 1.002, inverse_timesteps=False, extra_one_step=False, reverse_sigmas=False):
self.num_train_timesteps = num_train_timesteps
diff --git a/shared/utils/euler_scheduler.py b/shared/utils/euler_scheduler.py
new file mode 100644
index 0000000..c2f4a1d
--- /dev/null
+++ b/shared/utils/euler_scheduler.py
@@ -0,0 +1,86 @@
+import numpy as np
+import torch
+
+
+def _timestep_transform(t, shift=5.0, num_timesteps=1000):
+ t = t / num_timesteps
+ new_t = shift * t / (1 + (shift - 1) * t)
+ return new_t * num_timesteps
+
+
+class EulerSchedulerOutput:
+ def __init__(self, prev_sample, pred_original_sample=None):
+ self.prev_sample = prev_sample
+ if pred_original_sample is not None:
+ self.pred_original_sample = pred_original_sample
+
+ def __getitem__(self, index):
+ if index == 0:
+ return self.prev_sample
+ raise IndexError("EulerSchedulerOutput only supports index 0.")
+
+ def __iter__(self):
+ yield self.prev_sample
+
+
+class EulerScheduler:
+ is_stateful = False
+
+ def __init__(self, num_train_timesteps=1000, use_timestep_transform=True):
+ self.num_train_timesteps = num_train_timesteps
+ self.use_timestep_transform = use_timestep_transform
+ self.timesteps = None
+ self.num_inference_steps = None
+
+ def set_timesteps(self, num_inference_steps, device=None, shift=5.0):
+ self.num_inference_steps = num_inference_steps
+ timesteps = list(
+ np.linspace(self.num_train_timesteps, 1, num_inference_steps, dtype=np.float32)
+ )
+ timesteps.append(0.0)
+ if device is None:
+ timesteps = [torch.tensor([t]) for t in timesteps]
+ else:
+ timesteps = [torch.tensor([t], device=device) for t in timesteps]
+ if self.use_timestep_transform:
+ timesteps = [
+ _timestep_transform(t, shift=shift, num_timesteps=self.num_train_timesteps)
+ for t in timesteps
+ ][:-1]
+ self.timesteps = torch.tensor(timesteps)
+ return self.timesteps
+
+ def _timestep_to_index(self, timestep):
+ if self.timesteps is None:
+ raise ValueError("Timesteps are not set. Call set_timesteps first.")
+ if torch.is_tensor(timestep):
+ if timestep.numel() != 1:
+ t_val = timestep.flatten()[0].item()
+ else:
+ t_val = timestep.item()
+ else:
+ t_val = float(timestep)
+ diff = (self.timesteps - t_val).abs()
+ idx = int(torch.argmin(diff).item())
+ return idx, t_val
+
+ def step(self, model_output, timestep, sample, return_dict=True, **kwargs):
+ if self.timesteps is None:
+ raise ValueError("Timesteps are not set. Call set_timesteps first.")
+ idx, t_val = self._timestep_to_index(timestep)
+ if idx + 1 < len(self.timesteps):
+ dt_raw = self.timesteps[idx] - self.timesteps[idx + 1]
+ else:
+ dt_raw = self.timesteps[idx]
+ dt = dt_raw.item() / self.num_train_timesteps
+ prev_sample = sample - model_output * dt
+ pred_original_sample = sample - (t_val / self.num_train_timesteps) * model_output
+ if not return_dict:
+ return (prev_sample,)
+ return EulerSchedulerOutput(
+ prev_sample=prev_sample,
+ pred_original_sample=pred_original_sample,
+ )
+
+ def scale_model_input(self, sample, *args, **kwargs):
+ return sample
diff --git a/shared/utils/self_refiner.py b/shared/utils/self_refiner.py
index 8ef60ab..d08cc95 100644
--- a/shared/utils/self_refiner.py
+++ b/shared/utils/self_refiner.py
@@ -120,24 +120,14 @@ class PnPHandler:
latents_next = certain_mask_float * self.buffer[-1][2] + (1.0 - certain_mask_float) * latents_next
pred_original_sample = certain_mask_float * self.buffer[-1][1] + (1.0 - certain_mask_float) * pred_original_sample
- # Pack for buffer
- # we need to squeeze the mask back if we store it
certain_mask_stored = certain_mask # keep bool
else:
certain_mask_stored = None
-
self.buffer.append([certain_mask_stored, pred_original_sample, latents_next])
return latents_next
def perturb_latents(self, latents, buffer_latent, sigma, generator=None, device=None):
noise = randn_tensor(latents.shape, generator=generator, device=device, dtype=latents.dtype)
- # Re-noise: (1-sigma) * x0 + sigma * noise ??
- # Ref code: latents = (1.0 - sigma) * buffer[-1][1] + sigma * noise
- # This seems to assume x_t = (1-sigma)*x0 + sigma*noise?
- # Wait, Flow matching usually is x_t = t * x1 + (1-t) * x0.
- # If sigma is t, then x_sigma = sigma * x1 + (1-sigma) * x0.
- # If we target noise (epsilon), it varies.
- # The reference code uses this formula. We should probably stick to it if we assume sigma is correct.
return (1.0 - sigma) * buffer_latent + sigma * noise
@@ -153,26 +143,6 @@ class PnPHandler:
restore_func=None,
generator=None,
device=None):
- """
- Executes the PnP refinement loop.
-
- Args:
- latents: Current latents.
- noise_pred: Initial noise prediction.
- current_sigma: Current sigma (t/1000).
- next_sigma: Next sigma (t_next/1000).
- m_steps: Number of annealing steps.
- denoise_func: Callable(latents) -> noise_pred.
- step_func: Callable(noise_pred, latents) -> (latents_next, pred_original_sample).
- Should handle scheduler step.
- clone_func: Callable() -> scheduler_state (optional, for state restoration).
- restore_func: Callable(scheduler_state) -> None (optional).
- generator: Torch generator.
- device: Torch device.
-
- Returns:
- latents_next: The refined next latents.
- """
# Save initial state if needed
scheduler_state = None
@@ -217,95 +187,46 @@ class PnPHandler:
return latents_next
- def step(self, step_index, latents, noise_pred, context, diablecfg):
- """
- Processes a single generation step, deciding whether to perform PnP refinement
- or a standard step based on the provided context.
- """
- # Unpack context
- trans = context.get('trans')
- gen_args = context.get('gen_args')
- kwargs = context.get('kwargs')
- t = context.get('t')
- timesteps = context.get('timesteps')
- sample_solver = context.get('sample_solver')
- sample_scheduler = context.get('sample_scheduler')
- scheduler_kwargs = context.get('scheduler_kwargs')
- extended_input_dim = context.get('extended_input_dim')
- extended_latents = context.get('extended_latents')
- expand_shape = context.get('expand_shape')
- target_shape = context.get('target_shape')
- joint_pass = context.get('joint_pass')
- any_guidance = context.get('any_guidance')
- guide_scale = context.get('guide_scale')
- seed_g = context.get('seed_g')
- num_timesteps = context.get('self').num_timesteps if context.get('self') else 1000
-
+ def step(self, step_index, latents, noise_pred, t, timesteps, target_shape, seed_g, sample_scheduler, scheduler_kwargs, denoise_func):
+ # Reset per denoising step to avoid blending with stale buffers from prior timesteps.
+ self.reset_buffer()
# Calculate sigma for PnP
current_sigma = t.item() / 1000.0
next_sigma = (0. if step_index == len(timesteps)-1 else timesteps[step_index+1].item()) / 1000.0
m_steps = self.get_anneal_steps(step_index)
-
- # Euler DT calculation if needed
- dt = None
- if sample_solver == "euler":
- dt_raw = timesteps[step_index] if step_index == len(timesteps)-1 else (timesteps[step_index] - timesteps[step_index + 1])
- dt = dt_raw.item() / num_timesteps
if m_steps > 1 and not self.certain_flag:
- # PnP logic
- def denoise_func(latents_in):
- if extended_input_dim > 0:
- l_in_func = torch.cat([latents_in, extended_latents.expand(*expand_shape)], dim=extended_input_dim)
- else:
- l_in_func = latents_in
-
- if "x" in gen_args:
- if isinstance(gen_args["x"], list):
- gen_args["x"] = [l_in_func] * len(gen_args["x"])
-
- if joint_pass and any_guidance:
- ret_vals = trans(**gen_args, **kwargs)
- else:
- size = len(gen_args["x"]) if any_guidance else 1
- ret_vals = [None] * size
- for x_id in range(size):
- sub_gen_args = {k : [v[x_id]] for k, v in gen_args.items() }
- ret_vals[x_id] = trans( **sub_gen_args, x_id= x_id , **kwargs)[0]
-
- if not any_guidance:
- n_pred_func = ret_vals[0]
- else:
- if not diablecfg:
- n_cond, n_uncond = ret_vals
- n_pred_func = n_uncond + guide_scale * (n_cond - n_uncond)
- else:
- n_pred_func = ret_vals[0]
- return n_pred_func
+
+ def _get_prev_sample(step_out):
+ if hasattr(step_out, "prev_sample"):
+ return step_out.prev_sample
+ if isinstance(step_out, (tuple, list)):
+ return step_out[0]
+ return step_out
+
+ def _get_pred_original_sample(step_out, latents_in, n_pred_sliced):
+ if hasattr(step_out, "pred_original_sample"):
+ return step_out.pred_original_sample
+ t_val = t.item() if torch.is_tensor(t) else float(t)
+ return latents_in - (t_val / 1000.0) * n_pred_sliced
def step_func(n_pred_in, latents_in):
# Correct slicing:
# [:, :channels] slices Dimension 1
# [:, :, :frames] slices Dimension 2
n_pred_sliced = n_pred_in[:, :latents_in.shape[1], :target_shape[1]]
-
- if sample_solver == "euler":
- latents_next_out = latents_in - n_pred_sliced * dt
- pred_original_sample_out = latents_in - (t.item()/1000.0) * n_pred_sliced
- else:
- nonlocal sample_scheduler
- step_out = sample_scheduler.step(n_pred_sliced, t, latents_in, **scheduler_kwargs)
- latents_next_out = step_out.prev_sample
- if hasattr(step_out, 'pred_original_sample'):
- pred_original_sample_out = step_out.pred_original_sample
- else:
- # Fallback for solvers like UniPC that might not return pred_original_sample
- pred_original_sample_out = latents_in - (t.item()/1000.0) * n_pred_sliced
+
+ nonlocal sample_scheduler
+ step_out = sample_scheduler.step(n_pred_sliced, t, latents_in, **scheduler_kwargs)
+ latents_next_out = _get_prev_sample(step_out)
+ pred_original_sample_out = _get_pred_original_sample(step_out, latents_in, n_pred_sliced)
return latents_next_out, pred_original_sample_out
def clone_func():
- if sample_solver != "euler":
+ if sample_scheduler is None:
+ return None
+ if getattr(sample_scheduler, "is_stateful", True):
return copy.deepcopy(sample_scheduler)
return None
@@ -331,14 +252,13 @@ class PnPHandler:
# Standard logic
# Correct slicing: [:, :channels, :frames]
n_pred_sliced = noise_pred[:, :latents.shape[1], :target_shape[1]]
- if sample_solver == "euler":
- latents = latents - n_pred_sliced * dt
+ step_out = sample_scheduler.step( n_pred_sliced, t, latents, **scheduler_kwargs)
+ if hasattr(step_out, "prev_sample"):
+ latents = step_out.prev_sample
+ elif isinstance(step_out, (tuple, list)):
+ latents = step_out[0]
else:
- latents = sample_scheduler.step(
- n_pred_sliced,
- t,
- latents,
- **scheduler_kwargs)[0]
+ latents = step_out
return latents, sample_scheduler
diff --git a/wgp.py b/wgp.py
index 8d5a505..619a6d6 100644
--- a/wgp.py
+++ b/wgp.py
@@ -4278,9 +4278,9 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, aud
video_self_refiner_setting = configs.get("self_refiner_setting", 0)
if video_self_refiner_setting > 0:
video_self_refiner_plan = configs.get('self_refiner_plan','')
- if len(video_self_refiner_plan)==0: video_self_refiner_plan ='<default>'
- # values += [f"Norm P{video_self_refiner_setting}, Plan='{video_self_refiner_plan}', Uncertainty={configs.get('self_refiner_f_uncertainty',0.2)}, Certain Percentage='{configs.get('self_refiner_certain_percentage', 0.999)} "]
- values += [f"Norm P{video_self_refiner_setting}, Plan='{video_self_refiner_plan}'"]
+ if len(video_self_refiner_plan)==0: video_self_refiner_plan ='default'
+ values += [f"Norm P{video_self_refiner_setting}, Plan='{video_self_refiner_plan}', Uncertainty={configs.get('self_refiner_f_uncertainty',0.2)}, Certain Percentage='{configs.get('self_refiner_certain_percentage', 0.999)} "]
+ # values += [f"Norm P{video_self_refiner_setting}, Plan='{video_self_refiner_plan}'"]
labels += ["Self Refiner"]
video_apg_switch = configs.get("apg_switch", None)
if video_apg_switch is not None and video_apg_switch != 0:
@@ -5524,8 +5524,8 @@ def generate_video(
top_k,
self_refiner_setting,
self_refiner_plan,
- # self_refiner_f_uncertainty,
- # self_refiner_certain_percentage,
+ self_refiner_f_uncertainty,
+ self_refiner_certain_percentage,
output_filename,
state,
model_type,
@@ -6391,8 +6391,8 @@ def generate_video(
input_video_strength = input_video_strength,
self_refiner_setting = self_refiner_setting,
self_refiner_plan=self_refiner_plan,
- # self_refiner_f_uncertainty = self_refiner_f_uncertainty,
- # self_refiner_certain_percentage = self_refiner_certain_percentage,
+ self_refiner_f_uncertainty = self_refiner_f_uncertainty,
+ self_refiner_certain_percentage = self_refiner_certain_percentage,
**extra_generate_kwargs,
)
except Exception as e:
@@ -7706,8 +7706,8 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = None
pop += ["control_net_weight_alt"]
if not model_def.get("self_refiner", False):
- # pop += ["self_refiner_setting", "self_refiner_f_uncertainty", "self_refiner_plan", "self_refiner_certain_percentage"]
- pop += ["self_refiner_setting", "self_refiner_plan"]
+ pop += ["self_refiner_setting", "self_refiner_f_uncertainty", "self_refiner_plan", "self_refiner_certain_percentage"]
+ # pop += ["self_refiner_setting", "self_refiner_plan"]
if model_def.get("audio_scale_name", None) is None:
pop += ["audio_scale"]
@@ -8419,8 +8419,8 @@ def save_inputs(
top_k,
self_refiner_setting,
self_refiner_plan,
- # self_refiner_f_uncertainty,
- # self_refiner_certain_percentage,
+ self_refiner_f_uncertainty,
+ self_refiner_certain_percentage,
output_filename,
mode,
state,
@@ -10137,8 +10137,9 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
gr.Markdown("<B>Self-Refining Video Sampling (PnP) - should improve quality of Motion</B>")
self_refiner_setting = gr.Dropdown( choices=[("Disabled", 0),("Enabled with P1-Norm", 1), ("Enabled with P2-Norm", 2), ], value=ui_get("self_refiner_setting", 0), scale = 1, label="Self Refiner", )
self_refiner_plan = gr.Textbox( value=ui_get("self_refiner_plan", ""), label="P&P Plan (start-end:steps, comma-separated)", lines=1, placeholder="2-5:3,6-13:1" )
- # self_refiner_f_uncertainty = gr.Slider(0.0, 1.0, value=ui_get("self_refiner_f_uncertainty", 0.0), step=0.01, label="Uncertainty Threshold", show_reset_button= False)
- # self_refiner_certain_percentage = gr.Slider(0.0, 1.0, value=ui_get("self_refiner_certain_percentage", 0.999), step=0.001, label="Certainty Percentage Skip", show_reset_button= False)
+ with gr.Row():
+ self_refiner_f_uncertainty = gr.Slider(0.0, 1.0, value=ui_get("self_refiner_f_uncertainty", 0.1), step=0.01, label="Uncertainty Threshold", show_reset_button= False)
+ self_refiner_certain_percentage = gr.Slider(0.0, 1.0, value=ui_get("self_refiner_certain_percentage", 0.999), step=0.001, label="Certainty Percentage Skip", show_reset_button= False)
with gr.Tab("Sliding Window", visible= sliding_window_enabled and not image_outputs and not audio_only) as sliding_window_tab: