---
title: matrixgame2_preprocess_pipeline
---

<div class="python-reference">
<a id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline-classes"></a>
<a id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline-functions"></a>
<a id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2-functions"></a>
<a id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline"></a>

<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.get_local_torch_device"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.FastVideoArgs"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.FastVideoArgs.is_output_rank"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.FastVideoArgs.add_cli_args"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.FastVideoArgs.from_cli_args"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.FastVideoArgs.from_kwargs"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.FastVideoArgs.check_fastvideo_args"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.FastVideoArgs.finalize_device_offload_policy"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.FastVideoArgs.disable_offload_on_unified_memory"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.set_forward_context"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.BasePreprocessPipeline"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.BasePreprocessPipeline.create_pipeline_stages"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.BasePreprocessPipeline.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.BasePreprocessPipeline.get_extra_features"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.BasePreprocessPipeline.get_pyarrow_schema"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.BasePreprocessPipeline.get_schema_fields"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.BasePreprocessPipeline.create_record_for_schema"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.BasePreprocessPipeline.create_record"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.BasePreprocessPipeline.preprocess_video_and_text"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.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.ImageEncodingStage"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.ImageEncodingStage</code></h2>
<pre class="doc-signature"><code>ImageEncodingStage(image_encoder, image_processor)</code></pre>
<p>Stage for encoding image prompts into embeddings for diffusion models.</p>
<p>This stage handles the encoding of image prompts into the embedding space
expected by the diffusion model.</p>
<p>Initialize the prompt encoding stage.</p>
<h3>Parameters</h3>
<dl>
<dt><code>enable_logging</code></dt><dd><p>Whether to enable logging for this stage.</p></dd>
<dt><code>is_secondary</code></dt><dd><p>Whether this is a secondary image encoder.</p></dd>
</dl>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.ImageEncodingStage.forward"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.ImageEncodingStage.forward</code></h3>
<pre class="doc-signature"><code>forward(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; ForwardBatch</code></pre>
<p>Encode the prompt into image encoder hidden states.</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 encoded prompt embeddings.</p></dd>
</dl>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.ImageEncodingStage.verify_input"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.ImageEncodingStage.verify_input</code></h3>
<pre class="doc-signature"><code>verify_input(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify image encoding stage inputs.</p>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.ImageEncodingStage.verify_output"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.ImageEncodingStage.verify_output</code></h3>
<pre class="doc-signature"><code>verify_output(batch: ForwardBatch, fastvideo_args: FastVideoArgs) -&gt; VerificationResult</code></pre>
<p>Verify image encoding stage outputs.</p>
<h2 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2</code></h2>
<pre class="doc-signature"><code>PreprocessPipeline_MatrixGame2(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>I2V preprocessing pipeline implementation.</p>
<details><summary>Source</summary><pre><code>class PreprocessPipeline_MatrixGame2(BasePreprocessPipeline):
    &quot;&quot;&quot;I2V preprocessing pipeline implementation.&quot;&quot;&quot;

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

    def create_pipeline_stages(self, fastvideo_args: FastVideoArgs):
        self.add_stage(stage_name=&quot;image_encoding_stage&quot;,
                       stage=ImageEncodingStage(
                           image_encoder=self.get_module(&quot;image_encoder&quot;),
                           image_processor=self.get_module(&quot;image_processor&quot;),
                       ))

    def get_pyarrow_schema(self):
        &quot;&quot;&quot;Return the PyArrow schema for I2V pipeline.&quot;&quot;&quot;
        return pyarrow_schema_matrixgame2

    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
        # 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)

        latent_condition = encoder_outputs.mean
        if (hasattr(self.get_module(&quot;vae&quot;), &quot;shift_factor&quot;) and self.get_module(&quot;vae&quot;).shift_factor is not None):
            if isinstance(self.get_module(&quot;vae&quot;).shift_factor, torch.Tensor):
                latent_condition -= self.get_module(&quot;vae&quot;).shift_factor.to(latent_condition.device,
                                                                           latent_condition.dtype)
            else:
                latent_condition -= self.get_module(&quot;vae&quot;).shift_factor

        if isinstance(self.get_module(&quot;vae&quot;).scaling_factor, torch.Tensor):
            latent_condition = latent_condition * self.get_module(&quot;vae&quot;).scaling_factor.to(
                latent_condition.device, latent_condition.dtype)
        else:
            latent_condition = latent_condition * self.get_module(&quot;vae&quot;).scaling_factor

        # mask_lat_size = torch.ones(batch_size, 1, num_frames, latent_height,
        #                            latent_width)
        # mask_lat_size&#91;:, :, list(range(1, num_frames))&#93; = 0
        # first_frame_mask = mask_lat_size&#91;:, :, 0:1&#93;
        # first_frame_mask = torch.repeat_interleave(
        #     first_frame_mask,
        #     dim=2,
        #     repeats=self.get_module(&quot;vae&quot;).temporal_compression_ratio)
        # mask_lat_size = torch.concat(
        #     &#91;first_frame_mask, mask_lat_size&#91;:, :, 1:, :&#93;&#93;, dim=2)
        # mask_lat_size = mask_lat_size.view(
        #     batch_size, -1,
        #     self.get_module(&quot;vae&quot;).temporal_compression_ratio, latent_height,
        #     latent_width)
        # mask_lat_size = mask_lat_size.transpose(1, 2)
        # mask_lat_size = mask_lat_size.to(latent_condition.device)

        # image_latent = torch.concat(&#91;mask_lat_size, latent_condition&#93;, dim=1)

        features&#91;&quot;first_frame_latent&quot;&#93; = latent_condition

        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;
            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:
                            kb_length = len(action_dict&#91;&quot;keyboard&quot;&#93;)
                            assert kb_length &gt;= num_frames, (f&quot;keyboard length &#123;kb_length&#125; is smaller than &quot;
                                                             f&quot;num_frames &#123;num_frames&#125; for &#123;action_path&#125;.&quot;)
                            keyboard_cond_list.append(action_dict&#91;&quot;keyboard&quot;&#93;&#91;:num_frames&#93;.astype(np.float32))
                        if &quot;mouse&quot; in action_dict:
                            ms_length = len(action_dict&#91;&quot;mouse&quot;&#93;)
                            assert ms_length &gt;= num_frames, (f&quot;mouse length &#123;ms_length&#125; is smaller than &quot;
                                                             f&quot;num_frames &#123;num_frames&#125; for &#123;action_path&#125;.&quot;)
                            mouse_cond_list.append(action_dict&#91;&quot;mouse&quot;&#93;&#91;:num_frames&#93;)
                    else:
                        kb_length = len(action_data)
                        assert kb_length &gt;= num_frames, (f&quot;keyboard length &#123;kb_length&#125; is smaller than &quot;
                                                         f&quot;num_frames &#123;num_frames&#125; for &#123;action_path&#125;.&quot;)
                        keyboard_cond_list.append(action_data.astype(np.float32)&#91;:num_frames&#93;)
            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 create_record(self,
                      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;:
        &quot;&quot;&quot;Create a record for the Parquet dataset with CLIP features.&quot;&quot;&quot;
        record = super().create_record(video_name=video_name,
                                       vae_latent=vae_latent,
                                       text_embedding=text_embedding,
                                       valid_data=valid_data,
                                       idx=idx,
                                       extra_features=extra_features)

        if extra_features and &quot;clip_feature&quot; in extra_features:
            clip_feature = extra_features&#91;&quot;clip_feature&quot;&#93;
            record.update(&#123;
                &quot;clip_feature_bytes&quot;: clip_feature.tobytes(),
                &quot;clip_feature_shape&quot;: list(clip_feature.shape),
                &quot;clip_feature_dtype&quot;: str(clip_feature.dtype),
            &#125;)
        else:
            record.update(&#123;
                &quot;clip_feature_bytes&quot;: b&quot;&quot;,
                &quot;clip_feature_shape&quot;: &#91;&#93;,
                &quot;clip_feature_dtype&quot;: &quot;&quot;,
            &#125;)

        if extra_features and &quot;first_frame_latent&quot; in extra_features:
            first_frame_latent = extra_features&#91;&quot;first_frame_latent&quot;&#93;
            record.update(&#123;
                &quot;first_frame_latent_bytes&quot;: first_frame_latent.tobytes(),
                &quot;first_frame_latent_shape&quot;: list(first_frame_latent.shape),
                &quot;first_frame_latent_dtype&quot;: str(first_frame_latent.dtype),
            &#125;)
        else:
            record.update(&#123;
                &quot;first_frame_latent_bytes&quot;: b&quot;&quot;,
                &quot;first_frame_latent_shape&quot;: &#91;&#93;,
                &quot;first_frame_latent_dtype&quot;: &quot;&quot;,
            &#125;)

        if extra_features and &quot;pil_image&quot; in extra_features:
            pil_image = extra_features&#91;&quot;pil_image&quot;&#93;
            record.update(&#123;
                &quot;pil_image_bytes&quot;: pil_image.tobytes(),
                &quot;pil_image_shape&quot;: list(pil_image.shape),
                &quot;pil_image_dtype&quot;: str(pil_image.dtype),
            &#125;)
        else:
            record.update(&#123;
                &quot;pil_image_bytes&quot;: b&quot;&quot;,
                &quot;pil_image_shape&quot;: &#91;&#93;,
                &quot;pil_image_dtype&quot;: &quot;&quot;,
            &#125;)

        if extra_features and &quot;keyboard_cond&quot; in extra_features:
            keyboard_cond = extra_features&#91;&quot;keyboard_cond&quot;&#93;
            record.update(&#123;
                &quot;keyboard_cond_bytes&quot;: keyboard_cond.tobytes(),
                &quot;keyboard_cond_shape&quot;: list(keyboard_cond.shape),
                &quot;keyboard_cond_dtype&quot;: str(keyboard_cond.dtype),
            &#125;)
        else:
            record.update(&#123;
                &quot;keyboard_cond_bytes&quot;: b&quot;&quot;,
                &quot;keyboard_cond_shape&quot;: &#91;&#93;,
                &quot;keyboard_cond_dtype&quot;: &quot;&quot;,
            &#125;)

        if extra_features and &quot;mouse_cond&quot; in extra_features:
            mouse_cond = extra_features&#91;&quot;mouse_cond&quot;&#93;
            record.update(&#123;
                &quot;mouse_cond_bytes&quot;: mouse_cond.tobytes(),
                &quot;mouse_cond_shape&quot;: list(mouse_cond.shape),
                &quot;mouse_cond_dtype&quot;: str(mouse_cond.dtype),
            &#125;)
        else:
            record.update(&#123;
                &quot;mouse_cond_bytes&quot;: b&quot;&quot;,
                &quot;mouse_cond_shape&quot;: &#91;&#93;,
                &quot;mouse_cond_dtype&quot;: &quot;&quot;,
            &#125;)

        return record</code></pre></details>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2.create_pipeline_stages"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2.create_pipeline_stages</code></h3>
<pre class="doc-signature"><code>create_pipeline_stages(fastvideo_args: FastVideoArgs)</code></pre>

<details><summary>Source</summary><pre><code>def create_pipeline_stages(self, fastvideo_args: FastVideoArgs):
    self.add_stage(stage_name=&quot;image_encoding_stage&quot;,
                   stage=ImageEncodingStage(
                       image_encoder=self.get_module(&quot;image_encoder&quot;),
                       image_processor=self.get_module(&quot;image_processor&quot;),
                   ))</code></pre></details>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2.get_pyarrow_schema"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2.get_pyarrow_schema</code></h3>
<pre class="doc-signature"><code>get_pyarrow_schema()</code></pre>
<p>Return the PyArrow schema for I2V pipeline.</p>
<details><summary>Source</summary><pre><code>def get_pyarrow_schema(self):
    &quot;&quot;&quot;Return the PyArrow schema for I2V pipeline.&quot;&quot;&quot;
    return pyarrow_schema_matrixgame2</code></pre></details>
<h3 id="fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2.get_extra_features"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2.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
    # 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)

    latent_condition = encoder_outputs.mean
    if (hasattr(self.get_module(&quot;vae&quot;), &quot;shift_factor&quot;) and self.get_module(&quot;vae&quot;).shift_factor is not None):
        if isinstance(self.get_module(&quot;vae&quot;).shift_factor, torch.Tensor):
            latent_condition -= self.get_module(&quot;vae&quot;).shift_factor.to(latent_condition.device,
                                                                       latent_condition.dtype)
        else:
            latent_condition -= self.get_module(&quot;vae&quot;).shift_factor

    if isinstance(self.get_module(&quot;vae&quot;).scaling_factor, torch.Tensor):
        latent_condition = latent_condition * self.get_module(&quot;vae&quot;).scaling_factor.to(
            latent_condition.device, latent_condition.dtype)
    else:
        latent_condition = latent_condition * self.get_module(&quot;vae&quot;).scaling_factor

    # mask_lat_size = torch.ones(batch_size, 1, num_frames, latent_height,
    #                            latent_width)
    # mask_lat_size&#91;:, :, list(range(1, num_frames))&#93; = 0
    # first_frame_mask = mask_lat_size&#91;:, :, 0:1&#93;
    # first_frame_mask = torch.repeat_interleave(
    #     first_frame_mask,
    #     dim=2,
    #     repeats=self.get_module(&quot;vae&quot;).temporal_compression_ratio)
    # mask_lat_size = torch.concat(
    #     &#91;first_frame_mask, mask_lat_size&#91;:, :, 1:, :&#93;&#93;, dim=2)
    # mask_lat_size = mask_lat_size.view(
    #     batch_size, -1,
    #     self.get_module(&quot;vae&quot;).temporal_compression_ratio, latent_height,
    #     latent_width)
    # mask_lat_size = mask_lat_size.transpose(1, 2)
    # mask_lat_size = mask_lat_size.to(latent_condition.device)

    # image_latent = torch.concat(&#91;mask_lat_size, latent_condition&#93;, dim=1)

    features&#91;&quot;first_frame_latent&quot;&#93; = latent_condition

    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;
        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:
                        kb_length = len(action_dict&#91;&quot;keyboard&quot;&#93;)
                        assert kb_length &gt;= num_frames, (f&quot;keyboard length &#123;kb_length&#125; is smaller than &quot;
                                                         f&quot;num_frames &#123;num_frames&#125; for &#123;action_path&#125;.&quot;)
                        keyboard_cond_list.append(action_dict&#91;&quot;keyboard&quot;&#93;&#91;:num_frames&#93;.astype(np.float32))
                    if &quot;mouse&quot; in action_dict:
                        ms_length = len(action_dict&#91;&quot;mouse&quot;&#93;)
                        assert ms_length &gt;= num_frames, (f&quot;mouse length &#123;ms_length&#125; is smaller than &quot;
                                                         f&quot;num_frames &#123;num_frames&#125; for &#123;action_path&#125;.&quot;)
                        mouse_cond_list.append(action_dict&#91;&quot;mouse&quot;&#93;&#91;:num_frames&#93;)
                else:
                    kb_length = len(action_data)
                    assert kb_length &gt;= num_frames, (f&quot;keyboard length &#123;kb_length&#125; is smaller than &quot;
                                                     f&quot;num_frames &#123;num_frames&#125; for &#123;action_path&#125;.&quot;)
                    keyboard_cond_list.append(action_data.astype(np.float32)&#91;:num_frames&#93;)
        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.PreprocessPipeline_MatrixGame2.create_record"><code>fastvideo.pipelines.preprocess.matrixgame2.matrixgame2_preprocess_pipeline.PreprocessPipeline_MatrixGame2.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 with CLIP features.</p>
<details><summary>Source</summary><pre><code>def create_record(self,
                  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;:
    &quot;&quot;&quot;Create a record for the Parquet dataset with CLIP features.&quot;&quot;&quot;
    record = super().create_record(video_name=video_name,
                                   vae_latent=vae_latent,
                                   text_embedding=text_embedding,
                                   valid_data=valid_data,
                                   idx=idx,
                                   extra_features=extra_features)

    if extra_features and &quot;clip_feature&quot; in extra_features:
        clip_feature = extra_features&#91;&quot;clip_feature&quot;&#93;
        record.update(&#123;
            &quot;clip_feature_bytes&quot;: clip_feature.tobytes(),
            &quot;clip_feature_shape&quot;: list(clip_feature.shape),
            &quot;clip_feature_dtype&quot;: str(clip_feature.dtype),
        &#125;)
    else:
        record.update(&#123;
            &quot;clip_feature_bytes&quot;: b&quot;&quot;,
            &quot;clip_feature_shape&quot;: &#91;&#93;,
            &quot;clip_feature_dtype&quot;: &quot;&quot;,
        &#125;)

    if extra_features and &quot;first_frame_latent&quot; in extra_features:
        first_frame_latent = extra_features&#91;&quot;first_frame_latent&quot;&#93;
        record.update(&#123;
            &quot;first_frame_latent_bytes&quot;: first_frame_latent.tobytes(),
            &quot;first_frame_latent_shape&quot;: list(first_frame_latent.shape),
            &quot;first_frame_latent_dtype&quot;: str(first_frame_latent.dtype),
        &#125;)
    else:
        record.update(&#123;
            &quot;first_frame_latent_bytes&quot;: b&quot;&quot;,
            &quot;first_frame_latent_shape&quot;: &#91;&#93;,
            &quot;first_frame_latent_dtype&quot;: &quot;&quot;,
        &#125;)

    if extra_features and &quot;pil_image&quot; in extra_features:
        pil_image = extra_features&#91;&quot;pil_image&quot;&#93;
        record.update(&#123;
            &quot;pil_image_bytes&quot;: pil_image.tobytes(),
            &quot;pil_image_shape&quot;: list(pil_image.shape),
            &quot;pil_image_dtype&quot;: str(pil_image.dtype),
        &#125;)
    else:
        record.update(&#123;
            &quot;pil_image_bytes&quot;: b&quot;&quot;,
            &quot;pil_image_shape&quot;: &#91;&#93;,
            &quot;pil_image_dtype&quot;: &quot;&quot;,
        &#125;)

    if extra_features and &quot;keyboard_cond&quot; in extra_features:
        keyboard_cond = extra_features&#91;&quot;keyboard_cond&quot;&#93;
        record.update(&#123;
            &quot;keyboard_cond_bytes&quot;: keyboard_cond.tobytes(),
            &quot;keyboard_cond_shape&quot;: list(keyboard_cond.shape),
            &quot;keyboard_cond_dtype&quot;: str(keyboard_cond.dtype),
        &#125;)
    else:
        record.update(&#123;
            &quot;keyboard_cond_bytes&quot;: b&quot;&quot;,
            &quot;keyboard_cond_shape&quot;: &#91;&#93;,
            &quot;keyboard_cond_dtype&quot;: &quot;&quot;,
        &#125;)

    if extra_features and &quot;mouse_cond&quot; in extra_features:
        mouse_cond = extra_features&#91;&quot;mouse_cond&quot;&#93;
        record.update(&#123;
            &quot;mouse_cond_bytes&quot;: mouse_cond.tobytes(),
            &quot;mouse_cond_shape&quot;: list(mouse_cond.shape),
            &quot;mouse_cond_dtype&quot;: str(mouse_cond.dtype),
        &#125;)
    else:
        record.update(&#123;
            &quot;mouse_cond_bytes&quot;: b&quot;&quot;,
            &quot;mouse_cond_shape&quot;: &#91;&#93;,
            &quot;mouse_cond_dtype&quot;: &quot;&quot;,
        &#125;)

    return record</code></pre></details>
</div>
