Skip to content
Python

Revert per-phase/per-stage options

Chris Malonec3bf37071e54
diff --git a/models/wan/any2video.py b/models/wan/any2video.py
index cd7cd6e..e886008 100644
--- a/models/wan/any2video.py
+++ b/models/wan/any2video.py
@@ -1346,7 +1346,7 @@ class WanAny2V:
noise_pred = denoise_with_cfg_fn(latents)
if noise_pred is None: return clear()
if self_refiner_handler:
- 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, phase_index=(2 if guidance_switch2_done else 1 if guidance_switch_done else 0) if guide_phases > 1 else 0)
+ 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)
if latents is None: return clear()
else:
latents = sample_scheduler.step( noise_pred[:, :, :target_shape[1]], t, latents, **scheduler_kwargs)[0]
diff --git a/shared/utils/self_refiner.py b/shared/utils/self_refiner.py
index 26d3d26..5deb124 100644
--- a/shared/utils/self_refiner.py
+++ b/shared/utils/self_refiner.py
@@ -1,5 +1,6 @@
import torch
import copy
+import uuid
from diffusers.utils.torch_utils import randn_tensor
default_plan = [
@@ -16,45 +17,19 @@ def is_int_string(s: str) -> bool:
def normalize_self_refiner_plan(plan_input):
if not plan_input or not isinstance(plan_input, list):
- return [default_plan], ""
-
- if len(plan_input) > 0 and isinstance(plan_input[0], list):
- return plan_input, ""
-
- phases = {}
- max_phase = 0
- for rule in plan_input:
- p = int(rule.get("phase", 0))
- if p > max_phase: max_phase = p
- max_phase = max(max_phase, 2)
-
- for rule in plan_input:
- p = int(rule.get("phase", 0))
-
- targets = [p] if p >= 0 else range(max_phase + 1)
-
- for t_phase in targets:
- if t_phase not in phases: phases[t_phase] = []
- phases[t_phase].append(rule)
+ return default_plan, ""
- normalized = []
- for i in range(max_phase + 1):
- normalized.append(phases.get(i, []))
-
- if not normalized:
- return [default_plan], ""
-
- return normalized, ""
+ return plan_input, ""
def ensure_refiner_list(plan_data):
if not isinstance(plan_data, list):
return []
for rule in plan_data:
- if "phase" not in rule:
- rule["phase"] = 0
+ if "id" not in rule:
+ rule["id"] = str(uuid.uuid4())
return plan_data
-def add_refiner_rule(current_rules, range_val, steps_val, phase_val=None, max_phases_val=1):
+def add_refiner_rule(current_rules, range_val, steps_val):
new_start, new_end = int(range_val[0]), int(range_val[1])
if new_start >= new_end:
@@ -62,62 +37,27 @@ def add_refiner_rule(current_rules, range_val, steps_val, phase_val=None, max_ph
Info(f"Start step ({new_start}) must be smaller than End step ({new_end}).")
return current_rules
- phase_idx = 0
-
- if phase_val is not None:
- if isinstance(phase_val, str):
- if "All" in phase_val:
- phase_idx = -1
- elif "Phase" in phase_val or "Stage" in phase_val:
- try:
- phase_idx = int(phase_val.split()[-1]) - 1
- except:
- phase_idx = 0
- else:
- try:
- phase_idx = int(phase_val)
- except:
- phase_idx = 0
-
for rule in current_rules:
- r_phase = rule.get('phase', 0)
-
- phases_overlap = (phase_idx == -1) or (r_phase == -1) or (phase_idx == r_phase)
-
- if phases_overlap and new_start <= rule['end'] and new_end >= rule['start']:
+ if new_start <= rule['end'] and new_end >= rule['start']:
from gradio import Info
- p_name_existing = "All Phases" if r_phase == -1 else f"Phase/Stage {r_phase+1}"
- p_name_new = "All Phases" if phase_idx == -1 else f"Phase/Stage {phase_idx+1}"
- Info(f"Overlap detected! {p_name_new} steps {new_start}-{new_end} conflict with existing {p_name_existing} rule.")
+ Info(f"Overlap detected! Steps {new_start}-{new_end} conflict with existing rule {rule['start']}-{rule['end']}.")
return current_rules
new_rule = {
+ "id": str(uuid.uuid4()),
"start": new_start,
"end": new_end,
- "steps": int(steps_val),
- "phase": phase_idx
+ "steps": int(steps_val)
}
-
updated_list = current_rules + [new_rule]
- return sorted(updated_list, key=lambda x: (x.get('phase', 0), x['start']))
+ return sorted(updated_list, key=lambda x: x['start'])
-def remove_refiner_rule(current_rules, index):
- try:
- updated_list = list(current_rules)
- updated_list.pop(int(index))
- return updated_list
- except:
- return current_rules
+def remove_refiner_rule(current_rules, rule_id):
+ return [r for r in current_rules if r["id"] != rule_id]
class PnPHandler:
- def __init__(self, stochastic_plans, ths_uncertainty=0.0, p_norm=1, certain_percentage=0.999, channel_dim: int = 1):
- if stochastic_plans and isinstance(stochastic_plans[0], dict) and "start" in stochastic_plans[0]:
- stochastic_plans = [stochastic_plans]
- if not stochastic_plans:
- stochastic_plans = [[]]
-
- self.stochastic_step_maps = [self._build_stochastic_step_map(p) for p in stochastic_plans]
-
+ def __init__(self, stochastic_plan, ths_uncertainty=0.0, p_norm=1, certain_percentage=0.999, channel_dim: int = 1):
+ self.stochastic_step_map = self._build_stochastic_step_map(stochastic_plan)
self.ths_uncertainty = ths_uncertainty
self.p_norm = p_norm
self.certain_percentage = certain_percentage
@@ -137,9 +77,9 @@ class PnPHandler:
steps = entry.get("steps", entry.get("anneal", entry.get("num_anneal_steps", 1)))
else:
start, end, steps = entry
-
- start_i = max(0, int(start) - 1)
- end_i = max(0, int(end) - 1)
+
+ start_i = int(start)
+ end_i = int(end)
steps_i = int(steps)
if steps_i > 0:
@@ -147,10 +87,8 @@ class PnPHandler:
step_map[idx] = steps_i
return step_map
- def get_anneal_steps(self, step_index, phase_index=0):
- if 0 <= phase_index < len(self.stochastic_step_maps):
- return self.stochastic_step_maps[phase_index].get(step_index, 0)
- return 0
+ def get_anneal_steps(self, step_index):
+ return self.stochastic_step_map.get(step_index, 0)
def reset_buffer(self):
self.buffer = [None]
@@ -283,7 +221,7 @@ class PnPHandler:
return latents_next
- def step(self, step_index, latents, noise_pred, t, timesteps, target_shape, seed_g, sample_scheduler, scheduler_kwargs, denoise_func, phase_index=0):
+ def step(self, step_index, latents, noise_pred, t, timesteps, target_shape, seed_g, sample_scheduler, scheduler_kwargs, denoise_func):
if noise_pred is None:
return None, sample_scheduler
# Reset per denoising step to avoid blending with stale buffers from prior timesteps.
@@ -292,7 +230,7 @@ class PnPHandler:
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, phase_index)
+ m_steps = self.get_anneal_steps(step_index)
if m_steps > 1 and not self.certain_flag:
@@ -363,12 +301,12 @@ class PnPHandler:
return latents, sample_scheduler
def create_self_refiner_handler(pnp_plan, pnp_f_uncertainty, pnp_p_norm, pnp_certain_percentage, channel_dim: int = 1):
- stochastic_plans, _ = normalize_self_refiner_plan(pnp_plan)
- if not stochastic_plans:
- stochastic_plans = [default_plan]
+ stochastic_plan, _ = normalize_self_refiner_plan(pnp_plan)
+ if not stochastic_plan:
+ stochastic_plan = default_plan
return PnPHandler(
- stochastic_plans,
+ stochastic_plan,
ths_uncertainty=pnp_f_uncertainty,
p_norm=pnp_p_norm,
certain_percentage=pnp_certain_percentage,
diff --git a/wgp.py b/wgp.py
index 970cbbc..9ac01b7 100644
--- a/wgp.py
+++ b/wgp.py
@@ -9338,29 +9338,13 @@ def get_max_frames(nb):
return (nb - 1) * server_config.get("max_frames_multiplier",1) + 1
-def change_guidance_phases(state, guidance_phases, refiner_phase_val):
+def change_guidance_phases(state, guidance_phases):
model_type = get_state_model_type(state)
model_def = get_model_def(model_type)
visible_phases = model_def.get("visible_phases", guidance_phases)
multiple_submodels = model_def.get("multiple_submodels", False)
- label = "Phase 1-2" if guidance_phases == 3 else ("Model / Guidance Switch Threshold" if multiple_submodels else "Guidance Switch Threshold")
- is_ltx = get_model_family(model_type) == "ltx2"
- prefix = "Stage" if is_ltx else "Phase"
-
- if is_ltx:
- new_choices = ["Stage 1", "Stage 2"]
- new_val = "Stage 1"
- else:
- new_choices = [f"All {prefix}s"] + [f"{prefix} {i+1}" for i in range(guidance_phases)]
- new_val = new_choices[0]
-
- if refiner_phase_val:
- if "All" in str(refiner_phase_val) and "All" in new_choices[0]:
- new_val = new_choices[0]
- elif refiner_phase_val in new_choices:
- new_val = refiner_phase_val
-
- return (gr.update(visible=guidance_phases >= 3 and visible_phases >= 3 and multiple_submodels), gr.update(visible=guidance_phases >= 2 and visible_phases >= 2), gr.update(visible=guidance_phases >= 2 and visible_phases >= 2, label=label), gr.update(visible=guidance_phases >= 3 and visible_phases >= 3), gr.update(visible=guidance_phases >= 2 and visible_phases >= 2), gr.update(visible=guidance_phases >= 3 and visible_phases >= 3), gr.update(visible=guidance_phases >= 2, choices=new_choices, value=new_val))
+ label ="Phase 1-2" if guidance_phases ==3 else ( "Model / Guidance Switch Threshold" if multiple_submodels else "Guidance Switch Threshold" )
+ return gr.update(visible= guidance_phases >=3 and visible_phases >=3 and multiple_submodels) , gr.update(visible= guidance_phases >=2 and visible_phases >=2), gr.update(visible= guidance_phases >=2 and visible_phases >=2, label = label), gr.update(visible= guidance_phases >=3 and visible_phases >=3), gr.update(visible= guidance_phases >=2 and visible_phases >=2), gr.update(visible= guidance_phases >=3 and visible_phases >=3)
memory_profile_choices= [ ("Profile 1, HighRAM_HighVRAM: at least 64 GB of RAM and 24 GB of VRAM, the fastest for short videos with a RTX 3090 / RTX 4090", 1),
@@ -10434,70 +10418,34 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
with gr.Column(visible = model_def.get("self_refiner", False)) as self_refiner_col:
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")
+
refiner_val = ensure_refiner_list(ui_get("self_refiner_plan", []))
self_refiner_plan = refiner_val if update_form else gr.State(value=refiner_val)
- is_ltx_ui = get_model_family(model_type) == "ltx2"
- refiner_prefix_str = "Stage" if is_ltx_ui else "Phase"
- refiner_prefix_component = gr.Text(value=refiner_prefix_str, visible=False)
-
with gr.Column(visible=(update_form and ui_get("self_refiner_setting", 0) > 0)) as self_refiner_rules_ui:
gr.Markdown("#### Refiner Plan")
with gr.Row(elem_id="refiner-input-row"):
- current_phase_count = int(guidance_phases_value) if guidance_phases_value else 1
-
- if is_ltx_ui:
- refiner_choices = ["Stage 1", "Stage 2"]
- refiner_default = "Stage 1"
- else:
- refiner_choices = [f"All {refiner_prefix_str}s"] + [f"{refiner_prefix_str} {i+1}" for i in range(current_phase_count)]
- refiner_default = refiner_choices[0]
-
- refiner_phase = gr.Dropdown(choices=refiner_choices, value=refiner_default, label="Apply to", scale=1, visible=current_phase_count >= 2)
refiner_range = RangeSlider(minimum=1, maximum=100, value=(1, 10), step=1, label="Step Range", info="Start - End", scale=3)
refiner_mult = gr.Slider(label="Iterations", value=3, minimum=1, maximum=5, step=1, scale=2)
refiner_add_btn = gr.Button("➕ Add", variant="primary", scale=0, min_width=100)
if not update_form:
- def check_refiner_phase_restriction(selected_val):
- if is_ltx_ui and str(selected_val) == "Stage 2":
- gr.Info("Stage 2 is currently disabled for Self-Refiner in LTX-2.")
- return "Stage 1"
- return gr.update()
-
- refiner_phase.select(
- fn=check_refiner_phase_restriction,
- inputs=[refiner_phase],
- outputs=[refiner_phase]
- )
-
- refiner_add_btn.click(
- fn=add_refiner_rule,
- inputs=[self_refiner_plan, refiner_range, refiner_mult, refiner_phase, guidance_phases],
- outputs=[self_refiner_plan]
- )
-
+ refiner_add_btn.click(fn=add_refiner_rule, inputs=[self_refiner_plan, refiner_range, refiner_mult], outputs=[self_refiner_plan])
self_refiner_setting.change(fn=lambda s: gr.update(visible=s > 0), inputs=[self_refiner_setting], outputs=[self_refiner_rules_ui])
- @gr.render(inputs=[self_refiner_plan, guidance_phases, refiner_prefix_component])
- def render_refiner_plans(plans, phase_count, p_prefix):
+ @gr.render(inputs=self_refiner_plan)
+ def render_refiner_plans(plans):
if not plans:
gr.Markdown("<I style='padding: 8px;'>No plans defined. Using defaults: Steps 2-5 (3x), Steps 6-13 (1x).</I>")
return
- for idx, plan in enumerate(plans):
+ for plan in plans:
with gr.Row(elem_classes="rule-row"):
- p_idx = plan.get('phase', 0)
- if p_idx == -1:
- phase_label = f"All {p_prefix}s | "
- else:
- phase_label = f"{p_prefix} {p_idx + 1} | " if phase_count >= 2 or p_idx > 0 else ""
-
- text_display = f"{phase_label}Steps **{plan['start']} - {plan['end']}** : **{plan['steps']}x** iterations"
+ text_display = f"Steps **{plan['start']} - {plan['end']}** : **{plan['steps']}x** iterations"
gr.Markdown(text_display, elem_classes="rule-card")
gr.Button("✖", variant="stop", scale=0, elem_classes="delete-btn").click(
fn=remove_refiner_rule,
- inputs=[self_refiner_plan, gr.State(idx)],
+ inputs=[self_refiner_plan, gr.State(plan["id"])],
outputs=[self_refiner_plan]
)
@@ -10767,7 +10715,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
NAG_col, remove_background_sound , speakers_locations_row, embedded_guidance_row, guidance_phases_row, guidance_row, resolution_group, cfg_free_guidance_col, control_net_weights_row, guide_selection_row, image_mode_tabs,
min_frames_if_references_col, motion_amplitude_col, video_prompt_type_alignment, prompt_enhancer_btn, tab_inpaint, tab_t2v, resolution_row, loras_tab, post_processing_tab, temperature_row, *custom_settings_rows, top_pk_row,
number_frames_row, negative_prompt_row,
- self_refiner_col, pause_row, refiner_prefix_component, refiner_phase]+\
+ self_refiner_col, pause_row]+\
image_start_extra + image_end_extra + image_refs_extra # presets_column,
if update_form:
locals_dict = locals()
@@ -10787,7 +10735,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
gallery_tabs.select(fn=set_gallery_tab, inputs=[state], outputs=[current_gallery_tab, gallery_source]).then(
fn=select_video, inputs=[state, current_gallery_tab, output, last_choice, audio_files_paths, audio_file_selected, gallery_source], outputs=[last_choice, video_info, video_buttons_row, image_buttons_row, audio_buttons_row, deleted_video_buttons_row, deleted_audio_buttons_row, video_postprocessing_tab, audio_remuxing_tab], show_progress="hidden")
gr.on(triggers=[video_length.release, force_fps.change, video_guide.change, video_source.change], fn=refresh_video_length_label, inputs=[state, video_length, force_fps, video_guide, video_source] , outputs = video_length, trigger_mode="always_last", show_progress="hidden" )
- guidance_phases.change(fn=change_guidance_phases, inputs= [state, guidance_phases, refiner_phase], outputs =[model_switch_phase, guidance_phases_row, switch_threshold, switch_threshold2, guidance2_scale, guidance3_scale, refiner_phase ])
+ guidance_phases.change(fn=change_guidance_phases, inputs= [state, guidance_phases], outputs =[model_switch_phase, guidance_phases_row, switch_threshold, switch_threshold2, guidance2_scale, guidance3_scale ])
audio_prompt_type_remux.change(fn=refresh_audio_prompt_type_remux, inputs=[state, audio_prompt_type, audio_prompt_type_remux], outputs=[audio_prompt_type])
remove_background_sound.change(fn=refresh_remove_background_sound, inputs=[state, audio_prompt_type, remove_background_sound], outputs=[audio_prompt_type])
audio_prompt_type_sources.change(fn=refresh_audio_prompt_type_sources, inputs=[state, audio_prompt_type, audio_prompt_type_sources], outputs=[audio_prompt_type, audio_guide, audio_guide2, speakers_locations_row, remove_background_sound, audio_guide_row])