---
title: matrixgame2_preprocess_pipeline_ode_trajectory
---

<div class="python-reference">
<a id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory-classes"></a>
<a id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory-functions"></a>
<a id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory-functions"></a>
<a id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory"></a>
<p>ODE Trajectory Data Preprocessing pipeline implementation.</p>
<p>This module contains an implementation of the ODE Trajectory Data Preprocessing pipeline
using the modular pipeline architecture.</p>
<p>Sec 4.3 of CausVid paper: https://arxiv.org/pdf/2412.07772</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam</code></h2>
<pre class="doc-signature"><code>SamplingParam(data_type: str = &#x27;video&#x27;, image_path: str | None = None, pil_image: Any | None = None, last_image: Any | None = None, references: list&#91;Any&#93; | None = None, video_path: str | None = None, pose_video_path: str | None = None, face_video_path: str | None = None, background_video_path: str | None = None, mask_video_path: str | None = None, animate_mode: str | None = None, audio_path: str | None = None, latents: Any | None = None, audio_latents: Any | None = None, mouse_cond: Any | None = None, keyboard_cond: Any | None = None, grid_sizes: Any | None = None, pose: str | None = None, prompt_attention_mask: list = list(), negative_attention_mask: list = list(), c2ws_plucker_emb: Any | None = None, action_path: str | None = None, t_thresh: float = 0.5, num_cond_frames: int = 0, prompt: str | list&#91;str&#93; | None = None, negative_prompt: str = &#x27;Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards&#x27;, max_sequence_length: int | None = None, prompt_path: str | None = None, output_path: str = &#x27;outputs/&#x27;, output_video_name: str | None = None, num_videos_per_prompt: int = 1, seed: int = 1024, num_frames: int = 125, height: int = 720, width: int = 1280, height_sr: int = 1072, width_sr: int = 1920, fps: int = 24, num_inference_steps: int = 50, num_inference_steps_sr: int = 50, guidance_scale: float = 1.0, batch_cfg: bool = False, guidance_scale_2: float | None = None, use_embedded_guidance: bool = False, true_cfg_scale: float = 1.0, guidance_rescale: float = 0.0, boundary_ratio: float | None = None, sigmas: list&#91;float&#93; | None = None, pyramid_num_inference_steps_list: list&#91;int&#93; | None = None, history_sizes: list&#91;int&#93; | None = None, num_latent_frames_per_chunk: int = 9, keep_first_frame: bool = True, is_skip_first_chunk: bool = False, use_zero_init: bool = True, zero_steps: int = 1, is_amplify_first_chunk: bool = False, enable_teacache: bool = False, trajectory_type: str | None = None, movement_distance: float | None = None, camera_rotation: str | None = None, ltx2_cfg_scale_video: float = 1.0, ltx2_cfg_scale_audio: float = 1.0, ltx2_modality_scale_video: float = 1.0, ltx2_modality_scale_audio: float = 1.0, ltx2_rescale_scale: float = 0.0, ltx2_stg_scale_video: float = 0.0, ltx2_stg_scale_audio: float = 0.0, ltx2_stg_blocks_video: list&#91;int&#93; = (lambda: &#91;29&#93;)(), ltx2_stg_blocks_audio: list&#91;int&#93; = (lambda: &#91;29&#93;)(), ltx2_use_ancestral_sampler: bool = False, ltx2_images: list&#91;tuple&#91;str, int, float&#93;&#93; | None = None, ltx2_image_crf: float = 33.0, ltx2_conditioning_latent_stage1: Any | None = None, ltx2_conditioning_latent_stage2: Any | None = None, ltx2_video_conditions: list&#91;tuple&#91;list&#91;str&#93;, int, float&#93;&#93; | None = None, audio_start_in_s: float | None = None, audio_end_in_s: float | None = None, init_audio: Any = None, init_audio_strength: float | None = None, init_noise_level: float | None = None, inpaint_audio: Any = None, inpaint_mask: Any = None, continuation_state: ContinuationState | None = None, return_continuation_state: bool = False, save_video: bool = True, return_frames: bool = True, return_trajectory_latents: bool = False, return_trajectory_decoded: bool = False, *, return_samples: bool = False)</code></pre>
<p>Sampling parameters for video generation.</p>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam.check_sampling_param"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam.check_sampling_param</code></h3>
<pre class="doc-signature"><code>check_sampling_param() -&gt; None</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam.update"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam.update</code></h3>
<pre class="doc-signature"><code>update(source_dict: dict&#91;str, Any&#93;) -&gt; None</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam.from_pretrained"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam.from_pretrained</code></h3>
<pre class="doc-signature"><code>from_pretrained(model_path: str) -&gt; SamplingParam</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam.add_cli_args"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SamplingParam.add_cli_args</code></h3>
<pre class="doc-signature"><code>add_cli_args(parser: Any) -&gt; Any</code></pre>
<p>Add CLI arguments for SamplingParam fields</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.getdataset"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.getdataset</code></h2>
<pre class="doc-signature"><code>getdataset(args) -&gt; VideoCaptionMergedDataset</code></pre>

<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.get_local_torch_device"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.get_local_torch_device</code></h2>
<pre class="doc-signature"><code>get_local_torch_device() -&gt; torch.device</code></pre>
<p>Return the torch device for the current rank.</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs</code></h2>
<pre class="doc-signature"><code>FastVideoArgs(model_path: str, mode: ExecutionMode = ExecutionMode.INFERENCE, workload_type: WorkloadType = WorkloadType.T2V, distributed_executor_backend: str = &#x27;mp&#x27;, enable_streaming_ipc_queues: bool = False, ray_placement_group: PlacementGroup | None = None, ray_runtime_env: RuntimeEnv | None = None, inference_mode: bool = True, trust_remote_code: bool = False, revision: str | None = None, num_gpus: int = 1, tp_size: int = -1, sp_size: int = -1, hsdp_replicate_dim: int = 1, hsdp_shard_dim: int = -1, dist_timeout: int | None = None, pipeline_config: PipelineConfig = PipelineConfig(), preprocess_config: PreprocessConfig | None = None, lora_path: str | None = None, lora_nickname: str = &#x27;default&#x27;, lora_strength: float = 1.0, lora_target_modules: list&#91;str&#93; | None = None, output_type: str = &#x27;pil&#x27;, attention_backend: str | None = None, dit_cpu_offload: bool = True, use_fsdp_inference: bool = False, dit_layerwise_offload: bool = True, text_encoder_cpu_offload: bool = True, image_encoder_cpu_offload: bool = True, vae_cpu_offload: bool = True, pin_cpu_memory: bool = True, h3_sequential_load: bool | None = None, h3_encoder_split: bool | None = None, h3_encoder_nodes: int = -1, h3_encoder_workers: int = 0, video_decode_backend: str = &#x27;h3-vae&#x27;, taeh3_checkpoint: str | None = None, taeh3_chunk_size: int = 5, h3_vae_nvfp4_decoder: str | None = None, lazy_module_load: bool | None = None, vae_parallel_decode: bool = False, vae_parallel_encode: bool = False, vae_parallel_decode_strategy: str | None = None, enable_torch_compile: bool = False, regional_compile: bool = False, enable_torch_compile_text_encoder: bool = False, enable_torch_compile_vae: bool = False, enable_torch_compile_audio_vae: bool = False, torch_compile_kwargs: dict&#91;str, Any&#93; = dict(), torch_compile_kwargs_dit: dict&#91;str, Any&#93; = dict(), torch_compile_kwargs_text_encoder: dict&#91;str, Any&#93; = dict(), torch_compile_kwargs_vae: dict&#91;str, Any&#93; = dict(), torch_compile_kwargs_audio_vae: dict&#91;str, Any&#93; = dict(), inference_torch_compile: bool = False, h3_vsa_fp4: dict&#91;str, Any&#93; = dict(), disable_autocast: bool = False, VSA_sparsity: float | None = None, VSA_tile_size: int | None = None, moba_config_path: str | None = None, moba_config: dict&#91;str, Any&#93; = dict(), master_port: int | None = None, enable_stage_verification: bool = True, prompt_txt: str | None = None, ltx2_vae_tiling: bool | None = None, ltx2_vae_spatial_tile_size_in_pixels: int | None = None, ltx2_vae_spatial_tile_overlap_in_pixels: int | None = None, ltx2_vae_temporal_tile_size_in_frames: int | None = None, ltx2_vae_temporal_tile_overlap_in_frames: int | None = None, ltx2_initial_latent_path: str | None = None, ltx2_audio_latent_path: str | None = None, refine_enabled: bool | None = None, refine_upsampler_path: str | None = None, refine_transformer_path: str | None = None, refine_lora_path: str | None = None, refine_num_inference_steps: int | None = None, refine_guidance_scale: float | None = None, refine_add_noise: bool | None = None, refine_noise_path: str | None = None, refine_audio_noise_path: str | None = None, ltx2_refine_enabled: bool = False, ltx2_refine_upsampler_path: str | None = None, ltx2_refine_transformer_path: str | None = None, ltx2_refine_lora_path: str | None = None, ltx2_refine_num_inference_steps: int = 3, ltx2_refine_guidance_scale: float = 1.0, ltx2_refine_add_noise: bool = True, ltx2_refine_noise_path: str | None = None, ltx2_refine_audio_noise_path: str | None = None, ltx2_legacy_native_noise_order: bool = False, ltx2_use_distilled_sigmas: bool = True, model_paths: dict&#91;str, str&#93; = dict(), model_loaded: dict&#91;str, bool&#93; = (lambda: &#123;&#x27;transformer&#x27;: True, &#x27;vae&#x27;: True, &#x27;upsampler&#x27;: True&#125;)(), override_text_encoder_safetensors: str | None = None, override_text_encoder_quant: QuantizationMethods = None, transformer_quant: Any | None = None, override_transformer_cls_name: str | None = None, init_weights_from_safetensors: str = &#x27;&#x27;, init_weights_from_safetensors_2: str = &#x27;&#x27;, override_pipeline_cls_name: str | None = None, boundary_ratio: float | None = 0.875)</code></pre>


<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.is_output_rank"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.is_output_rank</code></h3>
<pre class="doc-signature"><code>is_output_rank: bool</code></pre>
<p>Whether this process may materialize user-facing outputs.</p>
<p>This is runtime state assigned by an SPMD executor, not a public
configuration field, so dataclass serialization and typed config
parsing deliberately ignore it.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.add_cli_args"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.add_cli_args</code></h3>
<pre class="doc-signature"><code>add_cli_args(parser: FlexibleArgumentParser) -&gt; FlexibleArgumentParser</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.from_cli_args"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.from_cli_args</code></h3>
<pre class="doc-signature"><code>from_cli_args(args: argparse.Namespace) -&gt; FastVideoArgs</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.from_kwargs"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.from_kwargs</code></h3>
<pre class="doc-signature"><code>from_kwargs(**kwargs: Any) -&gt; FastVideoArgs</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.check_fastvideo_args"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.check_fastvideo_args</code></h3>
<pre class="doc-signature"><code>check_fastvideo_args() -&gt; None</code></pre>
<p>Validate inference arguments for consistency</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.finalize_device_offload_policy"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.finalize_device_offload_policy</code></h3>
<pre class="doc-signature"><code>finalize_device_offload_policy(device_id: int = 0) -&gt; bool</code></pre>
<p>Apply device-local memory policy, then resolve incompatible modes.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.disable_offload_on_unified_memory"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.FastVideoArgs.disable_offload_on_unified_memory</code></h3>
<pre class="doc-signature"><code>disable_offload_on_unified_memory(device_id: int = 0, *, offload_flag: str | None = None) -&gt; bool</code></pre>
<p>Disable host offload after a worker has selected its device.</p>
<p>CUDA's unified-memory probe reads runtime device properties and may
initialize a CUDA context. Callers must therefore use this only inside
a device-owning process, after selecting and binding <code>device_id</code>.
Returning the classification lets direct component-loader callers
apply the same policy to explicit per-call overrides. When
<code>offload_flag</code> is given, the return value says whether this policy
covers that component role.</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.set_forward_context"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.set_forward_context</code></h2>
<pre class="doc-signature"><code>set_forward_context(current_timestep, attn_metadata, forward_batch: Optional&#91;ForwardBatch&#93; = None)</code></pre>
<p>A context manager that stores the current forward context,
can be attention metadata, etc.
Here we can inject common logic for every model forward pass.</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.init_logger"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.init_logger</code></h2>
<pre class="doc-signature"><code>init_logger(name: str) -&gt; _FastvideoLogger</code></pre>
<p>The main purpose of this function is to ensure that loggers are
retrieved in such a way that we can be sure the root fastvideo logger has
already been configured.</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler</code></h2>
<pre class="doc-signature"><code>SelfForcingFlowMatchScheduler(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, training = False)</code></pre>


<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.set_timesteps"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.set_timesteps</code></h3>
<pre class="doc-signature"><code>set_timesteps(num_inference_steps = 100, denoising_strength = 1.0, training = False, return_dict = False, **kwargs)</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.step"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.step</code></h3>
<pre class="doc-signature"><code>step(model_output: torch.FloatTensor, timestep: torch.FloatTensor, sample: torch.FloatTensor, to_final = False, return_dict = False, **kwargs)</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.calculate_alpha_beta_high"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.calculate_alpha_beta_high</code></h3>
<pre class="doc-signature"><code>calculate_alpha_beta_high(sigma, sigma_bound)</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.add_noise"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.add_noise</code></h3>
<pre class="doc-signature"><code>add_noise(original_samples, noise, timestep)</code></pre>
<p>Diffusion forward corruption process.
Input:
    - clean_latent: the clean latent with shape [B<em>T, C, H, W]
    - noise: the noise with shape [B</em>T, C, H, W]
    - timestep: the timestep with shape [B<em>T]
Output: the corrupted latent with shape [B</em>T, C, H, W]</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.add_noise_high"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.add_noise_high</code></h3>
<pre class="doc-signature"><code>add_noise_high(original_samples, noise, timestep, boundary_timestep)</code></pre>
<p>Diffusion forward corruption process.
Input:
    - clean_latent: the clean latent with shape [B<em>T, C, H, W]
    - noise: the noise with shape [B</em>T, C, H, W]
    - timestep: the timestep with shape [B<em>T]
Output: the corrupted latent with shape [B</em>T, C, H, W]</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.training_target"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.training_target</code></h3>
<pre class="doc-signature"><code>training_target(sample, noise, timestep)</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.training_weight"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.training_weight</code></h3>
<pre class="doc-signature"><code>training_weight(timestep)</code></pre>
<h4>Input</h4>
<ul>
<li>timestep: the timestep with shape [B*T]</li>
</ul>
<p>Output: the corresponding weighting [B*T]</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.scale_model_input"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.scale_model_input</code></h3>
<pre class="doc-signature"><code>scale_model_input(sample: torch.Tensor, timestep: int | None = None) -&gt; torch.Tensor</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.set_shift"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.SelfForcingFlowMatchScheduler.set_shift</code></h3>
<pre class="doc-signature"><code>set_shift(shift: float) -&gt; None</code></pre>

<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.ForwardBatch"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.ForwardBatch</code></h2>
<pre class="doc-signature"><code>ForwardBatch(data_type: str, generator: torch.Generator | list&#91;torch.Generator&#93; | None = None, image_path: str | None = None, image_embeds: list&#91;torch.Tensor&#93; = list(), pil_image: torch.Tensor | PIL.Image.Image | None = None, last_image: torch.Tensor | PIL.Image.Image | None = None, references: list&#91;Any&#93; | None = None, preprocessed_image: torch.Tensor | None = None, prompt: str | list&#91;str&#93; | None = None, negative_prompt: str | list&#91;str&#93; | None = None, prompt_path: str | None = None, output_path: str = &#x27;outputs/&#x27;, output_video_name: str | None = None, video_path: str | None = None, video_latent: torch.Tensor | None = None, pose_video_path: str | None = None, face_video_path: str | None = None, background_video_path: str | None = None, mask_video_path: str | None = None, animate_mode: str | None = None, pose_latents: torch.Tensor | None = None, face_pixel_values: torch.Tensor | None = None, audio_path: str | None = None, audio_embeds: torch.Tensor | None = None, t_thresh: float = 0.5, num_cond_frames: int = 0, prompt_embeds: list&#91;torch.Tensor&#93; = list(), negative_prompt_embeds: list&#91;torch.Tensor&#93; | None = None, prompt_attention_mask: list&#91;torch.Tensor&#93; | None = None, negative_attention_mask: list&#91;torch.Tensor&#93; | None = None, clip_embedding_pos: list&#91;torch.Tensor&#93; | None = None, clip_embedding_neg: list&#91;torch.Tensor&#93; | None = None, max_sequence_length: int | None = None, prompt_template: dict&#91;str, Any&#93; | None = None, do_classifier_free_guidance: bool = False, use_embedded_guidance: bool = False, true_cfg_scale: float = 1.0, batch_size: int | None = None, num_videos_per_prompt: int = 1, seed: int | None = None, seeds: list&#91;int&#93; | None = None, is_prompt_processed: bool = False, latents: torch.Tensor | None = None, audio_latents: torch.Tensor | None = None, lq_latents: torch.Tensor | None = None, raw_latent_shape: tuple&#91;int, ...&#93; | None = None, noise_pred: torch.Tensor | None = None, image_latent: torch.Tensor | None = None, first_frame_latent: torch.Tensor | None = None, helios_latent_chunks: list&#91;torch.Tensor&#93; | None = None, mouse_cond: torch.Tensor | None = None, keyboard_cond: torch.Tensor | None = None, grid_sizes: torch.Tensor | None = None, num_iterations: int | None = None, use_base_model: bool = False, pose: str | None = None, c2ws_plucker_emb: torch.Tensor | None = None, action_path: str | None = None, trajectory_type: str | None = None, movement_distance: float | None = None, camera_rotation: str | None = None, height_latents: list&#91;int&#93; | int | None = None, width_latents: list&#91;int&#93; | int | None = None, num_frames: list&#91;int&#93; | int = 1, height: list&#91;int&#93; | int | None = None, width: list&#91;int&#93; | int | None = None, height_sr: list&#91;int&#93; | int | None = None, width_sr: list&#91;int&#93; | int | None = None, fps: list&#91;int&#93; | int | None = None, timesteps: torch.Tensor | None = None, timestep: torch.Tensor | float | int | None = None, step_index: int | None = None, boundary_ratio: float | None = None, num_inference_steps: int = 50, num_inference_steps_sr: int = 50, guidance_scale: float = 1.0, batch_cfg: bool = False, guidance_scale_2: float | None = None, guidance_rescale: float = 0.0, eta: float = 0.0, sigmas: list&#91;float&#93; | None = None, pyramid_num_inference_steps_list: list&#91;int&#93; | None = None, history_sizes: list&#91;int&#93; | None = None, num_latent_frames_per_chunk: int = 9, keep_first_frame: bool = True, is_skip_first_chunk: bool = False, use_zero_init: bool = True, zero_steps: int = 1, is_amplify_first_chunk: bool = False, enable_teacache: bool = False, ltx2_cfg_scale_video: float = 1.0, ltx2_cfg_scale_audio: float = 1.0, ltx2_modality_scale_video: float = 1.0, ltx2_modality_scale_audio: float = 1.0, ltx2_rescale_scale: float = 0.0, ltx2_stg_scale_video: float = 0.0, ltx2_stg_scale_audio: float = 0.0, ltx2_stg_blocks_video: list&#91;int&#93; = list(), ltx2_stg_blocks_audio: list&#91;int&#93; = list(), ltx2_use_ancestral_sampler: bool = False, ltx2_images: list&#91;tuple&#91;str, int, float&#93;&#93; | None = None, ltx2_image_crf: float = 33.0, ltx2_conditioning_latent_stage1: torch.Tensor | None = None, ltx2_conditioning_latent_stage2: torch.Tensor | None = None, ltx2_video_conditions: list&#91;tuple&#91;list&#91;str&#93;, int, float&#93;&#93; | None = None, audio_start_in_s: float | None = None, audio_end_in_s: float | None = None, init_audio: Any = None, init_audio_strength: float | None = None, init_noise_level: float | None = None, inpaint_audio: Any = None, inpaint_mask: Any = None, n_tokens: int | None = None, extra_step_kwargs: dict&#91;str, Any&#93; = dict(), modules: dict&#91;str, Any&#93; = dict(), output: torch.Tensor | None = None, return_trajectory_latents: bool = False, return_trajectory_decoded: bool = False, trajectory_timesteps: list&#91;torch.Tensor&#93; | None = None, trajectory_latents: torch.Tensor | None = None, trajectory_decoded: list&#91;torch.Tensor&#93; | None = None, continuation_state: ContinuationState | None = None, return_continuation_state: bool = False, extra: dict&#91;str, Any&#93; = dict(), save_video: bool = True, return_frames: bool = False, is_cfg_negative: bool = False, VSA_sparsity: float = 0.0, logging_info: PipelineLoggingInfo = PipelineLoggingInfo(), *, return_samples: bool = False)</code></pre>
<p>Complete state passed through the pipeline execution.</p>
<p>This dataclass contains all information needed during the diffusion pipeline
execution, allowing methods to update specific components without needing
to manage numerous individual parameters.</p>

<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline</code></h2>
<pre class="doc-signature"><code>BasePreprocessPipeline(model_path: str, fastvideo_args: FastVideoArgs | TrainingArgs, required_config_modules: list&#91;str&#93; | None = None, loaded_modules: dict&#91;str, torch.nn.Module&#93; | None = None)</code></pre>
<p>Base class for preprocessing pipelines that handles common functionality.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.create_pipeline_stages"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.create_pipeline_stages</code></h3>
<pre class="doc-signature"><code>create_pipeline_stages(fastvideo_args: FastVideoArgs)</code></pre>
<p>Set up pipeline stages with proper dependency injection.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.forward</code></h3>
<pre class="doc-signature"><code>forward(batch: ForwardBatch, fastvideo_args: FastVideoArgs, args)</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.get_extra_features"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.get_extra_features</code></h3>
<pre class="doc-signature"><code>get_extra_features(valid_data: dict&#91;str, Any&#93;, fastvideo_args: FastVideoArgs) -&gt; dict&#91;str, Any&#93;</code></pre>
<p>Get additional features specific to the pipeline type. Override in subclasses.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.get_pyarrow_schema"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.get_pyarrow_schema</code></h3>
<pre class="doc-signature"><code>get_pyarrow_schema() -&gt; pa.Schema</code></pre>
<p>Return the PyArrow schema for this pipeline. Must be overridden.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.get_schema_fields"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.get_schema_fields</code></h3>
<pre class="doc-signature"><code>get_schema_fields() -&gt; list&#91;str&#93;</code></pre>
<p>Get the schema fields for the pipeline type.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.create_record_for_schema"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.create_record_for_schema</code></h3>
<pre class="doc-signature"><code>create_record_for_schema(preprocess_batch: PreprocessBatch, schema: pa.Schema, strict: bool = False) -&gt; dict&#91;str, Any&#93;</code></pre>
<p>Create a record for the Parquet dataset using a generic schema-based approach.</p>
<h4>Parameters</h4>
<dl>
<dt><code>preprocess_batch: PreprocessBatch</code></dt><dd><p>The batch containing the data to extract</p></dd>
<dt><code>schema: pa.Schema</code></dt><dd><p>PyArrow schema defining the expected fields</p></dd>
<dt><code>strict: bool</code></dt><dd><p>If True, raises an exception when required fields are missing or unfilled</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code>dict[str, Any]</code></dt><dd><p>Dictionary record matching the schema</p></dd>
</dl>
<h4>Raises</h4>
<dl>
<dt><code>ValueError</code></dt><dd><p>If strict=True and required fields are missing or unfilled</p></dd>
</dl>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.create_record"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.create_record</code></h3>
<pre class="doc-signature"><code>create_record(video_name: str, vae_latent: np.ndarray, text_embedding: np.ndarray, valid_data: dict&#91;str, Any&#93;, idx: int, extra_features: dict&#91;str, Any&#93; | None = None) -&gt; dict&#91;str, Any&#93;</code></pre>
<p>Create a record for the Parquet dataset.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.preprocess_video_and_text"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.BasePreprocessPipeline.preprocess_video_and_text</code></h3>
<pre class="doc-signature"><code>preprocess_video_and_text(fastvideo_args: FastVideoArgs, args)</code></pre>

<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage</code></h2>
<pre class="doc-signature"><code>DecodingStage(vae, pipeline = None)</code></pre>
<p>Stage for decoding latent representations into pixel space.</p>
<p>This stage handles the decoding of latent representations into the final
output format (e.g., pixel values).</p>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.verify_input"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.verify_input</code></h3>
<pre class="doc-signature"><code>verify_input(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify decoding stage inputs.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.verify_output"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.verify_output</code></h3>
<pre class="doc-signature"><code>verify_output(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify decoding stage outputs.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.decode"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.decode</code></h3>
<pre class="doc-signature"><code>decode(latents: torch.Tensor, fastvideo_args: FastVideoArgs) -&gt; torch.Tensor</code></pre>
<p>Decode latent representations into pixel space using VAE.</p>
<h4>Parameters</h4>
<dl>
<dt><code>latents: torch.Tensor</code></dt><dd><p>Input latent tensor with shape (batch, channels, frames, height_latents, width_latents)</p></dd>
<dt><code>fastvideo_args: FastVideoArgs</code></dt><dd><p>Configuration containing:
- disable_autocast: Whether to disable automatic mixed precision (default: False)
- pipeline_config.vae_precision: VAE computation precision ("fp32", "fp16", "bf16")
- pipeline_config.vae_tiling: Whether to enable VAE tiling for memory efficiency</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code>torch.Tensor</code></dt><dd><p>Decoded video tensor with shape (batch, channels, frames, height, width), </p></dd>
<dt><code>torch.Tensor</code></dt><dd><p>normalized to [0, 1] range and moved to CPU as float32</p></dd>
</dl>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.streaming_decode"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.streaming_decode</code></h3>
<pre class="doc-signature"><code>streaming_decode(latents: torch.Tensor, fastvideo_args: FastVideoArgs, cache: list&#91;torch.Tensor | None&#93; | None = None, is_first_chunk: bool = False) -&gt; tuple&#91;torch.Tensor, list&#91;torch.Tensor | None&#93;&#93;</code></pre>
<p>Decode latent representations into pixel space using VAE with streaming cache.</p>
<h4>Parameters</h4>
<dl>
<dt><code>latents: torch.Tensor</code></dt><dd><p>Input latent tensor with shape (batch, channels, frames, height_latents, width_latents)</p></dd>
<dt><code>fastvideo_args: FastVideoArgs</code></dt><dd><p>Configuration object.</p></dd>
<dt><code>cache: list[torch.Tensor | None] | None</code></dt><dd><p>VAE cache from previous call, or None to initialize a new cache.</p></dd>
<dt><code>is_first_chunk: bool</code></dt><dd><p>Whether this is the first chunk.</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code>tuple[torch.Tensor, list[torch.Tensor | None]]</code></dt><dd><p>A tuple of (decoded_frames, updated_cache).</p></dd>
</dl>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.DecodingStage.forward</code></h3>
<pre class="doc-signature"><code>forward(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; ForwardBatch</code></pre>
<p>Decode latent representations into pixel space.</p>
<p>This method processes the batch through the VAE decoder, converting latent
representations to pixel-space video/images. It also optionally decodes
trajectory latents for visualization purposes.</p>
<h4>Parameters</h4>
<dl>
<dt><code>batch: ForwardBatch</code></dt><dd><p>The current batch containing:
- latents: Tensor to decode (batch, channels, frames, height_latents, width_latents)
- return_trajectory_decoded (optional): Flag to decode trajectory latents
- trajectory_latents (optional): Latents at different timesteps
- trajectory_timesteps (optional): Corresponding timesteps</p></dd>
<dt><code>fastvideo_args: FastVideoArgs</code></dt><dd><p>Configuration containing:
- output_type: "latent" to skip decoding, otherwise decode to pixels
- vae_cpu_offload: Whether to offload VAE to CPU after decoding
- model_loaded: Track VAE loading state
- model_paths: Path to VAE model if loading needed</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code>ForwardBatch</code></dt><dd><p>Modified batch with:
- output: Decoded frames (batch, channels, frames, height, width) as CPU float32
- trajectory_decoded (if requested): List of decoded frames per timestep</p></dd>
</dl>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.InputValidationStage"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.InputValidationStage</code></h2>
<pre class="doc-signature"><code>InputValidationStage()</code></pre>
<p>Stage for validating and preparing inputs for diffusion pipelines.</p>
<p>This stage validates that all required inputs are present and properly formatted
before proceeding with the diffusion process.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.InputValidationStage.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.InputValidationStage.forward</code></h3>
<pre class="doc-signature"><code>forward(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; ForwardBatch</code></pre>
<p>Validate and prepare inputs.</p>
<h4>Parameters</h4>
<dl>
<dt><code>batch: ForwardBatch</code></dt><dd><p>The current batch information.</p></dd>
<dt><code>fastvideo_args: FastVideoArgs</code></dt><dd><p>The inference arguments.</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code>ForwardBatch</code></dt><dd><p>The validated batch information.</p></dd>
</dl>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.InputValidationStage.verify_input"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.InputValidationStage.verify_input</code></h3>
<pre class="doc-signature"><code>verify_input(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify input validation stage inputs.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.InputValidationStage.verify_output"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.InputValidationStage.verify_output</code></h3>
<pre class="doc-signature"><code>verify_output(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify input validation stage outputs.</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.LatentPreparationStage"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.LatentPreparationStage</code></h2>
<pre class="doc-signature"><code>LatentPreparationStage(scheduler, transformer, use_btchw_layout: bool = False)</code></pre>
<p>Stage for preparing initial latent variables for the diffusion process.</p>
<p>This stage handles the preparation of the initial latent variables that will be
denoised during the diffusion process.</p>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.LatentPreparationStage.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.LatentPreparationStage.forward</code></h3>
<pre class="doc-signature"><code>forward(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; ForwardBatch</code></pre>
<p>Prepare initial latent variables for the diffusion process.</p>
<h4>Parameters</h4>
<dl>
<dt><code>batch: ForwardBatch</code></dt><dd><p>The current batch information.</p></dd>
<dt><code>fastvideo_args: FastVideoArgs</code></dt><dd><p>The inference arguments.</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code>ForwardBatch</code></dt><dd><p>The batch with prepared latent variables.</p></dd>
</dl>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.LatentPreparationStage.verify_input"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.LatentPreparationStage.verify_input</code></h3>
<pre class="doc-signature"><code>verify_input(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify latent preparation stage inputs.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.LatentPreparationStage.verify_output"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.LatentPreparationStage.verify_output</code></h3>
<pre class="doc-signature"><code>verify_output(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify latent preparation stage outputs.</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2ImageEncodingStage"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2ImageEncodingStage</code></h2>
<pre class="doc-signature"><code>MatrixGame2ImageEncodingStage(image_encoder, image_processor)</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2ImageEncodingStage.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2ImageEncodingStage.forward</code></h3>
<pre class="doc-signature"><code>forward(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; ForwardBatch</code></pre>

<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.TimestepPreparationStage"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.TimestepPreparationStage</code></h2>
<pre class="doc-signature"><code>TimestepPreparationStage(scheduler)</code></pre>
<p>Stage for preparing timesteps for the diffusion process.</p>
<p>This stage handles the preparation of the timestep sequence that will be used
during the diffusion process.</p>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.TimestepPreparationStage.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.TimestepPreparationStage.forward</code></h3>
<pre class="doc-signature"><code>forward(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; ForwardBatch</code></pre>
<p>Prepare timesteps for the diffusion process.</p>
<h4>Parameters</h4>
<dl>
<dt><code>batch: ForwardBatch</code></dt><dd><p>The current batch information.</p></dd>
<dt><code>fastvideo_args: FastVideoArgs</code></dt><dd><p>The inference arguments.</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code>ForwardBatch</code></dt><dd><p>The batch with prepared timesteps.</p></dd>
</dl>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.TimestepPreparationStage.verify_input"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.TimestepPreparationStage.verify_input</code></h3>
<pre class="doc-signature"><code>verify_input(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify timestep preparation stage inputs.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.TimestepPreparationStage.verify_output"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.TimestepPreparationStage.verify_output</code></h3>
<pre class="doc-signature"><code>verify_output(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify timestep preparation stage outputs.</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage</code></h2>
<pre class="doc-signature"><code>MatrixGame2CausalDenoisingStage(transformer, scheduler, pipeline = None, transformer_2 = None, vae = None)</code></pre>


<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.forward</code></h3>
<pre class="doc-signature"><code>forward(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; ForwardBatch</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.streaming_reset"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.streaming_reset</code></h3>
<pre class="doc-signature"><code>streaming_reset(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; ForwardBatch</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.streaming_step"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.streaming_step</code></h3>
<pre class="doc-signature"><code>streaming_step(keyboard_action: torch.Tensor | None = None, mouse_action: torch.Tensor | None = None) -&gt; ForwardBatch</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.streaming_clear"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.streaming_clear</code></h3>
<pre class="doc-signature"><code>streaming_clear() -&gt; None</code></pre>

<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.verify_input"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.MatrixGame2CausalDenoisingStage.verify_input</code></h3>
<pre class="doc-signature"><code>verify_input(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>

<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.save_decoded_latents_as_video"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.save_decoded_latents_as_video</code></h2>
<pre class="doc-signature"><code>save_decoded_latents_as_video(decoded_latents: list&#91;torch.Tensor&#93;, output_path: str, fps: int)</code></pre>

<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.shallow_asdict"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.shallow_asdict</code></h2>
<pre class="doc-signature"><code>shallow_asdict(obj) -&gt; dict&#91;str, Any&#93;</code></pre>

<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory</code></h2>
<pre class="doc-signature"><code>PreprocessPipeline_MatrixGame2_ODE_Trajectory(model_path: str, fastvideo_args: FastVideoArgs | TrainingArgs, required_config_modules: list&#91;str&#93; | None = None, loaded_modules: dict&#91;str, torch.nn.Module&#93; | None = None)</code></pre>
<p>ODE Trajectory preprocessing pipeline implementation.</p>
<details><summary>Source</summary><pre><code>class PreprocessPipeline_MatrixGame2_ODE_Trajectory(BasePreprocessPipeline):
    &quot;&quot;&quot;ODE Trajectory preprocessing pipeline implementation.&quot;&quot;&quot;

    _required_config_modules = &#91;&quot;vae&quot;, &quot;image_encoder&quot;, &quot;image_processor&quot;, &quot;transformer&quot;, &quot;scheduler&quot;&#93;

    preprocess_dataloader: StatefulDataLoader
    preprocess_loader_iter: Iterator&#91;dict&#91;str, Any&#93;&#93;
    pbar: Any
    num_processed_samples: int

    def get_pyarrow_schema(self) -&gt; pa.Schema:
        &quot;&quot;&quot;Return the PyArrow schema for ODE Trajectory pipeline.&quot;&quot;&quot;
        return pyarrow_schema_matrixgame2_ode_trajectory

    def create_pipeline_stages(self, fastvideo_args: FastVideoArgs):
        &quot;&quot;&quot;Set up pipeline stages with proper dependency injection.&quot;&quot;&quot;
        assert fastvideo_args.pipeline_config.flow_shift == 5
        self.modules&#91;&quot;scheduler&quot;&#93; = SelfForcingFlowMatchScheduler(shift=fastvideo_args.pipeline_config.flow_shift,
                                                                  sigma_min=0.0,
                                                                  extra_one_step=True)
        self.modules&#91;&quot;scheduler&quot;&#93;.set_timesteps(num_inference_steps=48, denoising_strength=1.0)

        self.add_stage(stage_name=&quot;input_validation_stage&quot;, stage=InputValidationStage())
        self.add_stage(stage_name=&quot;image_encoding_stage&quot;,
                       stage=MatrixGame2ImageEncodingStage(
                           image_encoder=self.get_module(&quot;image_encoder&quot;),
                           image_processor=self.get_module(&quot;image_processor&quot;),
                       ))
        self.add_stage(stage_name=&quot;timestep_preparation_stage&quot;,
                       stage=TimestepPreparationStage(scheduler=self.get_module(&quot;scheduler&quot;)))
        self.add_stage(stage_name=&quot;latent_preparation_stage&quot;,
                       stage=LatentPreparationStage(scheduler=self.get_module(&quot;scheduler&quot;),
                                                    transformer=self.get_module(&quot;transformer&quot;, None)))
        self.add_stage(stage_name=&quot;denoising_stage&quot;,
                       stage=MatrixGame2CausalDenoisingStage(
                           transformer=self.get_module(&quot;transformer&quot;),
                           scheduler=self.get_module(&quot;scheduler&quot;),
                           pipeline=self,
                           vae=self.get_module(&quot;vae&quot;),
                       ))
        self.add_stage(stage_name=&quot;decoding_stage&quot;, stage=DecodingStage(vae=self.get_module(&quot;vae&quot;)))

    def get_extra_features(self, valid_data: dict&#91;str, Any&#93;, fastvideo_args: FastVideoArgs) -&gt; dict&#91;str, Any&#93;:

        # TODO(will): move these to cpu at some point
        self.get_module(&quot;image_encoder&quot;).to(get_local_torch_device())
        self.get_module(&quot;vae&quot;).to(get_local_torch_device())

        features = &#123;&#125;
        &quot;&quot;&quot;Get CLIP features from the first frame of each video.&quot;&quot;&quot;
        first_frame = valid_data&#91;&quot;pixel_values&quot;&#93;&#91;:, :, 0, :, :&#93;.permute(0, 2, 3, 1)  # (B, C, T, H, W) -&gt; (B, H, W, C)
        _, _, num_frames, height, width = valid_data&#91;&quot;pixel_values&quot;&#93;.shape
        # latent_height = height // self.get_module(
        #     &quot;vae&quot;).spatial_compression_ratio
        # latent_width = width // self.get_module(&quot;vae&quot;).spatial_compression_ratio

        processed_images = &#91;&#93;
        # Frame has values between -1 and 1
        for frame in first_frame:
            frame = (frame + 1) * 127.5
            frame_pil = Image.fromarray(frame.cpu().numpy().astype(np.uint8))
            processed_img = self.get_module(&quot;image_processor&quot;)(images=frame_pil, return_tensors=&quot;pt&quot;)
            processed_images.append(processed_img)

        # Get CLIP features
        pixel_values = torch.cat(&#91;img&#91;&#x27;pixel_values&#x27;&#93; for img in processed_images&#93;, dim=0).to(get_local_torch_device())
        with torch.no_grad():
            image_inputs = &#123;&#x27;pixel_values&#x27;: pixel_values&#125;
            with set_forward_context(current_timestep=0, attn_metadata=None):
                clip_features = self.get_module(&quot;image_encoder&quot;)(**image_inputs)
            clip_features = clip_features.last_hidden_state

        features&#91;&quot;clip_feature&quot;&#93; = clip_features
        features&#91;&quot;pil_image&quot;&#93; = first_frame
        # Get CLIP features from the first frame of each video.
        video_conditions = &#91;&#93;
        for frame in first_frame:
            processed_img = frame.to(device=&quot;cpu&quot;, dtype=torch.float32)
            processed_img = processed_img.unsqueeze(0).permute(0, 3, 1, 2).unsqueeze(2)
            # (B, H, W, C) -&gt; (B, C, 1, H, W)
            video_condition = torch.cat(&#91;
                processed_img,
                processed_img.new_zeros(processed_img.shape&#91;0&#93;, processed_img.shape&#91;1&#93;, num_frames - 1, height, width)
            &#93;,
                                        dim=2)
            video_condition = video_condition.to(device=get_local_torch_device(), dtype=torch.float32)
            video_conditions.append(video_condition)

        video_conditions = torch.cat(video_conditions, dim=0)

        with torch.autocast(device_type=&quot;cuda&quot;, dtype=torch.float32, enabled=True):
            encoder_outputs = self.get_module(&quot;vae&quot;).encode(video_conditions)

        # Use mode() instead of mean
        latent_condition = encoder_outputs.mode()

        # Use latents_mean/latents_std normalization to match
        vae = self.get_module(&quot;vae&quot;)
        if (hasattr(vae.config, &#x27;latents_mean&#x27;) and hasattr(vae.config, &#x27;latents_std&#x27;)):
            latents_mean = torch.tensor(vae.config.latents_mean,
                                        device=latent_condition.device,
                                        dtype=latent_condition.dtype).view(1, -1, 1, 1, 1)
            latents_std = torch.tensor(vae.config.latents_std,
                                       device=latent_condition.device,
                                       dtype=latent_condition.dtype).view(1, -1, 1, 1, 1)
            latent_condition = (latent_condition - latents_mean) / latents_std
        elif (hasattr(vae, &quot;shift_factor&quot;) and vae.shift_factor is not None):
            if isinstance(vae.shift_factor, torch.Tensor):
                latent_condition -= vae.shift_factor.to(latent_condition.device, latent_condition.dtype)
            else:
                latent_condition -= vae.shift_factor

            if isinstance(vae.scaling_factor, torch.Tensor):
                latent_condition = latent_condition * vae.scaling_factor.to(latent_condition.device,
                                                                            latent_condition.dtype)
            else:
                latent_condition = latent_condition * vae.scaling_factor

        # Create mask_cond: ones for first frame, zeros for rest
        # Shape: (B, 16, latent_frames, latent_height, latent_width)
        mask_cond = torch.ones_like(latent_condition)
        mask_cond&#91;:, :, 1:&#93; = 0  # Set all frames except first to 0
        # Create cond_concat: first 4 channels of mask + all 16 channels of img_cond
        # Shape: (B, 20, latent_frames, latent_height, latent_width)
        cond_concat = torch.cat(&#91;mask_cond&#91;:, :4&#93;, latent_condition&#93;, dim=1)
        features&#91;&quot;first_frame_latent&quot;&#93; = cond_concat

        if &quot;action_path&quot; in valid_data and valid_data&#91;&quot;action_path&quot;&#93;:
            keyboard_cond_list = &#91;&#93;
            mouse_cond_list = &#91;&#93;
            keyboard_dim = self.get_module(&quot;transformer&quot;).config.arch_config.action_config&#91;&quot;keyboard_dim_in&quot;&#93;
            for action_path in valid_data&#91;&quot;action_path&quot;&#93;:
                if action_path:
                    action_data = np.load(action_path, allow_pickle=True)
                    if isinstance(action_data, np.ndarray) and action_data.dtype == np.dtype(&#x27;O&#x27;):
                        action_dict = action_data.item()
                        if &quot;keyboard&quot; in action_dict:
                            keyboard_cond_list.append(action_dict&#91;&quot;keyboard&quot;&#93;&#91;:, :keyboard_dim&#93;.astype(np.float32))
                        if &quot;mouse&quot; in action_dict:
                            mouse_cond_list.append(action_dict&#91;&quot;mouse&quot;&#93;)
                    else:
                        keyboard_cond_list.append(action_data&#91;:, :keyboard_dim&#93;.astype(np.float32))
            if keyboard_cond_list:
                features&#91;&quot;keyboard_cond&quot;&#93; = keyboard_cond_list
            if mouse_cond_list:
                features&#91;&quot;mouse_cond&quot;&#93; = mouse_cond_list
        return features

    def preprocess_action_and_trajectory(self, fastvideo_args: FastVideoArgs, args):
        &quot;&quot;&quot;Preprocess data and generate trajectory information.&quot;&quot;&quot;

        for batch_idx, data in enumerate(self.pbar):
            if data is None:
                continue

            with torch.inference_mode():
                # Filter out invalid samples (those with all zeros)
                valid_indices = &#91;&#93;
                for i, pixel_values in enumerate(data&#91;&quot;pixel_values&quot;&#93;):
                    if not torch.all(pixel_values == 0):  # Check if all values are zero
                        valid_indices.append(i)
                self.num_processed_samples += len(valid_indices)

                if not valid_indices:
                    continue

                # Create new batch with only valid samples
                valid_data = &#123;
                    &quot;pixel_values&quot;: torch.stack(&#91;data&#91;&quot;pixel_values&quot;&#93;&#91;i&#93; for i in valid_indices&#93;),
                    &quot;path&quot;: &#91;data&#91;&quot;path&quot;&#93;&#91;i&#93; for i in valid_indices&#93;,
                &#125;

                if &quot;fps&quot; in data:
                    valid_data&#91;&quot;fps&quot;&#93; = &#91;data&#91;&quot;fps&quot;&#93;&#91;i&#93; for i in valid_indices&#93;
                if &quot;duration&quot; in data:
                    valid_data&#91;&quot;duration&quot;&#93; = &#91;data&#91;&quot;duration&quot;&#93;&#91;i&#93; for i in valid_indices&#93;
                if &quot;action_path&quot; in data:
                    valid_data&#91;&quot;action_path&quot;&#93; = &#91;data&#91;&quot;action_path&quot;&#93;&#91;i&#93; for i in valid_indices&#93;

                pixel_values = valid_data&#91;&quot;pixel_values&quot;&#93;
                if pixel_values.shape&#91;2&#93; == 1 and args.num_frames is not None:
                    pixel_values = pixel_values.repeat(1, 1, args.num_frames, 1, 1)
                    valid_data&#91;&quot;pixel_values&quot;&#93; = pixel_values

                # Get extra features if needed
                extra_features = self.get_extra_features(valid_data, fastvideo_args)

                clip_features = extra_features&#91;&#x27;clip_feature&#x27;&#93;
                image_latents = extra_features&#91;&#x27;first_frame_latent&#x27;&#93;
                image_latents = image_latents&#91;:, :, :args.num_latent_t&#93;
                pil_image = extra_features&#91;&#x27;pil_image&#x27;&#93;
                keyboard_cond = extra_features.get(&#x27;keyboard_cond&#x27;)
                mouse_cond = extra_features.get(&#x27;mouse_cond&#x27;)

                sampling_params = SamplingParam.from_pretrained(args.model_path)

                trajectory_latents = &#91;&#93;
                trajectory_timesteps = &#91;&#93;
                trajectory_decoded = &#91;&#93;

                device = get_local_torch_device()
                for i in range(len(valid_indices)):
                    # Collect the trajectory data
                    batch = ForwardBatch(**shallow_asdict(sampling_params), )
                    batch.image_embeds = &#91;clip_features&#91;i&#93;.unsqueeze(0)&#93;
                    batch.image_latent = image_latents&#91;i&#93;.unsqueeze(0)
                    batch.keyboard_cond = (torch.from_numpy(keyboard_cond&#91;i&#93;).unsqueeze(0).to(device)
                                           if keyboard_cond is not None else None)
                    batch.mouse_cond = (torch.from_numpy(mouse_cond&#91;i&#93;).unsqueeze(0).to(device)
                                        if mouse_cond is not None else None)
                    batch.num_inference_steps = 48
                    batch.return_trajectory_latents = True
                    # Enabling this will save the decoded trajectory videos.
                    # Used for debugging.
                    batch.return_trajectory_decoded = False
                    batch.height = args.max_height
                    batch.width = args.max_width
                    batch.fps = args.train_fps
                    batch.num_frames = valid_data&#91;&quot;pixel_values&quot;&#93;.shape&#91;2&#93;
                    batch.guidance_scale = 6.0
                    batch.do_classifier_free_guidance = False
                    batch.prompt = &quot;&quot;

                    result_batch = self.input_validation_stage(batch, fastvideo_args)
                    result_batch = self.timestep_preparation_stage(batch, fastvideo_args)
                    result_batch.timesteps = result_batch.timesteps.to(device)
                    result_batch = self.latent_preparation_stage(result_batch, fastvideo_args)
                    result_batch = self.denoising_stage(result_batch, fastvideo_args)
                    result_batch = self.decoding_stage(result_batch, fastvideo_args)

                    trajectory_latents.append(result_batch.trajectory_latents.cpu())
                    trajectory_timesteps.append(result_batch.trajectory_timesteps.cpu())
                    trajectory_decoded.append(result_batch.trajectory_decoded)

                # Prepare extra features
                extra_features = &#123;
                    &quot;trajectory_latents&quot;: trajectory_latents,
                    &quot;trajectory_timesteps&quot;: trajectory_timesteps
                &#125;

                if batch.return_trajectory_decoded:
                    for i, decoded_frames in enumerate(trajectory_decoded):
                        for j, decoded_frame in enumerate(decoded_frames):
                            save_decoded_latents_as_video(decoded_frame,
                                                          f&quot;decoded_videos/trajectory_decoded_&#123;i&#125;_&#123;j&#125;.mp4&quot;,
                                                          args.train_fps)

                # Prepare batch data for Parquet dataset
                batch_data: list&#91;dict&#91;str, Any&#93;&#93; = &#91;&#93;

                # Add progress bar for saving outputs
                save_pbar = tqdm(enumerate(valid_data&#91;&quot;path&quot;&#93;), desc=&quot;Saving outputs&quot;, unit=&quot;item&quot;, leave=False)

                for idx, video_path in save_pbar:
                    video_name = os.path.basename(video_path).split(&quot;.&quot;)&#91;0&#93;

                    clip_feature_np = clip_features&#91;idx&#93;.cpu().numpy()
                    first_frame_latent_np = image_latents&#91;idx&#93;.cpu().numpy()
                    pil_image_np = pil_image&#91;idx&#93;.cpu().numpy()
                    keyboard_cond_np = keyboard_cond&#91;idx&#93; if keyboard_cond is not None else None
                    mouse_cond_np = mouse_cond&#91;idx&#93; if mouse_cond is not None else None

                    # Get trajectory features for this sample
                    traj_latents = extra_features&#91;&quot;trajectory_latents&quot;&#93;&#91;idx&#93;
                    traj_timesteps = extra_features&#91;&quot;trajectory_timesteps&quot;&#93;&#91;idx&#93;
                    if isinstance(traj_latents, torch.Tensor):
                        traj_latents = traj_latents.cpu().float().numpy()
                    if isinstance(traj_timesteps, torch.Tensor):
                        traj_timesteps = traj_timesteps.cpu().float().numpy()

                    # Create record for Parquet dataset
                    record: dict&#91;str, Any&#93; = matrixgame2_ode_record_creator(video_name=video_name,
                                                                            clip_feature=clip_feature_np,
                                                                            first_frame_latent=first_frame_latent_np,
                                                                            trajectory_latents=traj_latents,
                                                                            trajectory_timesteps=traj_timesteps,
                                                                            pil_image=pil_image_np,
                                                                            keyboard_cond=keyboard_cond_np,
                                                                            mouse_cond=mouse_cond_np,
                                                                            caption=&quot;&quot;)
                    batch_data.append(record)

                if batch_data:
                    write_pbar = tqdm(total=1, desc=&quot;Writing to Parquet dataset&quot;, unit=&quot;batch&quot;)
                    table = records_to_table(batch_data, self.get_pyarrow_schema())
                    write_pbar.update(1)
                    write_pbar.close()

                    if not hasattr(self, &#x27;dataset_writer&#x27;):
                        self.dataset_writer = ParquetDatasetWriter(
                            out_dir=self.combined_parquet_dir,
                            samples_per_file=args.samples_per_file,
                        )
                    self.dataset_writer.append_table(table)

                    logger.info(&quot;Collected batch with %s samples&quot;, len(table))

                if self.num_processed_samples &gt;= args.flush_frequency:
                    written = self.dataset_writer.flush()
                    logger.info(&quot;Flushed %s samples to parquet&quot;, written)
                    self.num_processed_samples = 0

        # Final flush for any remaining samples
        if hasattr(self, &#x27;dataset_writer&#x27;):
            written = self.dataset_writer.flush(write_remainder=True)
            if written:
                logger.info(&quot;Final flush wrote %s samples&quot;, written)

    def forward(self, batch: ForwardBatch, fastvideo_args: FastVideoArgs, args):
        if not self.post_init_called:
            self.post_init()

        self.local_rank = int(os.getenv(&quot;RANK&quot;, 0))
        os.makedirs(args.output_dir, exist_ok=True)
        # Create directory for combined data
        self.combined_parquet_dir = os.path.join(args.output_dir, &quot;combined_parquet_dataset&quot;)
        os.makedirs(self.combined_parquet_dir, exist_ok=True)

        # Loading dataset
        train_dataset = getdataset(args)

        self.preprocess_dataloader = DataLoader(
            train_dataset,
            batch_size=args.preprocess_video_batch_size,
            num_workers=args.dataloader_num_workers,
        )

        self.preprocess_loader_iter = iter(self.preprocess_dataloader)

        self.num_processed_samples = 0
        # Add progress bar for video preprocessing
        self.pbar = tqdm(self.preprocess_loader_iter,
                         desc=&quot;Processing videos&quot;,
                         unit=&quot;batch&quot;,
                         disable=self.local_rank != 0)

        # Initialize class variables for data sharing
        self.video_data: dict&#91;str, Any&#93; = &#123;&#125;  # Store video metadata and paths
        self.latent_data: dict&#91;str, Any&#93; = &#123;&#125;  # Store latent tensors
        self.preprocess_action_and_trajectory(fastvideo_args, args)</code></pre></details>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.get_pyarrow_schema"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.get_pyarrow_schema</code></h3>
<pre class="doc-signature"><code>get_pyarrow_schema() -&gt; pa.Schema</code></pre>
<p>Return the PyArrow schema for ODE Trajectory pipeline.</p>
<details><summary>Source</summary><pre><code>def get_pyarrow_schema(self) -&gt; pa.Schema:
    &quot;&quot;&quot;Return the PyArrow schema for ODE Trajectory pipeline.&quot;&quot;&quot;
    return pyarrow_schema_matrixgame2_ode_trajectory</code></pre></details>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.create_pipeline_stages"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.create_pipeline_stages</code></h3>
<pre class="doc-signature"><code>create_pipeline_stages(fastvideo_args: FastVideoArgs)</code></pre>
<p>Set up pipeline stages with proper dependency injection.</p>
<details><summary>Source</summary><pre><code>def create_pipeline_stages(self, fastvideo_args: FastVideoArgs):
    &quot;&quot;&quot;Set up pipeline stages with proper dependency injection.&quot;&quot;&quot;
    assert fastvideo_args.pipeline_config.flow_shift == 5
    self.modules&#91;&quot;scheduler&quot;&#93; = SelfForcingFlowMatchScheduler(shift=fastvideo_args.pipeline_config.flow_shift,
                                                              sigma_min=0.0,
                                                              extra_one_step=True)
    self.modules&#91;&quot;scheduler&quot;&#93;.set_timesteps(num_inference_steps=48, denoising_strength=1.0)

    self.add_stage(stage_name=&quot;input_validation_stage&quot;, stage=InputValidationStage())
    self.add_stage(stage_name=&quot;image_encoding_stage&quot;,
                   stage=MatrixGame2ImageEncodingStage(
                       image_encoder=self.get_module(&quot;image_encoder&quot;),
                       image_processor=self.get_module(&quot;image_processor&quot;),
                   ))
    self.add_stage(stage_name=&quot;timestep_preparation_stage&quot;,
                   stage=TimestepPreparationStage(scheduler=self.get_module(&quot;scheduler&quot;)))
    self.add_stage(stage_name=&quot;latent_preparation_stage&quot;,
                   stage=LatentPreparationStage(scheduler=self.get_module(&quot;scheduler&quot;),
                                                transformer=self.get_module(&quot;transformer&quot;, None)))
    self.add_stage(stage_name=&quot;denoising_stage&quot;,
                   stage=MatrixGame2CausalDenoisingStage(
                       transformer=self.get_module(&quot;transformer&quot;),
                       scheduler=self.get_module(&quot;scheduler&quot;),
                       pipeline=self,
                       vae=self.get_module(&quot;vae&quot;),
                   ))
    self.add_stage(stage_name=&quot;decoding_stage&quot;, stage=DecodingStage(vae=self.get_module(&quot;vae&quot;)))</code></pre></details>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.get_extra_features"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.get_extra_features</code></h3>
<pre class="doc-signature"><code>get_extra_features(valid_data: dict&#91;str, Any&#93;, fastvideo_args: FastVideoArgs) -&gt; dict&#91;str, Any&#93;</code></pre>

<details><summary>Source</summary><pre><code>def get_extra_features(self, valid_data: dict&#91;str, Any&#93;, fastvideo_args: FastVideoArgs) -&gt; dict&#91;str, Any&#93;:

    # TODO(will): move these to cpu at some point
    self.get_module(&quot;image_encoder&quot;).to(get_local_torch_device())
    self.get_module(&quot;vae&quot;).to(get_local_torch_device())

    features = &#123;&#125;
    &quot;&quot;&quot;Get CLIP features from the first frame of each video.&quot;&quot;&quot;
    first_frame = valid_data&#91;&quot;pixel_values&quot;&#93;&#91;:, :, 0, :, :&#93;.permute(0, 2, 3, 1)  # (B, C, T, H, W) -&gt; (B, H, W, C)
    _, _, num_frames, height, width = valid_data&#91;&quot;pixel_values&quot;&#93;.shape
    # latent_height = height // self.get_module(
    #     &quot;vae&quot;).spatial_compression_ratio
    # latent_width = width // self.get_module(&quot;vae&quot;).spatial_compression_ratio

    processed_images = &#91;&#93;
    # Frame has values between -1 and 1
    for frame in first_frame:
        frame = (frame + 1) * 127.5
        frame_pil = Image.fromarray(frame.cpu().numpy().astype(np.uint8))
        processed_img = self.get_module(&quot;image_processor&quot;)(images=frame_pil, return_tensors=&quot;pt&quot;)
        processed_images.append(processed_img)

    # Get CLIP features
    pixel_values = torch.cat(&#91;img&#91;&#x27;pixel_values&#x27;&#93; for img in processed_images&#93;, dim=0).to(get_local_torch_device())
    with torch.no_grad():
        image_inputs = &#123;&#x27;pixel_values&#x27;: pixel_values&#125;
        with set_forward_context(current_timestep=0, attn_metadata=None):
            clip_features = self.get_module(&quot;image_encoder&quot;)(**image_inputs)
        clip_features = clip_features.last_hidden_state

    features&#91;&quot;clip_feature&quot;&#93; = clip_features
    features&#91;&quot;pil_image&quot;&#93; = first_frame
    # Get CLIP features from the first frame of each video.
    video_conditions = &#91;&#93;
    for frame in first_frame:
        processed_img = frame.to(device=&quot;cpu&quot;, dtype=torch.float32)
        processed_img = processed_img.unsqueeze(0).permute(0, 3, 1, 2).unsqueeze(2)
        # (B, H, W, C) -&gt; (B, C, 1, H, W)
        video_condition = torch.cat(&#91;
            processed_img,
            processed_img.new_zeros(processed_img.shape&#91;0&#93;, processed_img.shape&#91;1&#93;, num_frames - 1, height, width)
        &#93;,
                                    dim=2)
        video_condition = video_condition.to(device=get_local_torch_device(), dtype=torch.float32)
        video_conditions.append(video_condition)

    video_conditions = torch.cat(video_conditions, dim=0)

    with torch.autocast(device_type=&quot;cuda&quot;, dtype=torch.float32, enabled=True):
        encoder_outputs = self.get_module(&quot;vae&quot;).encode(video_conditions)

    # Use mode() instead of mean
    latent_condition = encoder_outputs.mode()

    # Use latents_mean/latents_std normalization to match
    vae = self.get_module(&quot;vae&quot;)
    if (hasattr(vae.config, &#x27;latents_mean&#x27;) and hasattr(vae.config, &#x27;latents_std&#x27;)):
        latents_mean = torch.tensor(vae.config.latents_mean,
                                    device=latent_condition.device,
                                    dtype=latent_condition.dtype).view(1, -1, 1, 1, 1)
        latents_std = torch.tensor(vae.config.latents_std,
                                   device=latent_condition.device,
                                   dtype=latent_condition.dtype).view(1, -1, 1, 1, 1)
        latent_condition = (latent_condition - latents_mean) / latents_std
    elif (hasattr(vae, &quot;shift_factor&quot;) and vae.shift_factor is not None):
        if isinstance(vae.shift_factor, torch.Tensor):
            latent_condition -= vae.shift_factor.to(latent_condition.device, latent_condition.dtype)
        else:
            latent_condition -= vae.shift_factor

        if isinstance(vae.scaling_factor, torch.Tensor):
            latent_condition = latent_condition * vae.scaling_factor.to(latent_condition.device,
                                                                        latent_condition.dtype)
        else:
            latent_condition = latent_condition * vae.scaling_factor

    # Create mask_cond: ones for first frame, zeros for rest
    # Shape: (B, 16, latent_frames, latent_height, latent_width)
    mask_cond = torch.ones_like(latent_condition)
    mask_cond&#91;:, :, 1:&#93; = 0  # Set all frames except first to 0
    # Create cond_concat: first 4 channels of mask + all 16 channels of img_cond
    # Shape: (B, 20, latent_frames, latent_height, latent_width)
    cond_concat = torch.cat(&#91;mask_cond&#91;:, :4&#93;, latent_condition&#93;, dim=1)
    features&#91;&quot;first_frame_latent&quot;&#93; = cond_concat

    if &quot;action_path&quot; in valid_data and valid_data&#91;&quot;action_path&quot;&#93;:
        keyboard_cond_list = &#91;&#93;
        mouse_cond_list = &#91;&#93;
        keyboard_dim = self.get_module(&quot;transformer&quot;).config.arch_config.action_config&#91;&quot;keyboard_dim_in&quot;&#93;
        for action_path in valid_data&#91;&quot;action_path&quot;&#93;:
            if action_path:
                action_data = np.load(action_path, allow_pickle=True)
                if isinstance(action_data, np.ndarray) and action_data.dtype == np.dtype(&#x27;O&#x27;):
                    action_dict = action_data.item()
                    if &quot;keyboard&quot; in action_dict:
                        keyboard_cond_list.append(action_dict&#91;&quot;keyboard&quot;&#93;&#91;:, :keyboard_dim&#93;.astype(np.float32))
                    if &quot;mouse&quot; in action_dict:
                        mouse_cond_list.append(action_dict&#91;&quot;mouse&quot;&#93;)
                else:
                    keyboard_cond_list.append(action_data&#91;:, :keyboard_dim&#93;.astype(np.float32))
        if keyboard_cond_list:
            features&#91;&quot;keyboard_cond&quot;&#93; = keyboard_cond_list
        if mouse_cond_list:
            features&#91;&quot;mouse_cond&quot;&#93; = mouse_cond_list
    return features</code></pre></details>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.preprocess_action_and_trajectory"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.preprocess_action_and_trajectory</code></h3>
<pre class="doc-signature"><code>preprocess_action_and_trajectory(fastvideo_args: FastVideoArgs, args)</code></pre>
<p>Preprocess data and generate trajectory information.</p>
<details><summary>Source</summary><pre><code>def preprocess_action_and_trajectory(self, fastvideo_args: FastVideoArgs, args):
    &quot;&quot;&quot;Preprocess data and generate trajectory information.&quot;&quot;&quot;

    for batch_idx, data in enumerate(self.pbar):
        if data is None:
            continue

        with torch.inference_mode():
            # Filter out invalid samples (those with all zeros)
            valid_indices = &#91;&#93;
            for i, pixel_values in enumerate(data&#91;&quot;pixel_values&quot;&#93;):
                if not torch.all(pixel_values == 0):  # Check if all values are zero
                    valid_indices.append(i)
            self.num_processed_samples += len(valid_indices)

            if not valid_indices:
                continue

            # Create new batch with only valid samples
            valid_data = &#123;
                &quot;pixel_values&quot;: torch.stack(&#91;data&#91;&quot;pixel_values&quot;&#93;&#91;i&#93; for i in valid_indices&#93;),
                &quot;path&quot;: &#91;data&#91;&quot;path&quot;&#93;&#91;i&#93; for i in valid_indices&#93;,
            &#125;

            if &quot;fps&quot; in data:
                valid_data&#91;&quot;fps&quot;&#93; = &#91;data&#91;&quot;fps&quot;&#93;&#91;i&#93; for i in valid_indices&#93;
            if &quot;duration&quot; in data:
                valid_data&#91;&quot;duration&quot;&#93; = &#91;data&#91;&quot;duration&quot;&#93;&#91;i&#93; for i in valid_indices&#93;
            if &quot;action_path&quot; in data:
                valid_data&#91;&quot;action_path&quot;&#93; = &#91;data&#91;&quot;action_path&quot;&#93;&#91;i&#93; for i in valid_indices&#93;

            pixel_values = valid_data&#91;&quot;pixel_values&quot;&#93;
            if pixel_values.shape&#91;2&#93; == 1 and args.num_frames is not None:
                pixel_values = pixel_values.repeat(1, 1, args.num_frames, 1, 1)
                valid_data&#91;&quot;pixel_values&quot;&#93; = pixel_values

            # Get extra features if needed
            extra_features = self.get_extra_features(valid_data, fastvideo_args)

            clip_features = extra_features&#91;&#x27;clip_feature&#x27;&#93;
            image_latents = extra_features&#91;&#x27;first_frame_latent&#x27;&#93;
            image_latents = image_latents&#91;:, :, :args.num_latent_t&#93;
            pil_image = extra_features&#91;&#x27;pil_image&#x27;&#93;
            keyboard_cond = extra_features.get(&#x27;keyboard_cond&#x27;)
            mouse_cond = extra_features.get(&#x27;mouse_cond&#x27;)

            sampling_params = SamplingParam.from_pretrained(args.model_path)

            trajectory_latents = &#91;&#93;
            trajectory_timesteps = &#91;&#93;
            trajectory_decoded = &#91;&#93;

            device = get_local_torch_device()
            for i in range(len(valid_indices)):
                # Collect the trajectory data
                batch = ForwardBatch(**shallow_asdict(sampling_params), )
                batch.image_embeds = &#91;clip_features&#91;i&#93;.unsqueeze(0)&#93;
                batch.image_latent = image_latents&#91;i&#93;.unsqueeze(0)
                batch.keyboard_cond = (torch.from_numpy(keyboard_cond&#91;i&#93;).unsqueeze(0).to(device)
                                       if keyboard_cond is not None else None)
                batch.mouse_cond = (torch.from_numpy(mouse_cond&#91;i&#93;).unsqueeze(0).to(device)
                                    if mouse_cond is not None else None)
                batch.num_inference_steps = 48
                batch.return_trajectory_latents = True
                # Enabling this will save the decoded trajectory videos.
                # Used for debugging.
                batch.return_trajectory_decoded = False
                batch.height = args.max_height
                batch.width = args.max_width
                batch.fps = args.train_fps
                batch.num_frames = valid_data&#91;&quot;pixel_values&quot;&#93;.shape&#91;2&#93;
                batch.guidance_scale = 6.0
                batch.do_classifier_free_guidance = False
                batch.prompt = &quot;&quot;

                result_batch = self.input_validation_stage(batch, fastvideo_args)
                result_batch = self.timestep_preparation_stage(batch, fastvideo_args)
                result_batch.timesteps = result_batch.timesteps.to(device)
                result_batch = self.latent_preparation_stage(result_batch, fastvideo_args)
                result_batch = self.denoising_stage(result_batch, fastvideo_args)
                result_batch = self.decoding_stage(result_batch, fastvideo_args)

                trajectory_latents.append(result_batch.trajectory_latents.cpu())
                trajectory_timesteps.append(result_batch.trajectory_timesteps.cpu())
                trajectory_decoded.append(result_batch.trajectory_decoded)

            # Prepare extra features
            extra_features = &#123;
                &quot;trajectory_latents&quot;: trajectory_latents,
                &quot;trajectory_timesteps&quot;: trajectory_timesteps
            &#125;

            if batch.return_trajectory_decoded:
                for i, decoded_frames in enumerate(trajectory_decoded):
                    for j, decoded_frame in enumerate(decoded_frames):
                        save_decoded_latents_as_video(decoded_frame,
                                                      f&quot;decoded_videos/trajectory_decoded_&#123;i&#125;_&#123;j&#125;.mp4&quot;,
                                                      args.train_fps)

            # Prepare batch data for Parquet dataset
            batch_data: list&#91;dict&#91;str, Any&#93;&#93; = &#91;&#93;

            # Add progress bar for saving outputs
            save_pbar = tqdm(enumerate(valid_data&#91;&quot;path&quot;&#93;), desc=&quot;Saving outputs&quot;, unit=&quot;item&quot;, leave=False)

            for idx, video_path in save_pbar:
                video_name = os.path.basename(video_path).split(&quot;.&quot;)&#91;0&#93;

                clip_feature_np = clip_features&#91;idx&#93;.cpu().numpy()
                first_frame_latent_np = image_latents&#91;idx&#93;.cpu().numpy()
                pil_image_np = pil_image&#91;idx&#93;.cpu().numpy()
                keyboard_cond_np = keyboard_cond&#91;idx&#93; if keyboard_cond is not None else None
                mouse_cond_np = mouse_cond&#91;idx&#93; if mouse_cond is not None else None

                # Get trajectory features for this sample
                traj_latents = extra_features&#91;&quot;trajectory_latents&quot;&#93;&#91;idx&#93;
                traj_timesteps = extra_features&#91;&quot;trajectory_timesteps&quot;&#93;&#91;idx&#93;
                if isinstance(traj_latents, torch.Tensor):
                    traj_latents = traj_latents.cpu().float().numpy()
                if isinstance(traj_timesteps, torch.Tensor):
                    traj_timesteps = traj_timesteps.cpu().float().numpy()

                # Create record for Parquet dataset
                record: dict&#91;str, Any&#93; = matrixgame2_ode_record_creator(video_name=video_name,
                                                                        clip_feature=clip_feature_np,
                                                                        first_frame_latent=first_frame_latent_np,
                                                                        trajectory_latents=traj_latents,
                                                                        trajectory_timesteps=traj_timesteps,
                                                                        pil_image=pil_image_np,
                                                                        keyboard_cond=keyboard_cond_np,
                                                                        mouse_cond=mouse_cond_np,
                                                                        caption=&quot;&quot;)
                batch_data.append(record)

            if batch_data:
                write_pbar = tqdm(total=1, desc=&quot;Writing to Parquet dataset&quot;, unit=&quot;batch&quot;)
                table = records_to_table(batch_data, self.get_pyarrow_schema())
                write_pbar.update(1)
                write_pbar.close()

                if not hasattr(self, &#x27;dataset_writer&#x27;):
                    self.dataset_writer = ParquetDatasetWriter(
                        out_dir=self.combined_parquet_dir,
                        samples_per_file=args.samples_per_file,
                    )
                self.dataset_writer.append_table(table)

                logger.info(&quot;Collected batch with %s samples&quot;, len(table))

            if self.num_processed_samples &gt;= args.flush_frequency:
                written = self.dataset_writer.flush()
                logger.info(&quot;Flushed %s samples to parquet&quot;, written)
                self.num_processed_samples = 0

    # Final flush for any remaining samples
    if hasattr(self, &#x27;dataset_writer&#x27;):
        written = self.dataset_writer.flush(write_remainder=True)
        if written:
            logger.info(&quot;Final flush wrote %s samples&quot;, written)</code></pre></details>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline_ode_trajectory.PreprocessPipeline_MatrixGame2_ODE_Trajectory.forward</code></h3>
<pre class="doc-signature"><code>forward(batch: ForwardBatch, fastvideo_args: FastVideoArgs, args)</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, batch: ForwardBatch, fastvideo_args: FastVideoArgs, args):
    if not self.post_init_called:
        self.post_init()

    self.local_rank = int(os.getenv(&quot;RANK&quot;, 0))
    os.makedirs(args.output_dir, exist_ok=True)
    # Create directory for combined data
    self.combined_parquet_dir = os.path.join(args.output_dir, &quot;combined_parquet_dataset&quot;)
    os.makedirs(self.combined_parquet_dir, exist_ok=True)

    # Loading dataset
    train_dataset = getdataset(args)

    self.preprocess_dataloader = DataLoader(
        train_dataset,
        batch_size=args.preprocess_video_batch_size,
        num_workers=args.dataloader_num_workers,
    )

    self.preprocess_loader_iter = iter(self.preprocess_dataloader)

    self.num_processed_samples = 0
    # Add progress bar for video preprocessing
    self.pbar = tqdm(self.preprocess_loader_iter,
                     desc=&quot;Processing videos&quot;,
                     unit=&quot;batch&quot;,
                     disable=self.local_rank != 0)

    # Initialize class variables for data sharing
    self.video_data: dict&#91;str, Any&#93; = &#123;&#125;  # Store video metadata and paths
    self.latent_data: dict&#91;str, Any&#93; = &#123;&#125;  # Store latent tensors
    self.preprocess_action_and_trajectory(fastvideo_args, args)</code></pre></details>
</div>
