Skip to content

[feat] Add inference for MoE SF#880

Merged
SolitaryThinker merged 15 commits intomainfrom
wei/SF_infer
Nov 19, 2025
Merged

[feat] Add inference for MoE SF#880
SolitaryThinker merged 15 commits intomainfrom
wei/SF_infer

Conversation

@JerryZhou54
Copy link
Copy Markdown
Collaborator

No description provided.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @JerryZhou54, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request integrates Mixture-of-Experts (MoE) inference capabilities into the self-forcing causal video generation pipeline, particularly for image-to-video tasks. It introduces a new example script and modifies core components like the VAE configuration, sampling parameters, scheduler, and the causal denoising stage. The changes enable the system to leverage multiple transformer models and manage their states effectively based on noise levels, enhancing the model's ability to generate videos from images.

Highlights

  • MoE Self-Forcing Inference Script: A new example script has been added to demonstrate inference for the Mixture-of-Experts (MoE) Self-Forcing model, specifically for image-to-video generation.
  • VAE Configuration Update: The SelfForcingWan2_2_T2V480PConfig now explicitly ensures that the VAE encoder and decoder are loaded during initialization, which is crucial for the image-to-video pipeline.
  • Sampling Parameter Refinement: Redundant guidance_scale parameters have been removed from the SelfForcingWan2_2_T2V_A14B_480P_SamplingParam configuration, streamlining the sampling process.
  • Scheduler Enhancements for MoE: New methods, calculate_alpha_beta_high and add_noise_high, have been introduced in the self-forcing flow match scheduler to correctly handle noise addition for high noise timesteps in the MoE context.
  • Noise Prediction Utility: A new utility function, pred_noise_to_x_bound, has been added to convert predicted noise to a clean latent representation, specifically considering boundary timesteps for improved accuracy.
  • Causal Denoising Stage Refactor: The CausalDMDDenosingStage has been significantly refactored to support MoE inference, including passing the VAE, managing separate KV caches for different noise regimes (high vs. low noise), and dynamically selecting the appropriate transformer model based on the current timestep relative to a defined boundary.
  • Input Validation for Causal Pipelines: The input validation stage now applies image processing logic not only for text-to-image-to-video (ti2v) tasks but also for general causal pipelines, ensuring consistent input handling.
  • New Prompt Data: A new JSONL file, prompts/mixkit_i2v.jsonl, has been added, containing a collection of prompts and corresponding image paths for image-to-video generation tasks.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds inference capabilities for a Mixture-of-Experts Self-Forcing model. The changes span across new example scripts, scheduler logic, utility functions, and updates to pipeline stages for causal denoising. My review focuses on improving code maintainability, fixing potential bugs, and ensuring the new logic is robust. I've identified several areas for improvement, including hardcoded paths in the example script, a potential bug in a configuration class's __post_init__ method, duplicated code that could be refactored, a misleading error message, and hardcoded logic that should be dynamic. Addressing these points will enhance the code's portability, correctness, and maintainability.

Comment on lines +190 to +192
def __post_init__(self) -> None:
self.vae_config.load_encoder = True
self.vae_config.load_decoder = True
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The __post_init__ method in SelfForcingWan2_2_T2V480PConfig overrides the parent's __post_init__ without calling super().__post_init__(). The parent class Wan2_2_T2V_A14B_Config has an important initialization logic in its __post_init__ (setting self.dit_config.boundary_ratio). By not calling super(), this logic is skipped, which is likely a bug.

Suggested change
def __post_init__(self) -> None:
self.vae_config.load_encoder = True
self.vae_config.load_decoder = True
def __post_init__(self) -> None:
super().__post_init__()
self.vae_config.load_encoder = True
self.vae_config.load_decoder = True

Comment thread fastvideo/models/utils.py
else:
assert timestep.numel() == noise_input_latent.shape[0]
else:
raise ValueError(f"[pred_noise_to_pred_video] Invalid timestep shape: {timestep.shape}")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The error message in the ValueError is incorrect. It seems to be copy-pasted from pred_noise_to_pred_video and should be updated to pred_noise_to_x_bound. This can be misleading during debugging.

Suggested change
raise ValueError(f"[pred_noise_to_pred_video] Invalid timestep shape: {timestep.shape}")
raise ValueError(f"[pred_noise_to_x_bound] Invalid timestep shape: {timestep.shape}")

Comment on lines +140 to +141
block_sizes = [self.num_frames_per_block] * 7
block_sizes[0] = 1
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The block_sizes are hardcoded to [self.num_frames_per_block] * 7 with the first element set to 1. This seems incorrect as it doesn't adapt to the total number of frames (t) in the input latents. The previous implementation calculated the number of blocks based on t, which is more robust. This hardcoded value could lead to processing an incorrect number of frames and cause unexpected behavior or errors.

        if (t - 1) % self.num_frames_per_block != 0:
            raise ValueError(
                f"(num_frames - 1) must be divisible by num_frames_per_block when using a conditioning image. "
                f"Got num_frames={t} and num_frames_per_block={self.num_frames_per_block}"
            )
        num_blocks = (t - 1) // self.num_frames_per_block
        block_sizes = [1] + [self.num_frames_per_block] * num_blocks

Comment on lines +24 to +25
init_weights_from_safetensors="/mnt/sharefs/users/hao.zhang/wei/SFwan2.2_distill_self_forcing_release_x0_CacheAppend_1333/checkpoint-442_weight_only/ema/generator_ema.safetensors",
init_weights_from_safetensors_2="/mnt/sharefs/users/hao.zhang/wei/SFwan2.2_distill_self_forcing_release_x0_CacheAppend_1333/checkpoint-442_weight_only/ema/generator_ema_2.safetensors",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The paths to the model weights are hardcoded to a user-specific location. This makes the example script not portable and difficult for other users to run. It's better to use command-line arguments or environment variables for such paths to make the example more generic and reusable.

Comment on lines +123 to +135
if timestep.ndim == 2:
timestep = timestep.flatten(0, 1)
if boundary_timestep.ndim == 2:
boundary_timestep = boundary_timestep.flatten(0, 1)
self.sigmas = self.sigmas.to(noise.device)
self.timesteps = self.timesteps.to(noise.device)
timestep_id = torch.argmin(
(self.timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1)
sigma = self.sigmas[timestep_id].reshape(-1, 1, 1, 1)

boundary_timestep_id = torch.argmin(
(self.timesteps.unsqueeze(0) - boundary_timestep.unsqueeze(1)).abs(), dim=1)
sigma_boundary = self.sigmas[boundary_timestep_id].reshape(-1, 1, 1, 1)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The logic for finding sigma and sigma_boundary from timestep and boundary_timestep is very similar to the logic in the add_noise method. This code duplication can be avoided by refactoring it into a helper method. This would improve maintainability and reduce redundancy.

Comment thread fastvideo/models/utils.py
Comment on lines +203 to +228
# If timestep is [bs, num_frames]
if timestep.ndim == 2:
timestep = timestep.flatten(0, 1)
assert timestep.numel() == noise_input_latent.shape[0]
elif timestep.ndim == 1:
# If timestep is [1]
if timestep.shape[0] == 1:
timestep = timestep.expand(noise_input_latent.shape[0])
else:
assert timestep.numel() == noise_input_latent.shape[0]
else:
raise ValueError(f"[pred_noise_to_pred_video] Invalid timestep shape: {timestep.shape}")
# timestep shape should be [B]
dtype = pred_noise.dtype
device = pred_noise.device
pred_noise = pred_noise.double().to(device)
noise_input_latent = noise_input_latent.double().to(device)
sigmas = scheduler.sigmas.double().to(device)
timesteps = scheduler.timesteps.double().to(device)
timestep_id = torch.argmin(
(timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1)
sigma_t = sigmas[timestep_id].reshape(-1, 1, 1, 1)

boundary_timestep_id = torch.argmin(
(timesteps.unsqueeze(0) - boundary_timestep.unsqueeze(1)).abs(), dim=1)
sigma_t_boundary = sigmas[boundary_timestep_id].reshape(-1, 1, 1, 1)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There is significant code duplication between pred_noise_to_pred_video and pred_noise_to_x_bound for handling timestep shapes and calculating sigma_t. This logic could be extracted into a helper function to improve code reuse and maintainability.

Comment on lines +111 to +128
# ih, iw = img.height, img.width
# patch_size = fastvideo_args.pipeline_config.dit_config.arch_config.patch_size
# vae_stride = fastvideo_args.pipeline_config.vae_config.arch_config.scale_factor_spatial
# dh, dw = patch_size[1] * vae_stride, patch_size[2] * vae_stride
# max_area = 720 * 1280
# ow, oh = best_output_size(iw, ih, dw, dh, max_area)

# scale = max(ow / iw, oh / ih)
# img = img.resize((round(iw * scale), round(ih * scale)),
# Image.LANCZOS)
# logger.info("resized img height: %s, img width: %s", img.height,
# img.width)

# # center-crop
# x1 = (img.width - ow) // 2
# y1 = (img.height - oh) // 2
# img = img.crop((x1, y1, x1 + ow, y1 + oh))
# assert img.width == ow and img.height == oh
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This block of code for image resizing and cropping has been commented out. If this logic is no longer needed, it should be removed to improve code clarity. If it might be used in the future, it should be controlled by a configuration flag rather than being left as commented-out code.

@SolitaryThinker SolitaryThinker changed the title Add inference for MoE SF [feat] Add inference for MoE SF Nov 16, 2025
@JerryZhou54 JerryZhou54 force-pushed the wei/SF_infer branch 2 times, most recently from c709895 to 6939493 Compare November 19, 2025 19:49
@SolitaryThinker SolitaryThinker merged commit e3b4564 into main Nov 19, 2025
1 of 2 checks passed
shijiew555 pushed a commit to Gary-ChenJL/FastVideo that referenced this pull request Apr 8, 2026
Co-authored-by: RandNMR73 <notomatthew31@gmail.com>
Co-authored-by: SolitaryThinker <wlsaidhi@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants