Skip to content

[misc] update action loading in validation and preprocess#1143

Open
H1yori233 wants to merge 6 commits intohao-ai-lab:mainfrom
H1yori233:feat/kaiqin/action_loading
Open

[misc] update action loading in validation and preprocess#1143
H1yori233 wants to merge 6 commits intohao-ai-lab:mainfrom
H1yori233:feat/kaiqin/action_loading

Conversation

@H1yori233
Copy link
Contributor

  1. previous preprocessing is designed for footsies data, now it can be more generalized.
  2. robust process to make sure the length of action sequence is matched with num_frames.
  3. actions for validation should also loaded from files instead of being hardcoded.
  4. remove keyboard dim assert since we can have various keyboard dim

@gemini-code-assist
Copy link
Contributor

Summary of Changes

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

This pull request significantly enhances the flexibility and robustness of action data handling within the fastvideo project. It generalizes the loading and preprocessing of action sequences, moving away from hardcoded or game-specific assumptions. Key improvements include dynamic loading of action data for validation, rigorous length checks to ensure data integrity, and the removal of restrictive keyboard dimension validations, allowing for broader application of the system.

Highlights

  • Generalized Action Data Loading: Action data for validation is now loaded dynamically from files, rather than being hardcoded, enhancing flexibility for various data sources.
  • Robust Action Sequence Length Validation: Implemented robust checks to ensure that the length of loaded action sequences (keyboard and mouse) matches or exceeds the required num_frames, preventing data mismatches.
  • Simplified Action Preprocessing: The preprocessing pipeline for action data has been streamlined by removing specific bit-encoding logic and the num_bits constant, making it more generalized and less tied to specific data formats like 'footsies'.
  • Relaxed Keyboard Dimension Validation: The strict assertion on allowed keyboard_dim values has been removed, allowing for greater variability in keyboard input representations.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • fastvideo/dataset/validation_dataset.py
    • Imported numpy for array operations.
    • Implemented logic to load action data from action_path if available.
    • Added handling for action data stored as dictionaries (with 'keyboard' and 'mouse' keys) or direct arrays.
    • Introduced assertions to verify that keyboard and mouse action lengths are sufficient for num_frames.
    • Sliced loaded action data to match the num_frames length.
  • fastvideo/pipelines/preprocess/matrixgame/matrixgame_preprocess_pipeline.py
    • Removed the num_bits variable, which was specific to a previous encoding scheme.
    • Eliminated the complex multi-hot encoding conversion logic for keyboard data.
    • Added assertions to ensure keyboard and mouse action lengths are sufficient for num_frames.
    • Simplified the process of appending keyboard and mouse conditions, directly slicing to num_frames and casting to float32.
  • fastvideo/pipelines/stages/input_validation.py
    • Removed the assertion that restricted keyboard_dim to a predefined set of values ({2, 3, 4, 6, 7}).
Using Gemini Code Assist

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

Invoking Gemini

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

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

Customization

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

Limitations & Feedback

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

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

Footnotes

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

Copy link
Contributor

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

Choose a reason for hiding this comment

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

Code Review

This pull request updates the action loading mechanism in validation and preprocessing to be more generalized and robust. The changes ensure that the action sequence length matches the number of frames and removes a hardcoded assertion on keyboard dimensions. My review focuses on further improving the robustness of the data validation logic. I've suggested replacing assert statements with ValueError exceptions for data validation checks and adding checks for key existence before accessing dictionary elements to prevent potential KeyError exceptions. These improvements will make the data loading process more resilient to unexpected or malformed data.

Comment on lines +177 to +193
if isinstance(action_data, dict):
kb_length = len(action_data["keyboard"])
ms_length = len(action_data["mouse"])
assert kb_length >= num_frames, (
f"keyboard length {kb_length} is smaller than "
f"num_frames {num_frames} for {action_path}.")
assert ms_length >= num_frames, (
f"mouse length {ms_length} is smaller than "
f"num_frames {num_frames} for {action_path}.")
sample["keyboard_cond"] = action_data["keyboard"][:num_frames]
sample["mouse_cond"] = action_data["mouse"][:num_frames]
else:
kb_length = len(action_data)
assert kb_length >= num_frames, (
f"keyboard length {kb_length} is smaller than "
f"num_frames {num_frames} for {action_path}.")
sample["keyboard_cond"] = action_data[:num_frames]
Copy link
Contributor

Choose a reason for hiding this comment

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

high

This block has two issues that affect its robustness:

  1. Unsafe Dictionary Access: It directly accesses action_data["keyboard"] and action_data["mouse"] without first checking if these keys exist. This will raise a KeyError if the action data dictionary is missing one of these keys, crashing the data loading process.
  2. Non-Robust Validation: It uses assert for data validation. Assertions can be disabled in Python with the -O flag, which would cause these critical length checks to be skipped in optimized runs, potentially leading to silent errors downstream.

To make this code more robust, I suggest checking for key existence before access and using ValueError for validation, which is always active.

                    if isinstance(action_data, dict):
                        if "keyboard" in action_data:
                            kb_data = action_data["keyboard"]
                            if len(kb_data) < num_frames:
                                raise ValueError(
                                    f"keyboard length {len(kb_data)} is smaller than "
                                    f"num_frames {num_frames} for {action_path}.")
                            sample["keyboard_cond"] = kb_data[:num_frames]
                        if "mouse" in action_data:
                            ms_data = action_data["mouse"]
                            if len(ms_data) < num_frames:
                                raise ValueError(
                                    f"mouse length {len(ms_data)} is smaller than "
                                    f"num_frames {num_frames} for {action_path}.")
                            sample["mouse_cond"] = ms_data[:num_frames]
                    else:
                        if len(action_data) < num_frames:
                            raise ValueError(
                                f"keyboard length {len(action_data)} is smaller than "
                                f"num_frames {num_frames} for {action_path}.")
                        sample["keyboard_cond"] = action_data[:num_frames]

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm not sure if this makes sense.

Comment on lines +142 to +163
if "keyboard" in action_dict:
keyboard_raw = action_dict["keyboard"]
# Convert 1D bit-flag values to 2D multi-hot encoding
if isinstance(keyboard_raw, np.ndarray):
if keyboard_raw.ndim == 1:
# [T] -> [T, num_bits]
T = len(keyboard_raw)
multi_hot = np.zeros((T, num_bits),
dtype=np.float32)
action_values = keyboard_raw.astype(int)
for bit_idx in range(num_bits):
target_idx = (
2 -
(bit_idx % 3)) + 3 * (bit_idx // 3)
if target_idx < num_bits:
multi_hot[:, target_idx] = (
(action_values >> bit_idx)
& 1).astype(np.float32)
keyboard_cond_list.append(multi_hot)
else:
# If already 2D, pad to num_bits if necessary
k_data = keyboard_raw.astype(np.float32)
if k_data.ndim == 2 and k_data.shape[
-1] < num_bits:
padding = np.zeros(
(k_data.shape[0],
num_bits - k_data.shape[-1]),
dtype=np.float32)
k_data = np.concatenate(
[k_data, padding], axis=-1)
keyboard_cond_list.append(k_data)
else:
keyboard_cond_list.append(keyboard_raw)
kb_length = len(action_dict["keyboard"])
assert kb_length >= num_frames, (
f"keyboard length {kb_length} is smaller than "
f"num_frames {num_frames} for {action_path}.")
keyboard_cond_list.append(
action_dict["keyboard"][:num_frames].astype(
np.float32))
if "mouse" in action_dict:
mouse_cond_list.append(action_dict["mouse"])
ms_length = len(action_dict["mouse"])
assert ms_length >= num_frames, (
f"mouse length {ms_length} is smaller than "
f"num_frames {num_frames} for {action_path}.")
mouse_cond_list.append(
action_dict["mouse"][:num_frames])
else:
if isinstance(action_data,
np.ndarray) and action_data.ndim == 1:
T = len(action_data)
multi_hot = np.zeros((T, num_bits),
dtype=np.float32)
action_values = action_data.astype(int)
for bit_idx in range(num_bits):
target_idx = (
2 - (bit_idx % 3)) + 3 * (bit_idx // 3)
if target_idx < num_bits:
multi_hot[:, target_idx] = (
(action_values >> bit_idx) & 1).astype(
np.float32)
keyboard_cond_list.append(multi_hot)
else:
# If already 2D, pad to num_bits if necessary
k_data = action_data.astype(np.float32)
if k_data.ndim == 2 and k_data.shape[-1] < num_bits:
padding = np.zeros(
(k_data.shape[0],
num_bits - k_data.shape[-1]),
dtype=np.float32)
k_data = np.concatenate([k_data, padding],
axis=-1)
keyboard_cond_list.append(k_data)
kb_length = len(action_data)
assert kb_length >= num_frames, (
f"keyboard length {kb_length} is smaller than "
f"num_frames {num_frames} for {action_path}.")
keyboard_cond_list.append(
action_data.astype(np.float32)[:num_frames])
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Using assert for data validation is not robust, as assertions can be disabled with Python's -O flag. This could lead to silent failures or incorrect behavior if the action data has an unexpected length. It's safer to raise a ValueError for invalid data to ensure the check is always performed. The suggested change replaces all assert statements in this block with explicit ValueError checks.

                        if "keyboard" in action_dict:
                            kb_data = action_dict["keyboard"]
                            if len(kb_data) < num_frames:
                                raise ValueError(
                                    f"keyboard length {len(kb_data)} is smaller than "
                                    f"num_frames {num_frames} for {action_path}.")
                            keyboard_cond_list.append(
                                kb_data[:num_frames].astype(
                                    np.float32))
                        if "mouse" in action_dict:
                            ms_data = action_dict["mouse"]
                            if len(ms_data) < num_frames:
                                raise ValueError(
                                    f"mouse length {len(ms_data)} is smaller than "
                                    f"num_frames {num_frames} for {action_path}.")
                            mouse_cond_list.append(ms_data[:num_frames])
                    else:
                        if len(action_data) < num_frames:
                            raise ValueError(
                                f"keyboard length {len(action_data)} is smaller than "
                                f"num_frames {num_frames} for {action_path}.")
                        keyboard_cond_list.append(
                            action_data.astype(np.float32)[:num_frames])

Copy link
Contributor Author

Choose a reason for hiding this comment

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

same

@jzhang38 jzhang38 added the go Trigger Buildkite CI label Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Trigger Buildkite CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants