Skip to content
Python

refactor to move the bulk of code to external module

Chris Malone00e49d4329f6
diff --git a/models/wan/any2video.py b/models/wan/any2video.py
index 97a3e73..1c7308e 100644
--- a/models/wan/any2video.py
+++ b/models/wan/any2video.py
@@ -46,7 +46,7 @@ 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 .pnp_utils import PnPHandler
+from .pnp_utils import PnPHandler, create_pnp_handler
from mmgp import safetensors2
from shared.utils import files_locator as fl
@@ -1140,16 +1140,8 @@ class WanAny2V:
torch.cuda.empty_cache()
# denoising
trans = self.model
-
- # PnP Setup
- pnp_handler = None
- if enable_self_refine:
- # Default plan from paper/code
- stochastic_plan = [
- {"start": 1, "end": 5, "steps": 3},
- {"start": 6, "end": 13, "steps": 1},
- ]
- pnp_handler = PnPHandler(stochastic_plan, ths_uncertainty=pnp_f_uncertainty, p_norm=pnp_p_norm, certain_percentage=pnp_certain_percentage)
+
+ pnp_handler = create_pnp_handler(enable_self_refine, pnp_f_uncertainty, pnp_p_norm, pnp_certain_percentage)
for i, t in enumerate(tqdm(timesteps)):
guide_scale, guidance_switch_done, trans, denoising_extra = update_guidance(i, t, guide_scale, guide2_scale, guidance_switch_done, switch_threshold, trans, 2, denoising_extra)
@@ -1347,255 +1339,10 @@ class WanAny2V:
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
- # PnP Loop Wrap
- # If PnP is enabled, we might loop here for refinement
- # The reference logic:
- # m = current_num_anneal_steps + 1 if in_stoch else 1
- # loop m times.
-
- current_num_anneal_steps = 0
+
if pnp_handler:
- # Map step i to stochastic steps. Note: 'i' here is 0..num_steps.
- # The reference uses index in timesteps array.
- current_num_anneal_steps = pnp_handler.get_anneal_steps(i)
-
- in_stoch = current_num_anneal_steps > 0
- m_steps = current_num_anneal_steps + 1 if in_stoch else 1
-
- # We need to save the initial state if we are going to perturb it,
- # BUT the reference logic suggests we perturb *after* the first prediction if m > 1.
- # Actually, the reference logic is:
- # For ii in range(m):
- # if ii > 0: latents = perturb(...)
- # noise_pred = model(latents)
- # latents_next = step(latents, noise_pred)
- # if in_stoch: update_buffer(...)
- # if ii == m-1: latents = buffer[-1][2] (the refined result)
-
- # The structure of any2video's loop is:
- # 1. Update guidance/Lora
- # 2. Prepare latent_model_input
- # 3. Model forward (noise_pred)
- # 4. Step (latents -> latents_next)
-
- # To integrate PnP, we need to repeat steps 2, 3, 4 'm' times.
- # However, Steps 1 (Update guidance) only needs to happen once per timestep 't'.
- # So we can wrap 2, 3, 4 in a loop.
-
- # BUT `noise_pred` was already computed above (Step 3).
- # So the first iteration (ii=0) is effectively done up to the `step` call.
-
- # Wait, if we loop, we need to re-compute noise_pred for ii > 0 because latents changed (perturbation).
- # The code above (lines 1143-1331) computes `noise_pred` for the *initial* latents of this step.
-
- # Reorganization:
- # We treat the code above as the "first iteration calculation of noise_pred".
- # Then we enter the PnP block.
-
- # Check for PnP "certainty" skip
- if pnp_handler and pnp_handler.certain_flag:
- # If certain, we skip refinement (m=1), and we might just take the simple step.
- # Actually ref code says: if certain_flag break loop and take buffer[-1][2]
- # But buffer is from PREVIOUS step.
- # If certain_flag was set in PREVIOUS step, we wouldn't even be here?
- # No, the flag is set during the annealing loop of step i.
- pass
-
- # Calculate sigma/sigma_next for PnP step
- current_sigma = t.item() / 1000.0
- next_sigma = (0. if i == len(timesteps)-1 else timesteps[i+1].item()) / 1000.0
-
- if sample_solver == "euler":
- dt = timesteps[i] if i == len(timesteps)-1 else (timesteps[i] - timesteps[i + 1])
- sig_t = t / 1000.0
- # sigma_next?
- # t goes 1000->0. sig goes 1->0.
- # next t is timesteps[i+1]
- t_next = 0. if i == len(timesteps)-1 else timesteps[i+1].item()
- sig_next = t_next / 1000.0
-
- # In reference: latents = latents - noise_pred * dt
- # dt here is (t - t_next) / 1000 roughly?
- # dt item() / 1000.
- # Reference: latents - sigma * noise_pred. Wait.
- # If sigma is `t`, then `latents - t * noise_pred` predicts x0?
- # Yes, in flow matching x0 = xt - t * vt.
- # And x_next = x0 + t_next * vt? No.
- # x_next = x_t + (t_next - t) * vt.
-
- # any2video Euler: latents = latents - noise_pred * dt
- # dt = (t - t_next) / 1000.
- # So latents = latents + (t_next/1000 - t/1000) * noise_pred.
- # This matches x_next = x_t + (sigma_next - sigma) * noise_pred.
- pass
-
- # Helper to run model forward (re-using the logic above would be hard due to local vars)
- # We can define a closure or helper if we need to re-run.
- def run_model_forward(current_latents):
- # Prepare inputs (similar to lines 1176-1245)
- if extended_input_dim > 0:
- l_in = torch.cat([current_latents, extended_latents.expand(*expand_shape)], dim=extended_input_dim)
- else:
- l_in = current_latents
-
- # We need to handle all the complex guidance cases (Phantom, Fantasy, SteadyDancer, etc.)
- # This is very invasive to copy-paste.
- # Ideally we refactor the forward pass into a function.
- # For now, to minimize risk, we only support PnP for standard T2V/I2V logic if possible,
- # or we try to reuse `trans` call.
-
- # Simplified forward for re-iterations (assuming basic logic for now or copy-paste relevant parts)
- # PnP usually is for standard generation.
-
- # To properly support all models, we really should refactor the forward pass.
- # However, since we are in `EXECUTION`, refactoring might break things.
- # Strategy: Only support PnP for standard generation where we can easily call `trans`.
- # If complex models (SteadyDancer, etc) are used, we might disable PnP or warn.
- pass
-
- if pnp_handler and m_steps > 1 and not pnp_handler.certain_flag:
- # We need to iterate.
- # Setup scheduler state for rewinding
- scheduler_orig_state = None
- if sample_solver != "euler":
- try:
- scheduler_orig_state = copy.deepcopy(sample_scheduler)
- except Exception as e:
- print(f"Warning: Could not deepcopy scheduler: {e}. PnP may not work correctly with {sample_solver}.")
-
- # Step 0 (Initial)
- latents_next_0 = None
- pred_original_sample_0 = None
-
- if sample_solver == "euler":
- # Simulate the step to get x_next and x0
- pass
- else:
- # Non-Euler initial step
- # We are essentially "peeking" the next step to see if we need to refine.
- # BUT `sample_scheduler.step` advances state.
- # We will restore it if we loop.
- step_output = sample_scheduler.step(
- noise_pred[:, :, :target_shape[1]],
- t,
- latents,
- **scheduler_kwargs)
- latents_next_0 = step_output.prev_sample
- # Try to get pred_original_sample from output if available, else calc
- if hasattr(step_output, 'pred_original_sample') and step_output.pred_original_sample is not None:
- pred_original_sample_0 = step_output.pred_original_sample
-
- # Process Step 0 through PnP handler
- latents_next = pnp_handler.process_step(
- latents, noise_pred, current_sigma, next_sigma,
- latents_next=latents_next_0, pred_original_sample=pred_original_sample_0
- )
-
- # If we found certainty, we might stop?
- if pnp_handler.certain_flag:
- latents = latents_next
- # If non-euler and we stepped, we are good.
- # If euler, latents_next is calculated inside process_step (via formula).
- # Loop finishes
- else:
- # Loop for ii = 1 to m_steps
- for ii in range(1, m_steps):
-
- if sample_solver != "euler" and scheduler_orig_state is not None:
- # Restore scheduler state for the 'rewind'
- # sample_scheduler = copy.deepcopy(scheduler_orig_state) # This rebinds the name, but the object might be used elsewhere?
- # `sample_scheduler` is a local var or instance var? `sample_scheduler` comes from `self.scheduler` typically or passed in?
- # In `generate` it is a local var `sample_scheduler`.
- # BUT `any2video` methods line 1121 `sample_scheduler` comes from `self.scheduler` usually? No it's likely passed or `self.scheduler`.
- # line 474: `sample_scheduler = self.scheduler`.
- # So re-assigning it is fine for the local scope.
- sample_scheduler = copy.deepcopy(scheduler_orig_state)
-
- # Perturb
- # latents (x_t) = perturb(latents (from buffer), buffer_latents, sigma)
- latents_perturbed = pnp_handler.perturb_latents(latents, pnp_handler.buffer[-1][1], current_sigma, generator=seed_g, device=self.device)
-
- # Recalculate noise_pred
- # We need to construct input
- if extended_input_dim > 0:
- l_in = torch.cat([latents_perturbed, extended_latents.expand(*expand_shape)], dim=extended_input_dim)
- else:
- l_in = latents_perturbed
-
- # Call model (same simplified logic as before)
- if joint_pass and any_guidance:
- ret_vals = trans( **gen_args , **kwargs)
- else:
- # Use simplified single pass if guidance logic is too complex to reconstruct perfectly properly here
- # But wait, `gen_args` might have multiple inputs [latent, latent]
- # We must update `gen_args` 'x' values.
- if "x" in gen_args:
- if isinstance(gen_args["x"], list):
- count = len(gen_args["x"])
- # Assuming all inputs are the latent (e.g. cond/uncond/text)
- gen_args["x"] = [l_in] * count
-
- 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]
-
- # Combine noise
- if not any_guidance:
- n_pred = ret_vals[0]
- else:
- # Simplified CFG logic again
- if not (phantom or fantasy or steadydancer or multitalk):
- n_cond, n_uncond = ret_vals
- n_pred = n_uncond + guide_scale * (n_cond - n_uncond)
- else:
- # Fallback
- n_pred = ret_vals[0]
-
- # Step
- latents_next_loop = None
- pred_original_sample_loop = None
-
- if sample_solver != "euler":
- step_output = sample_scheduler.step(
- n_pred[:, :, :target_shape[1]],
- t,
- latents_perturbed, # We perturb the input latent
- **scheduler_kwargs)
- latents_next_loop = step_output.prev_sample
- if hasattr(step_output, 'pred_original_sample') and step_output.pred_original_sample is not None:
- pred_original_sample_loop = step_output.pred_original_sample
-
- latents_next = pnp_handler.process_step(
- latents_perturbed, n_pred, current_sigma, next_sigma,
- latents_next=latents_next_loop, pred_original_sample=pred_original_sample_loop
- )
-
- if pnp_handler.certain_flag:
- break # break inner loop
-
- latents = latents_next # Final result of annealing
-
- # If we finished the loop and used non-euler scheduler, the scheduler state `sample_scheduler`
- # is now in the state AFTER the last step calculation.
- # Since we deepcopied, we are fine?
- # Wait. If we are in the main loop `for i, t in enumerate(tqdm(timesteps)):`
- # The scheduler state needs to be correct for the NEXT iteration `i+1`.
- # If we restored state `sample_scheduler = copy.deepcopy(scheduler_orig_state)`
- # And then called `step()`, the state advanced ONCE.
- # So it is ready for `i+1`.
- # Correct.
-
- else:
- # Fallback to standard step if PnP logic didn't trigger refinement or m_steps=1
- # If m_steps=1 (implicit in block above?), checking `m_steps>1`.
- # If m_steps == 1, we still need to take the step!
- # My logic above: `if pnp_handler and m_steps > 1 ... else ...`
- # If m_steps=1, we DO NOT enter the block. So we fall through to here.
- # BUT if `pnp_handler` is None, we also fall through.
-
- # Standard Step
+ latents, sample_scheduler = pnp_handler.step(i, latents, noise_pred, locals())
+ 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
diff --git a/models/wan/pnp_utils.py b/models/wan/pnp_utils.py
index 43f0b5d..fe1873b 100644
--- a/models/wan/pnp_utils.py
+++ b/models/wan/pnp_utils.py
@@ -1,4 +1,5 @@
import torch
+import copy
from diffusers.utils.torch_utils import randn_tensor
class PnPHandler:
@@ -98,3 +99,210 @@ class PnPHandler:
# 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
+
+ def run_refinement_loop(self,
+ latents,
+ noise_pred,
+ current_sigma,
+ next_sigma,
+ m_steps,
+ denoise_func,
+ step_func,
+ clone_func=None,
+ 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
+ if clone_func:
+ scheduler_state = clone_func()
+
+ # Step 0 (Initial)
+ latents_next_0, pred_original_sample_0 = step_func(noise_pred, latents)
+
+ latents_next = self.process_step(
+ latents, noise_pred, current_sigma, next_sigma,
+ latents_next=latents_next_0, pred_original_sample=pred_original_sample_0
+ )
+
+ if self.certain_flag:
+ return latents_next
+
+ # Refinement Loop
+ for ii in range(1, m_steps):
+ if restore_func and scheduler_state is not None:
+ restore_func(scheduler_state)
+
+ # Perturb
+ latents_perturbed = self.perturb_latents(
+ latents, self.buffer[-1][1], current_sigma, generator=generator, device=device
+ )
+
+ # Denoise
+ n_pred = denoise_func(latents_perturbed)
+
+ # Step
+ latents_next_loop, pred_original_sample_loop = step_func(n_pred, latents_perturbed)
+
+ # Refine
+ latents_next = self.process_step(
+ latents_perturbed, n_pred, current_sigma, next_sigma,
+ latents_next=latents_next_loop, pred_original_sample=pred_original_sample_loop
+ )
+
+ if self.certain_flag:
+ break
+
+ return latents_next
+
+ def step(self, step_index, latents, noise_pred, context):
+ """
+ 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')
+ phantom = context.get('phantom')
+ fantasy = context.get('fantasy')
+ steadydancer = context.get('steadydancer')
+ multitalk = context.get('multitalk')
+ 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
+
+ # 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 (phantom or fantasy or steadydancer or multitalk):
+ 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 step_func(n_pred_in, latents_in):
+ if sample_solver == "euler":
+ latents_next_out = latents_in - n_pred_in * dt
+ pred_original_sample_out = latents_in - (t.item()/1000.0) * n_pred_in
+ else:
+ nonlocal sample_scheduler
+ step_out = sample_scheduler.step(n_pred_in[:, :, :target_shape[1]], 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
+ return latents_next_out, pred_original_sample_out
+
+ def clone_func():
+ if sample_solver != "euler":
+ return copy.deepcopy(sample_scheduler)
+ return None
+
+ def restore_func(saved_state):
+ nonlocal sample_scheduler
+ if saved_state:
+ sample_scheduler = copy.deepcopy(saved_state)
+
+ latents = self.run_refinement_loop(
+ latents=latents,
+ noise_pred=noise_pred,
+ current_sigma=current_sigma,
+ next_sigma=next_sigma,
+ m_steps=m_steps,
+ denoise_func=denoise_func,
+ step_func=step_func,
+ clone_func=clone_func,
+ restore_func=restore_func,
+ generator=seed_g,
+ device=latents.device
+ )
+ else:
+ # Standard logic
+ if sample_solver == "euler":
+ latents = latents - noise_pred * dt
+ else:
+ latents = sample_scheduler.step(
+ noise_pred[:, :, :target_shape[1]],
+ t,
+ latents,
+ **scheduler_kwargs)[0]
+
+ return latents, sample_scheduler
+
+def create_pnp_handler(enable_self_refine, pnp_f_uncertainty, pnp_p_norm, pnp_certain_percentage):
+ if not enable_self_refine:
+ return None
+
+ # Default plan from paper/code
+ stochastic_plan = [
+ {"start": 1, "end": 5, "steps": 3},
+ {"start": 6, "end": 13, "steps": 1},
+ ]
+ from .pnp_utils import PnPHandler
+ return PnPHandler(stochastic_plan, ths_uncertainty=pnp_f_uncertainty, p_norm=pnp_p_norm, certain_percentage=pnp_certain_percentage)