diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/flowcache_physicsiq.sh b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/flowcache_physicsiq.sh new file mode 100644 index 0000000000000000000000000000000000000000..a8fe190bf2ae65452378348a8869b65fce40c4b0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/flowcache_physicsiq.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +# FlowCache PhysicsIQ sampling script +# Usage: bash flowcache_physicsiq.sh [yaml_config_path] +# Default config: yaml_config/sample/flowcache_physicsiq.yaml + +export DEVICES="0,1,2,3,4" + +export XDG_CACHE_HOME="/path/to/tmp" + +export PAD_HQ=1 +export PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +export MAGI_ROOT="$MAGI_ROOT" + +# YAML config file path (can be overridden via command line argument) +YAML_CONFIG="${1:-yaml_config/sample/flowcache_physicsiq.yaml}" + +if [ ! -f "$YAML_CONFIG" ]; then + echo "❌ YAML config file not found: $YAML_CONFIG" + exit 1 +fi + +echo "📋 Using YAML config: $YAML_CONFIG" + +# Create log directory +LOG_DIR="./logs" +mkdir -p "$LOG_DIR" +LOG_FILE="$LOG_DIR/flowcache_physicsiq_$(date +%Y%m%d_%H%M%S).log" +exec > >(tee -a "$LOG_FILE") 2>&1 + +echo "🚀 Starting multi-GPU benchmark sampling" +echo "🎮 GPUs: $DEVICES" + +# Run sampling +python sample_video.py "$YAML_CONFIG" + +if [ $? -eq 0 ]; then + echo "✅ Sampling completed successfully." +else + echo "❌ Sampling failed. Check log: $LOG_FILE" + exit 1 +fi + +echo "---" +echo "🎉 All sampling tasks completed." diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/flowcache_vbench.sh b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/flowcache_vbench.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a125d1e2e7de9de388d6b7e8bb4bd79e2b30772 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/flowcache_vbench.sh @@ -0,0 +1,83 @@ +#!/bin/bash + +# FlowCache VBench sampling script +# Usage: bash flowcache_vbench.sh [yaml_config_path] +# Default config: yaml_config/sample/flowcache_vbench.yaml + +export DEVICES="1,3,4,6" + +export PAD_HQ=1 +export PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +export MAGI_ROOT="$MAGI_ROOT" + +# YAML config file path (can be overridden via command line argument) +YAML_CONFIG="${1:-yaml_config/sample/flowcache_vbench.yaml}" + +if [ ! -f "$YAML_CONFIG" ]; then + echo "❌ YAML config file not found: $YAML_CONFIG" + exit 1 +fi + +echo "📋 Using YAML config: $YAML_CONFIG" + +# Create log directory +LOG_DIR="./logs" +mkdir -p "$LOG_DIR" +LOG_FILE="$LOG_DIR/flowcache_vbench_$(date +%Y%m%d_%H%M%S).log" +exec > >(tee -a "$LOG_FILE") 2>&1 + +echo "🚀 Starting multi-GPU benchmark sampling" +echo "🎮 GPUs: $DEVICES" + +# Define list of dimensions to process +DIMENSIONS=("overall_consistency" "subject_consistency" "scene") + +echo "🔢 Total dimensions to process: ${#DIMENSIONS[@]}" +echo "📋 Dimensions: ${DIMENSIONS[*]}" + +# Loop through each dimension +for DIMENSION in "${DIMENSIONS[@]}"; do + echo "🔍 Processing dimension: $DIMENSION" + + # Use Python to temporarily modify the dimension in YAML, then run sampling + python3 -c " +import yaml +import sys + +# Read YAML config +with open('$YAML_CONFIG', 'r') as f: + config = yaml.safe_load(f) + +# Modify dimension +config['dimension'] = '$DIMENSION' + +# Save to temporary file +temp_config = '$YAML_CONFIG.tmp' +with open(temp_config, 'w') as f: + yaml.dump(config, f, default_flow_style=False) +print(temp_config) +" > /tmp/temp_config_path.txt + + TEMP_CONFIG=$(cat /tmp/temp_config_path.txt) + python sample_video.py "$TEMP_CONFIG" + rm "$TEMP_CONFIG" + + if [ $? -eq 0 ]; then + echo "✅ Completed: $DIMENSION" + else + echo "❌ Failed: $DIMENSION" + echo "🛑 Script paused due to error. Fix the issue and rerun." + exit 1 + fi + + echo "---" +done + +echo "🎉 All sampling tasks completed." diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/teacache_physicsiq.sh b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/teacache_physicsiq.sh new file mode 100644 index 0000000000000000000000000000000000000000..d4d0ffc2ce5fe7c329ff0cb766d56a28d6b289b4 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/teacache_physicsiq.sh @@ -0,0 +1,53 @@ +#!/bin/bash + +# TeaCache PhysicsIQ sampling script +# Usage: bash teacache_physicsiq.sh [yaml_config_path] +# Default config: yaml_config/sample/teacache_physicsiq.yaml + +export DEVICES="0,1,2,3,4,5,6,7" + +export PAD_HQ=1 +export PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +export MAGI_ROOT="$MAGI_ROOT" + +export XDG_CACHE_HOME="/path/to/tmp" +mkdir -p "$XDG_CACHE_HOME" + +# YAML config file path (can be overridden via command line argument) +YAML_CONFIG="${1:-yaml_config/sample/teacache_physicsiq.yaml}" + +if [ ! -f "$YAML_CONFIG" ]; then + echo "❌ YAML config file not found: $YAML_CONFIG" + exit 1 +fi + +echo "📋 Using YAML config: $YAML_CONFIG" + +# Create log directory +LOG_DIR="./logs" +mkdir -p "$LOG_DIR" +LOG_FILE="$LOG_DIR/teacache_physicsiq_$(date +%Y%m%d_%H%M%S).log" +exec > >(tee -a "$LOG_FILE") 2>&1 + +echo "🚀 Starting multi-GPU benchmark sampling" +echo "🎮 GPUs: $DEVICES" + +# Run sampling +python sample_video.py "$YAML_CONFIG" + +if [ $? -eq 0 ]; then + echo "✅ Sampling completed successfully." +else + echo "❌ Sampling failed. Check log: $LOG_FILE" + exit 1 +fi + +echo "---" +echo "🎉 All sampling tasks completed." diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/teacache_vbench.sh b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/teacache_vbench.sh new file mode 100644 index 0000000000000000000000000000000000000000..196d31a912ad4f83040091376e2032e9c78f0dab --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/sample/teacache_vbench.sh @@ -0,0 +1,82 @@ +#!/bin/bash + +# TeaCache VBench sampling script +# Usage: bash teacache_vbench.sh [yaml_config_path] +# Default config: yaml_config/sample/teacache_vbench.yaml + +export DEVICES="4,5,7" + +export PAD_HQ=1 +export PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +export MAGI_ROOT="$MAGI_ROOT" + +# YAML config file path (can be overridden via command line argument) +YAML_CONFIG="${1:-yaml_config/sample/teacache_vbench.yaml}" + +if [ ! -f "$YAML_CONFIG" ]; then + echo "❌ YAML config file not found: $YAML_CONFIG" + exit 1 +fi + +echo "📋 Using YAML config: $YAML_CONFIG" + +# Create log directory +LOG_DIR="./logs" +mkdir -p "$LOG_DIR" +LOG_FILE="$LOG_DIR/teacache_vbench_$(date +%Y%m%d_%H%M%S).log" +exec > >(tee -a "$LOG_FILE") 2>&1 + +echo "🚀 Starting multi-GPU benchmark sampling" +echo "🎮 GPUs: $DEVICES" + +# Define list of dimensions to process +DIMENSIONS=("overall_consistency" "subject_consistency" "scene") + +echo "🔢 Total dimensions to process: ${#DIMENSIONS[@]}" + +# Loop through each dimension +for DIMENSION in "${DIMENSIONS[@]}"; do + echo "📌 Processing dimension: $DIMENSION" + + # Use Python to temporarily modify the dimension in YAML, then run sampling + python3 -c " +import yaml +import sys + +# Read YAML config +with open('$YAML_CONFIG', 'r') as f: + config = yaml.safe_load(f) + +# Modify dimension +config['dimension'] = '$DIMENSION' + +# Save to temporary file +temp_config = '$YAML_CONFIG.tmp' +with open(temp_config, 'w') as f: + yaml.dump(config, f, default_flow_style=False) +print(temp_config) +" > /tmp/temp_config_path.txt + + TEMP_CONFIG=$(cat /tmp/temp_config_path.txt) + python sample_video.py "$TEMP_CONFIG" + rm "$TEMP_CONFIG" + + if [ $? -eq 0 ]; then + echo "✅ Successfully completed: $DIMENSION" + else + echo "❌ Failed: $DIMENSION" + echo "🛑 Script paused due to error. Fix the issue and rerun." + exit 1 + fi + + echo "---" +done + +echo "🎉 All sampling tasks completed." diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/flowcache_t2v.sh b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/flowcache_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..c7bf9910fcc4c4bcf401f9ef16c444808d495936 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/flowcache_t2v.sh @@ -0,0 +1,119 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export MASTER_ADDR=localhost +export MASTER_PORT=6005 +export GPUS_PER_NODE=1 +export NNODES=1 +export WORLD_SIZE=1 +export CUDA_VISIBLE_DEVICES=0 + +export PAD_HQ=1 +export PAD_DURATION=1 + +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MAGI_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +cd "$MAGI_ROOT" + +PROMPT="${PROMPT:-a woman dancing.}" +TIMESTAMP="${RUN_ID:-$(date "+%Y-%m-%d_%H-%M-%S")}" +PROMPT_DIR_NAME="${PROMPT_DIR_NAME:-$(python3 - "$PROMPT" <<'PY' +import re +import sys +import unicodedata + +prompt = unicodedata.normalize("NFKC", sys.argv[1]).strip() +prompt = re.sub(r"[\\/:\*\?\"<>\|\x00-\x1f]+", "_", prompt) +prompt = re.sub(r"\s+", "_", prompt) +prompt = prompt.strip("._") +print((prompt or "prompt")[:120]) +PY +)}" +OUTPUT_ROOT="${OUTPUT_ROOT:-outputs}" +EXP_DIR="${RUN_DIR:-$OUTPUT_ROOT/${PROMPT_DIR_NAME}_$TIMESTAMP}" +mkdir -p "$EXP_DIR" + +OUTPUT_PATH="${OUTPUT_PATH:-$EXP_DIR/output_$TIMESTAMP.mp4}" +RESIDUAL_JSON="${RESIDUAL_JSON:-$EXP_DIR/residual_stats_$TIMESTAMP.json}" +RESIDUAL_PNG="${RESIDUAL_PNG:-$EXP_DIR/residual_norms_$TIMESTAMP.png}" +L1_REL_JSON="${L1_REL_JSON:-$EXP_DIR/l1_rel_stats_$TIMESTAMP.json}" +L1_REL_PNG="${L1_REL_PNG:-$EXP_DIR/l1_rel_$TIMESTAMP.png}" +L1_REL_RATIO_PNG="${L1_REL_RATIO_PNG:-$EXP_DIR/l1_rel_ratio_$TIMESTAMP.png}" +X_EMBEDDER_L1_REL_PNG="${X_EMBEDDER_L1_REL_PNG:-$EXP_DIR/x_embedder_l1_rel_$TIMESTAMP.png}" +X_EMBEDDER_L1_REL_RATIO_PNG="${X_EMBEDDER_L1_REL_RATIO_PNG:-$EXP_DIR/x_embedder_l1_rel_ratio_$TIMESTAMP.png}" +FLOWCACHE_METRIC_JSON="${FLOWCACHE_METRIC_JSON:-$EXP_DIR/flowcache_metric_stats_$TIMESTAMP.json}" +FLOWCACHE_REL_L1_PNG="${FLOWCACHE_REL_L1_PNG:-$EXP_DIR/flowcache_rel_l1_$TIMESTAMP.png}" +FLOWCACHE_REL_L1_RATIO_PNG="${FLOWCACHE_REL_L1_RATIO_PNG:-$EXP_DIR/flowcache_rel_l1_ratio_$TIMESTAMP.png}" +FLOWCACHE_ACCUMULATED_REL_L1_PNG="${FLOWCACHE_ACCUMULATED_REL_L1_PNG:-$EXP_DIR/flowcache_accumulated_rel_l1_$TIMESTAMP.png}" +LOG_FILE="${LOG_FILE:-$EXP_DIR/infer_$TIMESTAMP.log}" + +export PYTHONPATH="$MAGI_ROOT:${PYTHONPATH:-}" +python3 inference/pipeline/flowcache.py \ + --config_file config/single_run/flowcache_t2v.json \ + --mode t2v \ + --prompt "$PROMPT" \ + --output_path "$OUTPUT_PATH" \ + --additional_config yaml_config/single_run/config.yaml \ + --residual_stats_path "$RESIDUAL_JSON" \ + --l1_rel_stats_path "$L1_REL_JSON" \ + --flowcache_metric_stats_path "$FLOWCACHE_METRIC_JSON" \ + 2>&1 | tee "$LOG_FILE" + +python3 tools/plot_residual_norms.py "$RESIDUAL_JSON" -o "$RESIDUAL_PNG" +python3 tools/plot_l1_rel.py "$L1_REL_JSON" -o "$L1_REL_PNG" +python3 tools/plot_l1_rel.py "$L1_REL_JSON" --y-field l1_rel_ratio -o "$L1_REL_RATIO_PNG" +python3 tools/plot_l1_rel.py "$L1_REL_JSON" --y-field x_embedder_l1_rel -o "$X_EMBEDDER_L1_REL_PNG" +python3 tools/plot_l1_rel.py "$L1_REL_JSON" --y-field x_embedder_l1_rel_ratio -o "$X_EMBEDDER_L1_REL_RATIO_PNG" +python3 tools/plot_l1_rel.py "$FLOWCACHE_METRIC_JSON" --x-field cur_denoise_step --y-field flowcache_rel_l1 -o "$FLOWCACHE_REL_L1_PNG" +python3 tools/plot_l1_rel.py "$FLOWCACHE_METRIC_JSON" --x-field cur_denoise_step --y-field flowcache_rel_l1_ratio -o "$FLOWCACHE_REL_L1_RATIO_PNG" +python3 tools/plot_l1_rel.py "$FLOWCACHE_METRIC_JSON" --x-field cur_denoise_step --y-field flowcache_accumulated_rel_l1 -o "$FLOWCACHE_ACCUMULATED_REL_L1_PNG" + +python3 - "$FLOWCACHE_METRIC_JSON" <<'PY' +import json +import sys + +with open(sys.argv[1], "r") as f: + payload = json.load(f) + +summary = payload.get("chunk_execution_summary", {}) +print("FlowCache actual execution summary:") +for chunk_id in sorted(summary, key=lambda value: int(value)): + item = summary[chunk_id] + print( + " chunk {chunk_idx}: reuse={reuse_steps}, compute={compute_steps}, " + "total={total_steps}, reuse_rate={reuse_rate:.2%}".format(**item) + ) +PY + +echo "Done." +echo " log: $LOG_FILE" +echo " video: $OUTPUT_PATH" +echo " residual json: $RESIDUAL_JSON" +echo " residual plot: $RESIDUAL_PNG" +echo " L1 rel json: $L1_REL_JSON" +echo " L1 rel plot: $L1_REL_PNG" +echo " L1 rel ratio plot: $L1_REL_RATIO_PNG" +echo " x_embedder L1 rel plot: $X_EMBEDDER_L1_REL_PNG" +echo " x_embedder L1 rel ratio plot: $X_EMBEDDER_L1_REL_RATIO_PNG" +echo " FlowCache metric json: $FLOWCACHE_METRIC_JSON" +echo " FlowCache rel L1 plot: $FLOWCACHE_REL_L1_PNG" +echo " FlowCache rel L1 ratio plot: $FLOWCACHE_REL_L1_RATIO_PNG" +echo " FlowCache accumulated rel L1 plot: $FLOWCACHE_ACCUMULATED_REL_L1_PNG" diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/flowcache_v2v.sh b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/flowcache_v2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..e6867ddc351383f193685fdea417c6f57058e0f9 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/flowcache_v2v.sh @@ -0,0 +1,51 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export MASTER_ADDR=localhost +export MASTER_PORT=6001 +export GPUS_PER_NODE=1 +export NNODES=1 +export WORLD_SIZE=1 +export CUDA_VISIBLE_DEVICES=7 + +export PAD_HQ=1 +export PAD_DURATION=1 + +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) + + +OUTPUT_NAME=flowcache +TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S") +EXP_DIR="/path/to/output/magi/${TIMESTAMP}_${OUTPUT_NAME}" +mkdir -p "$EXP_DIR" + +LOG_FILE="$EXP_DIR/log_${TIMESTAMP}.log" +OUTPUT_PATH="$EXP_DIR/output.mp4" + +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +python3 inference/pipeline/flowcache.py \ + --config_file config/single_run/flowcache_v2v.json \ + --mode v2v \ + --prompt "Two pillows on a table and two grabber tools hanging above them from which a brown tennis ball and an orange block are suspended. The grabber tools let go of the ball and block. Static shot with no camera movement." \ + --prefix_video_path "/path/to/physicsiq/conditioning_video.mp4" \ + --output_path $OUTPUT_PATH \ + --additional_config addconfig/config.yaml \ + 2>&1 | tee $LOG_FILE + +# a cat sitting on the grass diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/teacache_t2v.sh b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/teacache_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..e01f11f55fdbcb27fdebb14fffd4940517668db0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/teacache_t2v.sh @@ -0,0 +1,50 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export MASTER_ADDR=localhost +export MASTER_PORT=6002 +export GPUS_PER_NODE=1 +export NNODES=1 +export WORLD_SIZE=1 +export CUDA_VISIBLE_DEVICES=2 + +export PAD_HQ=1 +export PAD_DURATION=1 + +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) + + +OUTPUT_NAME=allreuse +TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S") +EXP_DIR="/path/to/output/magi/${TIMESTAMP}_${OUTPUT_NAME}" +mkdir -p "$EXP_DIR" + +LOG_FILE="$EXP_DIR/log_${TIMESTAMP}.log" +exec > >(tee -a "$LOG_FILE") 2>&1 +OUTPUT_PATH="$EXP_DIR/output.mp4" + +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +python3 inference/pipeline/teacache_all.py \ + --rel_l1_thresh 0.01 \ + --warmup_steps 5 \ + --config_file config/single_run/flowcache_t2v.json \ + --mode t2v \ + --prompt "A fantasy landscape" \ + --log \ + --output_path $OUTPUT_PATH \ \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/teacache_v2v.sh b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/teacache_v2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..d99fb479b9811b6ca93d23a73cdf9f3654ecf4eb --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/scripts/single_run/teacache_v2v.sh @@ -0,0 +1,52 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export MASTER_ADDR=localhost +export MASTER_PORT=6012 +export GPUS_PER_NODE=1 +export NNODES=1 +export WORLD_SIZE=1 +export CUDA_VISIBLE_DEVICES=1 +export CUDA_HOME="/usr/local/cuda-12.1" + +export PAD_HQ=1 +export PAD_DURATION=1 + +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) + + +OUTPUT_NAME=allreuse +TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S") +EXP_DIR="/path/to/output/magi/${TIMESTAMP}_${OUTPUT_NAME}" +mkdir -p "$EXP_DIR" + +LOG_FILE="$EXP_DIR/log_${TIMESTAMP}.log" +exec > >(tee -a "$LOG_FILE") 2>&1 +OUTPUT_PATH="$EXP_DIR/output.mp4" + +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +python3 inference/pipeline/teacache_all.py \ + --rel_l1_thresh 0.01 \ + --warmup_steps 5 \ + --config_file config/single_run/all_reuse.json \ + --mode v2v \ + --prompt "Two pillows on a table and two grabber tools hanging above them from which a brown tennis ball and an orange block are suspended. The grabber tools let go of the ball and block. Static shot with no camera movement." \ + --prefix_video_path "/path/to/physicsiq/conditioning_video.mp4" \ + --output_path $OUTPUT_PATH \ + --log \ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/tools/__pycache__/plot_l1_rel.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V1/tools/__pycache__/plot_l1_rel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e85d201a85bc30be7690f33a0276cc3134397c8 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V1/tools/__pycache__/plot_l1_rel.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/tools/__pycache__/plot_residual_norms.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V1/tools/__pycache__/plot_residual_norms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8453b79cd8122069b9c3886294fe9399dd435f7c Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V1/tools/__pycache__/plot_residual_norms.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/flowcache_physicsiq.yaml b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/flowcache_physicsiq.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c5e40e82e29ac3190a8dd8e042ba63073de54a90 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/flowcache_physicsiq.yaml @@ -0,0 +1,36 @@ +# FlowCache PhysicsIQ configuration file +# Usage: bash scripts/sample/flowcache_physicsiq.sh + +# Basic configuration +benchmark: physicsiq +config_file: config/sample/5s_physicsiq.json + +# GPU configuration +gpus: "0,1,2,3,4" + +# PhysicsIQ dataset configuration +physicsiq_data_dir: /path/to/physicsiq + +# Output path configuration +base_save_path: /path/to/output/physicsiq + +# Reuse strategy configuration +reuse_strategy: chunkwise +rel_l1_thresh: 0.01 +warmup_steps: 5 + +# KV cache compression configuration +compress_kv_cache: true +total_cache_chunk_nums: 6 +compress_strategy: token +query_granularity: token +mix_lambda: 0.07 +score_weighting_method: no_weight +power: 3 + +# Sampling range control +start: 150 +end: 200 + +# Log configuration +log: false diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/flowcache_vbench.yaml b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/flowcache_vbench.yaml new file mode 100644 index 0000000000000000000000000000000000000000..685c2d40dd2a50e132206950c9a6e041e149371a --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/flowcache_vbench.yaml @@ -0,0 +1,35 @@ +# FlowCache VBench configuration file +# Usage: bash scripts/sample/flowcache_vbench.sh + +# Basic configuration +benchmark: vbench +config_file: config/sample/10s_vbench.json + +# GPU configuration +gpus: "1,3,4,6" + +# VBench dataset configuration +vbench_prompt_dir: /path/to/vbench/prompts + +# Dimension configuration (specify the current dimension to process) +dimension: overall_consistency # Options: subject_consistency, scene, object_class, multiple_objects, color, spatial_relationship, temporal_style, human_action, temporal_flickering, appearance_style + +# Output path configuration +base_save_path: /path/to/output/vbench + +# Reuse strategy configuration +reuse_strategy: chunkwise +rel_l1_thresh: 0.01 +warmup_steps: 5 + +# KV cache compression configuration +compress_kv_cache: true +total_cache_chunk_nums: 6 +budget_cache_chunk_nums: 1 +compress_strategy: token +query_granularity: chunk +mix_lambda: 0.07 +discard_nearly_clean_chunk: true + +# Log configuration +log: false diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/teacache_physicsiq.yaml b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/teacache_physicsiq.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f741a8b42463fe060b37540792d1878d3fe2131e --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/teacache_physicsiq.yaml @@ -0,0 +1,23 @@ +# TeaCache PhysicsIQ configuration file +# Usage: bash scripts/sample/teacache_physicsiq.sh + +# Basic configuration +benchmark: physicsiq +config_file: config/sample/5s_physicsiq.json + +# GPU configuration +gpus: "0,1,2,3,4,5,6,7" + +# PhysicsIQ dataset configuration +physicsiq_data_dir: /path/to/physicsiq + +# Output path configuration +base_save_path: /path/to/output/physicsiq + +# Reuse strategy configuration +reuse_strategy: all +rel_l1_thresh: 0.01 +warmup_steps: 5 + +# Log configuration +log: false diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/teacache_vbench.yaml b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/teacache_vbench.yaml new file mode 100644 index 0000000000000000000000000000000000000000..53c133cd581b1099708d75c41b42aa6a5a8c53fa --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/sample/teacache_vbench.yaml @@ -0,0 +1,26 @@ +# TeaCache VBench configuration file +# Usage: bash scripts/sample/teacache_vbench.sh + +# Basic configuration +benchmark: vbench +config_file: config/sample/10s_vbench.json + +# GPU configuration +gpus: "4,5,7" + +# VBench dataset configuration +vbench_prompt_dir: /path/to/vbench/prompts + +# Dimension configuration (specify the current dimension to process) +dimension: overall_consistency # Options: subject_consistency, scene, object_class, multiple_objects, color, spatial_relationship, temporal_style, human_action, temporal_flickering, appearance_style + +# Output path configuration +base_save_path: /path/to/output/vbench + +# Reuse strategy configuration +reuse_strategy: all +rel_l1_thresh: 0.01 +warmup_steps: 5 + +# Log configuration +log: false diff --git a/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/single_run/config.yaml b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/single_run/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..78463d84ae51ccc251f9272651f299a997feba54 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V1/yaml_config/single_run/config.yaml @@ -0,0 +1,15 @@ +rel_l1_thresh: 0.015 +warmup_steps: 5 +discard_nearly_clean_chunk: true + +compress_kv_cache: true +total_cache_chunk_nums: 5 +compress_strategy: token +mix_lambda: 0.07 +query_granularity: frame +score_weighting_method: no_weight +power: 3 + +log: true +print_peak_memory: true +debug: false \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/__pycache__/sample_video.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/__pycache__/sample_video.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5610872b18f9cb5059446119d851dbb751f0916e Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/__pycache__/sample_video.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/config/sample/physicsiq.json b/FlowCache/FlowCache4MAGI-1-dev-V2/config/sample/physicsiq.json new file mode 100644 index 0000000000000000000000000000000000000000..17df1b44b67824c0a3d5db952fa8a1de7c3c9ba1 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/config/sample/physicsiq.json @@ -0,0 +1,81 @@ +{ + "model_config": { + "model_name": "videodit_ardf", + "num_layers": 34, + "hidden_size": 3072, + "ffn_hidden_size": 12288, + "num_attention_heads": 24, + "num_query_groups": 8, + "kv_channels": 128, + "layernorm_epsilon": 1e-06, + "apply_layernorm_1p": true, + "x_rescale_factor": 1, + "half_channel_vae": false, + "params_dtype": "torch.bfloat16", + "patch_size": 2, + "t_patch_size": 1, + "in_channels": 16, + "out_channels": 16, + "cond_hidden_ratio": 0.25, + "caption_channels": 4096, + "caption_max_length": 800, + "xattn_cond_hidden_ratio": 1.0, + "cond_gating_ratio": 1.0, + "gated_linear_unit": false + }, + "runtime_config": { + "cfg_number": 1, + "cfg_t_range": [ + 0.0, + 0.0217, + 0.1, + 0.3, + 0.999 + ], + "prev_chunk_scales": [ + 1.5, + 1.5, + 1.5, + 1.0, + 1.0 + ], + "text_scales": [ + 7.5, + 7.5, + 7.5, + 0.0, + 0.0 + ], + "noise2clean_kvrange": [], + "clean_chunk_kvrange": 1, + "clean_t": 0.9999, + "seed": 1234, + "num_frames": 120, + "video_size_h": 720, + "video_size_w": 1280, + "num_steps": 64, + "window_size": 4, + "fps": 24, + "chunk_width": 6, + "load": "./downloads/4.5B_distill", + "t5_pretrained": "./downloads/t5_pretrained", + "t5_device": "cuda", + "vae_pretrained": "./downloads/vae", + "scale_factor": 0.18215, + "temporal_downsample_factor": 4 + }, + "engine_config": { + "distributed_backend": "nccl", + "distributed_timeout_minutes": 15, + "pp_size": 1, + "cp_size": 1, + "cp_strategy": "none", + "ulysses_overlap_degree": 1, + "fp8_quant": false, + "distill_nearly_clean_chunk_threshold": 0.3, + "shortcut_mode": "8,16,16", + "distill": true, + "kv_offload": true, + "enable_cuda_graph": false + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/config/sample/vbench.json b/FlowCache/FlowCache4MAGI-1-dev-V2/config/sample/vbench.json new file mode 100644 index 0000000000000000000000000000000000000000..e549246b9b7757b12bb8822bac18da3345e41e3e --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/config/sample/vbench.json @@ -0,0 +1,81 @@ +{ + "model_config": { + "model_name": "videodit_ardf", + "num_layers": 34, + "hidden_size": 3072, + "ffn_hidden_size": 12288, + "num_attention_heads": 24, + "num_query_groups": 8, + "kv_channels": 128, + "layernorm_epsilon": 1e-06, + "apply_layernorm_1p": true, + "x_rescale_factor": 1, + "half_channel_vae": false, + "params_dtype": "torch.bfloat16", + "patch_size": 2, + "t_patch_size": 1, + "in_channels": 16, + "out_channels": 16, + "cond_hidden_ratio": 0.25, + "caption_channels": 4096, + "caption_max_length": 800, + "xattn_cond_hidden_ratio": 1.0, + "cond_gating_ratio": 1.0, + "gated_linear_unit": false + }, + "runtime_config": { + "cfg_number": 1, + "cfg_t_range": [ + 0.0, + 0.0217, + 0.1, + 0.3, + 0.999 + ], + "prev_chunk_scales": [ + 1.5, + 1.5, + 1.5, + 1.0, + 1.0 + ], + "text_scales": [ + 7.5, + 7.5, + 7.5, + 0.0, + 0.0 + ], + "noise2clean_kvrange": [], + "clean_chunk_kvrange": 1, + "clean_t": 0.9999, + "seed": 1234, + "num_frames": 240, + "video_size_h": 720, + "video_size_w": 720, + "num_steps": 16, + "window_size": 4, + "fps": 24, + "chunk_width": 6, + "load": "./downloads/4.5B_distill", + "t5_pretrained": "./downloads/t5_pretrained", + "t5_device": "cuda", + "vae_pretrained": "./downloads/vae", + "scale_factor": 0.18215, + "temporal_downsample_factor": 4 + }, + "engine_config": { + "distributed_backend": "nccl", + "distributed_timeout_minutes": 15, + "pp_size": 1, + "cp_size": 1, + "cp_strategy": "none", + "ulysses_overlap_degree": 1, + "fp8_quant": false, + "distill_nearly_clean_chunk_threshold": 0.3, + "shortcut_mode": "8,16,16", + "distill": true, + "kv_offload": true, + "enable_cuda_graph": false + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/config/single_run/flowcache_t2v.json b/FlowCache/FlowCache4MAGI-1-dev-V2/config/single_run/flowcache_t2v.json new file mode 100644 index 0000000000000000000000000000000000000000..6b0762dad4dc5ec0263248699721f97cd6feef9d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/config/single_run/flowcache_t2v.json @@ -0,0 +1,81 @@ +{ + "model_config": { + "model_name": "videodit_ardf", + "num_layers": 34, + "hidden_size": 3072, + "ffn_hidden_size": 12288, + "num_attention_heads": 24, + "num_query_groups": 8, + "kv_channels": 128, + "layernorm_epsilon": 1e-06, + "apply_layernorm_1p": true, + "x_rescale_factor": 1, + "half_channel_vae": false, + "params_dtype": "torch.bfloat16", + "patch_size": 2, + "t_patch_size": 1, + "in_channels": 16, + "out_channels": 16, + "cond_hidden_ratio": 0.25, + "caption_channels": 4096, + "caption_max_length": 800, + "xattn_cond_hidden_ratio": 1.0, + "cond_gating_ratio": 1.0, + "gated_linear_unit": false + }, + "runtime_config": { + "cfg_number": 1, + "cfg_t_range": [ + 0.0, + 0.0217, + 0.1, + 0.3, + 0.999 + ], + "prev_chunk_scales": [ + 1.5, + 1.5, + 1.5, + 1.0, + 1.0 + ], + "text_scales": [ + 7.5, + 7.5, + 7.5, + 0.0, + 0.0 + ], + "noise2clean_kvrange": [], + "clean_chunk_kvrange": 1, + "clean_t": 0.9999, + "seed": 1234, + "num_frames": 240, + "video_size_h": 720, + "video_size_w": 720, + "num_steps": 64, + "window_size": 4, + "fps": 24, + "chunk_width": 6, + "load": "./downloads/4.5B_distill", + "t5_pretrained": "./downloads/t5_pretrained", + "t5_device": "cuda", + "vae_pretrained": "./downloads/vae", + "scale_factor": 0.18215, + "temporal_downsample_factor": 4 + }, + "engine_config": { + "distributed_backend": "nccl", + "distributed_timeout_minutes": 15, + "pp_size": 1, + "cp_size": 1, + "cp_strategy": "none", + "ulysses_overlap_degree": 1, + "fp8_quant": false, + "distill_nearly_clean_chunk_threshold": 0.3, + "shortcut_mode": "8,16,16", + "distill": true, + "kv_offload": false, + "enable_cuda_graph": false + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/config/single_run/flowcache_v2v.json b/FlowCache/FlowCache4MAGI-1-dev-V2/config/single_run/flowcache_v2v.json new file mode 100644 index 0000000000000000000000000000000000000000..cdc9001264bce5c7ad72c2430b47540c9b8c85da --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/config/single_run/flowcache_v2v.json @@ -0,0 +1,86 @@ +{ + "model_config": { + "model_name": "videodit_ardf", + "num_layers": 34, + "hidden_size": 3072, + "ffn_hidden_size": 12288, + "num_attention_heads": 24, + "num_query_groups": 8, + "kv_channels": 128, + "layernorm_epsilon": 1e-06, + "apply_layernorm_1p": true, + "x_rescale_factor": 1, + "half_channel_vae": false, + "params_dtype": "torch.bfloat16", + "patch_size": 2, + "t_patch_size": 1, + "in_channels": 16, + "out_channels": 16, + "cond_hidden_ratio": 0.25, + "caption_channels": 4096, + "caption_max_length": 800, + "xattn_cond_hidden_ratio": 1.0, + "cond_gating_ratio": 1.0, + "gated_linear_unit": false + }, + "runtime_config": { + "cfg_number": 1, + "cfg_t_range": [ + 0.0, + 0.0217, + 0.1, + 0.3, + 0.999 + ], + "prev_chunk_scales": [ + 1.5, + 1.5, + 1.5, + 1.0, + 1.0 + ], + "text_scales": [ + 7.5, + 7.5, + 7.5, + 0.0, + 0.0 + ], + "noise2clean_kvrange": [ + 5, + 4, + 3, + 2 + ], + "clean_chunk_kvrange": 1, + "clean_t": 0.9999, + "seed": 1234, + "num_frames": 120, + "video_size_h": 720, + "video_size_w": 1280, + "num_steps": 8, + "window_size": 4, + "fps": 24, + "chunk_width": 6, + "load": "./downloads/4.5B_distill", + "t5_pretrained": "./downloads/t5_pretrained", + "t5_device": "cuda", + "vae_pretrained": "./downloads/vae", + "scale_factor": 0.18215, + "temporal_downsample_factor": 4 + }, + "engine_config": { + "distributed_backend": "nccl", + "distributed_timeout_minutes": 15, + "pp_size": 1, + "cp_size": 1, + "cp_strategy": "none", + "ulysses_overlap_degree": 1, + "fp8_quant": false, + "distill_nearly_clean_chunk_threshold": 0.3, + "shortcut_mode": "8,16,16", + "distill": true, + "kv_offload": false, + "enable_cuda_graph": false + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/magi/4.5B_base/inference_weight/model.safetensors.index.json b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/magi/4.5B_base/inference_weight/model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..625078aaaadc20f19a8e00209527d1fec6269f2a --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/magi/4.5B_base/inference_weight/model.safetensors.index.json @@ -0,0 +1,905 @@ +{ + "metadata": { + "total_size": 8961059904 + }, + "weight_map": { + "final_linear.linear.weight": "model-00001-of-00002.safetensors", + "rope.bands": "model-00001-of-00002.safetensors", + "t_embedder.mlp.0.bias": "model-00001-of-00002.safetensors", + "t_embedder.mlp.0.weight": "model-00001-of-00002.safetensors", + "t_embedder.mlp.2.bias": "model-00001-of-00002.safetensors", + "t_embedder.mlp.2.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.final_layernorm.bias": "model-00001-of-00002.safetensors", + "videodit_blocks.final_layernorm.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.1.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.1.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.10.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.10.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.11.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.11.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.12.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.12.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.13.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.13.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.14.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.14.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.15.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.15.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.16.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.16.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.17.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.17.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.18.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.18.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.19.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.19.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.2.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.2.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.20.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.20.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.21.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.21.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.22.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.22.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.23.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.23.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.24.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.24.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.25.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.25.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.26.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.26.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.27.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.27.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.28.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.28.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.29.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.29.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.3.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.3.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.30.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.30.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.31.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.31.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.32.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.32.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.33.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.33.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.4.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.4.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.5.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.5.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.6.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.6.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.7.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.7.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.8.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.8.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.ada_modulate_layer.proj.0.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.9.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.9.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_kv_xattn.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_proj.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.k.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.q.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.qx.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.v.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "x_embedder.weight": "model-00001-of-00002.safetensors", + "y_embedder.null_caption_embedding": "model-00001-of-00002.safetensors", + "y_embedder.y_proj_adaln.0.bias": "model-00001-of-00002.safetensors", + "y_embedder.y_proj_adaln.0.weight": "model-00001-of-00002.safetensors", + "y_embedder.y_proj_xattn.0.bias": "model-00001-of-00002.safetensors", + "y_embedder.y_proj_xattn.0.weight": "model-00001-of-00002.safetensors" + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/magi/4.5B_distill/inference_weight.distill/model.safetensors.index.json b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/magi/4.5B_distill/inference_weight.distill/model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..dbf56941e1b0dfded510870a45a995976a9c5dc9 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/magi/4.5B_distill/inference_weight.distill/model.safetensors.index.json @@ -0,0 +1,905 @@ +{ + "metadata": { + "total_size": 8961059904 + }, + "weight_map": { + "final_linear.linear.weight": "model-00001-of-00002.safetensors", + "rope.bands": "model-00001-of-00002.safetensors", + "t_embedder.mlp.0.bias": "model-00001-of-00002.safetensors", + "t_embedder.mlp.0.weight": "model-00001-of-00002.safetensors", + "t_embedder.mlp.2.bias": "model-00001-of-00002.safetensors", + "t_embedder.mlp.2.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.final_layernorm.bias": "model-00001-of-00002.safetensors", + "videodit_blocks.final_layernorm.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.0.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.1.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.1.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.10.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.10.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.11.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.11.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.12.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.12.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.13.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.13.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.14.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.14.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.15.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.15.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.16.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.16.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.17.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.17.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.18.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.18.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.19.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.19.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.2.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.2.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.20.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.20.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.21.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.21.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.22.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.22.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.23.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.23.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.24.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.24.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.25.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.25.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.26.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.26.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.27.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.27.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.28.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.28.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.29.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.29.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.3.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.3.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.30.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.30.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.31.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.31.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.32.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.32.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.33.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.33.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.4.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.4.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.5.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.5.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.6.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.6.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.7.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.7.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.8.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.8.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.ada_modulate_layer.proj.0.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.ada_modulate_layer.proj.0.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.mlp.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.mlp.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.mlp.linear_fc1.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.9.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.mlp_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.mlp_post_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.k_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.k_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.k_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.k_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_kv_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_proj.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.k.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.layer_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.layer_norm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.q.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.qx.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.linear_qkv.v.weight": "model-00001-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.q_layernorm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.q_layernorm.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.q_layernorm_xattn.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attention.q_layernorm_xattn.weight": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attn_post_norm.bias": "model-00002-of-00002.safetensors", + "videodit_blocks.layers.9.self_attn_post_norm.weight": "model-00002-of-00002.safetensors", + "x_embedder.weight": "model-00001-of-00002.safetensors", + "y_embedder.null_caption_embedding": "model-00001-of-00002.safetensors", + "y_embedder.y_proj_adaln.0.bias": "model-00001-of-00002.safetensors", + "y_embedder.y_proj_adaln.0.weight": "model-00001-of-00002.safetensors", + "y_embedder.y_proj_xattn.0.bias": "model-00001-of-00002.safetensors", + "y_embedder.y_proj_xattn.0.weight": "model-00001-of-00002.safetensors" + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/config.json b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d133daa4aefba0f8b2bd96d4cb52992b32dc693a --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/config.json @@ -0,0 +1,31 @@ +{ + "_name_or_path": "google/t5-v1_1-xxl", + "architectures": [ + "T5EncoderModel" + ], + "d_ff": 10240, + "d_kv": 64, + "d_model": 4096, + "decoder_start_token_id": 0, + "dense_act_fn": "gelu_new", + "dropout_rate": 0.1, + "eos_token_id": 1, + "feed_forward_proj": "gated-gelu", + "initializer_factor": 1.0, + "is_encoder_decoder": true, + "is_gated_act": true, + "layer_norm_epsilon": 1e-06, + "model_type": "t5", + "num_decoder_layers": 24, + "num_heads": 64, + "num_layers": 24, + "output_past": true, + "pad_token_id": 0, + "relative_attention_max_distance": 128, + "relative_attention_num_buckets": 32, + "tie_word_embeddings": false, + "torch_dtype": "float32", + "transformers_version": "4.21.1", + "use_cache": true, + "vocab_size": 32128 +} diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/pytorch_model.bin.index.json b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/pytorch_model.bin.index.json new file mode 100644 index 0000000000000000000000000000000000000000..1a33111ca9725d27f870b6797f3c9726654a0657 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/pytorch_model.bin.index.json @@ -0,0 +1,227 @@ +{ + "metadata": { + "total_size": 19575627776 + }, + "weight_map": { + "encoder.block.0.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.0.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.0.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.0.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.0.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.0.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.0.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.0.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.0.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.1.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.1.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.1.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.1.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.1.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.1.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.1.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.1.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.1.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.10.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.10.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.10.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.10.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.10.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.10.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.10.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.10.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.10.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.11.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.11.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.11.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.11.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.11.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.11.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.11.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.11.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.11.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.12.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.12.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.12.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.12.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.12.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.12.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.12.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.12.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.12.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.13.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.13.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.13.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.13.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.13.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.13.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.13.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.13.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.13.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.14.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.14.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.14.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.14.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.14.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.14.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.14.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.14.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.14.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.15.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.15.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.15.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.15.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.15.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.15.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.15.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.15.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.15.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.16.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.16.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.16.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.16.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.16.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.16.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.16.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.16.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.16.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.17.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.17.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.17.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.17.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.17.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.17.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.17.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.17.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.17.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.18.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.18.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.18.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.18.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.18.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.18.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.18.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.18.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.18.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.19.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.19.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.19.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.19.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.19.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.19.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.19.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.19.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.19.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.2.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.2.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.2.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.2.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.2.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.2.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.2.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.2.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.2.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.20.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.20.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.20.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.20.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.20.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.20.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.20.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.20.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.20.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.21.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.21.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.21.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.21.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.21.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.21.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.21.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.21.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.21.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.22.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.22.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.22.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.22.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.22.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.22.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.22.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.22.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.22.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.23.layer.0.SelfAttention.k.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.23.layer.0.SelfAttention.o.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.23.layer.0.SelfAttention.q.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.23.layer.0.SelfAttention.v.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.23.layer.0.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.23.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.23.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.23.layer.1.DenseReluDense.wo.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.23.layer.1.layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "encoder.block.3.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.3.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.3.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.3.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.3.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.3.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.3.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.3.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.3.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.4.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.4.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.4.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.4.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.4.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.4.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.4.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.4.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.4.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.5.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.5.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.5.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.5.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.5.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.5.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.5.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.5.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.5.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.6.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.6.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.6.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.6.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.6.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.6.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.6.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.6.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.6.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.7.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.7.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.7.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.7.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.7.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.7.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.7.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.7.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.7.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.8.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.8.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.8.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.8.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.8.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.8.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.8.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.8.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.8.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.9.layer.0.SelfAttention.k.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.9.layer.0.SelfAttention.o.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.9.layer.0.SelfAttention.q.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.9.layer.0.SelfAttention.v.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.9.layer.0.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.9.layer.1.DenseReluDense.wi_0.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.9.layer.1.DenseReluDense.wi_1.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.9.layer.1.DenseReluDense.wo.weight": "pytorch_model-00001-of-00002.bin", + "encoder.block.9.layer.1.layer_norm.weight": "pytorch_model-00001-of-00002.bin", + "encoder.embed_tokens.weight": "pytorch_model-00001-of-00002.bin", + "encoder.final_layer_norm.weight": "pytorch_model-00002-of-00002.bin", + "shared.weight": "pytorch_model-00001-of-00002.bin" + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/special_tokens_map.json b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/special_tokens_map.json new file mode 100644 index 0000000000000000000000000000000000000000..881bdbffc06e471924ecea57f962bc5f8e2a9f21 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/special_tokens_map.json @@ -0,0 +1 @@ +{"eos_token": "", "unk_token": "", "pad_token": "", "additional_special_tokens": ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]} \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/tokenizer_config.json b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/tokenizer_config.json new file mode 100644 index 0000000000000000000000000000000000000000..b114c318caf72f6e89ea92e0755c41327a453198 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/tokenizer_config.json @@ -0,0 +1 @@ +{"eos_token": "", "unk_token": "", "pad_token": "", "extra_ids": 100, "additional_special_tokens": ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], "model_max_length": 512, "name_or_path": "t5-small"} \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/vae/config.json b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/vae/config.json new file mode 100644 index 0000000000000000000000000000000000000000..441ae16ddd09dc4ea5a5269fce6827bb3ab6b799 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/_hf_raw/ckpt/vae/config.json @@ -0,0 +1,22 @@ +{ + "_class_name": "ViTVAE", + "_diffusers_version": "0.28.2", + "ddconfig": { + "conv_last_layer": true, + "depth": 24, + "double_z": true, + "embed_dim": 1024, + "in_chans": 3, + "ln_in_attn": true, + "mlp_ratio": 4, + "norm_code": false, + "num_heads": 16, + "patch_length": 4, + "patch_size": 8, + "qkv_bias": true, + "video_length": 16, + "video_size": 256, + "z_chans": 16 + }, + "model_type": "vit" +} diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/appearance_style.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/appearance_style.txt new file mode 100644 index 0000000000000000000000000000000000000000..68ccf36abeaaa4bb36ce3dbac70e0e4350cc4120 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/appearance_style.txt @@ -0,0 +1,90 @@ +A beautiful coastal beach in spring, waves lapping on sand, Van Gogh style +A beautiful coastal beach in spring, waves lapping on sand, oil painting +A beautiful coastal beach in spring, waves lapping on sand by Hokusai, in the style of Ukiyo +A beautiful coastal beach in spring, waves lapping on sand, black and white +A beautiful coastal beach in spring, waves lapping on sand, pixel art +A beautiful coastal beach in spring, waves lapping on sand, in cyberpunk style +A beautiful coastal beach in spring, waves lapping on sand, animated style +A beautiful coastal beach in spring, waves lapping on sand, watercolor painting +A beautiful coastal beach in spring, waves lapping on sand, surrealism style +The bund Shanghai, Van Gogh style +The bund Shanghai, oil painting +The bund Shanghai by Hokusai, in the style of Ukiyo +The bund Shanghai, black and white +The bund Shanghai, pixel art +The bund Shanghai, in cyberpunk style +The bund Shanghai, animated style +The bund Shanghai, watercolor painting +The bund Shanghai, surrealism style +a shark is swimming in the ocean, Van Gogh style +a shark is swimming in the ocean, oil painting +a shark is swimming in the ocean by Hokusai, in the style of Ukiyo +a shark is swimming in the ocean, black and white +a shark is swimming in the ocean, pixel art +a shark is swimming in the ocean, in cyberpunk style +a shark is swimming in the ocean, animated style +a shark is swimming in the ocean, watercolor painting +a shark is swimming in the ocean, surrealism style +A panda drinking coffee in a cafe in Paris, Van Gogh style +A panda drinking coffee in a cafe in Paris, oil painting +A panda drinking coffee in a cafe in Paris by Hokusai, in the style of Ukiyo +A panda drinking coffee in a cafe in Paris, black and white +A panda drinking coffee in a cafe in Paris, pixel art +A panda drinking coffee in a cafe in Paris, in cyberpunk style +A panda drinking coffee in a cafe in Paris, animated style +A panda drinking coffee in a cafe in Paris, watercolor painting +A panda drinking coffee in a cafe in Paris, surrealism style +A cute happy Corgi playing in park, sunset, Van Gogh style +A cute happy Corgi playing in park, sunset, oil painting +A cute happy Corgi playing in park, sunset by Hokusai, in the style of Ukiyo +A cute happy Corgi playing in park, sunset, black and white +A cute happy Corgi playing in park, sunset, pixel art +A cute happy Corgi playing in park, sunset, in cyberpunk style +A cute happy Corgi playing in park, sunset, animated style +A cute happy Corgi playing in park, sunset, watercolor painting +A cute happy Corgi playing in park, sunset, surrealism style +Gwen Stacy reading a book, Van Gogh style +Gwen Stacy reading a book, oil painting +Gwen Stacy reading a book by Hokusai, in the style of Ukiyo +Gwen Stacy reading a book, black and white +Gwen Stacy reading a book, pixel art +Gwen Stacy reading a book, in cyberpunk style +Gwen Stacy reading a book, animated style +Gwen Stacy reading a book, watercolor painting +Gwen Stacy reading a book, surrealism style +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, Van Gogh style +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, oil painting +A boat sailing leisurely along the Seine River with the Eiffel Tower in background by Hokusai, in the style of Ukiyo +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, black and white +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, pixel art +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, in cyberpunk style +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, animated style +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, watercolor painting +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, surrealism style +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, Van Gogh style +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, oil painting +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas by Hokusai, in the style of Ukiyo +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, black and white +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, pixel art +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, in cyberpunk style +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, animated style +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, watercolor painting +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, surrealism style +An astronaut flying in space, Van Gogh style +An astronaut flying in space, oil painting +An astronaut flying in space by Hokusai, in the style of Ukiyo +An astronaut flying in space, black and white +An astronaut flying in space, pixel art +An astronaut flying in space, in cyberpunk style +An astronaut flying in space, animated style +An astronaut flying in space, watercolor painting +An astronaut flying in space, surrealism style +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, Van Gogh style +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, oil painting +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks by Hokusai, in the style of Ukiyo +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, black and white +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, pixel art +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, in cyberpunk style +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, animated style +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, watercolor painting +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, surrealism style \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/color.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/color.txt new file mode 100644 index 0000000000000000000000000000000000000000..46eb5601ff5377afd324b5952b4f1b23d9b358c0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/color.txt @@ -0,0 +1,85 @@ +a red bicycle +a green bicycle +a blue bicycle +a yellow bicycle +an orange bicycle +a purple bicycle +a pink bicycle +a black bicycle +a white bicycle +a red car +a green car +a blue car +a yellow car +an orange car +a purple car +a pink car +a black car +a white car +a red bird +a green bird +a blue bird +a yellow bird +an orange bird +a purple bird +a pink bird +a black bird +a white bird +a black cat +a white cat +an orange cat +a yellow cat +a red umbrella +a green umbrella +a blue umbrella +a yellow umbrella +an orange umbrella +a purple umbrella +a pink umbrella +a black umbrella +a white umbrella +a red suitcase +a green suitcase +a blue suitcase +a yellow suitcase +an orange suitcase +a purple suitcase +a pink suitcase +a black suitcase +a white suitcase +a red bowl +a green bowl +a blue bowl +a yellow bowl +an orange bowl +a purple bowl +a pink bowl +a black bowl +a white bowl +a red chair +a green chair +a blue chair +a yellow chair +an orange chair +a purple chair +a pink chair +a black chair +a white chair +a red clock +a green clock +a blue clock +a yellow clock +an orange clock +a purple clock +a pink clock +a black clock +a white clock +a red vase +a green vase +a blue vase +a yellow vase +an orange vase +a purple vase +a pink vase +a black vase +a white vase \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/human_action.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/human_action.txt new file mode 100644 index 0000000000000000000000000000000000000000..77bf7854d85cbd4053cd81048e563c43f00f83a3 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/human_action.txt @@ -0,0 +1,100 @@ +A person is riding a bike +A person is marching +A person is roller skating +A person is tasting beer +A person is clapping +A person is drawing +A person is petting animal (not cat) +A person is eating watermelon +A person is playing harp +A person is wrestling +A person is riding scooter +A person is sweeping floor +A person is skateboarding +A person is dunking basketball +A person is playing flute +A person is stretching leg +A person is tying tie +A person is skydiving +A person is shooting goal (soccer) +A person is playing piano +A person is finger snapping +A person is canoeing or kayaking +A person is laughing +A person is digging +A person is clay pottery making +A person is shooting basketball +A person is bending back +A person is shaking hands +A person is bandaging +A person is push up +A person is catching or throwing frisbee +A person is playing trumpet +A person is flying kite +A person is filling eyebrows +A person is shuffling cards +A person is folding clothes +A person is smoking +A person is tai chi +A person is squat +A person is playing controller +A person is throwing axe +A person is giving or receiving award +A person is air drumming +A person is taking a shower +A person is planting trees +A person is sharpening knives +A person is robot dancing +A person is rock climbing +A person is hula hooping +A person is writing +A person is bungee jumping +A person is pushing cart +A person is cleaning windows +A person is cutting watermelon +A person is cheerleading +A person is washing hands +A person is ironing +A person is cutting nails +A person is hugging +A person is trimming or shaving beard +A person is jogging +A person is making bed +A person is washing dishes +A person is grooming dog +A person is doing laundry +A person is knitting +A person is reading book +A person is baby waking up +A person is massaging legs +A person is brushing teeth +A person is crawling baby +A person is motorcycling +A person is driving car +A person is sticking tongue out +A person is shaking head +A person is sword fighting +A person is doing aerobics +A person is strumming guitar +A person is riding or walking with horse +A person is archery +A person is catching or throwing baseball +A person is playing chess +A person is rock scissors paper +A person is using computer +A person is arranging flowers +A person is bending metal +A person is ice skating +A person is climbing a rope +A person is crying +A person is dancing ballet +A person is getting a haircut +A person is running on treadmill +A person is kissing +A person is counting money +A person is barbequing +A person is peeling apples +A person is milking cow +A person is shining shoes +A person is making snowman +A person is sailing \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/multiple_objects.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/multiple_objects.txt new file mode 100644 index 0000000000000000000000000000000000000000..68da059822e6cc438b7ee02849eab98e95fbbde4 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/multiple_objects.txt @@ -0,0 +1,82 @@ +a bird and a cat +a cat and a dog +a dog and a horse +a horse and a sheep +a sheep and a cow +a cow and an elephant +an elephant and a bear +a bear and a zebra +a zebra and a giraffe +a giraffe and a bird +a chair and a couch +a couch and a potted plant +a potted plant and a tv +a tv and a laptop +a laptop and a remote +a remote and a keyboard +a keyboard and a cell phone +a cell phone and a book +a book and a clock +a clock and a backpack +a backpack and an umbrella +an umbrella and a handbag +a handbag and a tie +a tie and a suitcase +a suitcase and a vase +a vase and scissors +scissors and a teddy bear +a teddy bear and a frisbee +a frisbee and skis +skis and a snowboard +a snowboard and a sports ball +a sports ball and a kite +a kite and a baseball bat +a baseball bat and a baseball glove +a baseball glove and a skateboard +a skateboard and a surfboard +a surfboard and a tennis racket +a tennis racket and a bottle +a bottle and a chair +an airplane and a train +a train and a boat +a boat and an airplane +a bicycle and a car +a car and a motorcycle +a motorcycle and a bus +a bus and a traffic light +a traffic light and a fire hydrant +a fire hydrant and a stop sign +a stop sign and a parking meter +a parking meter and a truck +a truck and a bicycle +a toilet and a hair drier +a hair drier and a toothbrush +a toothbrush and a sink +a sink and a toilet +a wine glass and a chair +a cup and a couch +a fork and a potted plant +a knife and a tv +a spoon and a laptop +a bowl and a remote +a banana and a keyboard +an apple and a cell phone +a sandwich and a book +an orange and a clock +broccoli and a backpack +a carrot and an umbrella +a hot dog and a handbag +a pizza and a tie +a donut and a suitcase +a cake and a vase +an oven and scissors +a toaster and a teddy bear +a microwave and a frisbee +a refrigerator and skis +a bicycle and an airplane +a car and a train +a motorcycle and a boat +a person and a toilet +a person and a hair drier +a person and a toothbrush +a person and a sink \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/object_class.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/object_class.txt new file mode 100644 index 0000000000000000000000000000000000000000..daac170edaff105a31ee26c3c4d9c2fa1f230ee9 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/object_class.txt @@ -0,0 +1,79 @@ +a person +a bicycle +a car +a motorcycle +an airplane +a bus +a train +a truck +a boat +a traffic light +a fire hydrant +a stop sign +a parking meter +a bench +a bird +a cat +a dog +a horse +a sheep +a cow +an elephant +a bear +a zebra +a giraffe +a backpack +an umbrella +a handbag +a tie +a suitcase +a frisbee +skis +a snowboard +a sports ball +a kite +a baseball bat +a baseball glove +a skateboard +a surfboard +a tennis racket +a bottle +a wine glass +a cup +a fork +a knife +a spoon +a bowl +a banana +an apple +a sandwich +an orange +broccoli +a carrot +a hot dog +a pizza +a donut +a cake +a chair +a couch +a potted plant +a bed +a dining table +a toilet +a tv +a laptop +a remote +a keyboard +a cell phone +a microwave +an oven +a toaster +a sink +a refrigerator +a book +a clock +a vase +scissors +a teddy bear +a hair drier +a toothbrush \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/overall_consistency.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/overall_consistency.txt new file mode 100644 index 0000000000000000000000000000000000000000..997a874fb4421275a78cd21c013e16274aa4f1b0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/overall_consistency.txt @@ -0,0 +1,93 @@ +Close up of grapes on a rotating table. +Turtle swimming in ocean. +A storm trooper vacuuming the beach. +A panda standing on a surfboard in the ocean in sunset. +An astronaut feeding ducks on a sunny afternoon, reflection from the water. +Two pandas discussing an academic paper. +Sunset time lapse at the beach with moving clouds and colors in the sky. +A fat rabbit wearing a purple robe walking through a fantasy landscape. +A koala bear playing piano in the forest. +An astronaut flying in space. +Fireworks. +An animated painting of fluffy white clouds moving in sky. +Flying through fantasy landscapes. +A bigfoot walking in the snowstorm. +A squirrel eating a burger. +A cat wearing sunglasses and working as a lifeguard at a pool. +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks. +Splash of turquoise water in extreme slow motion, alpha channel included. +an ice cream is melting on the table. +a drone flying over a snowy forest. +a shark is swimming in the ocean. +Aerial panoramic video from a drone of a fantasy land. +a teddy bear is swimming in the ocean. +time lapse of sunrise on mars. +golden fish swimming in the ocean. +An artist brush painting on a canvas close up. +A drone view of celebration with Christmas tree and fireworks, starry sky - background. +happy dog wearing a yellow turtleneck, studio, portrait, facing camera, dark background +Origami dancers in white paper, 3D render, on white background, studio shot, dancing modern dance. +Campfire at night in a snowy forest with starry sky in the background. +a fantasy landscape +A 3D model of a 1800s victorian house. +this is how I do makeup in the morning. +A raccoon that looks like a turtle, digital art. +Robot dancing in Times Square. +Busy freeway at night. +Balloon full of water exploding in extreme slow motion. +An astronaut is riding a horse in the space in a photorealistic style. +Macro slo-mo. Slow motion cropped closeup of roasted coffee beans falling into an empty bowl. +Sewing machine, old sewing machine working. +Motion colour drop in water, ink swirling in water, colourful ink in water, abstraction fancy dream cloud of ink. +Few big purple plums rotating on the turntable. water drops appear on the skin during rotation. isolated on the white background. close-up. macro. +Vampire makeup face of beautiful girl, red contact lenses. +Ashtray full of butts on table, smoke flowing on black background, close-up +Pacific coast, carmel by the sea ocean and waves. +A teddy bear is playing drum kit in NYC Times Square. +A corgi is playing drum kit. +An Iron man is playing the electronic guitar, high electronic guitar. +A raccoon is playing the electronic guitar. +A boat sailing leisurely along the Seine River with the Eiffel Tower in background by Vincent van Gogh +A corgi's head depicted as an explosion of a nebula +A fantasy landscape +A future where humans have achieved teleportation technology +A jellyfish floating through the ocean, with bioluminescent tentacles +A Mars rover moving on Mars +A panda drinking coffee in a cafe in Paris +A space shuttle launching into orbit, with flames and smoke billowing out from the engines +A steam train moving on a mountainside +A super cool giant robot in Cyberpunk Beijing +A tropical beach at sunrise, with palm trees and crystal-clear water in the foreground +Cinematic shot of Van Gogh's selfie, Van Gogh style +Gwen Stacy reading a book +Iron Man flying in the sky +The bund Shanghai, oil painting +Yoda playing guitar on the stage +A beautiful coastal beach in spring, waves lapping on sand by Hokusai, in the style of Ukiyo +A beautiful coastal beach in spring, waves lapping on sand by Vincent van Gogh +A boat sailing leisurely along the Seine River with the Eiffel Tower in background +A car moving slowly on an empty street, rainy evening +A cat eating food out of a bowl +A cat wearing sunglasses at a pool +A confused panda in calculus class +A cute fluffy panda eating Chinese food in a restaurant +A cute happy Corgi playing in park, sunset +A cute raccoon playing guitar in a boat on the ocean +A happy fuzzy panda playing guitar nearby a campfire, snow mountain in the background +A lightning striking atop of eiffel tower, dark clouds in the sky +A modern art museum, with colorful paintings +A panda cooking in the kitchen +A panda playing on a swing set +A polar bear is playing guitar +A raccoon dressed in suit playing the trumpet, stage background +A robot DJ is playing the turntable, in heavy raining futuristic tokyo rooftop cyberpunk night, sci-fi, fantasy +A shark swimming in clear Caribbean ocean +A super robot protecting city +A teddy bear washing the dishes +An epic tornado attacking above a glowing city at night, the tornado is made of smoke +An oil painting of a couple in formal evening wear going home get caught in a heavy downpour with umbrellas +Clown fish swimming through the coral reef +Hyper-realistic spaceship landing on Mars +The bund Shanghai, vibrant color +Vincent van Gogh is painting in the room +Yellow flowers swing in the wind \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/scene.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/scene.txt new file mode 100644 index 0000000000000000000000000000000000000000..729d4f263c7f4b60c55153b1601c6894960d6407 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/scene.txt @@ -0,0 +1,86 @@ +alley +amusement park +aquarium +arch +art gallery +bathroom +bakery shop +ballroom +bar +barn +basement +beach +bedroom +bridge +botanical garden +cafeteria +campsite +campus +carrousel +castle +cemetery +classroom +cliff +crosswalk +construction site +corridor +courtyard +desert +downtown +driveway +farm +food court +football field +forest road +fountain +gas station +glacier +golf course +indoor gymnasium +harbor +highway +hospital +house +iceberg +industrial area +jail cell +junkyard +kitchen +indoor library +lighthouse +laboratory +mansion +marsh +mountain +indoor movie theater +indoor museum +music studio +nursery +ocean +office +palace +parking lot +pharmacy +phone booth +raceway +restaurant +river +science museum +shower +ski slope +sky +skyscraper +baseball stadium +staircase +street +supermarket +indoor swimming pool +tower +outdoor track +train railway +train station platform +underwater coral reef +valley +volcano +waterfall +windmill \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/spatial_relationship.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/spatial_relationship.txt new file mode 100644 index 0000000000000000000000000000000000000000..05d30c07ade5b62b393dfc9e629ecf1c0d42018a --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/spatial_relationship.txt @@ -0,0 +1,84 @@ +a bicycle on the left of a car, front view +a car on the right of a motorcycle, front view +a motorcycle on the left of a bus, front view +a bus on the right of a traffic light, front view +a traffic light on the left of a fire hydrant, front view +a fire hydrant on the right of a stop sign, front view +a stop sign on the left of a parking meter, front view +a parking meter on the right of a bench, front view +a bench on the left of a truck, front view +a truck on the right of a bicycle, front view +a bird on the left of a cat, front view +a cat on the right of a dog, front view +a dog on the left of a horse, front view +a horse on the right of a sheep, front view +a sheep on the left of a cow, front view +a cow on the right of an elephant, front view +an elephant on the left of a bear, front view +a bear on the right of a zebra, front view +a zebra on the left of a giraffe, front view +a giraffe on the right of a bird, front view +a bottle on the left of a wine glass, front view +a wine glass on the right of a cup, front view +a cup on the left of a fork, front view +a fork on the right of a knife, front view +a knife on the left of a spoon, front view +a spoon on the right of a bowl, front view +a bowl on the left of a bottle, front view +a potted plant on the left of a remote, front view +a remote on the right of a clock, front view +a clock on the left of a vase, front view +a vase on the right of scissors, front view +scissors on the left of a teddy bear, front view +a teddy bear on the right of a potted plant, front view +a frisbee on the left of a sports ball, front view +a sports ball on the right of a baseball bat, front view +a baseball bat on the left of a baseball glove, front view +a baseball glove on the right of a tennis racket, front view +a tennis racket on the left of a frisbee, front view +a toilet on the left of a hair drier, front view +a hair drier on the right of a toothbrush, front view +a toothbrush on the left of a sink, front view +a sink on the right of a toilet, front view +a chair on the left of a couch, front view +a couch on the right of a bed, front view +a bed on the left of a tv, front view +a tv on the right of a dining table, front view +a dining table on the left of a chair, front view +an airplane on the left of a train, front view +a train on the right of a boat, front view +a boat on the left of an airplane, front view +an oven on the top of a toaster, front view +an oven on the bottom of a toaster, front view +a toaster on the top of a microwave, front view +a toaster on the bottom of a microwave, front view +a microwave on the top of an oven, front view +a microwave on the bottom of an oven, front view +a banana on the top of an apple, front view +a banana on the bottom of an apple, front view +an apple on the top of a sandwich, front view +an apple on the bottom of a sandwich, front view +a sandwich on the top of an orange, front view +a sandwich on the bottom of an orange, front view +an orange on the top of a carrot, front view +an orange on the bottom of a carrot, front view +a carrot on the top of a hot dog, front view +a carrot on the bottom of a hot dog, front view +a hot dog on the top of a pizza, front view +a hot dog on the bottom of a pizza, front view +a pizza on the top of a donut, front view +a pizza on the bottom of a donut, front view +a donut on the top of broccoli, front view +a donut on the bottom of broccoli, front view +broccoli on the top of a banana, front view +broccoli on the bottom of a banana, front view +skis on the top of a snowboard, front view +skis on the bottom of a snowboard, front view +a snowboard on the top of a kite, front view +a snowboard on the bottom of a kite, front view +a kite on the top of a skateboard, front view +a kite on the bottom of a skateboard, front view +a skateboard on the top of a surfboard, front view +a skateboard on the bottom of a surfboard, front view +a surfboard on the top of skis, front view +a surfboard on the bottom of skis, front view \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/subject_consistency.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/subject_consistency.txt new file mode 100644 index 0000000000000000000000000000000000000000..6f1f75c77c0bb36d933300ef2ba31254434cdda0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/subject_consistency.txt @@ -0,0 +1,72 @@ +a person swimming in ocean +a person giving a presentation to a room full of colleagues +a person washing the dishes +a person eating a burger +a person walking in the snowstorm +a person drinking coffee in a cafe +a person playing guitar +a bicycle leaning against a tree +a bicycle gliding through a snowy field +a bicycle slowing down to stop +a bicycle accelerating to gain speed +a car stuck in traffic during rush hour +a car turning a corner +a car slowing down to stop +a car accelerating to gain speed +a motorcycle cruising along a coastal highway +a motorcycle turning a corner +a motorcycle slowing down to stop +a motorcycle gliding through a snowy field +a motorcycle accelerating to gain speed +an airplane soaring through a clear blue sky +an airplane taking off +an airplane landing smoothly on a runway +an airplane accelerating to gain speed +a bus turning a corner +a bus stuck in traffic during rush hour +a bus accelerating to gain speed +a train speeding down the tracks +a train crossing over a tall bridge +a train accelerating to gain speed +a truck turning a corner +a truck anchored in a tranquil bay +a truck stuck in traffic during rush hour +a truck slowing down to stop +a truck accelerating to gain speed +a boat sailing smoothly on a calm lake +a boat slowing down to stop +a boat accelerating to gain speed +a bird soaring gracefully in the sky +a bird building a nest from twigs and leaves +a bird flying over a snowy forest +a cat grooming itself meticulously with its tongue +a cat playing in park +a cat drinking water +a cat running happily +a dog enjoying a peaceful walk +a dog playing in park +a dog drinking water +a dog running happily +a horse bending down to drink water from a river +a horse galloping across an open field +a horse taking a peaceful walk +a horse running to join a herd of its kind +a sheep bending down to drink water from a river +a sheep taking a peaceful walk +a sheep running to join a herd of its kind +a cow bending down to drink water from a river +a cow chewing cud while resting in a tranquil barn +a cow running to join a herd of its kind +an elephant spraying itself with water using its trunk to cool down +an elephant taking a peaceful walk +an elephant running to join a herd of its kind +a bear catching a salmon in its powerful jaws +a bear sniffing the air for scents of food +a bear climbing a tree +a bear hunting for prey +a zebra bending down to drink water from a river +a zebra running to join a herd of its kind +a zebra taking a peaceful walk +a giraffe bending down to drink water from a river +a giraffe taking a peaceful walk +a giraffe running to join a herd of its kind \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/temporal_flickering.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/temporal_flickering.txt new file mode 100644 index 0000000000000000000000000000000000000000..ce5104937764c492c7d0f735290019cd38878023 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/temporal_flickering.txt @@ -0,0 +1,75 @@ +In a still frame, a stop sign +a toilet, frozen in time +a laptop, frozen in time +A tranquil tableau of alley +A tranquil tableau of bar +A tranquil tableau of barn +A tranquil tableau of bathroom +A tranquil tableau of bedroom +A tranquil tableau of cliff +In a still frame, courtyard +In a still frame, gas station +A tranquil tableau of house +indoor gymnasium, frozen in time +A tranquil tableau of indoor library +A tranquil tableau of kitchen +A tranquil tableau of palace +In a still frame, parking lot +In a still frame, phone booth +A tranquil tableau of restaurant +A tranquil tableau of tower +A tranquil tableau of a bowl +A tranquil tableau of an apple +A tranquil tableau of a bench +A tranquil tableau of a bed +A tranquil tableau of a chair +A tranquil tableau of a cup +A tranquil tableau of a dining table +In a still frame, a pear +A tranquil tableau of a bunch of grapes +A tranquil tableau of a bowl on the kitchen counter +A tranquil tableau of a beautiful, handcrafted ceramic bowl +A tranquil tableau of an antique bowl +A tranquil tableau of an exquisite mahogany dining table +A tranquil tableau of a wooden bench in the park +A tranquil tableau of a beautiful wrought-iron bench surrounded by blooming flowers +In a still frame, a park bench with a view of the lake +A tranquil tableau of a vintage rocking chair was placed on the porch +A tranquil tableau of the jail cell was small and dimly lit, with cold, steel bars +A tranquil tableau of the phone booth was tucked away in a quiet alley +a dilapidated phone booth stood as a relic of a bygone era on the sidewalk, frozen in time +A tranquil tableau of the old red barn stood weathered and iconic against the backdrop of the countryside +A tranquil tableau of a picturesque barn was painted a warm shade of red and nestled in a picturesque meadow +In a still frame, within the desolate desert, an oasis unfolded, characterized by the stoic presence of palm trees and a motionless, glassy pool of water +In a still frame, the Parthenon's majestic Doric columns stand in serene solitude atop the Acropolis, framed by the tranquil Athenian landscape +In a still frame, the Temple of Hephaestus, with its timeless Doric grace, stands stoically against the backdrop of a quiet Athens +In a still frame, the ornate Victorian streetlamp stands solemnly, adorned with intricate ironwork and stained glass panels +A tranquil tableau of the Stonehenge presented itself as an enigmatic puzzle, each colossal stone meticulously placed against the backdrop of tranquility +In a still frame, in the vast desert, an oasis nestled among dunes, featuring tall palm trees and an air of serenity +static view on a desert scene with an oasis, palm trees, and a clear, calm pool of water +A tranquil tableau of an ornate Victorian streetlamp standing on a cobblestone street corner, illuminating the empty night +A tranquil tableau of a tranquil lakeside cabin nestled among tall pines, its reflection mirrored perfectly in the calm water +In a still frame, a vintage gas lantern, adorned with intricate details, gracing a historic cobblestone square +In a still frame, a tranquil Japanese tea ceremony room, with tatami mats, a delicate tea set, and a bonsai tree in the corner +A tranquil tableau of the Parthenon stands resolute in its classical elegance, a timeless symbol of Athens' cultural legacy +A tranquil tableau of in the heart of Plaka, the neoclassical architecture of the old city harmonizes with the ancient ruins +A tranquil tableau of in the desolate beauty of the American Southwest, Chaco Canyon's ancient ruins whispered tales of an enigmatic civilization that once thrived amidst the arid landscapes +A tranquil tableau of at the edge of the Arabian Desert, the ancient city of Petra beckoned with its enigmatic rock-carved façades +In a still frame, amidst the cobblestone streets, an Art Nouveau lamppost stood tall +A tranquil tableau of in the quaint village square, a traditional wrought-iron streetlamp featured delicate filigree patterns and amber-hued glass panels +A tranquil tableau of the lampposts were adorned with Art Deco motifs, their geometric shapes and frosted glass creating a sense of vintage glamour +In a still frame, in the picturesque square, a Gothic-style lamppost adorned with intricate stone carvings added a touch of medieval charm to the setting +In a still frame, in the heart of the old city, a row of ornate lantern-style streetlamps bathed the narrow alleyway in a warm, welcoming light +A tranquil tableau of in the heart of the Utah desert, a massive sandstone arch spanned the horizon +A tranquil tableau of in the Arizona desert, a massive stone bridge arched across a rugged canyon +A tranquil tableau of in the corner of the minimalist tea room, a bonsai tree added a touch of nature's beauty to the otherwise simple and elegant space +In a still frame, amidst the hushed ambiance of the traditional tea room, a meticulously arranged tea set awaited, with porcelain cups, a bamboo whisk +In a still frame, nestled in the Zen garden, a rustic teahouse featured tatami seating and a traditional charcoal brazier +A tranquil tableau of a country estate's library featured elegant wooden shelves +A tranquil tableau of beneath the shade of a solitary oak tree, an old wooden park bench sat patiently +A tranquil tableau of beside a tranquil pond, a weeping willow tree draped its branches gracefully over the water's surface, creating a serene tableau of reflection and calm +A tranquil tableau of in the Zen garden, a perfectly raked gravel path led to a serene rock garden +In a still frame, a tranquil pond was fringed by weeping cherry trees, their blossoms drifting lazily onto the glassy surface +In a still frame, within the historic library's reading room, rows of antique leather chairs and mahogany tables offered a serene haven for literary contemplation +A tranquil tableau of a peaceful orchid garden showcased a variety of delicate blooms +A tranquil tableau of in the serene courtyard, a centuries-old stone well stood as a symbol of a bygone era, its mossy stones bearing witness to the passage of time \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/temporal_style.txt b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/temporal_style.txt new file mode 100644 index 0000000000000000000000000000000000000000..9588b36c37801d1c71084ebb9a79801b18bb50ee --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/downloads/vbench/prompts_per_dimension/temporal_style.txt @@ -0,0 +1,100 @@ +A beautiful coastal beach in spring, waves lapping on sand, in super slow motion +A beautiful coastal beach in spring, waves lapping on sand, zoom in +A beautiful coastal beach in spring, waves lapping on sand, zoom out +A beautiful coastal beach in spring, waves lapping on sand, pan left +A beautiful coastal beach in spring, waves lapping on sand, pan right +A beautiful coastal beach in spring, waves lapping on sand, tilt up +A beautiful coastal beach in spring, waves lapping on sand, tilt down +A beautiful coastal beach in spring, waves lapping on sand, with an intense shaking effect +A beautiful coastal beach in spring, waves lapping on sand, featuring a steady and smooth perspective +A beautiful coastal beach in spring, waves lapping on sand, racking focus +The bund Shanghai, in super slow motion +The bund Shanghai, zoom in +The bund Shanghai, zoom out +The bund Shanghai, pan left +The bund Shanghai, pan right +The bund Shanghai, tilt up +The bund Shanghai, tilt down +The bund Shanghai, with an intense shaking effect +The bund Shanghai, featuring a steady and smooth perspective +The bund Shanghai, racking focus +a shark is swimming in the ocean, in super slow motion +a shark is swimming in the ocean, zoom in +a shark is swimming in the ocean, zoom out +a shark is swimming in the ocean, pan left +a shark is swimming in the ocean, pan right +a shark is swimming in the ocean, tilt up +a shark is swimming in the ocean, tilt down +a shark is swimming in the ocean, with an intense shaking effect +a shark is swimming in the ocean, featuring a steady and smooth perspective +a shark is swimming in the ocean, racking focus +A panda drinking coffee in a cafe in Paris, in super slow motion +A panda drinking coffee in a cafe in Paris, zoom in +A panda drinking coffee in a cafe in Paris, zoom out +A panda drinking coffee in a cafe in Paris, pan left +A panda drinking coffee in a cafe in Paris, pan right +A panda drinking coffee in a cafe in Paris, tilt up +A panda drinking coffee in a cafe in Paris, tilt down +A panda drinking coffee in a cafe in Paris, with an intense shaking effect +A panda drinking coffee in a cafe in Paris, featuring a steady and smooth perspective +A panda drinking coffee in a cafe in Paris, racking focus +A cute happy Corgi playing in park, sunset, in super slow motion +A cute happy Corgi playing in park, sunset, zoom in +A cute happy Corgi playing in park, sunset, zoom out +A cute happy Corgi playing in park, sunset, pan left +A cute happy Corgi playing in park, sunset, pan right +A cute happy Corgi playing in park, sunset, tilt up +A cute happy Corgi playing in park, sunset, tilt down +A cute happy Corgi playing in park, sunset, with an intense shaking effect +A cute happy Corgi playing in park, sunset, featuring a steady and smooth perspective +A cute happy Corgi playing in park, sunset, racking focus +Gwen Stacy reading a book, in super slow motion +Gwen Stacy reading a book, zoom in +Gwen Stacy reading a book, zoom out +Gwen Stacy reading a book, pan left +Gwen Stacy reading a book, pan right +Gwen Stacy reading a book, tilt up +Gwen Stacy reading a book, tilt down +Gwen Stacy reading a book, with an intense shaking effect +Gwen Stacy reading a book, featuring a steady and smooth perspective +Gwen Stacy reading a book, racking focus +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, in super slow motion +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, zoom in +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, zoom out +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, pan left +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, pan right +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, tilt up +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, tilt down +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, with an intense shaking effect +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, featuring a steady and smooth perspective +A boat sailing leisurely along the Seine River with the Eiffel Tower in background, racking focus +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, in super slow motion +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, zoom in +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, zoom out +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, pan left +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, pan right +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, tilt up +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, tilt down +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, with an intense shaking effect +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, featuring a steady and smooth perspective +A couple in formal evening wear going home get caught in a heavy downpour with umbrellas, racking focus +An astronaut flying in space, in super slow motion +An astronaut flying in space, zoom in +An astronaut flying in space, zoom out +An astronaut flying in space, pan left +An astronaut flying in space, pan right +An astronaut flying in space, tilt up +An astronaut flying in space, tilt down +An astronaut flying in space, with an intense shaking effect +An astronaut flying in space, featuring a steady and smooth perspective +An astronaut flying in space, racking focus +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, in super slow motion +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, zoom in +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, zoom out +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, pan left +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, pan right +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, tilt up +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, tilt down +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, with an intense shaking effect +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, featuring a steady and smooth perspective +Snow rocky mountains peaks canyon. snow blanketed rocky mountains surround and shadow deep canyons. the canyons twist and bend through the high elevated mountain peaks, racking focus \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3317ae2295580b9cb4375a375ed7cdea684ea036 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76af23d9fe0e895da97241ca2767a55cf4668f97 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..882ab751a039e9bc8fedd086c9b81e0e38110ed8 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__init__.py @@ -0,0 +1,37 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .common_utils import divide, env_is_true, set_random_seed +from .config import EngineConfig, MagiConfig, ModelConfig, RuntimeConfig +from .dataclass import InferenceParams, ModelMetaArgs, PackedCoreAttnParams, PackedCrossAttnParams +from .logger import magi_logger, print_per_rank, print_rank_0 +from .timer import event_path_timer + +__all__ = [ + "MagiConfig", + "ModelConfig", + "EngineConfig", + "RuntimeConfig", + "magi_logger", + "print_per_rank", + "print_rank_0", + "event_path_timer", + "divide", + "env_is_true", + "set_random_seed", + "PackedCoreAttnParams", + "PackedCrossAttnParams", + "ModelMetaArgs", + "InferenceParams", +] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94b58ef83885b13f2fac29a49e419234c0282605 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efba6b05e9e96e5fae3ea94af8559ee105fea9e9 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/common_utils.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/common_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9817adf9dafe07bcf61047e2b4f784ff02019036 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/common_utils.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/common_utils.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/common_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fea815164757dbcb742ea5b0119d196910bf0e9 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/common_utils.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/config.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ac962ebbbb89b559d49e3b47bc8ccf356bcf4c2 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/config.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/config.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f06f99f144f36dacd0ee80e2add0e8adfc18def1 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/config.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/dataclass.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/dataclass.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6d522f2878b89fa543c8534897c73d35cf0776e Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/dataclass.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/dataclass.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/dataclass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71d7ac2518432004ad1bef8fbd8a857fe5fdf0a7 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/dataclass.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/logger.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c5790384695b373abd3765c1292265cadcde60c Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/logger.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/logger.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e61cbd06d61225b7a6c148e4ffca44bc65df6997 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/logger.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/timer.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/timer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e46f55e2e204ff3daddf9a084a28a2788918d055 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/timer.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/timer.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/timer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4eafc37aa56b84ba71fbdd40162a609fa192a5b Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/__pycache__/timer.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/common_utils.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/common_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d3960150c93d595881e6d0be281ec5ffb0c22f73 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/common_utils.py @@ -0,0 +1,42 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import random + +import numpy as np +import torch + + +def env_is_true(env_name: str) -> bool: + return str(os.environ.get(env_name, "0")).lower() in {"1", "true", "yes", "y", "on", "enabled"} + + +def divide(numerator, denominator): + assert numerator % denominator == 0, "{} is not divisible by {}".format(numerator, denominator) + return numerator // denominator + + +def set_random_seed(seed): + """Set random seed. + + Args: + seed (int): Seed to be used. + """ + assert seed is not None, "Please provide a seed in config.json" + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + return seed diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/config.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a71ab92f693ad4c64f684e0ee45581db2a2a60df --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/config.py @@ -0,0 +1,180 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import dataclasses +import json +import os + +import torch + + +@dataclasses.dataclass +class ModelConfig: + model_name: str + + # Transformer + num_layers: int = None # Number of transformer layers. + hidden_size: int = None # Transformer hidden size. + ffn_hidden_size: int = None # Transformer Feed-Forward Network hidden size + num_attention_heads: int = None # Number of transformer attention heads. + num_query_groups: int = 1 # Number of query groups, which used for GQA + kv_channels: int = None # Projection weights dimension in multi-head attention + layernorm_epsilon: float = 1e-6 # Epsilon for layer norm and RMS norm. + apply_layernorm_1p: bool = False # Adjust LayerNorm weights which improves numerical stability. + x_rescale_factor: float = 1.0 + half_channel_vae: bool = False + params_dtype: torch.dtype = None + + # Embedding + patch_size: int = 2 # (latent) patch size for DiT patch embedding layer + t_patch_size: int = 1 # (latent) patch size for t dim patch embedding layer + in_channels: int = 4 # latent input channel for DiT + out_channels: int = 4 # latent output channel for DiT + cond_hidden_ratio: float = 0.25 + caption_channels: int = 4096 + caption_max_length: int = 800 + xattn_cond_hidden_ratio: float = 1.0 + cond_gating_ratio: float = 1.0 + gated_linear_unit: bool = False + + +@dataclasses.dataclass +class RuntimeConfig: + # Inference settings such as cfg, kv range, clean t, etc. + cfg_number: int = None # Number of CFG + cfg_t_range: list = dataclasses.field( + default_factory=lambda: [0, 0.0217, 0.1000, 0.3, 0.999] + ) # CFG t-range of each scales + prev_chunk_scales: list = dataclasses.field( + default_factory=lambda: [1.5, 1.5, 1.5, 1.5, 1.5] + ) # CFG scales of previous chunks + text_scales: list = dataclasses.field(default_factory=lambda: [7.5, 7.5, 7.5, 7.5, 7.5]) # CFG scales of text + + noise2clean_kvrange: list = dataclasses.field(default_factory=list) # Range of kv for noise2clean chunks + clean_chunk_kvrange: int = -1 # Range of kv for clean chunks + clean_t: float = 1.0 # timestep for clean chunks + + # Video settings + seed: int = 1234 # Random seed used for python, numpy, pytorch, and cuda. + num_frames: int = 128 + video_size_h: int = None + video_size_w: int = None + num_steps: int = 64 # Number of steps for the diffusion model + window_size: int = 4 # Window size for the diffusion model + fps: int = 24 # Frames per second + chunk_width: int = 6 # Clip width for the diffusion model + + # Checkpoint, includes t5, vae, dit, etc. + t5_pretrained: str = None # Path to load pretrained T5 model. + t5_device: str = "cuda" # Device for T5 model to run on. + vae_pretrained: str = None # Path to load pretrained VAE model. + scale_factor: float = 0.18215 # Scale factor for the vae + temporal_downsample_factor: int = 4 # Temporal downsample factor for the vae + load: str = None # Directory containing a model checkpoint. + + +@dataclasses.dataclass +class EngineConfig: + # Parallism strategy + distributed_backend: str = "nccl" # Choices: ["nccl", "gloo"] + distributed_timeout_minutes: int = 10 # Timeout minutes for torch.distributed. + pp_size: int = 1 # Degree of pipeline model parallelism. + cp_size: int = 1 # Degree of context parallelism. + cp_strategy: str = "none" # Choices: ["none", "cp_ulysses", "cp_shuffle_overlap"] + ulysses_overlap_degree: int = 1 # Overlap degree for Ulysses + + # Quantization + fp8_quant: bool = False # Enable 8-bit floating point quantization for model weights. + + # Distillation + distill_nearly_clean_chunk_threshold: float = 0.3 # Threshold for distilling nearly clean chunks + shortcut_mode: str = "8,16,16" # Parameters for shortcut mode + distill: bool = False # Use distill mode + + # Optimization + kv_offload: bool = False # Use kv-offload algorithm + enable_cuda_graph: bool = False # Enable CUDA graph for video generation + + +@dataclasses.dataclass +class MagiConfig: + model_config: ModelConfig + runtime_config: RuntimeConfig + engine_config: EngineConfig + + @classmethod + def _check_missing_fields(cls, config_dict: dict, required_fields: list): + actual_fields = set(config_dict.keys()) + missing_fields = set(required_fields) - actual_fields + if missing_fields: + raise ValueError(f"Missing fields in the configuration file: {', '.join(missing_fields)}") + + @classmethod + def _create_nested_config(cls, config_dict: dict, config_name: str, config_cls): + nested_config_dict = config_dict.get(config_name, {}) + cls._check_missing_fields(nested_config_dict, config_cls.__dataclass_fields__.keys()) + return config_cls(**nested_config_dict) + + @classmethod + def _create_config_from_dict(cls, config_dict: dict): + cls._check_missing_fields(config_dict, cls.__dataclass_fields__.keys()) + + # Create nested configs + model_config = cls._create_nested_config(config_dict, "model_config", ModelConfig) + runtime_config = cls._create_nested_config(config_dict, "runtime_config", RuntimeConfig) + engine_config = cls._create_nested_config(config_dict, "engine_config", EngineConfig) + + return cls(model_config=model_config, runtime_config=runtime_config, engine_config=engine_config) + + @classmethod + def from_json(cls, json_path: str): + def simple_json_decoder(dct): + dtype_map = {"torch.bfloat16": torch.bfloat16, "torch.float16": torch.float16, "torch.float32": torch.float32} + if 'params_dtype' in dct: + dct['params_dtype'] = dtype_map[dct['params_dtype']] + return dct + + with open(json_path, "r") as f: + config_dict = json.load(f, object_hook=simple_json_decoder) + magi_config = cls._create_config_from_dict(config_dict) + + def post_validation(magi_config): + if magi_config.engine_config.fp8_quant or magi_config.engine_config.distill: + assert ( + magi_config.runtime_config.cfg_number == 1 + ), "Please set `cfg_number: 1` in config.json for distill or quant model" + else: + assert magi_config.runtime_config.cfg_number == 3, "Please set `cfg_number: 3` in config.json for base model" + + post_validation(magi_config) + + return magi_config + + def to_json(self, json_path: str): + class SimpleJSONEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, torch.dtype): + return str(obj) + return super().default(obj) + + # Ensure the directory exists + os.makedirs(os.path.dirname(json_path), exist_ok=True) + + config_dict = { + "model_config": dataclasses.asdict(self.model_config), + "runtime_config": dataclasses.asdict(self.runtime_config), + "engine_config": dataclasses.asdict(self.engine_config), + } + with open(json_path, "w") as f: + json.dump(config_dict, f, indent=4, cls=SimpleJSONEncoder) diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/dataclass.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/dataclass.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe92d9a0b677683b37b5e750c193afe3397e6da --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/dataclass.py @@ -0,0 +1,97 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass +from typing import List + +import numpy as np +import torch + + +@dataclass(frozen=True) +class PackedCoreAttnParams: + # Packed sequence parameters for core_attn + q_range: torch.Tensor + k_range: torch.Tensor + np_q_range: np.ndarray + np_k_range: np.ndarray + max_seqlen_q: int + max_seqlen_k: int + + +@dataclass(frozen=True) +class PackedCrossAttnParams: + # Packed sequence parameters for cross_attn + q_ranges: torch.Tensor = None + kv_ranges: torch.Tensor = None + cu_seqlens_q: torch.Tensor = None + cu_seqlens_kv: torch.Tensor = None + max_seqlen_q: int = None + max_seqlen_kv: int = None + + +@dataclass(frozen=True) +class ModelMetaArgs: + H: int + W: int + cp_pad_size: int + cp_split_sizes: List[int] + slice_point: int + denoising_range_num: int + range_num: int + extract_prefix_video_feature: bool + fwd_extra_1st_chunk: bool + distill_nearly_clean_chunk: bool + clip_token_nums: int + enable_cuda_graph: bool + core_attn_params: PackedCoreAttnParams + cross_attn_params: PackedCrossAttnParams + timestep: torch.Tensor + get_attn_weights_layer_num: int + save_kvcache_every_forward: bool + cur_denoise_step: int + # Includes all chunks of the current sequence + start_chunk_id: int + end_chunk_id: int + compress_kv: bool # use kv cache compression or not + total_cache_len: int + budget_cache_len: int + chunk_num: int + debug: bool + near_clean_chunk_idx: int + +class InferenceParams: + """Inference parameters that are passed to the main model in order + to efficienly calculate and store the context during inference.""" + + def __init__(self, max_batch_size, max_sequence_length): + self.max_sequence_length = max_sequence_length + self.max_batch_size = max_batch_size + self.sequence_len_offset = 0 + self.key_value_memory_dict = {} + self.update_kv_cache = False + + self.kv_compressed = False + + def swap_key_value_dict(self, batch_idx): + "swap between batches" + if len(self.key_value_memory_dict) == 0: + raise ValueError("should not swap when dict in empty") + + for layer_number in self.key_value_memory_dict.keys(): + inference_key_memory, inference_value_memory = self.key_value_memory_dict[layer_number] + assert len(batch_idx) == inference_key_memory.shape[1] # make sure batch size is the same + new_inference_key_memory = inference_key_memory[:, batch_idx] + new_inference_value_memory = inference_value_memory[:, batch_idx] + self.key_value_memory_dict[layer_number] = (new_inference_key_memory, new_inference_value_memory) diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/logger.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5d1072df87334090dbe286f55d7a1056fd4cae2e --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/logger.py @@ -0,0 +1,51 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import torch + + +class GlobalLogger: + _logger = None + + @classmethod + def get_logger(cls, name=__name__, level=logging.INFO): + if cls._logger is None: + cls._logger = logging.getLogger("magi_logger") + cls._logger.setLevel(logging.INFO) + + cls._logger.propagate = False + cls._logger.handlers.clear() + formatter = logging.Formatter("[%(asctime)s - %(levelname)s] %(message)s") + handler = logging.StreamHandler() + handler.setFormatter(formatter) + cls._logger.addHandler(handler) + + return cls._logger + + +magi_logger = GlobalLogger.get_logger() + + +def print_per_rank(message): + magi_logger.info(message) + + +def print_rank_0(message): + if torch.distributed.is_initialized(): + if torch.distributed.get_rank() == 0: + magi_logger.info(message) + else: + magi_logger.info(message) diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/timer.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..d0c9f58fdeefb791f548276bea42f5e1288d495e --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/common/timer.py @@ -0,0 +1,85 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime + +import torch + +from .logger import print_rank_0 + + +class EventPathTimer: + """ + A lightweight class for recording time without any distributed barrier. + + This class allows for recording elapsed time between events without requiring + synchronization across distributed processes. It maintains the previous message + and time to calculate the duration between consecutive records. + """ + + def __init__(self): + """ + Initialize the EventPathTimer. + + This constructor sets the previous message and time to None, preparing + the instance for recording events. + """ + self.prev_message: str = None + self.prev_time: datetime = None + + def reset(self): + """ + Reset the recorded message and time. + + This method clears the previous message and time, allowing for a fresh + start in recording new events. + """ + self.prev_message = None + self.prev_time = None + + def synced_record(self, message): + """ + Record the current time with a message. + + Args: + message (str): A message to log along with the current time. + + This method synchronizes the CUDA operations, records the current time, + and calculates the elapsed time since the last recorded message, if any. + It then logs the elapsed time along with the previous and current messages. + """ + torch.cuda.synchronize() + current_time = datetime.now() + if self.prev_message is not None: + print_rank_0( + f"\nTime Elapsed: [{current_time - self.prev_time}] From [{self.prev_message} ({self.prev_time})] To [{message} ({current_time})]" + ) + self.prev_message = message + self.prev_time = current_time + + +_GLOBAL_LIGHT_TIMER = EventPathTimer() + + +def event_path_timer() -> EventPathTimer: + """Get the current EventPathTimer instance. + + Returns: + EventPathTimer: The current EventPathTimer instance. + + Raises: + AssertionError: If the EventPathTimer has not been initialized. + """ + assert _GLOBAL_LIGHT_TIMER is not None, "light time recorder is not initialized" + return _GLOBAL_LIGHT_TIMER diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1419f26c98ef95bed6651827747da6dca50b07 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .checkpointing import load_checkpoint + +__all__ = ["load_checkpoint"] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8597bf6ec7768fb12be7d6e87c76a094eaae8b8e Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..867772e83fac1164daefab338f157409d3de6d24 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7378664282df21ded92c47c3e940b3e2679e86f9 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/checkpointing.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/checkpointing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e6e0ab1708ac4082cdbb34de6667f4bf26a1034 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/__pycache__/checkpointing.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/checkpointing.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..983a0100d704e8e9403f785fe0cd4b060ff8eca3 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/checkpoint/checkpointing.py @@ -0,0 +1,180 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import io +import json +import os +import re +import subprocess +from collections import OrderedDict +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime + +import numpy as np +import torch +import torch.distributed +from safetensors.torch import load as load_from_bytes +from safetensors.torch import load_file +from tqdm.auto import tqdm + +import inference.infra.distributed.parallel_state as mpu +from inference.common import EngineConfig, ModelConfig, RuntimeConfig, print_per_rank, print_rank_0 + + +def _load_shard(shard_path, param_names, num_threads=None): + zstd_path = shard_path + ".zst" + if os.path.exists(zstd_path): + start_time = datetime.now() + print_per_rank(f"Decompressing {zstd_path} with {num_threads} threads") + cmd = ["zstd", "-d"] + if num_threads: + cmd.extend(["-T", str(num_threads)]) + + process = subprocess.Popen(cmd + ["-c", zstd_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) + + decompressed_data = process.stdout.read() + process.stdout.close() + + retcode = process.wait() + if retcode != 0: + raise RuntimeError(f"Decompression failed: {process.stderr.read().decode()}") + print_per_rank( + f"Decompressed {zstd_path} with {num_threads} threads, duration: {(datetime.now() - start_time).total_seconds()}s" + ) + + buffer = io.BytesIO(decompressed_data) + start_time = datetime.now() + print_per_rank(f"Loading {shard_path} from zstd file, start time: {start_time}") + weights = load_from_bytes(buffer.getvalue()) + print_per_rank(f"Loaded {shard_path} from zstd file, duration: {(datetime.now() - start_time).total_seconds()}s") + buffer.close() + else: + weights = load_file(shard_path) + + return {name: weights[name] for name in param_names} + + +def load_sharded_safetensors_parallel_with_progress(checkpoint_dir): + index_path = os.path.join(checkpoint_dir, "model.safetensors.index.json") + if not os.path.exists(index_path): + model_file_path = os.path.join(checkpoint_dir, "model.safetensors") + state_dict = load_file(model_file_path) + return state_dict + + with open(index_path, "r") as f: + index = json.load(f) + + state_dict = {} + shard_map = {} + + # Group parameters by shard file + for param_name, shard_file in index["weight_map"].items(): + shard_path = os.path.join(checkpoint_dir, shard_file) + if shard_path not in shard_map: + shard_map[shard_path] = [] + shard_map[shard_path].append(param_name) + + # Load shards in parallel with a progress bar + with ThreadPoolExecutor() as executor: + futures = { + executor.submit(_load_shard, shard_path, param_names): shard_path for shard_path, param_names in shard_map.items() + } + pbar = tqdm(futures, desc="Loading shards", total=len(futures)) + for future in pbar: + result = future.result() + state_dict.update(result) + + return state_dict + + +def unwrap_model(model): + return_list = True + if not isinstance(model, list): + model = [model] + return_list = False + unwrapped_model = [] + for model_module in model: + while hasattr(model_module, "module"): + model_module = model_module.module + unwrapped_model.append(model_module) + if not return_list: + return unwrapped_model[0] + return unwrapped_model + + +def _split_state_dict_for_pp(weight_dict: OrderedDict, model_config: ModelConfig): + num_layers = model_config.num_layers + partition = mpu.get_pp_world_size() + + ## use partition and num_layers to get current rank layer order + layers_for_each_stage = np.array_split(range(num_layers), partition) + current_stage = mpu.get_pp_rank() + allow_layer_num = layers_for_each_stage[current_stage] + layer_offset = allow_layer_num[0] + new_weight_dict = {} + for k, v in weight_dict.items(): + if "videodit_blocks.layers" in k: + layer_num = int(re.search(r"videodit_blocks\.layers\.(\d+)", k).group(1)) + if layer_num not in allow_layer_num: + continue + ## replace the old key name by new layer number + new_layer_num = layer_num - layer_offset + new_k = k.replace(f"videodit_blocks.layers.{layer_num}", f"videodit_blocks.layers.{new_layer_num}") + new_weight_dict[new_k] = v + else: + new_weight_dict[k] = v + return new_weight_dict + + +def load_state_dict(runtime_config: RuntimeConfig, engine_config: EngineConfig): + load_dir = runtime_config.load + + default_subdir = "inference_weight" + if engine_config.fp8_quant: + default_subdir = f"{default_subdir}.fp8" + if engine_config.distill: + default_subdir = f"{default_subdir}.distill" + inference_weight_dir = os.path.join(load_dir, default_subdir) + + print_rank_0(f"load {default_subdir} weight from {inference_weight_dir}") + assert ( + os.path.exists(inference_weight_dir) and len(os.listdir(inference_weight_dir)) > 0 + ), f"Ckpt directory {inference_weight_dir} does not exist or empty. If you are using fp8_quant, please run calibration first." + state_dict = load_sharded_safetensors_parallel_with_progress(inference_weight_dir) + return state_dict + + +def load_checkpoint(model): + state_dict = load_state_dict(model.runtime_config, model.engine_config) + + model = unwrap_model(model) + # if we use pipeline parallelism, we need to load the state dict for each stage + # as it always record layer from 0 -> num_layers//pipeline_parallel_size + # so we need to choose correct layer weight when load_state_dict + if mpu.get_pp_world_size() > 1: + state_dict = _split_state_dict_for_pp(state_dict, model.model_config) + + missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False, assign=True) + model.cuda(torch.cuda.current_device()) # bottleneck for loading + + if mpu.get_pp_world_size() > 1: + rank_msg = f"CP_rank={mpu.get_cp_rank()} PP_rank={mpu.get_pp_rank()}" + print_per_rank( + f"""[{rank_msg}] Load Weight Missing Keys: {missing_keys} Load Weight Unexpected Keys: {unexpected_keys} You should see message [missing fianl layer norm weight] except the final pipeline stage""" + ) + else: + print_rank_0(f"Load Weight Missing Keys: {missing_keys}") + print_rank_0(f"Load Weight Unexpected Keys: {unexpected_keys}") + + return model diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cd0ee9562fb933de643436dece53cc66c979214f --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__init__.py @@ -0,0 +1,73 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .dist_utils import dist_init, get_device, get_world_size, is_last_rank, is_last_tp_cp_rank +from .parallel_state import ( + destroy_model_parallel, + get_cp_group, + get_cp_rank, + get_cp_world_size, + get_dp_group, + get_dp_group_gloo, + get_dp_rank, + get_dp_world_size, + get_pipeline_model_parallel_first_rank, + get_pipeline_model_parallel_last_rank, + get_pipeline_model_parallel_next_rank, + get_pipeline_model_parallel_prev_rank, + get_pp_group, + get_pp_rank, + get_pp_world_size, + get_tensor_model_parallel_last_rank, + get_tensor_model_parallel_ranks, + get_tensor_model_parallel_src_rank, + get_tp_group, + get_tp_rank, + get_tp_world_size, + is_initialized, + is_pipeline_first_stage, + is_pipeline_last_stage, +) + +__all__ = [ + "dist_init", + "is_initialized", + "get_tp_group", + "get_pp_group", + "get_dp_group", + "get_dp_group_gloo", + "get_cp_group", + "get_tp_world_size", + "get_pp_world_size", + "get_dp_world_size", + "get_cp_world_size", + "get_tp_rank", + "get_pp_rank", + "get_dp_rank", + "get_cp_rank", + "is_pipeline_first_stage", + "is_pipeline_last_stage", + "get_tensor_model_parallel_src_rank", + "get_tensor_model_parallel_ranks", + "get_tensor_model_parallel_last_rank", + "get_pipeline_model_parallel_first_rank", + "get_pipeline_model_parallel_last_rank", + "get_pipeline_model_parallel_next_rank", + "get_pipeline_model_parallel_prev_rank", + "destroy_model_parallel", + "is_last_rank", + "is_last_tp_cp_rank", + "get_world_size", + "get_device", +] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c324778aa873f6736f99183b3c168076aa63f1b7 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b16084fbe45228dd7be901e4d6a72099178de4 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e73585e5c7687e4550b6a26cbf7c5d4cb5074b0 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/dist_utils.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/dist_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c78d21eac2fc09394d4f032206e908bf666467e Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/dist_utils.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..654aa0125a5cb770ef2baf892c41213027577965 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/parallel_state.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/parallel_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f1be984d5f5ee060bdda1f1c8eadb31fb900681 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/__pycache__/parallel_state.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/dist_utils.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/dist_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..35168c40b3413e91db14fa09c1a2e7e30f4da957 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/dist_utils.py @@ -0,0 +1,92 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from datetime import timedelta + +import torch + +import inference.infra.distributed.parallel_state as mpu +from inference.common import print_rank_0 +from inference.infra.parallelism.pipeline_parallel import init_pp_scheduler + +from . import parallel_state as mpu + + +def dist_init(config): + """Initialize torch.distributed and core model parallel.""" + + assert torch.cuda.is_available() + device_count = torch.cuda.device_count() + if torch.distributed.is_initialized(): + print_rank_0("Torch distribution already initialized, skipping initialization ...") + else: + rank = int(os.getenv("RANK", "0")) + world_size = int(os.getenv("WORLD_SIZE", "1")) + # Manually set the device ids. + if device_count > 0: + device = rank % device_count + torch.cuda.set_device(device) + # Call the init process + torch.distributed.init_process_group( + backend=config.engine_config.distributed_backend, + world_size=world_size, + rank=rank, + timeout=timedelta(minutes=config.engine_config.distributed_timeout_minutes), + ) + assert config.engine_config.cp_size * config.engine_config.pp_size == torch.distributed.get_world_size() + if device_count > 0: + if mpu.model_parallel_is_initialized(): + print_rank_0("Model parallel is already initialized") + else: + mpu.initialize_model_parallel( + cp_size=config.engine_config.cp_size, + pp_size=config.engine_config.pp_size, + nccl_communicator_config_path=None, + distributed_timeout_minutes=config.engine_config.distributed_timeout_minutes, + order="tp-cp-pp-dp", + ) + if mpu.get_pp_world_size() > 1: + init_pp_scheduler() + print_rank_0("Initialize torch distribution and model parallel successfully") + + +def is_last_rank(): + return torch.distributed.get_rank() == (torch.distributed.get_world_size() - 1) + + +def is_last_tp_cp_rank(): + return mpu.get_tp_rank(with_context_parallel=True) == mpu.get_tp_world_size(with_context_parallel=True) - 1 + + +def get_world_size(): + if torch.distributed.is_available() and torch.distributed.is_initialized(): + world_size = torch.distributed.get_world_size() + else: + world_size = 1 + return world_size + + +def get_device(local_rank=None): + backend = torch.distributed.get_backend() + if backend == "nccl": + if local_rank is None: + device = torch.device("cuda") + else: + device = torch.device(f"cuda:{local_rank}") + elif backend == "gloo": + device = torch.device("cpu") + else: + raise RuntimeError + return device diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/parallel_state.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/parallel_state.py new file mode 100644 index 0000000000000000000000000000000000000000..0ec2d14525eabcf739ab8eb1d4afebc3d58b29ca --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/distributed/parallel_state.py @@ -0,0 +1,672 @@ +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Model and data parallel groups.""" + +import warnings +from datetime import timedelta +from typing import List, Optional + +import torch + +# Intra-layer model parallel group that the current rank belongs to. +_TENSOR_MODEL_PARALLEL_GROUP = None +# Tensor parallel group information with context parallel combined. +_TENSOR_MODEL_PARALLEL_GROUP_WITH_CP = None +_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP = None +# Inter-layer model parallel group that the current rank belongs to. +_PIPELINE_MODEL_PARALLEL_GROUP = None +# Model parallel group (both intra- and pipeline) that the current rank belongs to. +_MODEL_PARALLEL_GROUP = None +# Data parallel group that the current rank belongs to. +_DATA_PARALLEL_GROUP = None +_DATA_PARALLEL_GROUP_GLOO = None +# tensor model parallel group and data parallel group combined +# used for fp8 and moe training +_TENSOR_AND_DATA_PARALLEL_GROUP = None + +# A list of global ranks for each pipeline group to ease calculation of the source +# rank when broadcasting from the first or last pipeline stage. +_PIPELINE_GLOBAL_RANKS = None + +# A list of global ranks for each data parallel group to ease calculation of the source +# rank when broadcasting weights from src to all other data parallel ranks +_DATA_PARALLEL_GLOBAL_RANKS = None + +# A list of global ranks for each tensor model parallel group to ease calculation of +# the first local rank in the tensor model parallel group +_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS = None + +# Context parallel group that the current rank belongs to +_CONTEXT_PARALLEL_GROUP = None +# A list of global ranks for each context parallel group to ease calculation of the +# destination rank when exchanging KV/dKV between context parallel_ranks +_CONTEXT_PARALLEL_GLOBAL_RANKS = None + +# Data parallel group information with context parallel combined. +_DATA_PARALLEL_GROUP_WITH_CP = None +_DATA_PARALLEL_GROUP_WITH_CP_GLOO = None +_DATA_PARALLEL_GLOBAL_RANKS_WITH_CP = None + +# combined parallel group of TP, DP, and CP used for fp8 +_TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP = None + + +def get_nccl_options(pg_name, nccl_comm_cfgs): + """Set the NCCL process group options. + + Args: + pg_name (str): process group name + nccl_comm_cfgs (dict): nccl communicator configurations + + When an option (e.g., max_ctas) is not found in the config, use the NCCL default setting. + """ + if pg_name in nccl_comm_cfgs: + nccl_options = torch.distributed.ProcessGroupNCCL.Options() + nccl_options.config.cga_cluster_size = nccl_comm_cfgs[pg_name].get("cga_cluster_size", 4) + nccl_options.config.max_ctas = nccl_comm_cfgs[pg_name].get("max_ctas", 32) + nccl_options.config.min_ctas = nccl_comm_cfgs[pg_name].get("min_ctas", 1) + return nccl_options + else: + return None + + +def generate_masked_orthogonal_rank_groups(world_size: int, parallel_size: List[int], mask: List[bool]) -> List[List[int]]: + """Generate orthogonal parallel groups based on the parallel size and mask. + + Arguments: + world_size (int): world size + + parallel_size (List[int]): + The parallel size of each orthogonal parallel type. For example, if + tensor_parallel_size = 2, pipeline_model_parallel_group = 3, data_parallel_size = 4, + and the parallel mapping order is tp-pp-dp, then the parallel_size = [2, 3, 4]. + + mask (List[bool]): + The mask controls which parallel methods the generated groups represent. If mask[i] is + True, it means the generated group contains the i-th parallelism method. For example, + if parallel_size = [tp_size, pp_size, dp_size], and mask = [True, False , True], then + the generated group is the `tp-dp` group, if the mask = [False, True, False], then the + generated group is the `pp` group. + + Algorithm: + For orthogonal parallelism, such as tp/dp/pp/cp, the global_rank and + local_rank satisfy the following equation: + global_rank = tp_rank + dp_rank * tp_size + pp_rank * tp_size * dp_size (1) + tp_rank \in [0, tp_size) + dp_rank \in [0, dp_size) + pp_rank \in [0, pp_size) + + If we want to get the `dp_group` (tp_size * pp_size groups of dp_size ranks each. + For example, if the gpu size is 8 and order is 'tp-pp-dp', size is '2-2-2', and the + dp_group here is [[0, 4], [1, 5], [2, 6], [3, 7]].) + The tp_rank and pp_rank will be combined to form the `dp_group_index`. + dp_group_index = tp_rank + pp_rank * tp_size (2) + + So, Given that tp_rank and pp_rank satisfy equation (2), and dp_rank in + range(0, dp_size), the ranks in dp_group[dp_group_index] satisfies the + equation (1). + + This function solve this math problem. + + For example, if the parallel_size = [tp_size, dp_size, pp_size] = [2, 3, 4], + and the mask = [False, True, False]. Then, + dp_group_index(0) = tp_rank(0) + pp_rank(0) * 2 + dp_group_index(1) = tp_rank(1) + pp_rank(0) * 2 + ... + dp_group_index(7) = tp_rank(1) + pp_rank(3) * 2 + + dp_group[0] = 0 + range(0, 3) * 2 + 0 = [0, 2, 4] + dp_group[1] = 1 + range(0, 3) * 2 + 0 = [1, 3, 5] + ... + dp_group[7] = 1 + range(0, 3) * 2 + 3 * 2 * 3 = [19, 21, 23] + """ + + def prefix_product(a: List[int], init=1) -> List[int]: + r = [init] + for v in a: + init = init * v + r.append(init) + return r + + def inner_product(a: List[int], b: List[int]) -> int: + return sum([x * y for x, y in zip(a, b)]) + + def decompose(index, shape, stride=None): + """ + This function solve the math problem below: + There is an equation: + index = sum(idx[i] * stride[i]) + And given the value of index, stride. + Return the idx. + This function will used to get the pp/dp/pp_rank + from group_index and rank_in_group. + """ + if stride is None: + stride = prefix_product(shape) + idx = [(index // d) % s for s, d in zip(shape, stride)] + # stride is a prefix_product result. And the value of stride[-1] + # is not used. + assert ( + sum([x * y for x, y in zip(idx, stride[:-1])]) == index + ), "idx {} with shape {} mismatch the return idx {}".format(index, shape, idx) + return idx + + masked_shape = [s for s, m in zip(parallel_size, mask) if m] + unmasked_shape = [s for s, m in zip(parallel_size, mask) if not m] + + global_stride = prefix_product(parallel_size) + masked_stride = [d for d, m in zip(global_stride, mask) if m] + unmasked_stride = [d for d, m in zip(global_stride, mask) if not m] + + group_size = prefix_product(masked_shape)[-1] + num_of_group = world_size // group_size + + ranks = [] + for group_index in range(num_of_group): + # get indices from unmaksed for group_index. + decomposed_group_idx = decompose(group_index, unmasked_shape) + rank = [] + for rank_in_group in range(group_size): + # get indices from masked for rank_in_group. + decomposed_rank_idx = decompose(rank_in_group, masked_shape) + rank.append( + inner_product(decomposed_rank_idx, masked_stride) + inner_product(decomposed_group_idx, unmasked_stride) + ) + ranks.append(rank) + return ranks + + +class RankGenerator(object): + def __init__(self, tp: int, dp: int, pp: int, cp: int, order: str) -> None: + self.tp = tp + self.dp = dp + self.pp = pp + self.cp = cp + self.world_size = tp * dp * pp * cp + + self.name_to_size = {"tp": self.tp, "pp": self.pp, "dp": self.dp, "cp": self.cp} + order = order.lower() + for name in self.name_to_size.keys(): + if name not in order and self.name_to_size[name] != 1: + raise RuntimeError( + f"The size of ({name}) is ({self.name_to_size[name]}), but you haven't specified the order ({self.order})." + ) + elif name not in order: + order = order + "-" + name + + self.order = order + self.ordered_size = [self.name_to_size[token] for token in order.split("-")] + + def get_mask(self, order: str, token: str): + ordered_token = order.split("-") + token = token.split("-") + mask = [False] * len(ordered_token) + for t in token: + mask[ordered_token.index(t)] = True + return mask + + def get_ranks(self, token): + """Get rank group by input token. + + Arguments: + token (str): + Specify the ranks type that want to get. If we want + to obtain multiple parallel types, we can use a hyphen + '-' to separate them. For example, if we want to obtain + the TP_DP group, the token should be 'tp-dp'. + """ + mask = self.get_mask(self.order, token) + ranks = generate_masked_orthogonal_rank_groups(self.world_size, self.ordered_size, mask) + return ranks + + +def initialize_model_parallel( + tp_size: int = 1, + pp_size: int = 1, + cp_size: int = 1, + nccl_communicator_config_path: Optional[str] = None, + distributed_timeout_minutes: int = 30, + order: str = "tp-cp-pp-dp", +) -> None: + """Initialize model data parallel groups. + Borrow from: https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py + + Args: + tp_size (int, default = 1): + The number of GPUs to split individual tensors across. + + pp_size (int, default = 1): + The number of tensor parallel GPU groups to split the + Transformer layers across. For example, if tp_size is 4 and + pp_size is 2, the model will be split into 2 groups of 4 GPUs. + + cp_size (int, default = 1): + The number of tensor parallel GPU groups to split the + network input sequence length across. Compute of attention + module requires tokens of full sequence length, so GPUs + in a context parallel group need to communicate with each + other to exchange information of other sequence chunks. + Each GPU and its counterparts in other tensor parallel + groups compose a context parallel group. + + For example, assume we have 8 GPUs, if tensor model parallel + size is 4 and context parallel size is 2, the network input + will be split into two sequence chunks, which are processed + by 2 different groups of 4 GPUs. One chunk is processed by + GPU0-3, the other chunk is processed by GPU4-7. Four groups + are build to do context parallel communications: [GPU0, GPU4], + [GPU1, GPU5], [GPU2, GPU6], and [GPU3, GPU7]. + + Context parallelism partitions sequence length, so it has no + impact on weights, which means weights are duplicated among + GPUs in a context parallel group. Hence, weight gradients + all-reduce is required in backward. For simplicity, we piggyback + GPUs of context parallelism on data parallel group for + weight gradient all-reduce. + + nccl_communicator_config_path (str, default = None): + Path to the yaml file of NCCL communicator configurations. + `min_ctas`, `max_ctas`, and `cga_cluster_size` can be set + for each communicator. + + distributed_timeout_minutes (int, default = 30): Timeout, in + minutes,for operations executed against distributed + process groups. See PyTorch documentation at + https://pytorch.org/docs/stable/distributed.html for + caveats. + + order (str, default=tp-dp-pp): + The rank initialization order of parallelism. Now we support + tp-dp-pp and tp-pp-dp orders. + + Let's say we have a total of 16 GPUs denoted by g0 ... g15 and we + use 2 GPUs to parallelize the model tensor, and 4 GPUs to parallelize + the model pipeline. The present function will + create 8 tensor model-parallel groups, 4 pipeline model-parallel groups + and 8 data-parallel groups as: + 8 data_parallel groups: + [g0, g2], [g1, g3], [g4, g6], [g5, g7], [g8, g10], [g9, g11], [g12, g14], [g13, g15] + 8 tensor model-parallel groups: + [g0, g1], [g2, g3], [g4, g5], [g6, g7], [g8, g9], [g10, g11], [g12, g13], [g14, g15] + 4 pipeline model-parallel groups: + [g0, g4, g8, g12], [g1, g5, g9, g13], [g2, g6, g10, g14], [g3, g7, g11, g15] + Note that for efficiency, the caller should make sure adjacent ranks + are on the same DGX box. For example if we are using 2 DGX-1 boxes + with a total of 16 GPUs, rank 0 to 7 belong to the first box and + ranks 8 to 15 belong to the second box. + + """ + # Get world size and rank. Ensure some consistencies. + assert torch.distributed.is_initialized() + world_size: int = torch.distributed.get_world_size() + if world_size % (tp_size * pp_size * cp_size) != 0: + raise RuntimeError( + f"world_size ({world_size}) is not divisible by tp_size " + f"({tp_size}) x pp_size ({pp_size}) " + f"x cp_size ({cp_size})" + ) + + nccl_comm_cfgs = {} + if nccl_communicator_config_path is not None: + try: + import yaml + except ImportError: + raise RuntimeError("Cannot import `yaml`. Setting custom nccl communicator configs " "requires the yaml package.") + + with open(nccl_communicator_config_path, "r") as stream: + nccl_comm_cfgs = yaml.safe_load(stream) + + dp_size: int = world_size // (tp_size * pp_size * cp_size) + rank = torch.distributed.get_rank() + rank_generator = RankGenerator(tp=tp_size, dp=dp_size, pp=pp_size, cp=cp_size, order=order) + timeout = timedelta(minutes=distributed_timeout_minutes) + + # Build the data-parallel groups. + global _DATA_PARALLEL_GROUP + global _DATA_PARALLEL_GROUP_GLOO + global _DATA_PARALLEL_GLOBAL_RANKS + global _DATA_PARALLEL_GROUP_WITH_CP + global _DATA_PARALLEL_GROUP_WITH_CP_GLOO + global _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP + assert _DATA_PARALLEL_GROUP is None, "data parallel group is already initialized" + + for ranks in rank_generator.get_ranks("dp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("dp", nccl_comm_cfgs)) + group_gloo = torch.distributed.new_group(ranks, timeout=timeout, backend="gloo") + if rank in ranks: + _DATA_PARALLEL_GROUP = group + _DATA_PARALLEL_GROUP_GLOO = group_gloo + _DATA_PARALLEL_GLOBAL_RANKS = ranks + for ranks_with_cp in rank_generator.get_ranks("dp-cp"): + group_with_cp = torch.distributed.new_group( + ranks_with_cp, timeout=timeout, pg_options=get_nccl_options("dp_cp", nccl_comm_cfgs) + ) + group_with_cp_gloo = torch.distributed.new_group(ranks_with_cp, timeout=timeout, backend="gloo") + if rank in ranks_with_cp: + _DATA_PARALLEL_GROUP_WITH_CP = group_with_cp + _DATA_PARALLEL_GROUP_WITH_CP_GLOO = group_with_cp_gloo + _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP = ranks_with_cp + + # Build the context-parallel groups. + global _CONTEXT_PARALLEL_GROUP + global _CONTEXT_PARALLEL_GLOBAL_RANKS + assert _CONTEXT_PARALLEL_GROUP is None, "context parallel group is already initialized" + for ranks in rank_generator.get_ranks("cp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("cp", nccl_comm_cfgs)) + if rank in ranks: + _CONTEXT_PARALLEL_GROUP = group + _CONTEXT_PARALLEL_GLOBAL_RANKS = ranks + + # Build the model-parallel groups. + global _MODEL_PARALLEL_GROUP + assert _MODEL_PARALLEL_GROUP is None, "model parallel group is already initialized" + for ranks in rank_generator.get_ranks("tp-pp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("mp", nccl_comm_cfgs)) + if rank in ranks: + _MODEL_PARALLEL_GROUP = group + + # Build the tensor model-parallel groups. + global _TENSOR_MODEL_PARALLEL_GROUP + global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS + assert _TENSOR_MODEL_PARALLEL_GROUP is None, "tensor model parallel group is already initialized" + for ranks in rank_generator.get_ranks("tp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp", nccl_comm_cfgs)) + if rank in ranks: + _TENSOR_MODEL_PARALLEL_GROUP = group + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS = ranks + + # Build the tensor + context parallel groups. + global _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP + global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP + assert ( + _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP is None + ), "tensor model parallel group with context parallel is already initialized" + for ranks in rank_generator.get_ranks("tp-cp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp_cp", nccl_comm_cfgs)) + if rank in ranks: + _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP = group + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP = ranks + + # Build the pipeline model-parallel groups + global _PIPELINE_MODEL_PARALLEL_GROUP + global _PIPELINE_GLOBAL_RANKS + assert _PIPELINE_MODEL_PARALLEL_GROUP is None, "pipeline model parallel group is already initialized" + for ranks in rank_generator.get_ranks("pp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("pp", nccl_comm_cfgs)) + if rank in ranks: + _PIPELINE_MODEL_PARALLEL_GROUP = group + _PIPELINE_GLOBAL_RANKS = ranks + + # Build the tensor + data parallel groups. + global _TENSOR_AND_DATA_PARALLEL_GROUP + global _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP + assert _TENSOR_AND_DATA_PARALLEL_GROUP is None, "Tensor + data parallel group is already initialized" + for ranks in rank_generator.get_ranks("tp-cp-dp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp_cp_dp", nccl_comm_cfgs)) + if rank in ranks: + _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP = group + for ranks in rank_generator.get_ranks("tp-dp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp_dp", nccl_comm_cfgs)) + if rank in ranks: + _TENSOR_AND_DATA_PARALLEL_GROUP = group + + +def is_initialized(): + """Useful for code segments that may be accessed with or without mpu initialization""" + return _DATA_PARALLEL_GROUP is not None + + +def is_unitialized() -> bool: + """Check if parallel state has been initialized + + Deprecated. Use is_initialized instead. + + """ + warnings.warn("is_unitialized is deprecated, use is_initialized instead", DeprecationWarning) + return not is_initialized() + + +def model_parallel_is_initialized(): + """Check if model and data parallel groups are initialized.""" + if _TENSOR_MODEL_PARALLEL_GROUP is None or _PIPELINE_MODEL_PARALLEL_GROUP is None or _DATA_PARALLEL_GROUP is None: + return False + return True + + +def get_model_parallel_group(): + """Get the model parallel group the caller rank belongs to.""" + assert _MODEL_PARALLEL_GROUP is not None, "model parallel group is not initialized" + return _MODEL_PARALLEL_GROUP + + +def get_tp_group(check_initialized=True, with_context_parallel=False): + """Get the tensor model parallel group the caller rank belongs to.""" + if check_initialized: + assert _TENSOR_MODEL_PARALLEL_GROUP is not None, "tensor model parallel group is not initialized" + if with_context_parallel: + assert ( + _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP is not None + ), "tensor model parallel group with context parallel combined is not initialized" + return _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP + else: + assert _TENSOR_MODEL_PARALLEL_GROUP is not None, "tensor model parallel group is not initialized" + return _TENSOR_MODEL_PARALLEL_GROUP + + +def get_pp_group(): + """Get the pipeline model parallel group the caller rank belongs to.""" + assert _PIPELINE_MODEL_PARALLEL_GROUP is not None, "pipeline_model parallel group is not initialized" + return _PIPELINE_MODEL_PARALLEL_GROUP + + +def get_dp_group(with_context_parallel=False): + """Get the data parallel group the caller rank belongs to.""" + if with_context_parallel: + assert ( + _DATA_PARALLEL_GROUP_WITH_CP is not None + ), "data parallel group with context parallel combined is not initialized" + return _DATA_PARALLEL_GROUP_WITH_CP + else: + assert _DATA_PARALLEL_GROUP is not None, "data parallel group is not initialized" + return _DATA_PARALLEL_GROUP + + +def get_dp_group_gloo(with_context_parallel=False): + """Get the data parallel group-gloo the caller rank belongs to.""" + if with_context_parallel: + assert ( + _DATA_PARALLEL_GROUP_WITH_CP_GLOO is not None + ), "data parallel group-gloo with context parallel combined is not initialized" + return _DATA_PARALLEL_GROUP_WITH_CP_GLOO + else: + assert _DATA_PARALLEL_GROUP_GLOO is not None, "data parallel group-gloo is not initialized" + return _DATA_PARALLEL_GROUP_GLOO + + +def get_cp_group(check_initialized=True): + """Get the context parallel group the caller rank belongs to.""" + if check_initialized: + assert _CONTEXT_PARALLEL_GROUP is not None, "context parallel group is not initialized" + return _CONTEXT_PARALLEL_GROUP + + +def get_tp_world_size(with_context_parallel=False): + """Return world size for the tensor model parallel group.""" + return torch.distributed.get_world_size(group=get_tp_group(with_context_parallel=with_context_parallel)) + + +def get_pp_world_size(): + """Return world size for the pipeline model parallel group.""" + return torch.distributed.get_world_size(group=get_pp_group()) + + +def get_tp_rank(with_context_parallel=False): + """Return my rank for the tensor model parallel group.""" + return torch.distributed.get_rank(group=get_tp_group(with_context_parallel=with_context_parallel)) + + +def get_pp_rank(): + """Return my rank for the pipeline model parallel group.""" + return torch.distributed.get_rank(group=get_pp_group()) + + +def is_pipeline_first_stage(): + """Return True if in the first pipeline model-parallel stage, False otherwise.""" + return get_pp_rank() == 0 + + +def is_pipeline_last_stage(): + """Return True if in the last pipeline model-parallel stage, False otherwise.""" + return get_pp_rank() == (get_pp_world_size() - 1) + + +def get_tensor_model_parallel_src_rank(with_context_parallel=False): + """Calculate the global rank corresponding to the first local rank + in the tensor model parallel group.""" + assert _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS is not None, "Tensor model parallel group is not initialized" + if with_context_parallel: + assert ( + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP is not None + ), "Tensor model parallel group with context parallel combined is not initialized" + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP[0] + else: + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS[0] + + +def get_tensor_model_parallel_ranks(with_context_parallel=False): + """Return all global ranks for the tensor model parallel group.""" + if with_context_parallel: + assert ( + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP is not None + ), "Tensor model parallel group with context parallel combined is not initialized" + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP + else: + assert _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS is not None, "Tensor model parallel group is not initialized" + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS + + +def get_tensor_model_parallel_last_rank(with_context_parallel=False): + """Calculate the global rank corresponding to the first local rank + in the tensor model parallel group.""" + assert _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS is not None, "Tensor model parallel group is not initialized" + if with_context_parallel: + assert ( + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP is not None + ), "Tensor model parallel group with context parallel combined is not initialized" + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP[-1] + else: + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS[-1] + + +def get_pipeline_model_parallel_first_rank(): + """Return the global rank of the first process in the pipeline for the + current tensor parallel group""" + assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized" + return _PIPELINE_GLOBAL_RANKS[0] + + +def get_pipeline_model_parallel_last_rank(): + """Return the global rank of the last process in the pipeline for the + current tensor parallel group""" + assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized" + last_rank_local = get_pp_world_size() - 1 + return _PIPELINE_GLOBAL_RANKS[last_rank_local] + + +def get_pipeline_model_parallel_next_rank(): + """Return the global rank that follows the caller in the pipeline""" + assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized" + rank_in_pipeline = get_pp_rank() + world_size = get_pp_world_size() + return _PIPELINE_GLOBAL_RANKS[(rank_in_pipeline + 1) % world_size] + + +def get_pipeline_model_parallel_prev_rank(): + """Return the global rank that preceeds the caller in the pipeline""" + assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized" + rank_in_pipeline = get_pp_rank() + world_size = get_pp_world_size() + return _PIPELINE_GLOBAL_RANKS[(rank_in_pipeline - 1) % world_size] + + +def get_dp_world_size(with_context_parallel=False): + """Return world size for the data parallel group.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_world_size(group=get_dp_group(with_context_parallel=with_context_parallel)) + else: + return 0 + + +def get_dp_rank(with_context_parallel=False): + """Return my rank for the data parallel group.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_rank(group=get_dp_group(with_context_parallel=with_context_parallel)) + else: + return 0 + + +def get_cp_world_size(): + """Return world size for the context parallel group.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_world_size(group=get_cp_group()) + else: + return 0 + + +def get_cp_rank(): + """Return my rank for the context parallel group.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_rank(group=get_cp_group()) + else: + return 0 + + +def destroy_model_parallel(): + """Set the groups to none.""" + global _MODEL_PARALLEL_GROUP + _MODEL_PARALLEL_GROUP = None + global _TENSOR_MODEL_PARALLEL_GROUP + _TENSOR_MODEL_PARALLEL_GROUP = None + global _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP + _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP = None + global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP = None + global _PIPELINE_MODEL_PARALLEL_GROUP + _PIPELINE_MODEL_PARALLEL_GROUP = None + global _DATA_PARALLEL_GROUP + _DATA_PARALLEL_GROUP = None + global _DATA_PARALLEL_GROUP_GLOO + _DATA_PARALLEL_GROUP_GLOO = None + global _TENSOR_AND_DATA_PARALLEL_GROUP + _TENSOR_AND_DATA_PARALLEL_GROUP = None + global _PIPELINE_GLOBAL_RANKS + _PIPELINE_GLOBAL_RANKS = None + global _DATA_PARALLEL_GLOBAL_RANKS + _DATA_PARALLEL_GLOBAL_RANKS = None + global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS = None + global _CONTEXT_PARALLEL_GROUP + _CONTEXT_PARALLEL_GROUP = None + global _CONTEXT_PARALLEL_GLOBAL_RANKS + _CONTEXT_PARALLEL_GLOBAL_RANKS = None + global _DATA_PARALLEL_GROUP_WITH_CP + _DATA_PARALLEL_GROUP_WITH_CP = None + global _DATA_PARALLEL_GROUP_WITH_CP_GLOO + _DATA_PARALLEL_GROUP_WITH_CP_GLOO = None + global _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP + _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP = None + global _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP + _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP = None diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..859ebeae3dfa76b926b41e78bab6af5cb99ae449 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .context_parallel import CSOHelper, UlyssesScheduler, cp_post_process, cp_pre_process, cso_communication +from .pipeline_parallel import pp_scheduler +from .tile_parallel import TileProcessor + +__all__ = [ + "CSOHelper", + "cso_communication", + "UlyssesScheduler", + "pp_scheduler", + "TileProcessor", + "cp_pre_process", + "cp_post_process", +] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c25f73425d5ec52ec47423bb4960b73d4f77d60 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..caae0f0008f0a9e02046f40a57fcead295e44c6a Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/context_parallel.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/context_parallel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9da338df86db8758eb4713907e8baf411f8dda0c Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/context_parallel.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/context_parallel.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/context_parallel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4559a33221db2b8e2f3e4cbe7b900d6429a27c4 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/context_parallel.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a33790dc4d7458c30b092ec0820c3bb849df9061 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6219368b896808f8791c766c8068dc787fb36814 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/tile_parallel.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/tile_parallel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd9bd747fb6f92fe264bc26bb17050142926456e Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/tile_parallel.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/tile_parallel.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/tile_parallel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0498a929061e89bbfdcf5bf2bb536ec647c9dfe8 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/__pycache__/tile_parallel.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/context_parallel.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/context_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..f7b803c2e79da5ebd6afecca165e03481fcc0738 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/context_parallel.py @@ -0,0 +1,673 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Callable, List, Tuple, Union + +import torch +import torch.distributed +from einops import rearrange + +from inference.common import ModelMetaArgs, PackedCoreAttnParams, PackedCrossAttnParams, divide +from inference.infra.distributed import parallel_state as mpu + + +##################################################### +# Common Primitives +##################################################### +def scatter_to_context_parallel_region(input_, cp_split_sizes, cp_shuffle_num=1, cp_pad_size=0): + """Split the tensor along its first dimension and keep the + corresponding slice.""" + + world_size = mpu.get_cp_world_size() + # Bypass the function if we are using only 1 GPU. + if world_size == 1: + return input_ + + # Split along first dimension with padding. + rank = mpu.get_cp_rank() + if cp_shuffle_num > 1: + cp_pad_size = divide(cp_pad_size, cp_shuffle_num) + cp_split_sizes = [divide(s, cp_shuffle_num) for s in cp_split_sizes] + dim_offset = sum(cp_split_sizes[:rank]) + xs = [] + for x in torch.chunk(input_, cp_shuffle_num, dim=0): + x = torch.nn.functional.pad(x, [0, 0] * (x.dim() - 1) + [0, cp_pad_size], mode="constant", value=0) + xs.append(x[dim_offset : dim_offset + cp_split_sizes[rank]]) + output = torch.concat(xs, dim=0) + else: + dim_offset = sum(cp_split_sizes[:rank]) + x = torch.nn.functional.pad(input_, [0, 0] * (input_.dim() - 1) + [0, cp_pad_size], mode="constant", value=0) + output = x[dim_offset : dim_offset + cp_split_sizes[rank]].contiguous() + return output + + +def gather_from_context_parallel_region(input_, cp_split_sizes, cp_shuffle_num=1, cp_pad_size=0): + """Gather tensors and concatinate along the first dimension.""" + + world_size = mpu.get_cp_world_size() + # Bypass the function if we are using only 1 GPU. + if world_size == 1: + return input_ + + input_ = input_.contiguous() + total_seq_len = sum(cp_split_sizes) + dim_size = list(input_.size()) + dim_size[0] = total_seq_len + + output = torch.empty(dim_size, dtype=input_.dtype, device=input_.device) + outputs = list(torch.split(output, cp_split_sizes, dim=0)) + torch.distributed.all_gather(outputs, input_, group=mpu.get_cp_group()) + if cp_shuffle_num > 1: + total_seq_len = divide(total_seq_len, cp_shuffle_num) + cp_pad_size = divide(cp_pad_size, cp_shuffle_num) + chunks = [torch.chunk(o, cp_shuffle_num, dim=0) for o in outputs] + output = torch.concat( + [ + torch.concat([chunk[i] for chunk in chunks], dim=0)[: total_seq_len - cp_pad_size] + for i in range(cp_shuffle_num) + ], + dim=0, + ) + else: + output = torch.concat(outputs, dim=0)[: total_seq_len - cp_pad_size] + + return output + + +class FakeHandle: + def __init__(self): + pass + + def wait(self): + pass + + +##################################################### +# Context Parallel Process +##################################################### +def update_packed_seq_params_for_cuda_graph(cross_attn_params: PackedCrossAttnParams, xattn_mask: torch.Tensor): + assert xattn_mask is not None + # xattn_mask: (N * denoising_range_num, L, 1, 1) + xattn_mask = xattn_mask.reshape(xattn_mask.shape[0], -1) + batch_size, static_caption_length = xattn_mask.shape + + # Get index_map for kv_range injection, map y_index to static_caption_length + y_index = torch.sum(xattn_mask, dim=-1) + cu_seqlens_k = torch.cat([y_index.new_tensor([0]), y_index]).to(torch.int32).to(xattn_mask.device) + cu_seqlens_k = cu_seqlens_k.cumsum(-1).to(torch.int32) + static_cu_seqlens_k = torch.arange(0, (batch_size + 1) * static_caption_length, static_caption_length) + assert cu_seqlens_k.shape[0] == batch_size + 1 == static_cu_seqlens_k.shape[0] + start_index_map = dict(zip(cu_seqlens_k.flatten().tolist(), static_cu_seqlens_k.flatten().tolist())) + + # Move kv_range to the right position + kv_range_start_list = cross_attn_params.kv_ranges[:, 0].flatten().tolist() + static_kv_range_start = [start_index_map[kv_range_start_list[i]] for i in range(len(kv_range_start_list))] + static_kv_range_start = torch.tensor(static_kv_range_start, dtype=torch.int32, device=xattn_mask.device) + assert static_kv_range_start.shape[0] == cross_attn_params.kv_ranges.shape[0] + static_kv_range_diff = cross_attn_params.kv_ranges[:, 1] - cross_attn_params.kv_ranges[:, 0] + static_kv_range_end = static_kv_range_start + static_kv_range_diff + static_kv_range = torch.stack((static_kv_range_start, static_kv_range_end), dim=1) + + assert static_kv_range.shape == cross_attn_params.kv_ranges.shape + return PackedCrossAttnParams( + q_ranges=cross_attn_params.q_ranges, + kv_ranges=static_kv_range, + cu_seqlens_q=cross_attn_params.cu_seqlens_q, + cu_seqlens_kv=cross_attn_params.cu_seqlens_kv, + max_seqlen_q=cross_attn_params.max_seqlen_q, + max_seqlen_kv=cross_attn_params.max_seqlen_kv, + ) + + +def cp_update_cross_attn_qkv_range( + cross_attn_params: PackedCrossAttnParams, + batch_size: int, + cp_split_sizes: List[int], + device: torch.device, + cp_shuffle_num: int = 1, + cp_pad_size: int = 0, +): + """ + Update cross_attn_params for cross_attn in context parallel. + + Input: + cross_attn_params: PackedCrossAttnParams. Packed sequence parameters for cross_atten + batch_size: int. Batch size + cp_split_sizes: List[int]. Split sizes for each rank + device: torch.device. Device + + Output: + cross_attn_params: PackedCrossAttnParams. Updated packed parameters for cross_atten + """ + # Update cu_seqlens_q and max_seqlen_q because split x maybe unbalanced + cp_rank = mpu.get_cp_rank() + seq_len_cur_rank = cp_split_sizes[cp_rank] + cp_split_sizes = [divide(x, cp_shuffle_num) for x in cp_split_sizes] + cp_split_sizes = torch.tensor(cp_split_sizes, dtype=torch.int32, device=device) + base_cp_boundaries = torch.cat((torch.zeros(1, dtype=torch.int32, device=device), cp_split_sizes.cumsum(0))) + total_seq_len = base_cp_boundaries[-1] + + cu_seqlens_q = cross_attn_params.cu_seqlens_q + cu_seqlens_k = cross_attn_params.cu_seqlens_kv + cu_seqlens_pad = torch.arange(cu_seqlens_q.shape[0], dtype=torch.int32, device=device) * divide( + cp_pad_size, cp_shuffle_num + ) + cu_seqlens_q = cu_seqlens_q + cu_seqlens_pad + + q_seg_starts, q_seg_ends = cu_seqlens_q[:-1], cu_seqlens_q[1:] + + xattn_q_ranges, xattn_k_ranges = [], [] + for i in range(batch_size): + inner_xattn_q_ranges, inner_xattn_k_ranges = [], [] + for j in range(cp_shuffle_num): + global_offset = i * total_seq_len * cp_shuffle_num + j * total_seq_len + cp_boundaries = base_cp_boundaries + global_offset + this_cp_start, this_cp_end = (cp_boundaries[cp_rank], cp_boundaries[cp_rank + 1]) + + q_inter_starts = torch.maximum(this_cp_start, q_seg_starts) + q_inter_ends = torch.minimum(this_cp_end, q_seg_ends) + + q_mask = q_inter_starts < q_inter_ends + valid_q_starts = q_inter_starts[q_mask] + valid_q_ends = q_inter_ends[q_mask] + + k_seg_starts, k_seg_ends = cu_seqlens_k[:-1], cu_seqlens_k[1:] + valid_indices = torch.nonzero(q_mask, as_tuple=True)[0] + + valid_k_starts = k_seg_starts[valid_indices] + valid_k_ends = k_seg_ends[valid_indices] + + part_xattn_q_rangs = torch.stack((valid_q_starts, valid_q_ends), dim=1) + offset = part_xattn_q_rangs[:, 0].min() + part_xattn_q_rangs = part_xattn_q_rangs - offset + + inner_xattn_q_ranges.append(part_xattn_q_rangs) + inner_xattn_k_ranges.append(torch.stack((valid_k_starts, valid_k_ends), dim=1)) + inner_end_values = torch.tensor([ranges[-1, -1] for ranges in inner_xattn_q_ranges], dtype=torch.int32) + inner_offsets = torch.cat((torch.zeros(1, dtype=inner_end_values.dtype), torch.cumsum(inner_end_values[:-1], dim=0))) + inner_xattn_q_ranges = [tensor + int(offset) for tensor, offset in zip(inner_xattn_q_ranges, inner_offsets)] + xattn_q_ranges.append(torch.cat(inner_xattn_q_ranges, dim=0)) + xattn_k_ranges.append(torch.cat(inner_xattn_k_ranges, dim=0)) + + end_values = torch.tensor([ranges[-1, -1].item() for ranges in xattn_q_ranges], dtype=torch.int32) + offsets = torch.cat((torch.zeros(1, dtype=end_values.dtype), torch.cumsum(end_values[:-1], dim=0))) + + shifted_tensors = [tensor + int(offset) for tensor, offset in zip(xattn_q_ranges, offsets)] + xattn_q_ranges_ts = torch.cat(shifted_tensors, dim=0) + xattn_k_ranges_ts = torch.cat(xattn_k_ranges, dim=0) + + cu_seqlens_q = torch.unique(xattn_q_ranges_ts) + cu_seqlens_k = torch.unique(xattn_k_ranges_ts) + assert ( + cu_seqlens_q.shape == cu_seqlens_k.shape + ), f"cu_seqlens_q.shape: {cu_seqlens_q.shape}, cu_seqlens_k.shape: {cu_seqlens_k.shape}, " + + return PackedCrossAttnParams( + q_ranges=xattn_q_ranges_ts, + kv_ranges=xattn_k_ranges_ts, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=cu_seqlens_k, + max_seqlen_q=seq_len_cur_rank, + max_seqlen_kv=cross_attn_params.max_seqlen_kv, + ) + + +def cp_ulysses_process( + cp_size: int, + x: torch.Tensor, + condition_map: torch.Tensor, + rope: torch.Tensor, + xattn_mask_for_cuda_graph: Union[torch.Tensor, None], + cross_attn_params: PackedCrossAttnParams, +): + seq_len, N, D = x.shape + assert seq_len == rope.size(0), f"seq_len: {seq_len} != rope.size(0): {rope.size(0)}" + assert condition_map.size(0) == seq_len, f"condition_map.size(0): {condition_map.size(0)} != seq_len: {seq_len}" + + # Part1: split for CP + cp_split_sizes = [seq_len // cp_size] * cp_size + for i in range(seq_len % cp_size): + cp_split_sizes[i] += 1 + + # Part2: scatter to CP + x = scatter_to_context_parallel_region(x, cp_split_sizes) + condition_map = scatter_to_context_parallel_region(condition_map, cp_split_sizes) + rope = scatter_to_context_parallel_region(rope, cp_split_sizes) + + # Part3: update cross_attn cross_attn_params + cross_attn_params = cp_update_cross_attn_qkv_range(cross_attn_params, N, cp_split_sizes, x.device) + if xattn_mask_for_cuda_graph is not None: + cross_attn_params = update_packed_seq_params_for_cuda_graph(cross_attn_params, xattn_mask_for_cuda_graph) + + return x, condition_map, rope, cp_split_sizes, cross_attn_params + + +def cp_shuffle_overlap_process( + cp_size: int, + x: torch.Tensor, + condition_map: torch.Tensor, + rope: torch.Tensor, + xattn_mask_for_cuda_graph: Union[torch.Tensor, None], + ardf_meta: dict, + core_attn_params: PackedCoreAttnParams, + cross_attn_params: PackedCrossAttnParams, +): + seq_len, N, D = x.shape + assert seq_len == rope.size(0), f"seq_len: {seq_len} != rope.size(0): {rope.size(0)}" + assert condition_map.size(0) == seq_len, f"condition_map.size(0): {condition_map.size(0)} != seq_len: {seq_len}" + cp_shuffle_num = ardf_meta["denoising_range_num"] + + # Part1: calculate cp_pad_size and cp_split_sizes + cp_pad_size = 0 + if divide(seq_len, cp_shuffle_num) % cp_size != 0: + cp_pad_size = (cp_size - divide(seq_len, cp_shuffle_num) % cp_size) * cp_shuffle_num + cp_split_sizes = [(seq_len + cp_pad_size) // cp_size] * cp_size + + # Part2: scatter to CP + x = scatter_to_context_parallel_region(x, cp_split_sizes, cp_shuffle_num, cp_pad_size) + condition_map = scatter_to_context_parallel_region(condition_map, cp_split_sizes, cp_shuffle_num, cp_pad_size) + rope = scatter_to_context_parallel_region(rope, cp_split_sizes, cp_shuffle_num, cp_pad_size) + + # Part3: update core_attn_params + gcd = math.gcd(seq_len, seq_len + cp_pad_size) + _sq = seq_len // gcd + _psq = (seq_len + cp_pad_size) // gcd + q_range = ardf_meta["q_range"] * _psq // _sq + max_seqlen_q = ardf_meta["max_seqlen_q"] * _psq // _sq + core_attn_params = PackedCoreAttnParams( + q_range=q_range, + k_range=ardf_meta["k_range"], + np_q_range=q_range.cpu().numpy(), + np_k_range=ardf_meta["k_range"].cpu().numpy(), + max_seqlen_q=max_seqlen_q, + max_seqlen_k=ardf_meta["max_seqlen_k"], + ) + + # Part4: update cross_attn cross_attn_params + cross_attn_params = cp_update_cross_attn_qkv_range( + cross_attn_params, N, cp_split_sizes, x.device, cp_shuffle_num, cp_pad_size + ) + if xattn_mask_for_cuda_graph is not None: + cross_attn_params = update_packed_seq_params_for_cuda_graph(cross_attn_params, xattn_mask_for_cuda_graph) + + return x, condition_map, rope, cp_pad_size, cp_split_sizes, core_attn_params, cross_attn_params + + +def cp_pre_process( + cp_size: int, + cp_strategy: str, + x: torch.Tensor, + condition_map: torch.Tensor, + rope: torch.Tensor, + xattn_mask_for_cuda_graph: Union[torch.Tensor, None], + ardf_meta: dict, + core_attn_params: PackedCoreAttnParams, + cross_attn_params: PackedCrossAttnParams, +): + """ + This function is used to handle context parallel behavior, + split input tensors into multiple parts and scatter them to different GPUs. + + Input: + cp_strategy: str. cp_ulysses for hopper or newer, cp_shuffle_overlap for 4090 or older + x: (S, N, D). torch.Tensor of inputs embedding (images or latent representations of images) + condition_map: (N * S). torch.Tensor determine which condition to use for each token + rope: (S, 96). torch.Tensor of rope + xattn_mask_for_cuda_graph: (N * denoising_range_num, L, 1, 1). torch.Tensor of xattn mask for cuda graph, None means no cuda graph + core_attn_params: PackedCoreAttnParams. Packed sequence parameters for core_atten + cross_attn_params: PackedCrossAttnParams. Packed sequence parameters for cross_atten + + Output: + x: (S', N, D). torch.Tensor of inputs embedding (images or latent representations of images) + condition_map: (N * S'). torch.Tensor determine which condition to use for each token + rope: (S', 96). torch.Tensor of rope + cp_split_sizes: List[int]. Split sizes for each rank + core_attn_params: PackedCoreAttnParams + cross_attn_params: PackedCrossAttnParams + """ + if cp_size == 1: + return x, condition_map, rope, None, None, core_attn_params, cross_attn_params + if cp_strategy == "cp_ulysses": + (x, condition_map, rope, cp_split_sizes, cross_attn_params) = cp_ulysses_process( + cp_size, x, condition_map, rope, xattn_mask_for_cuda_graph, cross_attn_params + ) + return (x, condition_map, rope, 0, cp_split_sizes, core_attn_params, cross_attn_params) + elif cp_strategy == "cp_shuffle_overlap": + ( + x, + condition_map, + rope, + cp_pad_size, + cp_split_sizes, + core_attn_params, + cross_attn_params, + ) = cp_shuffle_overlap_process( + cp_size, x, condition_map, rope, xattn_mask_for_cuda_graph, ardf_meta, core_attn_params, cross_attn_params + ) + return (x, condition_map, rope, cp_pad_size, cp_split_sizes, core_attn_params, cross_attn_params) + else: + raise ValueError(f"Invalid CP strategy: {cp_strategy}, expected cp_ulysses or cp_shuffle_overlap") + + +def cp_post_process(cp_size: int, cp_strategy: str, x: torch.Tensor, meta_args: ModelMetaArgs) -> torch.Tensor: + if cp_size == 1: + return x + if cp_strategy == "cp_shuffle_overlap": + x = gather_from_context_parallel_region( + x, meta_args.cp_split_sizes, meta_args.denoising_range_num, meta_args.cp_pad_size + ) + elif cp_strategy == "cp_ulysses": + x = gather_from_context_parallel_region(x, meta_args.cp_split_sizes) + else: + raise ValueError(f"Invalid CP strategy: {cp_strategy}, expected cp_ulysses or cp_shuffle_overlap") + return x + + +##################################################### +# Ulysses Attention Pipeline +##################################################### +def all_to_all_input_split(tensor: torch.Tensor, cp_split_sizes: List[int]) -> Tuple[torch.Tensor, torch.distributed.Work]: + """ + Scatter head_number and gather seq_len, for example: + input: (seq_len, cp * hn, hd) + output: (seq_len * cp, hn, hd) + NOTE: seq_len of input maybe not equal, which depends on cp_split_sizes[mpu.get_cp_rank()] + """ + cp_world_size = mpu.get_cp_world_size() + if cp_world_size == 1: + return tensor, FakeHandle() + assert cp_split_sizes is not None + _, hn, _ = tensor.shape + if cp_world_size % hn == 0 and cp_world_size != hn: + tensor = torch.repeat_interleave(tensor, repeats=divide(cp_world_size, hn), dim=1).contiguous() + assert tensor.is_contiguous() + input = rearrange(tensor, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous() + output = torch.empty([sum(cp_split_sizes), *input.shape[1:]], device=input.device, dtype=input.dtype) + handle = torch.distributed.all_to_all_single( + output, input, output_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=True + ) + return output, handle + + +def all_to_all_output_split(tensor: torch.Tensor, cp_split_sizes: List[int]) -> Tuple[torch.Tensor, torch.distributed.Work]: + """ + Scatter seq_len and gather head_number, for example: + input: (seq_len * cp, hn, hd) + output: (seq_len, cp * hn, hd) + NOTE: seq_len of output maybe not equal, which depends on cp_split_sizes[mpu.get_cp_rank()] + """ + cp_world_size = mpu.get_cp_world_size() + if cp_world_size == 1: + return tensor, FakeHandle() + assert cp_split_sizes is not None + assert tensor.is_contiguous() + _, hn, _ = tensor.shape + output = torch.empty( + [cp_split_sizes[mpu.get_cp_rank()] * cp_world_size, *tensor.shape[1:]], device=tensor.device, dtype=tensor.dtype + ) + handle = torch.distributed.all_to_all_single( + output, tensor, input_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=True + ) + return output, handle + + +def fused_qkv_communication( + q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cp_split_sizes: List[int] +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + cp_world_size = mpu.get_cp_world_size() + if cp_world_size == 1: + return q, k, v + assert cp_split_sizes is not None + _, k_head, _ = k.shape + if cp_world_size % k_head == 0 and cp_world_size != k_head: + k = torch.repeat_interleave(k, repeats=divide(cp_world_size, k_head), dim=1) + v = torch.repeat_interleave(v, repeats=divide(cp_world_size, k_head), dim=1) + + q = rearrange(q, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous() + k = rearrange(k, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous() + v = rearrange(v, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous() + head_split_number = [q.shape[1], k.shape[1], v.shape[1]] + qkv = torch.cat([q, k, v], dim=1).contiguous() + + qkv_output = torch.empty([sum(cp_split_sizes), *qkv.shape[1:]], device=qkv.device, dtype=qkv.dtype) + torch.distributed.all_to_all_single( + qkv_output, qkv, output_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=False + ) + q, k, v = torch.split(qkv_output, head_split_number, dim=1) + return q, k, v + + +class UlyssesScheduler: + def __init__(self): + pass + + @staticmethod + def get_attn_and_xattn_with_comm_overlap( + get_q_func: Callable, # [seq hn hd] + get_k_func: Callable, # [seq hn hd] + get_v_func: Callable, # [seq hn hd] + kv_cache_func: Callable, + core_attn_func: Callable, + cross_attn_func: Callable, + overlap_degree: int, + batch_size: int, + cp_size: int, + cp_split_sizes: List[int] = None, + ): + """ + Get Q, K, V with communication overlap. + Input: + get_q: Callable, function to get q, shape [b, sq, hn, hd] + get_k: Callable, function to get k, shape [sq, b, hn, hd] + get_v: Callable, function to get v, shape [sq, b, hn, hd] + NOTE: Why follow such compute and comm order? + 1. v_compute + 2. k_compute(overlap with v_comm) + 3. q_compute(overlap with k_comm) + 4. kv_cache_func(overlap with q_comm) + Follow the principle: We need to begin comm as soon as possible to hide the comm latency. + The computation flops and commnunication order is: + flops order: q_compute (larger hidden_size + layernorm) > k_compute (layernorm) > v_compute + comm order: q_compute (larger hidden_size) > k_compute = v_compute + """ + value = get_v_func() + value, handle_v = all_to_all_input_split(value, cp_split_sizes) + key = get_k_func() + key, handle_k = all_to_all_input_split(key, cp_split_sizes) + query = get_q_func() + query, handle_q = all_to_all_input_split(query, cp_split_sizes) + + handle_v.wait() + handle_k.wait() + kv = torch.concat([key, value], dim=-1) + + key, value = kv_cache_func(kv) + handle_q.wait() + return UlyssesScheduler.get_attn_and_xattn_base( + query, key, value, core_attn_func, cross_attn_func, overlap_degree, batch_size, cp_size, cp_split_sizes + ) + + @staticmethod + def get_attn_and_xattn_with_fused_kv_comm( + get_q_func: Callable, + get_kv_func: Callable, + kv_cache_func: Callable, + core_attn_func: Callable, + cross_attn_func: Callable, + overlap_degree: int, + batch_size: int, + cp_size: int, + cp_split_sizes: List[int] = None, + ): + """ + When seq_len is very small, CPU-bound issues are severe. By fusing kv communication, + CPU operations and the number of kernel launches are reduced. + """ + kv = get_kv_func() + kv, handle_kv = all_to_all_input_split(kv, cp_split_sizes) + query = get_q_func() + query, handle_q = all_to_all_input_split(query, cp_split_sizes) + handle_kv.wait() + key, value = kv_cache_func(kv) + handle_q.wait() + return UlyssesScheduler.get_attn_and_xattn_base( + query, key, value, core_attn_func, cross_attn_func, overlap_degree, batch_size, cp_size, cp_split_sizes + ) + + def get_attn_and_xattn_with_fused_qkv_comm( + get_qkv_func: Callable, + kv_cache_func: Callable, + core_attn_func: Callable, + cross_attn_func: Callable, + overlap_degree: int, + batch_size: int, + cp_size: int, + cp_split_sizes: List[int] = None, + ): + """ + By fusing the communication of q, k, and v together, further optimize CPU-bound issues. + """ + q, k, v = get_qkv_func() + q, k, v = fused_qkv_communication(q, k, v, cp_split_sizes) + k, v = kv_cache_func(torch.cat([k, v], dim=-1)) + return UlyssesScheduler.get_attn_and_xattn_base( + q, k, v, core_attn_func, cross_attn_func, overlap_degree, batch_size, cp_size, cp_split_sizes + ) + + @staticmethod + def get_attn_and_xattn_base( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + core_attn_func: Callable, + cross_attn_func: Callable, + overlap_degree: int, + batch_size: int, + cp_size: int, + cp_split_sizes: List[int] = None, + ): + # Split Query, Key, Value into multiple parts + # k/v may have different sequence length with q due to kv cache + q_seq, q_head, q_hidden = query.shape + kv_seq, kv_head, kv_hidden = key.shape + if overlap_degree == -1: + overlap_degree = q_head // kv_head + else: + assert overlap_degree <= q_head + + if overlap_degree == 1: + query = [query] + elif kv_head == 1: # MQA + query = query.chunk(overlap_degree, dim=1) + else: # GQA + assert q_head % (overlap_degree * kv_head) == 0 + query = query.reshape(q_seq, kv_head, -1, q_hidden) + query = query.chunk(overlap_degree, dim=2) + query = [q.reshape(q_seq, -1, q_hidden) for q in query] + + # Compute Core Attention + handle_attn = None + core_attn_out = None + core_attn_outs = [] + for i in range(overlap_degree): + core_attn_out_new = core_attn_func(query[i], key, value) + if not torch.isfinite(core_attn_out_new).all(): + import pdb; pdb.set_trace() + if handle_attn is not None: + handle_attn.wait() + core_attn_outs.append(core_attn_out) + core_attn_out, handle_attn = all_to_all_output_split(core_attn_out_new, cp_split_sizes) + if not torch.isfinite(core_attn_out).all(): + import pdb; pdb.set_trace() + + xattn_out = cross_attn_func() + handle_attn.wait() + if not torch.isfinite(core_attn_out).all(): + import pdb; pdb.set_trace() + core_attn_outs.append(core_attn_out) + core_attn_out = torch.cat(core_attn_outs, dim=1) + + if not torch.isfinite(core_attn_out).all(): + import pdb; pdb.set_trace() + + core_attn_out = rearrange(core_attn_out, "(cp sq b) hn hd -> (sq) b (cp hn hd)", cp=cp_size, b=batch_size) + return core_attn_out, xattn_out + + +##################################################### +# CSO(context shuffle overlap) Attention Pipeline +##################################################### +def cso_communication( + input: torch.Tensor, cp_world_size: int, cp_split_sizes: List[int], comm_type: str = None +) -> Tuple[torch.Tensor, torch.distributed.Work]: + if cp_world_size == 1: + return input, FakeHandle() + assert cp_split_sizes is not None + _, hn, _ = input.shape + if comm_type == "kv": + if cp_world_size % hn == 0 and cp_world_size != hn: + input = torch.repeat_interleave(input, repeats=divide(cp_world_size, hn), dim=1) + input = rearrange(input, "spb (cp hn) hd -> (cp spb) hn hd", cp=cp_world_size).contiguous() + output = torch.empty(input.shape, device=input.device, dtype=input.dtype) + + handle = torch.distributed.all_to_all_single( + output, input, input_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=True + ) + + return output, handle + + +class CSOHelper: + def __init__(self, cp_shuffle_num, cp_world_size, cp_split_sizes): + self.cp_shuffle_num = cp_shuffle_num + self.cp_world_size = cp_world_size + self.cp_split_sizes = [divide(x, self.cp_shuffle_num) for x in cp_split_sizes] + + def split_query_for_overlap(self, query): + query = rearrange( + query, "(dn spb) (cp hn) hd -> (dn cp spb) hn hd", cp=self.cp_world_size, dn=self.cp_shuffle_num + ).contiguous() + querys = list(torch.chunk(query, self.cp_shuffle_num, dim=0)) + querys[0], handle_q = cso_communication(querys[0], self.cp_world_size, self.cp_split_sizes) + return querys, handle_q + + def overlap(self, fattn, qs, k, v): + core_attn_outs = [] + for i in range(self.cp_shuffle_num): + if self.cp_shuffle_num == 1: + q = qs[0] + elif i == 0: + q = qs[0] + loop_var, loop_handle = cso_communication(qs[i + 1], self.cp_world_size, self.cp_split_sizes) + else: + loop_handle.wait() + if loop_var.numel() == qs[0].numel(): + q = loop_var + else: + assert loop_var.numel() == qs[0].numel() * 2 + q, ready_o = torch.chunk(loop_var, 2, dim=-1) + core_attn_outs.append(ready_o) + loop_var = torch.concat([qs[i + 1], o], dim=-1) if i < self.cp_shuffle_num - 1 else o + loop_var, loop_handle = cso_communication(loop_var, self.cp_world_size, self.cp_split_sizes) + + o = fattn(q, k, v, i) + if i == self.cp_shuffle_num - 1: + if i != 0: + loop_handle.wait() + assert loop_var.numel() == qs[0].numel() + core_attn_outs.append(loop_var) + last_o, handle_attn = cso_communication(o, self.cp_world_size, self.cp_split_sizes) + core_attn_outs.append(last_o) + return core_attn_outs, handle_attn diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/pipeline_parallel.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/pipeline_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..d97c91112392843d089f35eb3b28f7f6ed4674f5 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/pipeline_parallel.py @@ -0,0 +1,123 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import queue +from dataclasses import dataclass +from typing import Optional + +import torch + +from inference.infra.distributed import parallel_state as mpu + + +@dataclass +class TensorAndHandler: + tensor: torch.Tensor + handler: torch.distributed.Work + + +class PPScheduler: + def __init__(self): + """Initialize an instance of the PPScheduler class""" + + self.device: torch.device = torch.device(f"cuda:{torch.cuda.current_device()}") + self.recv_queue: queue.Queue = queue.Queue() + + def isend_next(self, tensor: torch.Tensor) -> torch.distributed.Work: + """Asynchronously send a tensor to the next pipeline and return the send handle. + + Args: + tensor (torch.Tensor): The tensor to be sent. + + Returns: + torch.distributed.Work: The handle for the send operation. + """ + handle = torch.distributed.isend( + tensor.contiguous(), dst=mpu.get_pipeline_model_parallel_next_rank(), group=mpu.get_pp_group() + ) + return handle + + def irecv_prev(self, buffer: torch.Tensor) -> torch.distributed.Work: + """Asynchronously receive a tensor from the previous pipeline and return the receive handle. + + Args: + buffer (torch.Tensor): The buffer tensor for receiving data. + + Returns: + torch.distributed.Work: The handle for the receive operation. + """ + handle = torch.distributed.irecv(buffer, src=mpu.get_pipeline_model_parallel_prev_rank(), group=mpu.get_pp_group()) + return handle + + def recv_prev_data(self, shape: torch.Size, dtype: torch.dtype) -> torch.Tensor: + """Receive data from the previous pipeline and return the received tensor. + + Args: + shape (torch.Size): The shape of the tensor to receive. + dtype (torch.dtype): The data type of the tensor to receive. + + Returns: + torch.Tensor: The received tensor. + """ + recv_tensor = torch.empty(shape, dtype=dtype, device=self.device) + self.irecv_prev(recv_tensor).wait() + return recv_tensor + + def queue_irecv_prev(self, shape: torch.Size, dtype: torch.dtype) -> None: + """Put the asynchronously received tensor and handle into the receive queue. + + Args: + shape (torch.Size): The shape of the tensor to receive. + dtype (torch.dtype): The data type of the tensor to receive. + """ + recv_tensor = torch.empty(shape, dtype=dtype, device=self.device) + handle = self.irecv_prev(recv_tensor) + self.recv_queue.put(TensorAndHandler(tensor=recv_tensor, handler=handle)) + + def queue_irecv_prev_data(self) -> torch.Tensor: + """Get a tensor from the receive queue and wait for the receive operation to complete. + + Returns: + torch.Tensor: The received tensor obtained from the queue. + """ + tensor_and_handler = self.recv_queue.get() + tensor_and_handler.handler.wait() + return tensor_and_handler.tensor + + +_PP_SCHEDULER: Optional[PPScheduler] = None + + +def init_pp_scheduler(): + """Initialize the PPScheduler instance. + + Raises: + AssertionError: If the PPScheduler is already initialized. + """ + global _PP_SCHEDULER + assert _PP_SCHEDULER is None, "pipeline model parallel group is already initialized" + _PP_SCHEDULER = PPScheduler() + + +def pp_scheduler() -> PPScheduler: + """Get the current PPScheduler instance. + + Returns: + PPScheduler: The current PPScheduler instance. + + Raises: + AssertionError: If the PPScheduler has not been initialized. + """ + assert _PP_SCHEDULER is not None, "pipeline model parallel group is not initialized" + return _PP_SCHEDULER diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/tile_parallel.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/tile_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe0c1b78b4b69e96b9b9e1b1d365b968561199d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/infra/parallelism/tile_parallel.py @@ -0,0 +1,448 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import OrderedDict +from typing import List + +import torch +from tqdm import tqdm + + +class ParallelHelper: + def __init__(self): + pass + + @staticmethod + def split_tile_list( + tile_numel_dict: OrderedDict[int, int], parallel_group: torch.distributed.ProcessGroup = None + ) -> List[int]: + """ + Splits the given tile size into a list of sizes that each rank should handle. + + This method takes into account the number of ranks in a distributed setting. + If the distributed environment is not initialized, it returns a list of + integers from 0 to tile_size - 1, representing each tile index. + + If the distributed environment is initialized, it calculates the base tile size + for each rank and distributes any remaining tiles among the ranks. + + Args: + tile_numel_dict (OrderedDict[int, int]): Dict of index and numel of tiles. + parallel_group (torch.distributed.ProcessGroup, optional): + Distributed decoding group. Defaults to None. + + Returns: + List[int]: A list of tile indices assigned to the current rank. + List[int]: A list of global tile indices. + """ + if not torch.distributed.is_initialized(): + return list(range(len(tile_numel_dict))), list(range(len(tile_numel_dict))) + else: + tile_idxs = list(OrderedDict(sorted(tile_numel_dict.items(), key=lambda x: x[1], reverse=True)).keys()) + world_size = torch.distributed.get_world_size(group=parallel_group) + cur_rank = torch.distributed.get_rank(group=parallel_group) + global_tile_idxs = [] + cur_rank_tile_idxs = [] + for rank in range(world_size): + rank_tile_idxs = [tile_idxs[rank + world_size * i] for i in range(len(tile_idxs) // world_size)] + if rank < len(tile_idxs) % world_size: + rank_tile_idxs.append(tile_idxs[len(tile_idxs) // world_size * world_size + rank]) + if rank == cur_rank: + cur_rank_tile_idxs = rank_tile_idxs + global_tile_idxs = global_tile_idxs + rank_tile_idxs + return cur_rank_tile_idxs, global_tile_idxs + + @staticmethod + def gather_frames( + frames: List[torch.Tensor], global_tile_idxs: List[int], parallel_group: torch.distributed.ProcessGroup = None + ) -> List[torch.Tensor]: + """ + Gathers frame data from all ranks in a distributed environment. + + This method collects frames from all ranks and combines them into a single list. + If the distributed environment is not initialized, it simply returns the input frames. + + Args: + frames (List[torch.Tensor]): A list of frames (tensors) from the current rank. + global_tile_idxs (List[int]): A list of global tile indices. + parallel_group (torch.distributed.ProcessGroup, optional): + Distributed decoding group. Defaults to None. + + Returns: + List[torch.Tensor]: A list of frames (tensors) from all ranks. + """ + if not torch.distributed.is_initialized(): + return frames + else: + # assert len(frames) > 0 + # Communicate shapes + if len(frames) == 0: + cur_rank_shapes = [] + else: + cur_rank_shapes = [frame.shape for frame in frames] + all_rank_shapes = [None] * torch.distributed.get_world_size(group=parallel_group) + torch.distributed.all_gather_object(all_rank_shapes, cur_rank_shapes, group=parallel_group) + + all_rank_sizes = [] + total_size = [] + for per_rank_shapes in all_rank_shapes: + per_rank_sizes = [] + per_rank_total_size = 0 + for shape in per_rank_shapes: + per_rank_sizes.append(shape[0] * shape[1] * shape[2] * shape[3] * shape[4]) + per_rank_total_size += shape[0] * shape[1] * shape[2] * shape[3] * shape[4] + all_rank_sizes.append(per_rank_sizes) + total_size.append(per_rank_total_size) + + # Gather all frames + if len(frames) == 0: + flattened_frames = torch.zeros([0], dtype=torch.bfloat16, device="cuda") + else: + flattened_frames = torch.cat([frame.flatten().contiguous() for frame in frames], dim=0) + assert flattened_frames.dtype == torch.bfloat16 + gather_tensors = [ + torch.zeros(total_size[i], dtype=torch.bfloat16, device="cuda") + for i in range(torch.distributed.get_world_size(group=parallel_group)) + ] + torch.distributed.all_gather(gather_tensors, flattened_frames, group=parallel_group) + + result_frames = [] + for idx, per_rank_shapes in enumerate(all_rank_shapes): + offset = 0 + for j, shape in enumerate(per_rank_shapes): + result_frames.append(gather_tensors[idx][offset : offset + all_rank_sizes[idx][j]].view(shape)) + offset += all_rank_sizes[idx][j] + result_frames_dict = OrderedDict((idx, frame) for idx, frame in zip(global_tile_idxs, result_frames)) + result_frames = list(OrderedDict(sorted(result_frames_dict.items())).values()) + return result_frames + + @staticmethod + def index_undot(index: int, loop_size: List[int]) -> List[int]: + """ + Converts a single index into a list of indices, representing the position in a multi-dimensional space. + + This method takes an integer index and a list of loop sizes, and converts the index into a list of indices + that correspond to the position in a multi-dimensional space. + + Args: + index (int): The single index to be converted. + loop_size (List[int]): A list of integers representing the size of each dimension in the multi-dimensional space. + + Returns: + List[int]: A list of integers representing the position in the multi-dimensional space. + """ + undotted_index = [] + for i in range(len(loop_size) - 1, -1, -1): + undotted_index.append(index % loop_size[i]) + index = index // loop_size[i] + undotted_index.reverse() + assert len(undotted_index) == len(loop_size) + return undotted_index + + @staticmethod + def index_dot(index: List[int], loop_size: List[int]) -> int: + """ + Converts a list of indices into a single index, representing the position in a multi-dimensional space. + + This method takes a list of indices and a list of loop sizes, and converts the list of indices into a single index + that corresponds to the position in a multi-dimensional space. + + Args: + index (List[int]): A list of integers representing the position in the multi-dimensional space. + loop_size (List[int]): A list of integers representing the size of each dimension in the multi-dimensional space. + + Returns: + int: A single integer representing the position in the multi-dimensional space. + """ + assert len(index) == len(loop_size) + dot_index = 0 + strides = [1] + for i in range(len(loop_size) - 1, -1, -1): + strides.append(strides[-1] * loop_size[i]) + strides.reverse() + strides = strides[1:] + assert len(index) == len(strides) + for i in range(len(index)): + dot_index += index[i] * strides[i] + return dot_index + + +class TileProcessor: + def __init__( + self, + encode_fn, + decode_fn, + tile_sample_min_height: int = 256, + tile_sample_min_width: int = 256, + tile_sample_min_length: int = 16, + spatial_downsample_factor: int = 8, + temporal_downsample_factor: int = 1, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + sr_ratio=1, + first_frame_as_image: bool = False, + parallel_group: torch.distributed.ProcessGroup = None, + ): + """ + Initializes an instance of the class. + + Args: + encode_fn (function): The encoding function used for tile sampling. + decode_fn (function): The decoding function used for tile reconstruction. + tile_sample_min_size (int, optional): The minimum size of the sampled tiles. Defaults to 256. + tile_sample_min_length (int, optional): The minimum length of the sampled tiles. Defaults to 16. + spatial_downsample_factor (int, optional): The actual spataial downsample factor of given encode_fn. Defaults to 8. + temporal_downsample_factor (int, optional): The actual temporal downsample factor of the latent space tiles. Defaults to 1. + tile_overlap_factor (float, optional): The overlap factor between adjacent tiles. Defaults to 0.25. + parallel_group (torch.distributed.ProcessGroup, optional): Distributed decoding group. Defaults to None. + """ + self.encode_fn = encode_fn + self.decode_fn = decode_fn + + self.spatial_downsample_factor = spatial_downsample_factor + self.temporal_downsample_factor = temporal_downsample_factor + self.tile_sample_min_height = tile_sample_min_height + self.tile_sample_min_width = tile_sample_min_width + self.tile_sample_min_length = tile_sample_min_length + self.tile_latent_min_height = tile_sample_min_height // spatial_downsample_factor + self.tile_latent_min_width = tile_sample_min_width // spatial_downsample_factor + + self.tile_latent_min_length = tile_sample_min_length // temporal_downsample_factor + if first_frame_as_image: + self.tile_latent_min_length += 1 + + self.spatial_tile_overlap_factor = spatial_tile_overlap_factor + self.temporal_tile_overlap_factor = temporal_tile_overlap_factor + self.sr_ratio = sr_ratio + self.parallel_group = parallel_group + + def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: + blend_extent = min(a.shape[2], b.shape[2], blend_extent) + for t in range(blend_extent): + b[:, :, t, :, :] = a[:, :, -blend_extent + t, :, :] * (1 - t / blend_extent) + b[:, :, t, :, :] * ( + t / blend_extent + ) + return b + + def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: + blend_extent = min(a.shape[3], b.shape[3], blend_extent) + for y in range(blend_extent): + b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * ( + y / blend_extent + ) + return b + + def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: + blend_extent = min(a.shape[4], b.shape[4], blend_extent) + for x in range(blend_extent): + b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * ( + x / blend_extent + ) + return b + + def tiled_encode(self, x: torch.FloatTensor, verbose: bool = False): + overlap_height = int(self.tile_sample_min_height * (1 - self.spatial_tile_overlap_factor)) + overlap_width = int(self.tile_sample_min_width * (1 - self.spatial_tile_overlap_factor)) + overlap_length = int(self.tile_sample_min_length * (1 - self.temporal_tile_overlap_factor)) + blend_extent_h = int(self.tile_latent_min_height * self.spatial_tile_overlap_factor) + blend_extent_w = int(self.tile_latent_min_width * self.spatial_tile_overlap_factor) + blend_extent_t = int(self.tile_latent_min_length * self.temporal_tile_overlap_factor) + height_limit = self.tile_latent_min_height - blend_extent_h + width_limit = self.tile_latent_min_width - blend_extent_w + frame_limit = self.tile_latent_min_length - blend_extent_t + + length_tile_size = (x.shape[2] + overlap_length - 1) // overlap_length + height_tile_size = (x.shape[3] + overlap_height - 1) // overlap_height + width_tile_size = (x.shape[4] + overlap_width - 1) // overlap_width + total_tile_size = length_tile_size * height_tile_size * width_tile_size + for_loop_size = [length_tile_size, height_tile_size, width_tile_size] + + tiles = [] + tile_numel_dict = OrderedDict() + for tile_index in range(total_tile_size): + undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size) + f_idx, i_idx, j_idx = undot_tile_index + f = f_idx * overlap_length + i = i_idx * overlap_height + j = j_idx * overlap_width + + # Extract the tile from the latent representation and decode it + tile = x[ + :, + :, + f : f + self.tile_sample_min_length, + i : i + self.tile_sample_min_height, + j : j + self.tile_sample_min_width, + ] + tiles.append(tile) + tile_numel_dict[tile_index] = tile.numel() + tile_index_list, global_tile_index_list = ParallelHelper.split_tile_list( + tile_numel_dict, parallel_group=self.parallel_group + ) + progress_bar = tqdm( + total=len(tile_index_list), + desc=f"[Rank {torch.distributed.get_rank(group=self.parallel_group)}] Encoding Tiles", + disable=not verbose, + ) + + frames = [] + # Encode each tile based on the tile index list + for tile_index in tile_index_list: + tile = tiles[tile_index] + encoded = self.encode_fn(tile) + frames.append(encoded) + progress_bar.update(1) + + # Gather all decoded frames from different ranks + frames = ParallelHelper.gather_frames(frames, global_tile_index_list, parallel_group=self.parallel_group) + assert len(frames) == total_tile_size + progress_bar.close() + + result_frames = [] + # Blend the encoded tiles to create the final output + for tile_index in range(total_tile_size): + undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size) + f, i, j = undot_tile_index + + tile = frames[tile_index] + # Blend with previous tiles if applicable + if f > 0: + idx = ParallelHelper.index_dot([f - 1, i, j], for_loop_size) + tile = self.blend_t(frames[idx], tile, blend_extent_t) + if i > 0: + idx = ParallelHelper.index_dot([f, i - 1, j], for_loop_size) + tile = self.blend_v(frames[idx], tile, blend_extent_h) + if j > 0: + idx = ParallelHelper.index_dot([f, i, j - 1], for_loop_size) + tile = self.blend_h(frames[idx], tile, blend_extent_w) + result_frames.append(tile[:, :, :frame_limit, :height_limit, :width_limit]) + + assert len(result_frames) == total_tile_size + + concat_frames = [] + for f in range(length_tile_size): + result_rows = [] + for i in range(height_tile_size): + result_row = [] + for j in range(width_tile_size): + idx = ParallelHelper.index_dot([f, i, j], for_loop_size) + result_row.append(result_frames[idx]) + result_rows.append(torch.cat(result_row, dim=4)) + concat_frames.append(torch.cat(result_rows, dim=3)) + + # Concatenate all result frames along the temporal dimension + result = torch.cat(concat_frames, dim=2) + return result + + def tiled_decode(self, z: torch.FloatTensor, verbose: bool = False): + overlap_height = int(self.tile_latent_min_height * (1 - self.spatial_tile_overlap_factor)) + overlap_width = int(self.tile_latent_min_width * (1 - self.spatial_tile_overlap_factor)) + overlap_length = int(self.tile_latent_min_length * (1 - self.temporal_tile_overlap_factor)) + + real_tile_sample_min_height = int(self.tile_latent_min_height * self.spatial_downsample_factor * self.sr_ratio) + real_tile_sample_min_width = int(self.tile_latent_min_width * self.spatial_downsample_factor * self.sr_ratio) + real_tile_sample_min_length = int(self.tile_latent_min_length * self.temporal_downsample_factor) + + blend_extent_h = int(real_tile_sample_min_height * self.spatial_tile_overlap_factor) + blend_extent_w = int(real_tile_sample_min_width * self.spatial_tile_overlap_factor) + blend_extent_t = int(real_tile_sample_min_length * self.temporal_tile_overlap_factor) + + height_limit = real_tile_sample_min_height - blend_extent_h + width_limit = real_tile_sample_min_width - blend_extent_w + frame_limit = real_tile_sample_min_length - blend_extent_t + + length_tile_size = (z.shape[2] + overlap_length - 1) // overlap_length + height_tile_size = (z.shape[3] + overlap_height - 1) // overlap_height + width_tile_size = (z.shape[4] + overlap_width - 1) // overlap_width + total_tile_size = length_tile_size * height_tile_size * width_tile_size + for_loop_size = [length_tile_size, height_tile_size, width_tile_size] + + tiles = [] + tile_numel_dict = OrderedDict() + for tile_index in range(total_tile_size): + undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size) + f_idx, i_idx, j_idx = undot_tile_index + f = f_idx * overlap_length + i = i_idx * overlap_height + j = j_idx * overlap_width + + # Extract the tile from the latent representation and decode it + tile = z[ + :, + :, + f : f + self.tile_latent_min_length, + i : i + self.tile_latent_min_height, + j : j + self.tile_latent_min_width, + ] + tiles.append(tile) + tile_numel_dict[tile_index] = tile.numel() + tile_index_list, global_tile_index_list = ParallelHelper.split_tile_list( + tile_numel_dict, parallel_group=self.parallel_group + ) + progress_bar = tqdm( + total=len(tile_index_list), + desc=f"[Rank {torch.distributed.get_rank(group=self.parallel_group)}] Decoding Tiles", + disable=not verbose, + ) + + frames = [] + # Decode each tile based on the tile index list + for tile_index in tile_index_list: + tile = tiles[tile_index] + decoded = self.decode_fn(tile) + frames.append(decoded) + progress_bar.update(1) + + progress_bar.close() + # Gather all decoded frames from different ranks + frames = ParallelHelper.gather_frames(frames, global_tile_index_list, parallel_group=self.parallel_group) + assert len(frames) == total_tile_size + + result_frames = [] + # Blend the decoded tiles to create the final output + for tile_index in tile_index_list: + undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size) + f, i, j = undot_tile_index + + tile = frames[tile_index].clone() + # Blend with previous tiles if applicable + if f > 0: + idx = ParallelHelper.index_dot([f - 1, i, j], for_loop_size) + tile = torch.compile(self.blend_t, dynamic=False)(frames[idx], tile, blend_extent_t) + if i > 0: + idx = ParallelHelper.index_dot([f, i - 1, j], for_loop_size) + tile = torch.compile(self.blend_v, dynamic=False)(frames[idx], tile, blend_extent_h) + if j > 0: + idx = ParallelHelper.index_dot([f, i, j - 1], for_loop_size) + tile = torch.compile(self.blend_h, dynamic=False)(frames[idx], tile, blend_extent_w) + result_frames.append(tile[:, :, :frame_limit, :height_limit, :width_limit]) + + # Gather and concatenate the final result frames + result_frames = ParallelHelper.gather_frames(result_frames, global_tile_index_list, parallel_group=self.parallel_group) + assert len(result_frames) == total_tile_size + + concat_frames = [] + for f in range(length_tile_size): + result_rows = [] + for i in range(height_tile_size): + result_row = [] + for j in range(width_tile_size): + idx = ParallelHelper.index_dot([f, i, j], for_loop_size) + result_row.append(result_frames[idx]) + result_rows.append(torch.cat(result_row, dim=4)) + concat_frames.append(torch.cat(result_rows, dim=3)) + + # Concatenate all result frames along the temporal dimension + result = torch.cat(concat_frames, dim=2) + return result diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..518895680251c2b1e91bd1a67426e1bd12ba9e08 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .dit_model import get_dit, VideoDiTModel +from .dit_module import FullyParallelAttention + +__all__ = ["get_dit", "VideoDiTModel", "FullyParallelAttention"] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..302f828fc9bf55c8de87cb646e916792b5672235 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b546f93c997fcca08967575205a0bdb10cb8073 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_model.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a4caa39a725a8e7ab3bc02bc3f806ac7c5b26a1 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_model.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_model.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dd2433d40a15e77238be45722d08d066b30cffe Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_model.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_module.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_module.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d66eb2621a5dfb467832fb79bbe2cba4e7aafa7c Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_module.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_module.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64f16e15bd7360ef558fef9d4fded7721d6a4305 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/__pycache__/dit_module.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_model.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b6cd2d98c52322baa2bf6519705e4a4cc65dd0c5 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_model.py @@ -0,0 +1,733 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import math +import os +from typing import Tuple + +import torch +import torch.distributed +import torch.nn as nn +from einops import rearrange + +from inference.common import ( + InferenceParams, + MagiConfig, + ModelMetaArgs, + PackedCoreAttnParams, + PackedCrossAttnParams, + env_is_true, + print_per_rank, + print_rank_0, +) +from inference.infra.checkpoint import load_checkpoint +from inference.infra.distributed import parallel_state as mpu +from inference.infra.parallelism import cp_post_process, cp_pre_process, pp_scheduler + +from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + + +class VideoDiTModel(torch.nn.Module): + """VideoDiT model for video diffusion. + + Args: + config (MagiConfig): Transformer config + pre_process (bool, optional): Include embedding layer (used with pipeline parallelism). Defaults to True. + post_process (bool, optional): Include an output layer (used with pipeline parallelism). Defaults to True. + """ + + def __init__(self, config: MagiConfig, pre_process: bool = True, post_process: bool = True) -> None: + super().__init__() + + self.model_config = config.model_config + self.runtime_config = config.runtime_config + self.engine_config = config.engine_config + + self.pre_process = pre_process + self.post_process = post_process + self.in_channels = self.model_config.in_channels + self.out_channels = self.model_config.out_channels + self.patch_size = self.model_config.patch_size + self.t_patch_size = self.model_config.t_patch_size + self.caption_max_length = self.model_config.caption_max_length + self.num_heads = self.model_config.num_attention_heads + + self.x_embedder = nn.Conv3d( + self.model_config.in_channels, + self.model_config.hidden_size, + kernel_size=(self.model_config.t_patch_size, self.model_config.patch_size, self.model_config.patch_size), + stride=(self.model_config.t_patch_size, self.model_config.patch_size, self.model_config.patch_size), + bias=False, + ) + self.t_embedder = TimestepEmbedder(model_config=self.model_config) + self.y_embedder = CaptionEmbedder(model_config=self.model_config) + self.rope = LearnableRotaryEmbeddingCat( + self.model_config.hidden_size // self.model_config.num_attention_heads, in_pixels=False + ) + + # trm block + self.videodit_blocks = TransformerBlock( + model_config=self.model_config, + engine_config=self.engine_config, + pre_process=pre_process, + post_process=post_process, + ) + + self.final_linear = FinalLinear( + self.model_config.hidden_size, self.model_config.patch_size, self.model_config.t_patch_size, self.out_channels + ) + + def generate_kv_range_for_uncondition(self, uncond_x) -> torch.Tensor: + device = f"cuda:{torch.cuda.current_device()}" + B, C, T, H, W = uncond_x.shape + chunk_token_nums = ( + (T // self.model_config.t_patch_size) * (H // self.model_config.patch_size) * (W // self.model_config.patch_size) + ) + + k_chunk_start = torch.linspace(0, (B - 1) * chunk_token_nums, steps=B).reshape((B, 1)) + k_chunk_end = torch.linspace(chunk_token_nums, B * chunk_token_nums, steps=B).reshape((B, 1)) + return torch.concat([k_chunk_start, k_chunk_end], dim=1).to(torch.int32).to(device) + + def unpatchify(self, x, H, W): + return rearrange( + x, + "(T H W) N (pT pH pW C) -> N C (T pT) (H pH) (W pW)", + H=H, + W=W, + pT=self.t_patch_size, + pH=self.patch_size, + pW=self.patch_size, + ).contiguous() + + @torch.no_grad() + def get_embedding_and_meta(self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs): + """ + Forward embedding and meta for VideoDiT. + NOTE: This function should only handle single card behavior. + + Input: + x: (N, C, T, H, W). torch.Tensor of spatial inputs (images or latent representations of images) + t: (N, denoising_range_num). torch.Tensor of diffusion timesteps + y: (N * denoising_range_num, 1, L, C). torch.Tensor of class labels + caption_dropout_mask: (N). torch.Tensor of whether to drop caption + xattn_mask: (N * denoising_range_num, 1, L). torch.Tensor of xattn mask + kv_range: (N * denoising_range_num, 2). torch.Tensor of kv range + + Output: + x: (S, N, D). torch.Tensor of inputs embedding (images or latent representations of images) + condition: (N, denoising_range_num, D). torch.Tensor of condition embedding + condition_map: (S, N). torch.Tensor determine which condition to use for each token + rope: (S, 96). torch.Tensor of rope + y_xattn_flat: (total_token, D). torch.Tensor of y_xattn_flat + cuda_graph_inputs: (y_xattn_flat, xattn_mask) or None. None means no cuda graph + NOTE: y_xattn_flat and xattn_mask with static shape + H: int. Height of the input + W: int. Width of the input + ardf_meta: dict. Meta information for ardf + cross_attn_params: PackedCrossAttnParams. Packed sequence parameters for cross_atten + """ + + ################################### + # Part1: Embed x # + ################################### + x = self.x_embedder(x) # [N, C, T, H, W] + batch_size, _, T, H, W = x.shape + + # Prepare necessary variables + range_num = kwargs["range_num"] + denoising_range_num = kwargs["denoising_range_num"] + slice_point = kwargs.get("slice_point", 0) + frame_in_range = T // denoising_range_num + prev_clean_T = frame_in_range * slice_point + T_total = T + prev_clean_T + + ################################### + # Part2: rope # + ################################### + # caculate rescale_factor for multi-resolution & multi aspect-ratio training + # the base_size [16*16] is A predefined size based on data:(256x256) vae: (8,8,4) patch size: (1,1,2) + # This definition do not have any relationship with the actual input/model/setting. + # ref_feat_shape is used to calculate innner rescale factor, so it can be float. + rescale_factor = math.sqrt((H * W) / (16 * 16)) + rope = self.rope.get_embed(shape=[T_total, H, W], ref_feat_shape=[T_total, H / rescale_factor, W / rescale_factor]) + # the shape of rope is (T*H*W, -1) aka (seq_length, head_dim), as T is the first dimension, we can directly cut it. + rope = rope[-(T * H * W) :] + + + ################################### + # Part3: Embed t # + ################################### + assert t.shape[0] == batch_size, f"Invalid t shape, got {t.shape[0]} != {batch_size}" # nolint + assert t.shape[1] == denoising_range_num, f"Invalid t shape, got {t.shape[1]} != {denoising_range_num}" # nolint + t_flat = t.flatten() # (N * denoising_range_num,) + t = self.t_embedder(t_flat) # (N, D) + + if self.engine_config.distill: + distill_dt_scalar = 2 + if kwargs["num_steps"] == 12: + base_chunk_step = 4 + distill_dt_factor = base_chunk_step / kwargs["distill_interval"] * distill_dt_scalar + else: + distill_dt_factor = kwargs["num_steps"] / 4 * distill_dt_scalar + distill_dt = torch.ones_like(t_flat) * distill_dt_factor + distill_dt_embed = self.t_embedder(distill_dt) + t = t + distill_dt_embed + t = t.reshape(batch_size, denoising_range_num, -1) # (N, range_num, D) + + ###################################################### + # Part4: Embed y, prepare condition and y_xattn_flat # + ###################################################### + # (N * denoising_range_num, 1, L, D) + y_xattn, y_adaln = self.y_embedder(y, self.training, caption_dropout_mask) + + assert xattn_mask is not None + xattn_mask = xattn_mask.squeeze(1).squeeze(1) + + # condition: (N, range_num, D) + y_adaln = y_adaln.squeeze(1) # (N, D) + condition = t + y_adaln.unsqueeze(1) + + assert condition.shape[0] == batch_size + assert condition.shape[1] == denoising_range_num + seqlen_per_chunk = (T * H * W) // denoising_range_num + condition_map = torch.arange(batch_size * denoising_range_num, device=x.device) + condition_map = torch.repeat_interleave(condition_map, seqlen_per_chunk) + condition_map = condition_map.reshape(batch_size, -1).transpose(0, 1).contiguous() + + # y_xattn_flat: (total_token, D) + y_xattn_flat = torch.masked_select(y_xattn.squeeze(1), xattn_mask.unsqueeze(-1).bool()).reshape(-1, y_xattn.shape[-1]) + xattn_mask_for_cuda_graph = None + + ###################################################### + # Part5: Prepare cross_attn_params for cross_atten # + ###################################################### + # (N * denoising_range_num, L) + xattn_mask = xattn_mask.reshape(xattn_mask.shape[0], -1) + y_index = torch.sum(xattn_mask, dim=-1) + clip_token_nums = H * W * frame_in_range + + cu_seqlens_q = torch.Tensor([0] + ([clip_token_nums] * denoising_range_num * batch_size)).to(torch.int64).to(x.device) + cu_seqlens_k = torch.cat([y_index.new_tensor([0]), y_index]).to(torch.int64).to(x.device) + cu_seqlens_q = cu_seqlens_q.cumsum(-1).to(torch.int32) + cu_seqlens_k = cu_seqlens_k.cumsum(-1).to(torch.int32) + + assert ( + cu_seqlens_q.shape == cu_seqlens_k.shape + ), f"cu_seqlens_q.shape: {cu_seqlens_q.shape}, cu_seqlens_k.shape: {cu_seqlens_k.shape}" + + xattn_q_ranges = torch.cat([cu_seqlens_q[:-1].unsqueeze(1), cu_seqlens_q[1:].unsqueeze(1)], dim=1) + xattn_k_ranges = torch.cat([cu_seqlens_k[:-1].unsqueeze(1), cu_seqlens_k[1:].unsqueeze(1)], dim=1) + assert ( + xattn_q_ranges.shape == xattn_k_ranges.shape + ), f"xattn_q_ranges.shape: {xattn_q_ranges.shape}, xattn_k_ranges.shape: {xattn_k_ranges.shape}" + + cross_attn_params = PackedCrossAttnParams( + q_ranges=xattn_q_ranges, + kv_ranges=xattn_k_ranges, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=cu_seqlens_k, + max_seqlen_q=clip_token_nums, + max_seqlen_kv=self.caption_max_length, + ) + + ################################################## + # Part6: Prepare core_atten related q/kv range # + ################################################## + q_range = torch.cat([cu_seqlens_q[:-1].unsqueeze(1), cu_seqlens_q[1:].unsqueeze(1)], dim=1) + flat_kv = torch.unique(kv_range, sorted=True) + max_seqlen_k = (flat_kv[-1] - flat_kv[0]).cpu().item() + + ardf_meta = dict( + clip_token_nums=clip_token_nums, + slice_point=slice_point, + range_num=range_num, + denoising_range_num=denoising_range_num, + q_range=q_range, + k_range=kv_range, + max_seqlen_q=clip_token_nums, + max_seqlen_k=max_seqlen_k, + ) + + return (x, condition, condition_map, rope, y_xattn_flat, xattn_mask_for_cuda_graph, H, W, ardf_meta, cross_attn_params) + + @torch.no_grad() + def forward_pre_process( + self, x, t, y, caption_dropout_mask=None, xattn_mask=None, kv_range=None, **kwargs + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, ModelMetaArgs]: + assert kv_range is not None, "Please ensure kv_range is provided" + + x = x * self.model_config.x_rescale_factor + + if self.model_config.half_channel_vae: + assert x.shape[1] == 16 + x = torch.cat([x, x], dim=1) + + x = x.float() + t = t.float() + y = y.float() + # embedder context will ensure that the processing is in high precision even if the embedder params is in bfloat16 mode + with torch.autocast(device_type="cuda", dtype=torch.float32): + ( + x, + condition, + condition_map, + rope, + y_xattn_flat, + xattn_mask_for_cuda_graph, + H, + W, + ardf_meta, + cross_attn_params, + ) = self.get_embedding_and_meta(x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs) + + # Downcast x and rearrange x + x = x.to(self.model_config.params_dtype) + x = rearrange(x, "N C T H W -> (T H W) N C").contiguous() # (thw, N, D) + + # condition and y_xattn_flat will be downcast to bfloat16 in transformer block. + condition = condition.to(self.model_config.params_dtype) + y_xattn_flat = y_xattn_flat.to(self.model_config.params_dtype) + + core_attn_params = PackedCoreAttnParams( + q_range=ardf_meta["q_range"], + k_range=ardf_meta["k_range"], + np_q_range=ardf_meta["q_range"].cpu().numpy(), + np_k_range=ardf_meta["k_range"].cpu().numpy(), + max_seqlen_q=ardf_meta["max_seqlen_q"], + max_seqlen_k=ardf_meta["max_seqlen_k"], + ) + + (x, condition_map, rope, cp_pad_size, cp_split_sizes, core_attn_params, cross_attn_params) = cp_pre_process( + self.engine_config.cp_size, + self.engine_config.cp_strategy, + x, + condition_map, + rope, + xattn_mask_for_cuda_graph, + ardf_meta, + core_attn_params, + cross_attn_params, + ) + + meta_args = ModelMetaArgs( + H=H, + W=W, + cp_pad_size=cp_pad_size, + cp_split_sizes=cp_split_sizes, + slice_point=ardf_meta["slice_point"], + denoising_range_num=ardf_meta["denoising_range_num"], + range_num=ardf_meta["range_num"], + extract_prefix_video_feature=kwargs.get("extract_prefix_video_feature", False), + fwd_extra_1st_chunk=kwargs["fwd_extra_1st_chunk"], + distill_nearly_clean_chunk=kwargs.get("distill_nearly_clean_chunk", False), + clip_token_nums=ardf_meta["clip_token_nums"], + enable_cuda_graph=xattn_mask_for_cuda_graph is not None, + core_attn_params=core_attn_params, + cross_attn_params=cross_attn_params, + timestep=t, # add to get attention weights for each timestep + get_attn_weights_layer_num=-1, + save_kvcache_every_forward=kwargs.get("save_kvcache_every_forward", False), + cur_denoise_step=kwargs.get("cur_denoise_step", 0), + start_chunk_id=kwargs["start_chunk_id"], + end_chunk_id=kwargs["end_chunk_id"], + compress_kv=kwargs.get("compress_kv", False), + total_cache_len=kwargs.get("total_cache_len", 0), + budget_cache_len=kwargs.get("budget_cache_len", 0), + chunk_num=kwargs["chunk_num"], + debug=kwargs.get("debug", False), + near_clean_chunk_idx=kwargs.get("near_clean_chunk_idx", -1), + ) + + return (x, condition, condition_map, y_xattn_flat, rope, meta_args) + + @torch.no_grad() + def forward_post_process(self, x, meta_args: ModelMetaArgs) -> torch.Tensor: + x = x.float() + # embedder context will ensure that the processing is in high precision even if the embedder params is in bfloat16 mode + with torch.autocast(device_type="cuda", dtype=torch.float32): + x = self.final_linear(x) # (thw/cp, N, patch_size ** 2 * out_channels) + + # leave context parallel region + x = cp_post_process(self.engine_config.cp_size, self.engine_config.cp_strategy, x, meta_args) + + # N C T H W + x = self.unpatchify(x, meta_args.H, meta_args.W) + + if self.model_config.half_channel_vae: + assert x.shape[1] == 32 + x = x[:, :16] + + x = x / self.model_config.x_rescale_factor + + return x + + @torch.no_grad() + def forward( + self, + x, + t, + y, + caption_dropout_mask=None, + xattn_mask=None, + kv_range=None, + inference_params: InferenceParams = None, + **kwargs, + ) -> torch.Tensor: + (x, condition, condition_map, y_xattn_flat, rope, meta_args) = self.forward_pre_process( + x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs + ) + + if not self.pre_process: + x = pp_scheduler().recv_prev_data(x.shape, x.dtype) + self.videodit_blocks.set_input_tensor(x) + else: + # clone a new tensor to ensure x is not a view of other tensor + x = x.clone() + + x = self.videodit_blocks.forward( + hidden_states=x, + condition=condition, + condition_map=condition_map, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rope, + inference_params=inference_params, + meta_args=meta_args, + ) + + if not self.post_process: + pp_scheduler().isend_next(x) + + return self.forward_post_process(x, meta_args) + + def forward_3cfg( + self, x, timestep, y, mask, kv_range, inference_params, **kwargs + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]: + """ + Forward pass of PixArt, but also batches the unconditional forward pass for classifier-free guidance. + """ + # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb + + assert x.shape[0] == 2 + assert mask.shape[0] % 2 == 0 # mask should be a multiple of 2 + x = torch.cat([x[0:1], x[0:1]], dim=0) + caption_dropout_mask = torch.tensor([False, True], dtype=torch.bool, device=x.device) + + inference_params.update_kv_cache = False + out_cond_pre_and_text = self.forward( + x[0:1], + timestep[0:1], + y[0 : y.shape[0] // 2], + caption_dropout_mask=caption_dropout_mask[0:1], + xattn_mask=mask[0 : y.shape[0] // 2], + kv_range=kv_range, + inference_params=inference_params, + **kwargs, + ) + + inference_params.update_kv_cache = True + out_cond_pre = self.forward( + x[1:2], + timestep[1:2], + y[y.shape[0] // 2 : y.shape[0]], + caption_dropout_mask=caption_dropout_mask[1:2], + xattn_mask=mask[y.shape[0] // 2 : y.shape[0]], + kv_range=kv_range, + inference_params=inference_params, + **kwargs, + ) + + def chunk_to_batch(input, denoising_range_num): + input = input.squeeze(0) + input = input.reshape(-1, denoising_range_num, kwargs["chunk_width"], *input.shape[2:]) + return input.transpose(0, 1) # (denoising_range_num, chn, chunk_width, h, w) + + def batch_to_chunk(input, denoising_range_num): + input = input.transpose(0, 1) + input = input.reshape(1, -1, denoising_range_num * kwargs["chunk_width"], *input.shape[3:]) + return input + + class UnconditionGuard: + def __init__(self, kwargs): + self.kwargs = kwargs + self.prev_state = { + "range_num": kwargs["range_num"], + "denoising_range_num": kwargs["denoising_range_num"], + "slice_point": kwargs["slice_point"], + "fwd_extra_1st_chunk": kwargs["fwd_extra_1st_chunk"], + } + + def __enter__(self): + if self.kwargs.get("fwd_extra_1st_chunk", False): + self.kwargs["denoising_range_num"] -= 1 + self.kwargs["slice_point"] += 1 + self.kwargs["fwd_extra_1st_chunk"] = False + + def __exit__(self, exc_type, exc_val, exc_tb): + self.kwargs["range_num"] = self.prev_state["range_num"] + self.kwargs["denoising_range_num"] = self.prev_state["denoising_range_num"] + self.kwargs["slice_point"] = self.prev_state["slice_point"] + self.kwargs["fwd_extra_1st_chunk"] = self.prev_state["fwd_extra_1st_chunk"] + + with UnconditionGuard(kwargs): + denoising_range_num = kwargs["denoising_range_num"] + denoise_width = kwargs["chunk_width"] * denoising_range_num + uncond_x = chunk_to_batch(x[0:1, :, -denoise_width:], denoising_range_num) + timestep = timestep[0:1, -denoising_range_num:].transpose(0, 1) + uncond_y = y[y.shape[0] // 2 : y.shape[0]][-denoising_range_num:] + caption_dropout_mask = torch.tensor([True], dtype=torch.bool, device=x.device) + uncond_mask = mask[y.shape[0] // 2 : y.shape[0]][-denoising_range_num:] + uncond_kv_range = self.generate_kv_range_for_uncondition(uncond_x) + + kwargs["range_num"] = 1 + kwargs["denoising_range_num"] = 1 + kwargs["slice_point"] = 0 + out_uncond = self.forward( + uncond_x, + timestep, + uncond_y, + caption_dropout_mask=caption_dropout_mask, + xattn_mask=uncond_mask, + kv_range=uncond_kv_range, + inference_params=None, + **kwargs, + ) + out_uncond = batch_to_chunk(out_uncond, denoising_range_num) + + return out_cond_pre_and_text, out_cond_pre, out_uncond, denoise_width + + def get_cfg_scale(self, t, cfg_t_range, prev_chunk_scale_s, text_scale_s): + indices = torch.searchsorted(cfg_t_range - 1e-7, t) - 1 + assert indices.min() >= 0 and indices.max() < len(prev_chunk_scale_s) + return prev_chunk_scale_s[indices], text_scale_s[indices] + + def forward_dispatcher(self, x, timestep, y, mask, kv_range, inference_params, **kwargs): + if self.runtime_config.cfg_number == 3: + (out_cond_pre_and_text, out_cond_pre, out_uncond, denoise_width) = self.forward_3cfg( + x, timestep, y, mask, kv_range, inference_params, **kwargs + ) + + prev_chunk_scale_s = torch.tensor(self.runtime_config.prev_chunk_scales).cuda() + text_scale_s = torch.tensor(self.runtime_config.text_scales).cuda() + cfg_t_range = torch.tensor(self.runtime_config.cfg_t_range).cuda() + applied_cfg_range_num, chunk_width = (kwargs["denoising_range_num"], kwargs["chunk_width"]) + if kwargs["fwd_extra_1st_chunk"]: + applied_cfg_range_num -= 1 + cfg_timestep = timestep[0, -applied_cfg_range_num:] + + assert len(prev_chunk_scale_s) == len(cfg_t_range), "prev_chunks_scale and t_range should have the same length" + assert len(text_scale_s) == len(cfg_t_range), "text_scale and t_range should have the same length" + + cfg_output_list = [] + + for chunk_idx in range(applied_cfg_range_num): + prev_chunk_scale, text_scale = self.get_cfg_scale( + cfg_timestep[chunk_idx], cfg_t_range, prev_chunk_scale_s, text_scale_s + ) + l = chunk_idx * chunk_width + r = (chunk_idx + 1) * chunk_width + cfg_output = ( + (1 - prev_chunk_scale) * out_uncond[:, :, l:r] + + (prev_chunk_scale - text_scale) * out_cond_pre[:, :, -denoise_width:][:, :, l:r] + + text_scale * out_cond_pre_and_text[:, :, -denoise_width:][:, :, l:r] + ) + cfg_output_list.append(cfg_output) + + cfg_output = torch.cat(cfg_output_list, dim=2) + + # Reconstruct input x for the next diffusion step + x = torch.cat([x[0:1, :, :-denoise_width], cfg_output], dim=2) + x = torch.cat([x, x], dim=0) + return x + elif self.runtime_config.cfg_number == 1: + assert x.shape[0] == 2 + x = torch.cat([x[0:1], x[0:1]], dim=0) + + kwargs["caption_dropout_mask"] = torch.tensor([False], dtype=torch.bool, device=x.device) + inference_params.update_kv_cache = True + if kwargs.get("distill_nearly_clean_chunk", False): + prev_chunks_scale = float(os.getenv("prev_chunks_scale", 0.7)) + slice_start = 1 if kwargs["fwd_extra_1st_chunk"] else 0 + cond_pre_and_text_channel = x.shape[2] + new_x_chunk = x[0:1, :, slice_start * kwargs["chunk_width"] : (slice_start + 1) * kwargs["chunk_width"]] + new_kvrange = self.generate_kv_range_for_uncondition(new_x_chunk) + kwargs["denoising_range_num"] += 1 + cat_x_chunk = torch.cat([x[0:1], new_x_chunk], dim=2) + new_kvrange = new_kvrange + kv_range.max() + cat_kvrange = torch.cat([kv_range, new_kvrange], dim=0) + cat_t = torch.cat([timestep[0:1], timestep[0:1, slice_start : slice_start + 1]], dim=1) + cat_y = torch.cat([y[0 : y.shape[0] // 2], y[slice_start : slice_start + 1]], dim=0) + cat_xattn_mask = torch.cat([mask[0 : y.shape[0] // 2], mask[slice_start : slice_start + 1]], dim=0) + + cat_out = self.forward( + cat_x_chunk, + cat_t, + cat_y, + xattn_mask=cat_xattn_mask, + kv_range=cat_kvrange, + inference_params=inference_params, + **kwargs, + ) + # flowcache processes one chunk at a time and returns all chunks in a dictionary after processing is complete + if type(cat_out) == dict: + # No artifact chunk in 3 cases: + # 1. Discard artifact chunk is set + # 2. No recomputed output part + # 3. Although there is artifact chunk, the corresponding nearly clean chunk can be reused directly, so no need to compute artifact chunk separately + if self.discard_nearly_clean_chunk or (not cat_out.keys()) or max(cat_out) != self.near_clean_chunk_idx: + out_cond_pre_and_text = cat_out + else: + near_clean_out_cond_text = cat_out[max(cat_out)] + near_clean_out_cond_pre_and_text = cat_out[min(cat_out)] + cat_out[min(cat_out)] = ( + near_clean_out_cond_pre_and_text * prev_chunks_scale + near_clean_out_cond_text * (1 - prev_chunks_scale) + ) + # Remove the output corresponding to nearly clean chunk + cat_out.pop(max(cat_out)) + out_cond_pre_and_text = cat_out + elif type(cat_out) == torch.Tensor: + # Adapt to teacache + if hasattr(self, "discard_nearly_clean_chunk") and self.discard_nearly_clean_chunk: + # No need to do extra forward for nearly clean chunk, so no need to add proportionally + out_cond_pre_and_text = cat_out + # Reset + self.discard_nearly_clean_chunk = False + else: + near_clean_out_cond_pre_and_text = cat_out[ + :, :, slice_start * kwargs["chunk_width"] : (slice_start + 1) * kwargs["chunk_width"] + ] + near_clean_out_cond_text = cat_out[:, :, cond_pre_and_text_channel:] + + near_out_cond_pre_and_text = ( + near_clean_out_cond_pre_and_text * prev_chunks_scale + near_clean_out_cond_text * (1 - prev_chunks_scale) + ) + + cat_out[ + :, :, slice_start * kwargs["chunk_width"] : (slice_start + 1) * kwargs["chunk_width"] + ] = near_out_cond_pre_and_text + out_cond_pre_and_text = cat_out[:, :, :cond_pre_and_text_channel] + else: + raise RuntimeError + else: + out_cond_pre_and_text = self.forward( + x[0:1], + timestep[0:1], + y[0 : y.shape[0] // 2], + xattn_mask=mask[0 : y.shape[0] // 2], + kv_range=kv_range, + inference_params=inference_params, + **kwargs, + ) + + if type(out_cond_pre_and_text) == dict: + return_velocity = {} + for key, value in out_cond_pre_and_text.items(): + return_velocity[key] = torch.cat([value[0:1], value[0:1]], dim=0) + return return_velocity + else: + # Adapt to teacache + # "denoising_range_num" will be modified inside forward, note that kwargs here is still before modification + if hasattr(self, "denoising_range_num"): + kwargs["denoising_range_num"] = self.denoising_range_num + del self.denoising_range_num + + denoise_width = kwargs["chunk_width"] * kwargs["denoising_range_num"] + if kwargs["fwd_extra_1st_chunk"]: + denoise_width -= kwargs["chunk_width"] + + if hasattr(self, "single_chunk_inference") and self.single_chunk_inference: + x = torch.cat([out_cond_pre_and_text, out_cond_pre_and_text], dim=0) + return x + else: + x = torch.cat([x[0:1, :, :-denoise_width], out_cond_pre_and_text[:, :, -denoise_width:]], dim=2) + x = torch.cat([x[0:1], x[0:1]], dim=0) + return x + else: + raise NotImplementedError + + +def _build_dit_model(config: MagiConfig): + """Builds the model""" + device = "cuda" if env_is_true("SKIP_LOAD_MODEL") else "meta" + with torch.device(device): + model = VideoDiTModel( + config=config, pre_process=mpu.is_pipeline_first_stage(), post_process=mpu.is_pipeline_last_stage() + ) + # print_rank_0(model) + + # Print number of parameters. + param_count = sum([p.nelement() for p in model.parameters()]) + model_size_gb = sum([p.nelement() * p.element_size() for p in model.parameters()]) / (1024**3) + print_per_rank( + f"(cp, pp) rank ({mpu.get_cp_rank()}, {mpu.get_pp_rank()}): param count {param_count}, model size {model_size_gb:.2f} GB".format( + mpu.get_cp_rank(), mpu.get_pp_rank(), param_count, model_size_gb + ) + ) + + return model + + +def _high_precision_promoter(module: VideoDiTModel): + module.x_embedder.float() + module.y_embedder.float() + module.t_embedder.float() + module.final_linear.float() + module.rope.float() + for name, sub_module in module.named_modules(): + # skip qk_layernorm_xattn + if "_xattn" in name: + continue + # high precision qk_layernorm by default + if "q_layernorm" in name or "k_layernorm" in name: + sub_module.float() + if "self_attn_post_norm" in name or "mlp_post_norm" in name: + sub_module.float() + if "final_layernorm" in name: + sub_module.float() + return module + + +def get_dit(config: MagiConfig): + """Build and load VideoDiT model""" + model = _build_dit_model(config) + print_rank_0("Build DiTModel successfully") + + mem_allocated_gb = torch.cuda.memory_allocated() / 1024**3 + mem_reserved_gb = torch.cuda.memory_reserved() / 1024**3 + print_rank_0( + f"After build_dit_model, memory allocated: {mem_allocated_gb:.2f} GB, memory reserved: {mem_reserved_gb:.2f} GB" + ) + + # To avoid Error in debug mode, set default iteration to 0 + if not env_is_true("SKIP_LOAD_MODEL"): + model = load_checkpoint(model) + mem_allocated_gb = torch.cuda.memory_allocated() / 1024**3 + mem_reserved_gb = torch.cuda.memory_reserved() / 1024**3 + print_rank_0( + f"After load_checkpoint, memory allocated: {mem_allocated_gb:.2f} GB, memory reserved: {mem_reserved_gb:.2f} GB" + ) + + model = _high_precision_promoter(model) + mem_allocated_gb = torch.cuda.memory_allocated() / 1024**3 + mem_reserved_gb = torch.cuda.memory_reserved() / 1024**3 + print_rank_0( + f"After high_precision_promoter, memory allocated: {mem_allocated_gb:.2f} GB, memory reserved: {mem_reserved_gb:.2f} GB" + ) + + model.eval() + gc.collect() + torch.cuda.empty_cache() + + print_rank_0("Load checkpoint successfully") + return model diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py new file mode 100644 index 0000000000000000000000000000000000000000..0aab4dbfac5223a37e6d98fdfc1a9042c7ef80f5 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py @@ -0,0 +1,1599 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +import numbers +from functools import partial +from typing import Callable, List, Optional, Tuple, Dict, Set +import flashinfer +import torch +import torch.distributed +import torch.nn as nn +import torch.nn.functional as F +import triton +import triton.language as tl +from einops import rearrange +from flash_attn import flash_attn_varlen_func +from flash_attn.flash_attn_interface import flash_attn_func +from flash_attn.layers.rotary import apply_rotary_emb as flash_apply_rotary_emb +from flashinfer.gemm import bmm_fp8 + +try: + from magi_attention.functional import flex_flash_attn_func + + flex_attention = flex_flash_attn_func +except: + flex_attention = None + +from torch import Tensor +from torch.nn import Parameter + +from inference.common import EngineConfig, InferenceParams, ModelConfig, ModelMetaArgs, PackedCrossAttnParams, divide +from inference.infra.distributed import parallel_state +from inference.infra.parallelism import CSOHelper, UlyssesScheduler, cso_communication + +########################################################## +# TimestepEmbedder +########################################################## +class TimestepEmbedder(nn.Module): + """ + Embeds scalar timesteps into vector representations. + """ + + def __init__(self, model_config: ModelConfig, frequency_embedding_size=256): + super().__init__() + + self.data_type = model_config.params_dtype + hidden_size = model_config.hidden_size + + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, int(hidden_size * model_config.cond_hidden_ratio), bias=True), + nn.SiLU(), + nn.Linear( + int(hidden_size * model_config.cond_hidden_ratio), int(hidden_size * model_config.cond_hidden_ratio), bias=True + ), + ) + self.frequency_embedding_size = frequency_embedding_size + + # rescale the timestep for the general transport model + self.timestep_rescale_factor = 1000 + + @staticmethod + def timestep_embedding(t, dim, max_period=10000, timestep_rescale_factor=1): + """ + Create sinusoidal timestep embeddings. + :param t: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an (N, D) Tensor of positional embeddings. + """ + # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py + half = dim // 2 + freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to( + device=t.device + ) + args = t[:, None].float() * freqs[None] * timestep_rescale_factor + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + return embedding + + def forward(self, t): + t = t.to(torch.float32) + t_freq = self.timestep_embedding( + t, self.frequency_embedding_size, timestep_rescale_factor=self.timestep_rescale_factor + ) + t_emb = self.mlp(t_freq.to(self.data_type)) + return t_emb + + +########################################################## +# CaptionEmbedder +########################################################## +class CaptionEmbedder(nn.Module): + """ + Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. + """ + + def __init__(self, model_config: ModelConfig): + super().__init__() + + in_channels = model_config.caption_channels + hidden_size = model_config.hidden_size + caption_max_length = model_config.caption_max_length + + self.y_proj_xattn = nn.Sequential( + nn.Linear(in_channels, int(hidden_size * model_config.xattn_cond_hidden_ratio), bias=True), nn.SiLU() + ) + + self.y_proj_adaln = nn.Sequential(nn.Linear(in_channels, int(hidden_size * model_config.cond_hidden_ratio), bias=True)) + + self.null_caption_embedding = Parameter(torch.empty(caption_max_length, in_channels)) + + def caption_drop(self, caption, caption_dropout_mask): + """ + Drops labels to enable classifier-free guidance. + caption.shape = (N, 1, cap_len, C) + """ + dropped_caption = torch.where( + caption_dropout_mask[:, None, None, None], # (N, 1, 1, 1) + self.null_caption_embedding[None, None, :], # (1, 1, cap_len, C) + caption, # (N, 1, cap_len, C) + ) + return dropped_caption + + def caption_drop_single_token(self, caption_dropout_mask): + dropped_caption = torch.where( + caption_dropout_mask[:, None, None], # (N, 1, 1) + self.null_caption_embedding[None, -1, :], # (1, 1, C) + self.null_caption_embedding[None, -2, :], # (1, 1, C) + ) + return dropped_caption # (N, 1, C) + + def forward(self, caption, train, caption_dropout_mask=None): + if train and caption_dropout_mask is not None: + caption = self.caption_drop(caption, caption_dropout_mask) + caption_xattn = self.y_proj_xattn(caption) + if caption_dropout_mask is not None: + caption = self.caption_drop_single_token(caption_dropout_mask) + + caption_adaln = self.y_proj_adaln(caption) + return caption_xattn, caption_adaln + + +########################################################## +# FinalLinear +########################################################## +class FinalLinear(nn.Module): + """ + The final linear layer of DiT. + """ + + def __init__(self, hidden_size, patch_size, t_patch_size, out_channels): + super().__init__() + self.linear = nn.Linear(hidden_size, patch_size * patch_size * t_patch_size * out_channels, bias=False) + + def forward(self, x): + x = self.linear(x) + return x + + +########################################################## +# AdaModulateLayer +########################################################## +class AdaModulateLayer(torch.nn.Module): + def __init__(self, model_config: ModelConfig): + super().__init__() + self.model_config = model_config + + self.gate_num_chunks = 2 + self.act = nn.SiLU() + self.proj = nn.Sequential( + nn.Linear( + int(self.model_config.hidden_size * self.model_config.cond_hidden_ratio), + int(self.model_config.hidden_size * self.model_config.cond_gating_ratio * self.gate_num_chunks), + bias=True, + dtype=self.model_config.params_dtype, + ) + ) + + def forward(self, c): + c = self.act(c) + return self.proj(c) + + +########################################################## +# bias_modulate_add +########################################################## +@triton.jit +def range_mod_kernel_fwd( + X, # pointer to the input + MAP, # map x index to gating index + GATINGS, # pointer to the gatings + Y, # pointer to the output + M, # number of rows in X, unused + N, # number of columns in X + stride_xm, # how much to increase the pointer when moving by 1 row in X + stride_xn, # how much to increase the pointer when moving by 1 column in X + stride_gm, # how much to increase the pointer when moving by 1 row in GATINGS + stride_gn, # how much to increase the pointer when moving by 1 column in GATINGS + stride_ym, # how much to increase the pointer when moving by 1 row in Y + stride_yn, # how much to increase the pointer when moving by 1 column in Y + BLOCK_SIZE: tl.constexpr, # number of columns in a block +): + # Map the program id to the row of X and Y it should compute. + row = tl.program_id(0) + + cur_X = X + row * stride_xm + x_cols = tl.arange(0, BLOCK_SIZE) * stride_xn + x_mask = x_cols < N * stride_xn + x = tl.load(cur_X + x_cols, mask=x_mask, other=0.0) + + cur_MAP = MAP + row + gating_index = tl.load(cur_MAP) + cur_GATING = GATINGS + gating_index * stride_gm + gating_cols = tl.arange(0, BLOCK_SIZE) * stride_gn + gating_mask = gating_cols < N * stride_gn + gating = tl.load(cur_GATING + gating_cols, mask=gating_mask, other=0.0) + + cur_Y = Y + row * stride_ym + y_cols = tl.arange(0, BLOCK_SIZE) * stride_yn + y_mask = y_cols < N * stride_yn + tl.store(cur_Y + y_cols, x * gating, mask=y_mask) + + +def range_mod_triton(x, c_mapping, gatings): + """ + Inputs: + x: (s, b, h). Tensor of inputs embedding (images or latent representations of images) + c_mapping: (s, b). Tensor of condition map + gatings: (b, denoising_range_num, h). Tensor of condition embedding + """ + + assert x.is_cuda, "x is not on cuda" + assert c_mapping.is_cuda, "c_mapping is not on cuda" + assert gatings.is_cuda, "gatings is not on cuda" + + # TODO: use 3D tensor for x, c_mapping, and gatings + s, b, h = x.shape + x = x.transpose(0, 1).flatten(0, 1) + c_mapping = c_mapping.transpose(0, 1).flatten(0, 1) + gatings = gatings.flatten(0, 1) + + assert x.dim() == 2, f"x must be a 2D tensor but got {x.dim()}D" + assert c_mapping.dim() == 1, f"c_mapping must be a 1D tensor but got {c_mapping.dim()}D" + assert gatings.dim() == 2, f"gatings must be a 2D tensor but got {gatings.dim()}D" + + M, N = x.shape + if c_mapping.size(0) != M: + import pdb; pdb.set_trace() # noqa: T201 + assert c_mapping.size(0) == M, "c_mapping must have the same number of rows as x" + + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + if N > BLOCK_SIZE: + raise RuntimeError("range_mod_triton doesn't support feature dim >= 64KB.") + + MAP = c_mapping + y = torch.empty_like(x) + + range_mod_kernel_fwd[(M,)]( + x, + MAP, + gatings, + y, + M, + N, + x.stride(0), + x.stride(1), + gatings.stride(0), + gatings.stride(1), + y.stride(0), + y.stride(1), + BLOCK_SIZE=BLOCK_SIZE, + ) + y = y.reshape(b, s, h).transpose(0, 1) + + return y + + +def bias_modulate_add( + x: torch.Tensor, residual: torch.Tensor, condition_map: torch.Tensor, gate: torch.Tensor, post_norm: torch.nn.Module +): + assert gate.shape[-1] == x.shape[-1] + + original_dtype = x.dtype + x = x.float() + residual = residual.float() + gate = gate.float() + + try: + x = range_mod_triton(x, condition_map, gate) + except RuntimeError as e: + print(f"RuntimeError in range_mod_triton: {e}") + import pdb;pdb.set_trace() + + x = post_norm(x) + x = x + residual + x = x.to(original_dtype) + + return x + + +########################################################## +# FusedLayerNorm +########################################################## +def make_viewless_tensor(inp, requires_grad): + # return tensor as-is, if not a 'view' + if inp._base is None: + return inp + + out = torch.empty((1,), dtype=inp.dtype, device=inp.device, requires_grad=requires_grad) + out.data = inp.data + return out + + +class FusedLayerNorm(torch.nn.Module): + + """ + Layer Norm, fused into a single CUDA kernel. + Borrow from: https://github.com/NVIDIA/Megatron-LM/blob/6501752396e9cc360ce894cda4b2217a58c1c09d/megatron/core/fusions/fused_layer_norm.py#L30 + + Args: + hidden_size (int): Transformer hidden dimension. + + eps (float): Epsilon added to denominator, for numerical stability. + + zero_centered_gamma (bool): Adjust LayerNorm weights such that they are + centered around zero. This improves numerical stability. + + model_config (ModelConfig): Transformer config. Include to match custom + layer norm interfaces. + + normalization (str): Normalization type, used for Transformer Engine. + Must equal 'LayerNorm' here. + """ + + def __init__(self, model_config: ModelConfig, hidden_size: int): + super().__init__() + + self.zero_centered_gamma = model_config.apply_layernorm_1p + if isinstance(hidden_size, numbers.Integral): + hidden_size = (hidden_size,) + self.hidden_size = torch.Size(hidden_size) + self.eps = model_config.layernorm_epsilon + self.weight = Parameter(torch.empty(*hidden_size, dtype=model_config.params_dtype)) + self.bias = Parameter(torch.empty(*hidden_size, dtype=model_config.params_dtype)) + + def forward(self, input: Tensor) -> Tensor: + weight = self.weight + 1 if self.zero_centered_gamma else self.weight + return torch.nn.functional.layer_norm(input, self.hidden_size, weight, self.bias, self.eps) + + +def softcap(x: torch.Tensor, cap: int): + return (cap * torch.tanh(x.float() / cap)).to(x.dtype) + + +def div_clamp_to(x: torch.Tensor, scale: torch.Tensor): + fp8_min = torch.finfo(torch.float8_e4m3fn).min + fp8_max = torch.finfo(torch.float8_e4m3fn).max + prefix_shape = x.shape[:-1] + last_shape = x.shape[-1] + x = x.flatten().reshape(-1, last_shape) + # Split x into 256 MB parts to avoid big memory peak + part_size = 256 * 1024 * 1024 // last_shape + part_num = (x.shape[0] + part_size - 1) // part_size + return ( + torch.cat( + [ + torch.clamp(x[i * part_size : (i + 1) * part_size].float() / scale.float(), fp8_min, fp8_max).bfloat16() + for i in range(part_num) + ], + dim=0, + ) + .to(torch.float8_e4m3fn) + .reshape(*prefix_shape, last_shape) + .contiguous() + ) + + +########################################################## +# CustomLayerNormLinear +########################################################## +class CustomLayerNormLinear(torch.nn.Module): + def __init__( + self, + input_size: int, + output_size_q: int, + output_size_kv: int, + layer_number: int, + model_config: ModelConfig, + engine_config: EngineConfig, + ): + super().__init__() + self.layer_norm = torch.nn.LayerNorm(input_size, eps=model_config.layernorm_epsilon, dtype=model_config.params_dtype) + + self.layer_number = layer_number + layers = {"q": output_size_q, "qx": output_size_q, "k": output_size_kv, "v": output_size_kv} + + for name, output_size in layers.items(): + if not engine_config.fp8_quant or self.layer_number == 0 or self.layer_number == model_config.num_layers - 1: + setattr(self, name, torch.nn.Linear(input_size, output_size, bias=False, dtype=model_config.params_dtype)) + else: + setattr(self, name, PerTensorQuantizedFp8Linear(input_size, output_size)) + + def forward_ln(self, hidden_states): + return self.layer_norm(hidden_states) + + def forward_q(self, hidden_states): + return self.q(hidden_states) + + def forward_qx(self, hidden_states): + return self.qx(hidden_states) + + def forward_k(self, hidden_states): + return self.k(hidden_states) + + def forward_v(self, hidden_states): + return self.v(hidden_states) + + +########################################################## +# PerTensorQuantizedFp8Linear +########################################################## +class PerTensorQuantizedFp8Linear(torch.nn.Module): + # The bias and device parameter is not used; it is included for compatibility with Linear's parameters. + def __init__(self, in_features: int, out_features: int, bias=False, dtype=torch.bfloat16, device=None) -> None: + super().__init__() + + self.in_features = in_features + self.out_features = out_features + self.finfo = torch.finfo(torch.float8_e4m3fn) + self.output_dtype = dtype + + self.weight = Parameter(torch.empty((1, out_features, in_features), dtype=torch.float8_e4m3fn)) + self.weight_scale = Parameter(torch.empty(1, dtype=torch.float32)) + self.input_scale = Parameter(torch.empty(in_features, dtype=torch.float32)) + + def forward(self, input: torch.Tensor): + input = div_clamp_to(input, self.input_scale) + + prefix_shape = input.shape[:-1] + # column major weight + return bmm_fp8( + input.reshape(1, -1, self.in_features), + self.weight.transpose(-2, -1), + self.input_scale, + self.weight_scale, + dtype=self.output_dtype, + ).reshape(prefix_shape + (self.out_features,)) + + +########################################################## +# PerChannelQuantizedFp8Linear +########################################################## +class PerChannelQuantizedFp8Linear(torch.nn.Module): + # The bias and device parameter is not used; it is included for compatibility with Linear's parameters. + def __init__(self, in_features: int, out_features: int, bias=False, dtype=torch.bfloat16, device=None) -> None: + super().__init__() + + self.in_features = in_features + self.out_features = out_features + self.output_dtype = dtype + self.finfo = torch.finfo(torch.float8_e4m3fn) + + self.weight = Parameter(torch.empty((1, out_features, in_features), dtype=torch.float8_e4m3fn)) + self.weight_scale = Parameter(torch.empty(1, dtype=torch.float32)) + self.input_scale = Parameter(torch.empty(1, dtype=torch.float32)) + self.smooth_scale = Parameter(torch.empty(1, in_features, dtype=torch.float32)) + + def forward(self, x): + x = div_clamp_to(x, self.smooth_scale.to(torch.float32)) + + prefix_shape = x.shape[:-1] + return bmm_fp8( + x.reshape(1, -1, self.in_features), + self.weight.transpose(-2, -1), + self.input_scale, + self.weight_scale, + dtype=self.output_dtype, + ).reshape(prefix_shape + (self.out_features,)) + + +########################################################## +# CustomMLP +########################################################## +class CustomMLP(torch.nn.Module): + """ + CustomMLP will take the input with h hidden state, project it to 4*h + hidden dimension, perform nonlinear transformation, and project the + state back into h hidden dimension. + + + Returns an output and a bias to be added to the output. + + We use the following notation: + h: hidden size + p: number of tensor model parallel partitions + b: batch size + s: sequence length + """ + + def __init__(self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int, input_size: int = None): + super().__init__() + + self.model_config: ModelConfig = model_config + self.engine_config: EngineConfig = engine_config + self.layer_number = layer_number + + self.input_size = input_size if input_size != None else self.model_config.hidden_size + self.layer_norm = torch.nn.LayerNorm( + self.input_size, eps=self.model_config.layernorm_epsilon, dtype=self.model_config.params_dtype + ) + + submodules_linear_fc1 = torch.nn.Linear + if self.engine_config.fp8_quant and self.layer_number != 0 and self.layer_number != model_config.num_layers - 1: + submodules_linear_fc1 = PerTensorQuantizedFp8Linear + + if self.model_config.gated_linear_unit: + self.linear_fc1 = submodules_linear_fc1( + self.input_size, 2 * self.model_config.ffn_hidden_size, bias=False, dtype=self.model_config.params_dtype + ) + else: + self.linear_fc1 = submodules_linear_fc1( + self.input_size, self.model_config.ffn_hidden_size, bias=False, dtype=self.model_config.params_dtype + ) + + submodules_linear_fc2 = torch.nn.Linear + if engine_config.fp8_quant and self.layer_number != 0 and self.layer_number != model_config.num_layers - 1: + submodules_linear_fc2 = PerChannelQuantizedFp8Linear + + self.linear_fc2 = submodules_linear_fc2( + self.model_config.ffn_hidden_size, self.model_config.hidden_size, bias=False, dtype=self.model_config.params_dtype + ) + + def forward(self, hidden_states): + hidden_states = self.layer_norm(hidden_states) + hidden_states = self.linear_fc1(hidden_states) + if self.model_config.gated_linear_unit: + hidden_states = flashinfer.activation.silu_and_mul(hidden_states) + else: + hidden_states = torch.nn.functional.gelu(hidden_states) + hidden_states = self.linear_fc2(hidden_states) + + return hidden_states + + +########################################################## +# LearnableRotaryEmbeddingCat +########################################################## +def ndgrid(*tensors) -> Tuple[torch.Tensor, ...]: + """generate N-D grid in dimension order. + + The ndgrid function is like meshgrid except that the order of the first two input arguments are switched. + + That is, the statement + [X1,X2,X3] = ndgrid(x1,x2,x3) + + produces the same result as + + [X2,X1,X3] = meshgrid(x2,x1,x3) + + This naming is based on MATLAB, the purpose is to avoid confusion due to torch's change to make + torch.meshgrid behaviour move from matching ndgrid ('ij') indexing to numpy meshgrid defaults of ('xy'). + + """ + try: + return torch.meshgrid(*tensors, indexing="ij") + except TypeError: + # old PyTorch < 1.10 will follow this path as it does not have indexing arg, + # the old behaviour of meshgrid was 'ij' + return torch.meshgrid(*tensors) + + +def pixel_freq_bands( + num_bands: int, max_freq: float = 224.0, linear_bands: bool = True, device: Optional[torch.device] = None +): + if linear_bands: + bands = torch.linspace(1.0, max_freq / 2, num_bands, dtype=torch.float32, device=device) + else: + bands = 2 ** torch.linspace(0, math.log(max_freq, 2) - 1, num_bands, dtype=torch.float32, device=device) + return bands * torch.pi + + +def freq_bands( + num_bands: int, temperature: float = 10000.0, step: int = 2, device: Optional[torch.device] = None +) -> torch.Tensor: + exp = torch.arange(0, num_bands, step, dtype=torch.int64, device=device).to(torch.float32) / num_bands + bands = 1.0 / (temperature**exp) + return bands + + +def build_fourier_pos_embed( + feat_shape: List[int], + bands: Optional[torch.Tensor] = None, + num_bands: int = 64, + max_res: int = 224, + temperature: float = 10000.0, + linear_bands: bool = False, + include_grid: bool = False, + in_pixels: bool = True, + ref_feat_shape: Optional[List[int]] = None, + dtype: torch.dtype = torch.float32, + device: Optional[torch.device] = None, +) -> List[torch.Tensor]: + """ + + Args: + feat_shape: Feature shape for embedding. + bands: Pre-calculated frequency bands. + num_bands: Number of frequency bands (determines output dim). + max_res: Maximum resolution for pixel based freq. + temperature: Temperature for non-pixel freq. + linear_bands: Linear band spacing for pixel based freq. + include_grid: Include the spatial grid in output. + in_pixels: Output in pixel freq. + ref_feat_shape: Reference feature shape for resize / fine-tune. + dtype: Output dtype. + device: Output device. + + Returns: + + """ + if bands is None: + if in_pixels: + bands = pixel_freq_bands(num_bands, float(max_res), linear_bands=linear_bands, device=device) + else: + bands = freq_bands(num_bands, temperature=temperature, step=1, device=device) + else: + if device is None: + device = bands.device + if dtype is None: + dtype = bands.dtype + + if in_pixels: + t = [torch.linspace(-1.0, 1.0, steps=s, device=device, dtype=torch.float32) for s in feat_shape] + else: + t = [torch.arange(s, device=device, dtype=torch.int64).to(torch.float32) for s in feat_shape] + # align spatial center (H/2,W/2) to (0,0) + t[1] = t[1] - (feat_shape[1] - 1) / 2 + t[2] = t[2] - (feat_shape[2] - 1) / 2 + if ref_feat_shape is not None: + # eva's scheme for resizing rope embeddings (ref shape = pretrain) + # aligning to the endpoint e.g [0,1,2] -> [0, 0.4, 0.8, 1.2, 1.6, 2] + t_rescaled = [] + for x, f, r in zip(t, feat_shape, ref_feat_shape): + # deal with image input + if f == 1: + assert r == 1, "ref_feat_shape must be 1 when feat_shape is 1" + t_rescaled.append(x) + else: + t_rescaled.append(x / (f - 1) * (r - 1)) + t = t_rescaled + + grid = torch.stack(ndgrid(t), dim=-1) + grid = grid.unsqueeze(-1) + pos = grid * bands + + pos_sin, pos_cos = pos.sin().to(dtype=dtype), pos.cos().to(dtype) + out = [grid, pos_sin, pos_cos] if include_grid else [pos_sin, pos_cos] + return out + + +def build_rotary_pos_embed( + feat_shape: List[int], + bands: Optional[torch.Tensor] = None, + dim: int = 64, + max_res: int = 224, + temperature: float = 10000.0, + linear_bands: bool = False, + in_pixels: bool = True, + ref_feat_shape: Optional[List[int]] = None, + dtype: torch.dtype = torch.float32, + device: Optional[torch.device] = None, +): + """ + + Args: + feat_shape: Spatial shape of the target tensor for embedding. + bands: Optional pre-generated frequency bands + dim: Output dimension of embedding tensor. + max_res: Maximum resolution for pixel mode. + temperature: Temperature (inv freq) for non-pixel mode + linear_bands: Linearly (instead of log) spaced bands for pixel mode + in_pixels: Pixel vs language (inv freq) mode. + dtype: Output dtype. + device: Output device. + + Returns: + + """ + sin_emb, cos_emb = build_fourier_pos_embed( + feat_shape, + bands=bands, + num_bands=dim // 8, + max_res=max_res, + temperature=temperature, + linear_bands=linear_bands, + in_pixels=in_pixels, + ref_feat_shape=ref_feat_shape, + device=device, + dtype=dtype, + ) + num_spatial_dim = 1 + # this would be much nicer as a .numel() call to torch.Size(), but torchscript sucks + for x in feat_shape: + num_spatial_dim *= x + + sin_emb = sin_emb.reshape(num_spatial_dim, -1) + cos_emb = cos_emb.reshape(num_spatial_dim, -1) + return sin_emb, cos_emb + + +class LearnableRotaryEmbeddingCat(nn.Module): + """Rotary position embedding w/ concatenatd sin & cos + + The following impl/resources were referenced for this impl: + * https://github.com/lucidrains/vit-pytorch/blob/6f3a5fcf0bca1c5ec33a35ef48d97213709df4ba/vit_pytorch/rvt.py + * https://blog.eleuther.ai/rotary-embeddings/ + """ + + def __init__( + self, + dim, + max_res=224, + temperature=10000, + in_pixels=True, + linear_bands: bool = False, + feat_shape: Optional[List[int]] = None, + ref_feat_shape: Optional[List[int]] = None, + ): + super().__init__() + self.dim = dim + self.max_res = max_res + self.temperature = temperature + self.in_pixels = in_pixels + self.linear_bands = linear_bands + self.feat_shape = feat_shape + self.ref_feat_shape = ref_feat_shape + self.bands = nn.Parameter(self.get_default_bands()) + + def get_default_bands(self): + if self.in_pixels: + bands = pixel_freq_bands( + self.dim // 8, float(self.max_res), linear_bands=self.linear_bands, devicse=torch.cuda.current_device() + ) + else: + bands = freq_bands(self.dim // 8, temperature=self.temperature, step=1, device=torch.cuda.current_device()) + return bands + + def get_embed(self, shape: Optional[List[int]], ref_feat_shape: Optional[List[int]] = None): + # rebuild bands and embeddings every call, use if target shape changes + embeds = build_rotary_pos_embed( + feat_shape=shape, + bands=self.bands, # use learned bands + dim=self.dim, + max_res=self.max_res, + linear_bands=self.linear_bands, + in_pixels=self.in_pixels, + ref_feat_shape=ref_feat_shape if ref_feat_shape else self.ref_feat_shape, + temperature=self.temperature, + device=torch.cuda.current_device(), + ) + return torch.cat(embeds, -1) + + +########################################################## +# Attention +########################################################## +class Attention(torch.nn.Module): + """ + Attention layer abstract class. + """ + + def __init__(self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int): + super().__init__() + + self.model_config: ModelConfig = model_config + self.engine_config: EngineConfig = engine_config + self.layer_number = layer_number + + self.hidden_size_per_attention_head = self.model_config.kv_channels + # num_query_groups and num_attention_heads are different for GQA + self.query_projection_size = self.model_config.kv_channels * self.model_config.num_attention_heads + self.kv_projection_size = self.model_config.kv_channels * self.model_config.num_query_groups + + # Per attention head and per partition values. + world_size = parallel_state.get_tp_world_size(with_context_parallel=True) + if world_size > self.model_config.num_query_groups and world_size % self.model_config.num_query_groups == 0: + self.num_query_groups_per_partition = 1 + else: + self.num_query_groups_per_partition = divide(self.model_config.num_query_groups, world_size) + + def _allocate_key_and_value_memory(self, sequence_length, batch_size, dtype): + """Allocate memory to store kv cache during inference.""" + + if self.engine_config.kv_offload: + return torch.empty( + sequence_length * batch_size, + self.num_query_groups_per_partition, + self.hidden_size_per_attention_head * 2, + dtype=dtype, + device=torch.cpu.current_device(), + pin_memory=True, + ) + else: + return torch.empty( + sequence_length * batch_size, + self.num_query_groups_per_partition, + self.hidden_size_per_attention_head * 2, + dtype=dtype, + device=torch.cuda.current_device(), + ) + + +########################################################## +# FullyParallelAttention +########################################################## +def split_tensor_along_last_dim( + tensor: torch.Tensor, num_partitions: int, contiguous_split_chunks: bool = False +) -> List[torch.Tensor]: + """Split a tensor along its last dimension. + + Args: + tensor: input tensor. + num_partitions: number of partitions to split the tensor + contiguous_split_chunks: If True, make each chunk contiguous + in memory. + + Returns: + A list of Tensors + """ + # Get the size and dimension. + last_dim = tensor.dim() - 1 + last_dim_size = divide(tensor.size()[last_dim], num_partitions) + # Split. + tensor_list = torch.split(tensor, last_dim_size, dim=last_dim) + # Note: torch.split does not create contiguous tensors by default. + if contiguous_split_chunks: + return tuple(chunk.contiguous() for chunk in tensor_list) + + return tensor_list + + +class FullyParallelAttention(Attention): + def __init__(self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int): + super().__init__(model_config=model_config, engine_config=engine_config, layer_number=layer_number) + + # output 2x query, one for self-attn, one for cross-attn with condition + self.linear_qkv = CustomLayerNormLinear( + input_size=self.model_config.hidden_size, + output_size_q=self.query_projection_size, + output_size_kv=self.kv_projection_size, + layer_number=self.layer_number, + model_config=self.model_config, + engine_config=self.engine_config, + ) + + # kv from condition, e.g., caption + self.linear_kv_xattn = torch.nn.Linear( + int(self.model_config.hidden_size * self.model_config.xattn_cond_hidden_ratio), # 6144 + 2 * self.kv_projection_size, # 2048 + dtype=self.model_config.params_dtype, + bias=False, + ) + + # Output. + self.adapt_linear_quant = ( + self.engine_config.fp8_quant and self.layer_number != 0 and self.layer_number != model_config.num_layers - 1 + ) + submodules_linear_proj = PerChannelQuantizedFp8Linear if self.adapt_linear_quant else torch.nn.Linear + self.linear_proj = submodules_linear_proj( + 2 * self.query_projection_size, self.model_config.hidden_size, dtype=self.model_config.params_dtype, bias=False + ) + + self.q_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head) + self.q_layernorm_xattn = FusedLayerNorm( + model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head + ) + self.k_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head) + self.k_layernorm_xattn = FusedLayerNorm( + model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head + ) + + self.attn_weights_history = [] + + def _full_adjust_key_and_value( + self, inference_params: InferenceParams, key_and_value: torch.Tensor, meta_args: ModelMetaArgs + ): + """ + Saves the generated key and value tensors to the end of the buffers in inference_params. + Returns the full size keys and values from the provided inference_params + + Returns a tuple: (key, value) + """ + # ================================================= + # Pre-allocate memory for key-values for inference. + # ================================================= + inf_max_seq_length = inference_params.max_sequence_length + inf_max_batch_size = inference_params.max_batch_size + + if self.layer_number not in inference_params.key_value_memory_dict: + inference_key_and_value_memory = self._allocate_key_and_value_memory( + inf_max_seq_length, inf_max_batch_size, key_and_value.dtype + ) + inference_params.key_value_memory_dict[self.layer_number] = inference_key_and_value_memory + else: + # Get the pre-allocated buffers for this layer + inference_key_and_value_memory = inference_params.key_value_memory_dict[self.layer_number] + + sequence_start = meta_args.slice_point * meta_args.clip_token_nums * inf_max_batch_size + # Only take clean kv cache here, but for partial reuse, the kv of the currently denoising chunk is not passed to forward, so this part of kv is also needed + get_key_and_value = inference_key_and_value_memory[:sequence_start, ...].cuda() + + # Copy key and values. + if inference_params.update_kv_cache: + key_and_value_total = key_and_value + + clip_size = ( + key_and_value_total.size(0) - meta_args.clip_token_nums * inf_max_batch_size + if meta_args.distill_nearly_clean_chunk + else key_and_value_total.size(0) + ) + sequence_end = sequence_start + clip_size + assert sequence_end <= inference_key_and_value_memory.size(0) + # update kv cache + inference_key_and_value_memory[sequence_start:sequence_end, ...] = key_and_value_total[:clip_size] + + return torch.cat([get_key_and_value, key_and_value], dim=0) + + def _custom_adjust_key_and_value( + self, inference_params: InferenceParams, key_and_value: torch.Tensor, meta_args: ModelMetaArgs + ): + """ + Saves the generated key and value tensors to the end of the buffers in inference_params. + Returns the full size keys and values from the provided inference_params + + Returns a tuple: (key, value) + """ + # ================================================= + # Pre-allocate memory for key-values for inference. + # ================================================= + + # 1. The principle is to update the kv cache for whichever chunk is passed in + inf_max_seq_length = inference_params.max_sequence_length + inf_max_batch_size = inference_params.max_batch_size + + if self.layer_number not in inference_params.key_value_memory_dict: + inference_key_and_value_memory = self._allocate_key_and_value_memory( + inf_max_seq_length, inf_max_batch_size, key_and_value.dtype + ) + inference_params.key_value_memory_dict[self.layer_number] = inference_key_and_value_memory + else: + # Get the pre-allocated buffers for this layer + inference_key_and_value_memory = inference_params.key_value_memory_dict[self.layer_number] + + chunk_start = meta_args.start_chunk_id + chunk_end = meta_args.end_chunk_id + if meta_args.distill_nearly_clean_chunk: + chunk_end -= 1 + + sequence_start = chunk_start * meta_args.clip_token_nums * inf_max_batch_size + sequence_end = chunk_end * meta_args.clip_token_nums * inf_max_batch_size + # 1. Update values in inference_key_and_value_memory + clip_size = ( + key_and_value.size(0) - meta_args.clip_token_nums * inf_max_batch_size + if meta_args.distill_nearly_clean_chunk + else key_and_value.size(0) + ) + try: + inference_key_and_value_memory[sequence_start:sequence_end, ...] = key_and_value[:clip_size] + except Exception as e: + print(f"Error updating inference key and value memory: {e}") + import pdb; pdb.set_trace() + + # 2. Concatenate kv values from previous chunks + key_and_value_total = key_and_value + past_chunk_kv = inference_key_and_value_memory[:sequence_start, ...].cuda() + key_and_value_total = torch.cat([past_chunk_kv, key_and_value], dim=0) + + return key_and_value_total + + def _compresskv_adjust_key_and_value( + self, inference_params: InferenceParams, key_and_value: torch.Tensor, meta_args: ModelMetaArgs + ): + inf_max_seq_length = inference_params.max_sequence_length + inf_max_batch_size = inference_params.max_batch_size + + if self.layer_number not in inference_params.key_value_memory_dict: + inference_key_and_value_memory = self._allocate_key_and_value_memory( + meta_args.total_cache_len, inf_max_batch_size, key_and_value.dtype + ) + inference_params.key_value_memory_dict[self.layer_number] = inference_key_and_value_memory + else: + inference_key_and_value_memory = inference_params.key_value_memory_dict[self.layer_number] + + tracker = inference_params.kv_chunk_tracker + + # Calculate the chunk range being processed + chunk_start = meta_args.start_chunk_id + chunk_end = meta_args.end_chunk_id + if meta_args.distill_nearly_clean_chunk: + chunk_end -= 1 + + current_chunk_ids = list(range(chunk_start, chunk_end)) # e.g., [3, 4, 5] + + if len(current_chunk_ids) > 0: + # Allocate kv cache ranges, skip if already allocated + tracker.register_chunks(current_chunk_ids) + + # === Split key_and_value by chunk === + tokens_per_chunk = meta_args.clip_token_nums + # Split tensor: one segment per chunk + chunk_tensors = [] + start_idx = 0 + for i, cid in enumerate(current_chunk_ids): + chunk_len = tokens_per_chunk + end_idx = start_idx + chunk_len + chunk_tensors.append(key_and_value[start_idx:end_idx, ...]) + start_idx = end_idx + + # === Write each chunk to its allocated position === + for cid, chunk_kv in zip(current_chunk_ids, chunk_tensors): + s, e = tracker.get_range(cid) + target_length = e - s + assert chunk_kv.size(0) == target_length, f"Chunk size mismatch: chunk {cid}, expected {target_length}, got {chunk_kv.size(0)}" + + inference_key_and_value_memory[s : s + chunk_kv.size(0), ...] = chunk_kv + + + # === Concatenate past KV === + past_ranges = tracker.get_all_ranges_previous(current_chunk_ids) + past_chunks = [] + for s, e in past_ranges: + past_chunks.append(inference_key_and_value_memory[s:e, ...].cuda()) + + if past_chunks: + past_kv = torch.cat(past_chunks, dim=0) + key_and_value_total = torch.cat([past_kv, key_and_value], dim=0) + else: + key_and_value_total = key_and_value.cuda() + + return key_and_value_total + + def adjust_key_and_value_for_inference( + self, key_and_value: torch.Tensor, inference_params: InferenceParams, meta_args: ModelMetaArgs + ): + if inference_params is None: + return torch.chunk(key_and_value, 2, dim=-1) + + # Only update kvcache when necessary, include 3 conditions: + # 1. extract prefix video clean feature + # 2. the first chunk of current kv is clean, we need to save their feature + # 3. previous chunk is clean and we need to save/load their feature + + # Priority: compress_kv > save_kvcache_every_forward > full_adjust + if meta_args.compress_kv: + key_and_value = self._compresskv_adjust_key_and_value(inference_params, key_and_value, meta_args) + elif meta_args.save_kvcache_every_forward: + key_and_value = self._custom_adjust_key_and_value(inference_params, key_and_value, meta_args) + elif (meta_args.extract_prefix_video_feature or meta_args.fwd_extra_1st_chunk or meta_args.slice_point > 0) and \ + not meta_args.save_kvcache_every_forward: + key_and_value = self._full_adjust_key_and_value(inference_params, key_and_value, meta_args) + key, value = torch.chunk(key_and_value, 2, dim=-1) + return key.contiguous(), value.contiguous() + + # ===================== + # Get Query for core attn + # [sq, b, (hn hd)] -> [(sq b), hn, hd] + # ===================== + + def get_q(self, mixed_qqkv: torch.Tensor, cos_emb: torch.Tensor, sin_emb: torch.Tensor): + query = self.linear_qkv.forward_q(mixed_qqkv) + query = query.reshape(query.size(0), query.size(1), -1, self.hidden_size_per_attention_head) + assert self.q_layernorm is not None + original_dtype = query.dtype + query = query.float() + query = self.q_layernorm(query) + query = query.transpose(0, 1).contiguous() + query = flash_apply_rotary_emb(query, cos_emb, sin_emb) + query = query.to(original_dtype) + return rearrange(query, "b sq hn hd -> (sq b) hn hd").contiguous() + + # ===================== + # Get Key for core attn + # [sq, b, (hn hd)] -> [(sq b), hn, hd] + # ===================== + + def get_k(self, mixed_qqkv: torch.Tensor, cos_emb: torch.Tensor, sin_emb: torch.Tensor): + key = self.linear_qkv.forward_k(mixed_qqkv) + key = key.reshape(key.size(0), key.size(1), -1, self.hidden_size_per_attention_head) + assert self.k_layernorm is not None + original_dtype = key.dtype + key = key.float() + key = self.k_layernorm(key) + key = key.transpose(0, 1).contiguous() + key = flash_apply_rotary_emb(key, cos_emb, sin_emb) + key = key.to(original_dtype) + return rearrange(key, "b sq hn hd -> (sq b) hn hd").contiguous() + + # ===================== + # Get Value for core attn + # [sq, b, (hn hd)] -> [(sq b), hn, hd] + # ===================== + + def get_v(self, mixed_qqkv: torch.Tensor): + value = self.linear_qkv.forward_v(mixed_qqkv) + return rearrange(value, "sq b (hn hd) -> (sq b) hn hd", hd=self.hidden_size_per_attention_head).contiguous() + + def get_kv(self, mixed_qqkv: torch.Tensor, cos_emb: torch.Tensor, sin_emb: torch.Tensor): + # Get KV together for better performance when encoutering cpu-bound, mainly used by cuda graph + key = self.get_k(mixed_qqkv, cos_emb, sin_emb) + value = self.get_v(mixed_qqkv) + # [(sq b), hn, hd] -> [(sq b), hn, 2 * hd] + return torch.cat([key, value], dim=-1) + + def get_qkv(self, mixed_qqkv: torch.Tensor, cos_emb: torch.Tensor, sin_emb: torch.Tensor): + # Get QKV together for better performance when encoutering cpu-bound, mainly used by cuda graph + q = self.get_q(mixed_qqkv, cos_emb, sin_emb) + k = self.get_k(mixed_qqkv, cos_emb, sin_emb) + v = self.get_v(mixed_qqkv) + return q, k, v + + def get_xqkv(self, mixed_qqkv: torch.Tensor, key_value_states: torch.Tensor): + query_xattn = self.linear_qkv.forward_qx(mixed_qqkv) + query_xattn = rearrange(query_xattn, "sq b (hn hd) -> (b sq) hn hd", hd=self.hidden_size_per_attention_head) + query_xattn = self.q_layernorm_xattn(query_xattn) + + # [y_total_token, h] --> [y_total_token, 2*hp] + mixed_kv_xattn = torch.concat( + [torch.matmul(key_value_states, w.t()) for w in torch.chunk(self.linear_kv_xattn.weight, 8, axis=0)], axis=1 + ) + # [y_total_token, 2*hn*hd] --> [y_total_token, hn, 2*hd] + mixed_kv_xattn = mixed_kv_xattn.view(key_value_states.shape[0], -1, 2 * self.hidden_size_per_attention_head) + + # [y_total_token, hn, 2*hd] --> 2 [y_total_token, hn, hd] + (key_xattn, value_xattn) = split_tensor_along_last_dim(mixed_kv_xattn, 2) + + key_xattn = self.k_layernorm_xattn(key_xattn) + return query_xattn, key_xattn, value_xattn + + + def core_attention(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, bs: int, meta_args: ModelMetaArgs): + + # (sq b) hn hd -> b sq hn hd + query = query.reshape(-1, bs, query.shape[1], query.shape[2]).transpose(0, 1).contiguous() + # (sq b) hn hd -> b sq hn hd + key = key.reshape(-1, bs, key.shape[1], key.shape[2]).transpose(0, 1).contiguous() + # (sq b) hn hd -> b sq hn hd + value = value.reshape(-1, bs, value.shape[1], value.shape[2]).transpose(0, 1).contiguous() + + if torch.cuda.get_device_capability()[0] >= 9 and flex_attention is not None: + core_attn_out, _ = flex_attention( + query.flatten(0, 1), + key.flatten(0, 1), + value.flatten(0, 1), + meta_args.core_attn_params.q_range, + meta_args.core_attn_params.k_range, + max_seqlen_q=meta_args.core_attn_params.max_seqlen_q, + max_seqlen_k=meta_args.core_attn_params.max_seqlen_k, + softmax_scale=None, + deterministic=torch.are_deterministic_algorithms_enabled(), + disable_fwd_atomic_reduction=True, + ) + # (b sq) hn hd -> (sq b) hn hd + core_attn_out = rearrange(core_attn_out, "(b sq) h d -> (sq b) h d", b=bs) + else: + # NOTE(lml): We convert multi denoising_range_num input into multi batch_size input at third time forward under 3_cfg mode, thus could not support normal multi batch_size input. We use an assert statement to ensure that it is still in this situation, thereby guaranteeing the correct use of q_range and k_range later on. + assert not (bs > 1 and meta_args.denoising_range_num > 1) + q_range = meta_args.core_attn_params.np_q_range + k_range = meta_args.core_attn_params.np_k_range + core_attn_outs = [] + q_seqlen = query.shape[1] + + try: + # Adapt to flowcache case where only a single chunk is passed + if q_seqlen == meta_args.clip_token_nums: + q = query + i = meta_args.start_chunk_id - meta_args.slice_point + k = key[:, k_range[i, 0] : k_range[i, 1]] + v = value[:, k_range[i, 0] : k_range[i, 1]] + o = flash_attn_func(q=q, k=k, v=v, deterministic=torch.are_deterministic_algorithms_enabled()) + o = rearrange(o, "b sq h d -> (sq b) h d", b=bs) + core_attn_outs.append(o) + # Original + else: + for i in range(meta_args.denoising_range_num): # chunk_end - chunk_start + if bs == 1: + q = query[:, q_range[i, 0] : q_range[i, 1]] + k = key[:, k_range[i, 0] : k_range[i, 1]] + v = value[:, k_range[i, 0] : k_range[i, 1]] + else: + assert i == 0 + q = query[:, q_range[0, 0] : q_range[0, 1]] + k = key[:, k_range[0, 0] : k_range[0, 1]] + v = value[:, k_range[0, 0] : k_range[0, 1]] + + o = flash_attn_func(q=q, k=k, v=v, deterministic=torch.are_deterministic_algorithms_enabled()) + o = rearrange(o, "b sq h d -> (sq b) h d", b=bs) + core_attn_outs.append(o) + except RuntimeError as e: + print(f"RuntimeError in core_attention: {e}") + import pdb; pdb.set_trace() + + core_attn_out = torch.cat(core_attn_outs, dim=0) + return core_attn_out + + def full_attention(self, bs: int, meta_args: ModelMetaArgs, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, i: int): + # NOTE(lml): full_attention is used under cp_shuffle_overlap strategy. We further limit it to the case of bs=1, so that we do not need to pay attention to the arrangement of sq and bs dimensions. + assert bs == 1 + if torch.cuda.get_device_capability()[0] >= 9 and flex_attention is not None: + q_range = meta_args.core_attn_params.q_range[i : i + 1] - meta_args.core_attn_params.q_range[i, 0] + k_range = meta_args.core_attn_params.k_range[i : i + 1] + o, _ = flex_attention( + q, + k, + v, + q_ranges=q_range, + k_ranges=k_range, + max_seqlen_q=meta_args.core_attn_params.max_seqlen_q, + max_seqlen_k=meta_args.core_attn_params.max_seqlen_k, + softmax_scale=None, + deterministic=torch.are_deterministic_algorithms_enabled(), + disable_fwd_atomic_reduction=True, + ) + else: + k_range = meta_args.core_attn_params.np_k_range[i : i + 1] + k = k[k_range[0, 0] : k_range[0, 1]] + v = v[k_range[0, 0] : k_range[0, 1]] + o = flash_attn_func( + q=q.unsqueeze(0), + k=k.unsqueeze(0), + v=v.unsqueeze(0), + deterministic=torch.are_deterministic_algorithms_enabled(), + ).flatten(0, 1) + return o + + def cross_attention( + self, + mixed_qqkv: torch.Tensor, + key_value_states: torch.Tensor, + cross_attn_params: PackedCrossAttnParams, + get_xqkv_func: Callable, + ): + # ================= + # cross-attn for aggragating caption / condition + # ================= + query_xattn, key_xattn, value_xattn = get_xqkv_func(mixed_qqkv, key_value_states) + + if torch.cuda.get_device_capability()[0] >= 9 and flex_attention is not None: + xattn_out, _ = flex_attention( + query_xattn, + key_xattn, + value_xattn, + cross_attn_params.q_ranges, + cross_attn_params.kv_ranges, + max_seqlen_q=cross_attn_params.max_seqlen_q, + max_seqlen_k=cross_attn_params.max_seqlen_kv, + softmax_scale=None, + deterministic=False, + disable_fwd_atomic_reduction=True, + ) + else: + xattn_out = flash_attn_varlen_func( + query_xattn, # [b*sq, hn, hd] + key_xattn, # [y_total_token, hn, hd] + value_xattn, # [y_total_token, hn, hd] + cu_seqlens_q=cross_attn_params.cu_seqlens_q, + cu_seqlens_k=cross_attn_params.cu_seqlens_kv, + max_seqlen_q=cross_attn_params.max_seqlen_q, + max_seqlen_k=cross_attn_params.max_seqlen_kv, + deterministic=torch.are_deterministic_algorithms_enabled(), + ) + + batch_size = mixed_qqkv.shape[1] + xattn_out = rearrange(xattn_out, "(b sq) hn hd -> sq b (hn hd)", b=batch_size).contiguous() + return xattn_out + + def forward( + self, + hidden_states: torch.Tensor, + key_value_states: torch.Tensor, + inference_params: InferenceParams, + rotary_pos_emb: torch.Tensor, + meta_args: ModelMetaArgs, + ): + assert rotary_pos_emb is not None, "FullyParallelAttention needs rotary_pos_emb" + sin_emb, cos_emb = rotary_pos_emb.tensor_split(2, -1) + batch_size = hidden_states.shape[1] + # All comminications operate on dimensions shaped as (cp * sq * b) + batch_cp_split_sizes = None if meta_args.cp_split_sizes is None else [x * batch_size for x in meta_args.cp_split_sizes] + + # Attention heads [sq, b, h] --> [sq, b, q + qx + k + v] + mixed_qqkv = self.linear_qkv.forward_ln(hidden_states) + + # ===================== + # Function wrapper + # ===================== + get_kv_func = self.get_kv + get_q_func = self.get_q + get_qkv_func = self.get_qkv + get_xqkv_func = self.get_xqkv + + # ===================== + # Parallel Strategy + # ===================== + if self.engine_config.cp_strategy == "none": + assert self.engine_config.cp_size == 1 + key_and_value = get_kv_func(mixed_qqkv, cos_emb, sin_emb) + query = get_q_func(mixed_qqkv, cos_emb, sin_emb) + + key, value = self.adjust_key_and_value_for_inference(key_and_value, inference_params, meta_args) + + # Save current query for subsequent compression + self._last_query = query.detach().clone() + + core_attn_out = self.core_attention(query, key, value, batch_size, meta_args) + core_attn_out = rearrange(core_attn_out, "(sq b) hn hd -> sq b (hn hd)", b=batch_size) + xattn_out = self.cross_attention(mixed_qqkv, key_value_states, meta_args.cross_attn_params, get_xqkv_func) + + elif self.engine_config.cp_strategy == "cp_ulysses": + get_kv_func = partial(get_kv_func, mixed_qqkv, cos_emb, sin_emb) + get_q_func = partial(get_q_func, mixed_qqkv, cos_emb, sin_emb) + get_qkv_func = partial(get_qkv_func, mixed_qqkv, cos_emb, sin_emb) + kv_cache_func = partial( + self.adjust_key_and_value_for_inference, inference_params=inference_params, meta_args=meta_args + ) + if meta_args.enable_cuda_graph and meta_args.denoising_range_num <= 3: + # Temporal solution for first chunk opt + core_attn_out, xattn_out = UlyssesScheduler.get_attn_and_xattn_with_fused_qkv_comm( + get_qkv_func, + kv_cache_func, + partial(self.core_attention, bs=batch_size, meta_args=meta_args), + partial(self.cross_attention, mixed_qqkv, key_value_states, meta_args.cross_attn_params, get_xqkv_func), + self.engine_config.ulysses_overlap_degree, + batch_size, + self.engine_config.cp_size, + batch_cp_split_sizes, + ) + else: + core_attn_out, xattn_out = UlyssesScheduler.get_attn_and_xattn_with_fused_kv_comm( + get_q_func, + get_kv_func, + kv_cache_func, + partial(self.core_attention, bs=batch_size, meta_args=meta_args), + partial(self.cross_attention, mixed_qqkv, key_value_states, meta_args.cross_attn_params, get_xqkv_func), + self.engine_config.ulysses_overlap_degree, + batch_size, + self.engine_config.cp_size, + batch_cp_split_sizes, + ) + + elif self.engine_config.cp_strategy == "cp_shuffle_overlap": + key_and_value = self.get_kv(mixed_qqkv, cos_emb, sin_emb) + key_and_value, handle_kv = cso_communication(key_and_value, self.engine_config.cp_size, batch_cp_split_sizes, "kv") + + query = get_q_func(mixed_qqkv, cos_emb, sin_emb) + cso_helper = CSOHelper(meta_args.denoising_range_num, self.engine_config.cp_size, batch_cp_split_sizes) + query, handle_q = cso_helper.split_query_for_overlap(query) + + handle_kv.wait() + # NOTE(lml): rearrange and unpad key_and_value for later attention compute under cp_shuffle_overlap strategy, and we should split sqb into sq and b when support multi batch_size input. + key_and_value = ( + rearrange( + key_and_value, + "(cp dn sqb) hn nhd -> dn (cp sqb) hn nhd", + dn=meta_args.denoising_range_num, + cp=self.engine_config.cp_size, + )[:, : meta_args.clip_token_nums] + .flatten(0, 1) + .contiguous() + ) + key, value = self.adjust_key_and_value_for_inference(key_and_value, inference_params, meta_args) + + handle_q.wait() + core_attn_out, handle_attn = cso_helper.overlap( + partial(self.full_attention, hidden_states.shape[1], meta_args), query, key, value + ) + xattn_out = self.cross_attention(mixed_qqkv, key_value_states, meta_args.cross_attn_params, get_xqkv_func) + + handle_attn.wait() + core_attn_out = rearrange( + torch.concat(core_attn_out, dim=0), + "(dn cp sq b) hn hd -> (dn sq) b (cp hn hd)", + cp=self.engine_config.cp_size, + b=hidden_states.shape[1], + dn=meta_args.denoising_range_num, + ) + else: + raise ValueError(f"Unsupported cp_strategy: {self.engine_config.cp_strategy}") + + return core_attn_out, xattn_out + + +########################################################## +# TransformerLayer +########################################################## +class TransformerLayer(torch.nn.Module): + """A single transformer layer. + + Transformer layer takes input with size [s, b, h] and returns an + output of the same size. + """ + + def __init__(self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int = 1): + super().__init__() + self.model_config = model_config + self.engine_config = engine_config + self.layer_number = layer_number + self._get_layer_offset() + ## [Module 1: ada_modulate_layer + self.ada_modulate_layer = AdaModulateLayer(model_config=self.model_config) + + ## [Module 2: SelfAttention] + self.self_attention = FullyParallelAttention( + model_config=self.model_config, engine_config=self.engine_config, layer_number=self.layer_number + ) + + ## [Module 3: SelfAttention PostNorm] + self.self_attn_post_norm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.model_config.hidden_size) + + ## [Module 4: MLP block] + self.mlp = CustomMLP(model_config=self.model_config, engine_config=self.engine_config, layer_number=self.layer_number) + + ## [Module 5: MLP PostNorm] + self.mlp_post_norm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.model_config.hidden_size) + + def _get_layer_offset(self): + pipeline_rank = parallel_state.get_pp_rank() + + num_layers_per_pipeline_rank = self.model_config.num_layers // parallel_state.get_pp_world_size() + + # Each stage gets a contiguous set of layers. + if parallel_state.get_pp_world_size() > 1: + offset = pipeline_rank * num_layers_per_pipeline_rank + else: + offset = 0 + + return offset + + def forward( + self, + hidden_states: torch.Tensor, + condition: torch.Tensor, + condition_map: torch.Tensor, + y_xattn_flat: torch.Tensor, + rotary_pos_emb: torch.Tensor, + inference_params: InferenceParams, + meta_args: ModelMetaArgs, + ): + # hidden_states: [s/cp/sp, b, h] + residual = hidden_states + + # Self attention. + core_attn_out, cross_attn_out = self.self_attention( + hidden_states, + key_value_states=y_xattn_flat, + inference_params=inference_params, + rotary_pos_emb=rotary_pos_emb, + meta_args=meta_args, + ) + hidden_states = self.attn_post_process(core_attn_out, cross_attn_out, residual, condition, condition_map) + + return hidden_states + + def attn_post_process( + self, + core_attn_out: torch.Tensor, + cross_attn_out: torch.Tensor, + residual: torch.Tensor, + condition: torch.Tensor, + condition_map: torch.Tensor, + ): + hidden_states = self.attn_linear_proj(core_attn_out, cross_attn_out) + hidden_states = self.gating_and_mlp(hidden_states, residual, condition, condition_map) + return hidden_states + + def attn_linear_proj(self, core_attn_out: torch.Tensor, cross_attn_out: torch.Tensor): + # ============================================ + # attention post-process , output. [sq, b, h] + # ============================================ + + attn_out = torch.concat([core_attn_out, cross_attn_out], dim=2) + # NOTE: hn=8 is hardcoded to align with TP8 traning and TP1 inference + attn_out = rearrange(attn_out, "sq b (n hn hd) -> sq b (hn n hd)", n=2, hn=8) + if self.self_attention.adapt_linear_quant: + attn_out = self.self_attention.linear_proj(attn_out) + else: + # Use high-precision for non-quantized linear projection + with torch.autocast(device_type="cuda", dtype=torch.float32): + attn_out = self.self_attention.linear_proj(attn_out) + + return attn_out + + def gating_and_mlp( + self, hidden_states: torch.Tensor, residual: torch.Tensor, condition: torch.Tensor, condition_map: torch.Tensor + ): + gate_output = self.ada_modulate_layer(condition) + softcap_gate_cap = 1.0 + gate_output = softcap(gate_output, softcap_gate_cap) + gate_msa, gate_mlp = gate_output.chunk(2, dim=-1) + + # Residual connection for self-attention. + hidden_states = bias_modulate_add(hidden_states, residual, condition_map, gate_msa, self.self_attn_post_norm).to( + self.model_config.params_dtype + ) + + residual = hidden_states + hidden_states = self.mlp(hidden_states) + # Residual connection for MLP. + hidden_states = bias_modulate_add(hidden_states, residual, condition_map, gate_mlp, self.mlp_post_norm).to( + self.model_config.params_dtype + ) + return hidden_states + + +########################################################## +# TransformerBlock +########################################################## +class TransformerBlock(torch.nn.Module): + """Transformer class.""" + + def __init__( + self, model_config: ModelConfig, engine_config: EngineConfig, pre_process: bool = True, post_process: bool = True + ): + super().__init__() + + self.model_config = model_config + self.engine_config = engine_config + self.pre_process = pre_process + self.post_process = post_process + + # required for pipeline parallel schedules + self.input_tensor = None + + layer_number = self.model_config.num_layers // parallel_state.get_pp_world_size() + # offset is implicit in TransformerLayer + self.layers = torch.nn.ModuleList( + [ + TransformerLayer(model_config=self.model_config, engine_config=self.engine_config, layer_number=i) + for i in range(layer_number) + ] + ) + if self.post_process: + # Final layer norm before output. + self.final_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.model_config.hidden_size) + + def set_input_tensor(self, input_tensor: Tensor): + """Set input tensor to be used instead of forward()'s input. + + When doing pipeline parallelism the input from the previous + stage comes from communication, not from the input, so the + model's forward_step_func won't have it. This function is thus + used by internal code to bypass the input provided by the + forward_step_func""" + self.input_tensor = input_tensor + + @torch.no_grad() + def forward( + self, + hidden_states: Tensor, + condition: Tensor, + condition_map: Tensor, + y_xattn_flat: Tensor, + rotary_pos_emb: Tensor, + inference_params: InferenceParams, + meta_args: ModelMetaArgs, + ) -> torch.Tensor: + if not self.pre_process: + assert self.input_tensor is not None, "please call set_input_tensor for pp" + hidden_states = self.input_tensor + + for layer in self.layers: + hidden_states = layer( + hidden_states=hidden_states, + condition=condition, + condition_map=condition_map, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rotary_pos_emb, + inference_params=inference_params, + meta_args=meta_args, + ) + + # Final layer norm. + if self.post_process: + hidden_states = self.final_layernorm(hidden_states.float()) + + return hidden_states \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1b0a916be0148ab30dac23af283700ba551f72ac --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .t5_model import T5Embedder + +__all__ = ["T5Embedder"] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e20a457ac8442cd79dbc9cf29005b756fa92bc74 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/__pycache__/t5_model.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/__pycache__/t5_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b32cd3130fcd59d91ecfc28178db7f60e773d9e2 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/__pycache__/t5_model.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/t5_model.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/t5_model.py new file mode 100644 index 0000000000000000000000000000000000000000..1f3ccbee178b51cd0cfa781d0479ff961e848f41 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/t5/t5_model.py @@ -0,0 +1,286 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import html +import os +import re +import urllib.parse as ul + +import ftfy +import torch +from bs4 import BeautifulSoup +from huggingface_hub import hf_hub_download +from transformers import AutoTokenizer, T5EncoderModel + + +def save_model_as_safetensors(model): + from safetensors.torch import save_file + state_dict = model.state_dict() + for k in state_dict: + state_dict[k] = state_dict[k].contiguous() + + save_file(state_dict, "/path/to/t5/model.safetensors") + +class T5Embedder: + available_models = ["t5-v1_1-xxl"] + bad_punct_regex = re.compile( + r"[" + "#®•©™&@·º½¾¿¡§~" + "\)" + "\(" + "\]" + "\[" + "\}" + "\{" + "\|" + "\\" + "\/" + "\*" + r"]{1,}" + ) # noqa + + def __init__( + self, + device, + dir_or_name="t5-v1_1-xxl", + *, + local_cache=False, + cache_dir=None, + hf_token=None, + use_text_preprocessing=True, + t5_model_kwargs=None, + torch_dtype=None, + use_offload_folder=None, + model_max_length=120, + ): + self.device = torch.device(device) + self.torch_dtype = torch_dtype or torch.bfloat16 + if t5_model_kwargs is None: + t5_model_kwargs = {"low_cpu_mem_usage": True, "torch_dtype": self.torch_dtype} + if use_offload_folder is not None: + t5_model_kwargs["offload_folder"] = use_offload_folder + t5_model_kwargs["device_map"] = { + "shared": self.device, + "encoder.embed_tokens": self.device, + "encoder.block.0": self.device, + "encoder.block.1": self.device, + "encoder.block.2": self.device, + "encoder.block.3": self.device, + "encoder.block.4": self.device, + "encoder.block.5": self.device, + "encoder.block.6": self.device, + "encoder.block.7": self.device, + "encoder.block.8": self.device, + "encoder.block.9": self.device, + "encoder.block.10": self.device, + "encoder.block.11": self.device, + "encoder.block.12": "disk", + "encoder.block.13": "disk", + "encoder.block.14": "disk", + "encoder.block.15": "disk", + "encoder.block.16": "disk", + "encoder.block.17": "disk", + "encoder.block.18": "disk", + "encoder.block.19": "disk", + "encoder.block.20": "disk", + "encoder.block.21": "disk", + "encoder.block.22": "disk", + "encoder.block.23": "disk", + "encoder.final_layer_norm": "disk", + "encoder.dropout": "disk", + } + else: + t5_model_kwargs["device_map"] = {"shared": self.device, "encoder": self.device} + self.use_text_preprocessing = use_text_preprocessing + self.hf_token = hf_token + self.cache_dir = cache_dir or os.path.expanduser("~/.cache/IF_") + self.dir_or_name = dir_or_name + tokenizer_path, path = dir_or_name, dir_or_name + if local_cache: + cache_dir = os.path.join(self.cache_dir, dir_or_name) + tokenizer_path, path = cache_dir, cache_dir + elif dir_or_name in self.available_models: + cache_dir = os.path.join(self.cache_dir, dir_or_name) + for filename in [ + "config.json", + "special_tokens_map.json", + "spiece.model", + "tokenizer_config.json", + "pytorch_model.bin.index.json", + "pytorch_model-00001-of-00002.bin", + "pytorch_model-00002-of-00002.bin", + ]: + hf_hub_download( + repo_id=f"DeepFloyd/{dir_or_name}", + filename=filename, + cache_dir=cache_dir, + force_filename=filename, + token=self.hf_token, + ) + tokenizer_path, path = cache_dir, cache_dir + else: + cache_dir = os.path.join(self.cache_dir, "t5-v1_1-xxl") + for filename in ["config.json", "special_tokens_map.json", "spiece.model", "tokenizer_config.json"]: + hf_hub_download( + repo_id="DeepFloyd/t5-v1_1-xxl", + filename=filename, + cache_dir=cache_dir, + force_filename=filename, + token=self.hf_token, + ) + tokenizer_path = cache_dir + + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) + self.model = T5EncoderModel.from_pretrained(path, **t5_model_kwargs).eval() + self.model_max_length = model_max_length + + + def get_text_embeddings(self, texts): + texts = [self.text_preprocessing(text) for text in texts] + + text_tokens_and_mask = self.tokenizer( + texts, + max_length=self.model_max_length, + padding="max_length", + truncation=True, + return_attention_mask=True, + add_special_tokens=True, + return_tensors="pt", + ) + + text_tokens_and_mask["input_ids"] = text_tokens_and_mask["input_ids"] + text_tokens_and_mask["attention_mask"] = text_tokens_and_mask["attention_mask"] + + with torch.no_grad(): + text_encoder_embs = self.model( + input_ids=text_tokens_and_mask["input_ids"].to(self.device), + attention_mask=text_tokens_and_mask["attention_mask"].to(self.device), + )["last_hidden_state"].detach() + return text_encoder_embs, text_tokens_and_mask["attention_mask"].to(self.device) + + def text_preprocessing(self, text): + if self.use_text_preprocessing: + # The exact text cleaning as was in the training stage: + text = self.clean_caption(text) + text = self.clean_caption(text) + return text + else: + return text.lower().strip() + + @staticmethod + def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + def clean_caption(self, caption): + caption = str(caption) + caption = ul.unquote_plus(caption) + caption = caption.strip().lower() + caption = re.sub("", "person", caption) + # urls: + caption = re.sub( + r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa + "", + caption, + ) # regex for urls + caption = re.sub( + r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa + "", + caption, + ) # regex for urls + # html: + caption = BeautifulSoup(caption, features="html.parser").text + + # @ + caption = re.sub(r"@[\w\d]+\b", "", caption) + + # 31C0—31EF CJK Strokes + # 31F0—31FF Katakana Phonetic Extensions + # 3200—32FF Enclosed CJK Letters and Months + # 3300—33FF CJK Compatibility + # 3400—4DBF CJK Unified Ideographs Extension A + # 4DC0—4DFF Yijing Hexagram Symbols + # 4E00—9FFF CJK Unified Ideographs + caption = re.sub(r"[\u31c0-\u31ef]+", "", caption) + caption = re.sub(r"[\u31f0-\u31ff]+", "", caption) + caption = re.sub(r"[\u3200-\u32ff]+", "", caption) + caption = re.sub(r"[\u3300-\u33ff]+", "", caption) + caption = re.sub(r"[\u3400-\u4dbf]+", "", caption) + caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption) + caption = re.sub(r"[\u4e00-\u9fff]+", "", caption) + ####################################################### + + # все виды тире / all types of dash --> "-" + caption = re.sub( + r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa + "-", + caption, + ) + + # кавычки к одному стандарту + caption = re.sub(r"[`´«»“”¨]", '"', caption) + caption = re.sub(r"[‘’]", "'", caption) + + # " + caption = re.sub(r""?", "", caption) + # & + caption = re.sub(r"&", "", caption) + + # ip adresses: + caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption) + + # article ids: + caption = re.sub(r"\d:\d\d\s+$", "", caption) + + # \n + caption = re.sub(r"\\n", " ", caption) + + # "#123" + caption = re.sub(r"#\d{1,3}\b", "", caption) + # "#12345.." + caption = re.sub(r"#\d{5,}\b", "", caption) + # "123456.." + caption = re.sub(r"\b\d{6,}\b", "", caption) + # filenames: + caption = re.sub(r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption) + + # + caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT""" + caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT""" + + caption = re.sub(self.bad_punct_regex, r" ", caption) # ***AUSVERKAUFT***, #AUSVERKAUFT + caption = re.sub(r"\s+\.\s+", r" ", caption) # " . " + + # this-is-my-cute-cat / this_is_my_cute_cat + regex2 = re.compile(r"(?:\-|\_)") + if len(re.findall(regex2, caption)) > 3: + caption = re.sub(regex2, " ", caption) + + caption = self.basic_clean(caption) + + caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640 + caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc + caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231 + + caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption) + caption = re.sub(r"(free\s)?download(\sfree)?", "", caption) + caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption) + caption = re.sub(r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption) + caption = re.sub(r"\bpage\s+\d+\b", "", caption) + + caption = re.sub(r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption) # j2d1a2a... + + caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption) + + caption = re.sub(r"\b\s+\:\s+", r": ", caption) + caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption) + caption = re.sub(r"\s+", " ", caption) + + caption.strip() + + caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption) + caption = re.sub(r"^[\'\_,\-\:;]", r"", caption) + caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption) + caption = re.sub(r"^\.\S+$", "", caption) + + return caption.strip() diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc68d8a76ae0ccc0b43d5faa4cafc5c7d1e1c2d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .vae_model import AutoModel, VideoTokenizerABC, ViTVAE +from .vae_module import DiagonalGaussianDistribution + +__all__ = ["AutoModel", "VideoTokenizerABC", "ViTVAE", "DiagonalGaussianDistribution"] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bb9bb10ec18ac42dfedf3d2babbdb728a14d1e1 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__pycache__/vae_model.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__pycache__/vae_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a447c822f0afd4419a8c52b12a1abdf09fe96a5 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__pycache__/vae_model.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__pycache__/vae_module.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__pycache__/vae_module.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bad6bae604842a9c56464bf000f2b57a2c486fae Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/__pycache__/vae_module.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/vae_model.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/vae_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b8812c11b0b084ff65a3d74c1d485a0a038d28b0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/vae_model.py @@ -0,0 +1,361 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +from abc import ABC, abstractmethod +from typing import Literal + +import torch +from diffusers import ConfigMixin, ModelMixin +from diffusers.configuration_utils import register_to_config + +from inference.infra.parallelism import TileProcessor + +from .vae_module import DiagonalGaussianDistribution, ViTDecoder, ViTEncoder + + +class VideoTokenizerABC(ABC): + """ + Abstract base class for video tokenizers. + + This class defines the interface for video tokenizers and provides common methods and properties. + """ + + @property + @abstractmethod + def spatial_downsample_factor(self): + """ + Property representing the spatial downsample factor. + + Returns: + int: The spatial downsample factor. + """ + raise NotImplementedError + + @property + @abstractmethod + def temporal_downsample_factor(self): + """ + Property representing the temporal downsample factor. + + Returns: + int: The temporal downsample factor. + """ + raise NotImplementedError + + @property + def first_frame_as_image(self): + """ + Property representing the first frame as image. + For tokenizer like CausalVAE, Omnitokenizer, the first frame is treated as image. + in this case if the temporal downsample factor is 4, the input should be 4*x+1, and encoded tensor would be x+1. + for example encode 65 frames to 17 frames. and decode 17 frames to 65 frames. + + Returns: + bool: The first frame as image. + """ + return False + + @property + def allow_spatial_tiling(self): + """ + Determines whether spatial tiling is allowed or not. + + Returns: + bool: True if spatial tiling is allowed, False otherwise. + """ + return True + + @abstractmethod + def encode(self, x) -> torch.Tensor: + """ + Abstract method for encoding the input tensor. + + Args: + x (torch.Tensor [N C T H W] range[-1, 1]): The input tensor to be encoded. + + Returns: + torch.Tensor: The encoded tensor. + """ + raise NotImplementedError + + @abstractmethod + def decode(self, x) -> torch.Tensor: + """ + Abstract method for decoding the input tensor. + + Args: + x (torch.Tensor [N C T H W]): The input tensor to be decoded. + + Returns: + torch.Tensor [N C T H W] range[-1, 1]: The decoded tensor. + """ + raise NotImplementedError + + def tile_processor( + self, + tile_sample_min_height=256, + tile_sample_min_width=256, + tile_sample_min_length=16, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> TileProcessor: + """ + Property representing the tiled encoder or decoder. + + Returns: + TileProcessor: The tiled encoder or decoder. + """ + return TileProcessor( + encode_fn=self.encode, + decode_fn=self.decode, + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + tile_sample_min_length=tile_sample_min_length, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + sr_ratio=getattr(self, 'sr_ratio', 1), + spatial_downsample_factor=self.spatial_downsample_factor, + temporal_downsample_factor=self.temporal_downsample_factor, + first_frame_as_image=self.first_frame_as_image, + parallel_group=parallel_group, + ) + + @torch.inference_mode() + def tiled_encode_3d( + self, + x, + tile_sample_min_height=256, + tile_sample_min_width=256, + tile_sample_min_length: int = 16, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + allow_spatial_tiling: bool = None, + verbose: bool = False, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> torch.Tensor: + """ + Encodes the input tensor `x` using tiled encoding. + + Args: + x (torch.Tensor shape:[N C T H W]): The input tensor to be encoded. + tile_sample_min_height (int, optional): The minimum height of each tile sample. Defaults to 256. + tile_sample_min_width (int, optional): The minimum width of each tile sample. Defaults to 256. + tile_sample_min_length (int, optional): The minimum length of each tile sample. Defaults to 16. + spatial_tile_overlap_factor (float, optional): Overlap factor for spatial tiles. Defaults to 0.25. + temporal_tile_overlap_factor (float, optional): Overlap factor for temporal tiles. Defaults to 0. + allow_spatial_tiling (bool, optional): Whether spatial tiling is allowed. Defaults to None. + verbose (bool, optional): Whether to print verbose information. Defaults to False. + parallel_group (torch.distributed.ProcessGroup, optional): Distributed encoding group. Defaults to None. + Returns: + torch.Tensor: The encoded tensor. + """ + allow_spatial_tiling = allow_spatial_tiling if allow_spatial_tiling is not None else self.allow_spatial_tiling + if not allow_spatial_tiling: + tile_sample_min_height = 100000 + tile_sample_min_width = 100000 + return self.tile_processor( + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + tile_sample_min_length=tile_sample_min_length, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + parallel_group=parallel_group, + ).tiled_encode(x, verbose) + + @torch.inference_mode() + def tiled_decode_3d( + self, + x, + tile_sample_min_height=256, + tile_sample_min_width=256, + tile_sample_min_length: int = 16, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + allow_spatial_tiling: bool = None, + verbose: bool = False, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> torch.Tensor: + """ + Decodes the input tensor using the tile autoencoder. + + Args: + x (torch.Tensor): The input tensor to be decoded. + tile_sample_min_height (int, optional): The minimum height of each tile sample. Defaults to 256. + tile_sample_min_width (int, optional): The minimum width of each tile sample. Defaults to 256. + tile_sample_min_length (int, optional): The minimum length of each tile sample. Defaults to 16. + spatial_tile_overlap_factor (float, optional): Overlap factor for spatial tiles. Defaults to 0.25. + temporal_tile_overlap_factor (float, optional): Overlap factor for temporal tiles. Defaults to 0. + allow_spatial_tiling (bool, optional): Whether spatial tiling is allowed. Defaults to None. + verbose (bool, optional): Whether to print verbose information. Defaults to False. + parallel_group (torch.distributed.ProcessGroup, optional): Distributed decoding group. Defaults to None. + Returns: + torch.Tensor shape:[N C T H W]: The decoded tensor. + """ + allow_spatial_tiling = allow_spatial_tiling if allow_spatial_tiling is not None else self.allow_spatial_tiling + if not allow_spatial_tiling: + tile_sample_min_height = 100000 + tile_sample_min_width = 100000 + return self.tile_processor( + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + tile_sample_min_length=tile_sample_min_length, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + parallel_group=parallel_group, + ).tiled_decode(x, verbose) + + +class ViTVAE(ModelMixin, ConfigMixin, VideoTokenizerABC): + @register_to_config + def __init__(self, ddconfig: dict, model_type: Literal['vit', 'vit_ncthw'] = 'vit'): + super().__init__() + + if model_type == 'vit': + self.encoder = ViTEncoder(**ddconfig) + self.decoder = ViTDecoder(**ddconfig) + elif model_type == 'vit_ncthw': + from videotokenizer.modules.vit_ncthw import ViTDecoderNCTHW, ViTEncoderNCTHW + + self.encoder = ViTEncoderNCTHW(**ddconfig) + self.decoder = ViTDecoderNCTHW(**ddconfig) + else: + raise ValueError(f"model_type {model_type} not supported") + + if 'patch_length' in ddconfig: + self._temporal_downsample_factor = ddconfig['patch_length'] + else: + self._temporal_downsample_factor = 1 + + if 'patch_size' in ddconfig: + self._spatial_downsample_factor = ddconfig['patch_size'] + else: + self._spatial_downsample_factor = 8 + + @property + def spatial_downsample_factor(self): + return self._spatial_downsample_factor + + @property + def temporal_downsample_factor(self): + return self._temporal_downsample_factor + + def init_from_ckpt(self, path, ignore_keys=list()): + raise NotImplementedError + + def encode(self, x, sample_posterior=True): + """ + Encode the input video. + + Args: + x (torch.Tensor): Input video tensor has shape N C T H W + + Returns: + tuple: Tuple containing the quantized tensor, embedding loss, and additional information. + """ + N, C, T, H, W = x.shape + if T == 1 and self._temporal_downsample_factor > 1: + x = x.expand(-1, -1, 4, -1, -1) + x = self.encoder(x) + posterior = DiagonalGaussianDistribution(x) + if sample_posterior: + z = posterior.sample() + else: + z = posterior.mode() + + return z[:, :, :1, :, :].type(x.dtype) + else: + x = self.encoder(x) + posterior = DiagonalGaussianDistribution(x) + if sample_posterior: + z = posterior.sample() + else: + z = posterior.mode() + + return z.type(x.dtype) + + def decode(self, x): + """ + Decode the quantized tensor. + + Args: + quant (torch.Tensor): Quantized tensor. + + Returns: + torch.Tensor: Decoded tensor. + """ + N, C, T, H, W = x.shape + if T == 1: + x = x.expand(-1, -1, 1, -1, -1) + x = self.decoder(x) + x = x[:, :, :1, :, :] + return x + else: + x = self.decoder(x) + return x + + def forward(self, x, sample_posterior=True): + x = self.encoder(x) + posterior = DiagonalGaussianDistribution(x) + + if sample_posterior: + z = posterior.sample() + else: + z = posterior.mode() + + dec = self.decoder(z) + return dec, posterior + + def get_last_layer(self): + """ + Get the last layer of the decoder. + + Returns: + torch.Tensor: Last layer of the decoder. + """ + return self.decoder.last_layer.weight + + @property + def allow_spatial_tiling(self): + return False + + +class AutoModel: + r""" + :class:`~models.AutoModel` is a generic model class + that will be instantiated as one of the base model classes of the library + when created with the `AutoModel.from_pretrained(pretrained_model_name_or_path)` + + + This class cannot be instantiated using `__init__()` (throws an error). + """ + + def __init__(self): + raise EnvironmentError( + "AutoModel is designed to be instantiated " + "using the `AutoModel.from_pretrained(pretrained_model_name_or_path)` method." + ) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs) -> VideoTokenizerABC: + config = os.path.join(pretrained_model_name_or_path, 'config.json') + if not os.path.exists(config): + raise ValueError("Can't find a model config file at {}.".format(config)) + # Load config + with open(config, 'r') as json_file: + config_dict = json.load(json_file) + assert config_dict['_class_name'] == 'ViTVAE' + return ViTVAE.from_pretrained(pretrained_model_name_or_path, *args, **kwargs) diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/vae_module.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/vae_module.py new file mode 100644 index 0000000000000000000000000000000000000000..eb4501b045bd11fde4920ea316a39b792eca92e1 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/vae/vae_module.py @@ -0,0 +1,757 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from functools import lru_cache +from typing import List, Optional, Tuple + +import numpy as np +import torch +import torch.nn as nn +from einops import rearrange +from flash_attn import flash_attn_func, flash_attn_qkvpacked_func +from timm.models.layers import to_2tuple, trunc_normal_ + +################################################### +# modified 3D rotary embedding from timm +################################################### + + +def ndgrid(*tensors) -> Tuple[torch.Tensor, ...]: + """generate N-D grid in dimension order. + + The ndgrid function is like meshgrid except that the order of the first two input arguments are switched. + + That is, the statement + [X1,X2,X3] = ndgrid(x1,x2,x3) + + produces the same result as + + [X2,X1,X3] = meshgrid(x2,x1,x3) + + This naming is based on MATLAB, the purpose is to avoid confusion due to torch's change to make + torch.meshgrid behaviour move from matching ndgrid ('ij') indexing to numpy meshgrid defaults of ('xy'). + + """ + try: + return torch.meshgrid(*tensors, indexing='ij') + except TypeError: + # old PyTorch < 1.10 will follow this path as it does not have indexing arg, + # the old behaviour of meshgrid was 'ij' + return torch.meshgrid(*tensors) + + +def freq_bands( + num_bands: int, temperature: float = 10000.0, step: int = 2, device: Optional[torch.device] = None +) -> torch.Tensor: + exp = torch.arange(0, num_bands, step, dtype=torch.int64, device=device).to(torch.float32) / num_bands + bands = 1.0 / (temperature**exp) + return bands + + +def pixel_freq_bands( + num_bands: int, max_freq: float = 224.0, linear_bands: bool = True, device: Optional[torch.device] = None +): + if linear_bands: + bands = torch.linspace(1.0, max_freq / 2, num_bands, dtype=torch.float32, device=device) + else: + bands = 2 ** torch.linspace(0, math.log(max_freq, 2) - 1, num_bands, dtype=torch.float32, device=device) + return bands * torch.pi + + +def build_fourier_pos_embed( + feat_shape: List[int], + bands: Optional[torch.Tensor] = None, + num_bands: int = 64, + max_res: int = 224, + temperature: float = 10000.0, + linear_bands: bool = False, + include_grid: bool = False, + in_pixels: bool = True, + ref_feat_shape: Optional[List[int]] = None, + dtype: torch.dtype = torch.float32, + device: Optional[torch.device] = None, + center_imgidx=True, +) -> List[torch.Tensor]: + """ + + Args: + feat_shape: Feature shape for embedding. + bands: Pre-calculated frequency bands. + num_bands: Number of frequency bands (determines output dim). + max_res: Maximum resolution for pixel based freq. + temperature: Temperature for non-pixel freq. + linear_bands: Linear band spacing for pixel based freq. + include_grid: Include the spatial grid in output. + in_pixels: Output in pixel freq. + ref_feat_shape: Reference feature shape for resize / fine-tune. + dtype: Output dtype. + device: Output device. + + Returns: + + """ + if bands is None: + if in_pixels: + bands = pixel_freq_bands(num_bands, float(max_res), linear_bands=linear_bands, device=device) + else: + bands = freq_bands(num_bands, temperature=temperature, step=1, device=device) + else: + if device is None: + device = bands.device + if dtype is None: + dtype = bands.dtype + + if in_pixels: + t = [torch.linspace(-1.0, 1.0, steps=s, device=device, dtype=torch.float32) for s in feat_shape] + else: + if center_imgidx: + t = [ + torch.arange(s, device=device, dtype=torch.int64).to(torch.float32) - (s - 1) / 2 + if len(feat_shape) == 2 or i != 0 + else torch.arange(s, device=device, dtype=torch.int64).to(torch.float32) + for i, s in enumerate(feat_shape) + ] + else: + t = [torch.arange(s, device=device, dtype=torch.int64).to(torch.float32) for s in feat_shape] + + if ref_feat_shape is not None: + assert len(feat_shape) == len(ref_feat_shape), 'shape must be in same dimension' + # eva's scheme for resizing rope embeddings (ref shape = pretrain) + t = [x / f * r for x, f, r in zip(t, feat_shape, ref_feat_shape)] + + grid = torch.stack(ndgrid(t), dim=-1) + grid = grid.unsqueeze(-1) + pos = grid * bands + pos_sin, pos_cos = pos.sin().to(dtype=dtype), pos.cos().to(dtype) + out = [grid, pos_sin, pos_cos] if include_grid else [pos_sin, pos_cos] + return out + + +def rot(x): + return torch.stack([-x[..., 1::2], x[..., ::2]], -1).reshape(x.shape) + + +def apply_rot_embed(x: torch.Tensor, sin_emb, cos_emb): + if sin_emb.ndim == 3: + return x * cos_emb.unsqueeze(1).expand_as(x) + rot(x) * sin_emb.unsqueeze(1).expand_as(x) + # import ipdb; ipdb.set_trace() + return x * cos_emb + rot(x) * sin_emb + + +def build_rotary_pos_embed( + feat_shape: List[int], + bands: Optional[torch.Tensor] = None, + dim: int = 64, + max_res: int = 224, + temperature: float = 10000.0, + linear_bands: bool = False, + in_pixels: bool = True, + ref_feat_shape: Optional[List[int]] = None, + dtype: torch.dtype = torch.float32, + device: Optional[torch.device] = None, + center_imgidx=True, +): + """ + + Args: + feat_shape: Spatial shape of the target tensor for embedding. + bands: Optional pre-generated frequency bands + dim: Output dimension of embedding tensor. + max_res: Maximum resolution for pixel mode. + temperature: Temperature (inv freq) for non-pixel mode + linear_bands: Linearly (instead of log) spaced bands for pixel mode + in_pixels: Pixel vs language (inv freq) mode. + dtype: Output dtype. + device: Output device. + + Returns: + + """ + sin_emb, cos_emb = build_fourier_pos_embed( + feat_shape, + bands=bands, + num_bands=dim // (len(feat_shape) * 2), + max_res=max_res, + temperature=temperature, + linear_bands=linear_bands, + in_pixels=in_pixels, + ref_feat_shape=ref_feat_shape, + device=device, + dtype=dtype, + center_imgidx=center_imgidx, + ) + num_spatial_dim = 1 + # this would be much nicer as a .numel() call to torch.Size(), but torchscript sucks + for x in feat_shape: + num_spatial_dim *= x + sin_emb = sin_emb.reshape(num_spatial_dim, -1).repeat_interleave(2, -1) + cos_emb = cos_emb.reshape(num_spatial_dim, -1).repeat_interleave(2, -1) + return sin_emb, cos_emb + + +################################################### +# Mlp +################################################### +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +################################################### +# ManualLayerNorm +################################################### +class ManualLayerNorm(nn.Module): + def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True): + super(ManualLayerNorm, self).__init__() + self.normalized_shape = normalized_shape + self.eps = eps + self.elementwise_affine = elementwise_affine + + def forward(self, x): + mean = x.mean(dim=-1, keepdim=True) + std = x.std(dim=-1, keepdim=True, unbiased=False) + + x_normalized = (x - mean) / (std + self.eps) + + return x_normalized + + +################################################### +# Attention +################################################### +@lru_cache(maxsize=50) +def cache_rotary_emb(feat_shape, device='cuda', dim=64, dtype=torch.bfloat16, max_res=512, ref_feat_shape=(4, 16, 16)): + return build_rotary_pos_embed( + feat_shape=feat_shape, + dim=dim, + max_res=max_res, + in_pixels=False, + ref_feat_shape=ref_feat_shape, + device=device, + dtype=dtype, + ) + + +class Attention(nn.Module): + def __init__( + self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, ln_in_attn=False, use_rope=False + ): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop_rate = attn_drop + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + if ln_in_attn: + self.qkv_norm = ManualLayerNorm(head_dim, elementwise_affine=False) + else: + self.qkv_norm = nn.Identity() + self.use_rope = use_rope + + def forward(self, x, feat_shape=None): + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) + + qkv = self.qkv_norm(qkv) + q, k, v = qkv.chunk(3, dim=2) + if self.use_rope: + assert feat_shape is not None + q, k, v = qkv.chunk(3, dim=2) + rope_emb = cache_rotary_emb(feat_shape=feat_shape, dim=C // self.num_heads, device=x.device, dtype=x.dtype) + sin_emb = rope_emb[0].unsqueeze(0).unsqueeze(2) + cos_emb = rope_emb[1].unsqueeze(0).unsqueeze(2) + print(q.shape, sin_emb.shape) + q[:, 1:, :] = apply_rot_embed(q[:, 1:, :], sin_emb, cos_emb).bfloat16() + k[:, 1:, :] = apply_rot_embed(k[:, 1:, :], sin_emb, cos_emb).bfloat16() + x = flash_attn_func(q, k, v, dropout_p=self.attn_drop_rate) + else: + x = flash_attn_qkvpacked_func(qkv=qkv.bfloat16(), dropout_p=self.attn_drop_rate) + # x = v + x = x.reshape(B, N, C) + # import ipdb; ipdb.set_trace() + x = self.proj(x) + x = self.proj_drop(x) + return x + + +################################################### +# Block +################################################### +class Block(nn.Module): + def __init__( + self, + dim, + num_heads, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + ln_in_attn=False, + use_rope=False, + ): + super().__init__() + if not ln_in_attn: + self.norm1 = norm_layer(dim) + else: + self.norm1 = nn.Identity() + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop, + ln_in_attn=ln_in_attn, + use_rope=use_rope, + ) + self.drop_path = nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + def forward(self, x, feat_shape=None): + x = x + self.drop_path(self.attn(self.norm1(x), feat_shape=feat_shape)) + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +################################################### +# PatchEmbed +################################################### +class PatchEmbed(nn.Module): + """Image to Patch Embedding""" + + def __init__(self, video_size=224, video_length=16, patch_size=16, patch_length=1, in_chans=3, embed_dim=768): + super().__init__() + video_size = to_2tuple(video_size) + patch_size = to_2tuple(patch_size) + + num_patches = (video_length // patch_length) * (video_size[1] // patch_size[1]) * (video_size[0] // patch_size[0]) + + self.video_size = video_size + self.patch_size = patch_size + + self.video_length = video_length + self.patch_length = patch_length + + self.num_patches = num_patches + + self.proj = nn.Conv3d( + in_chans, + embed_dim, + kernel_size=(patch_length, patch_size[0], patch_size[1]), + stride=(patch_length, patch_size[0], patch_size[1]), + ) + + def forward(self, x): + """ + Forward pass of the PatchEmbed module. + + Args: + x (torch.Tensor): Input tensor of shape (B, C, T, H, W), where + B is the batch size, C is the number of channels, T is the + number of frames, H is the height, and W is the width. + + Returns: + torch.Tensor: Output tensor of shape (B, L, C'), where B is the + batch size, L is the number of tokens, and C' is the number + of output channels after flattening and transposing. + """ + B, C, T, H, W = x.shape + + x = self.proj(x) + return x + + +################################################### +# ViTEncoder +################################################### +def resize_pos_embed(posemb, src_shape, target_shape): + posemb = posemb.reshape(1, src_shape[0], src_shape[1], src_shape[2], -1) + posemb = posemb.permute(0, 4, 1, 2, 3) + posemb = nn.functional.interpolate(posemb, size=target_shape, mode='trilinear', align_corners=False) + posemb = posemb.permute(0, 2, 3, 4, 1) + posemb = posemb.reshape(1, target_shape[0] * target_shape[1] * target_shape[2], -1) + return posemb + + +class ViTEncoder(nn.Module): + """Vision Transformer with support for patch or hybrid CNN input stage""" + + def __init__( + self, + video_size=256, + video_length=16, + patch_size=8, + patch_length=4, + in_chans=3, + z_chans=4, + double_z=True, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + with_cls_token=True, + norm_code=False, + ln_in_attn=False, + conv_last_layer=False, + use_rope=False, + use_final_proj=False, + ): + super().__init__() + + conv_last_layer = False # duplicate argument + + # self.num_classes = num_classes + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + + self.latent_size = video_size // patch_size + self.latent_length = video_length // patch_length + + self.patch_embed = PatchEmbed( + video_size=video_size, + video_length=video_length, + patch_size=patch_size, + patch_length=patch_length, + in_chans=in_chans, + embed_dim=embed_dim, + ) + + num_patches = self.patch_embed.num_patches + self.with_cls_token = with_cls_token + if with_cls_token: + self.cls_token_nums = 1 + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + else: + self.cls_token_nums = 0 + self.cls_token = None + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.cls_token_nums, embed_dim)) + self.pos_drop = nn.Dropout(p=drop_rate) + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + self.blocks = nn.ModuleList( + [ + Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + ln_in_attn=ln_in_attn, + use_rope=use_rope, + ) + for i in range(depth) + ] + ) + self.norm = norm_layer(embed_dim) + + self.norm_code = norm_code + + self.out_channels = z_chans * 2 if double_z else z_chans + self.last_layer = nn.Linear(embed_dim, self.out_channels, bias=True) + + trunc_normal_(self.pos_embed, std=0.02) + + if self.with_cls_token: + trunc_normal_(self.cls_token, std=0.02) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay(self): + return {'pos_embed', 'cls_token'} + + def forward(self, x): + B = x.shape[0] + # B C T H W -> B C T/pT H/pH W//pW + x = self.patch_embed(x) + latentT, latentH, latentW = x.shape[2], x.shape[3], x.shape[4] + # B C T/pT H/pH W//pW -> B (T/pT H/pH W//pW) C + x = x.flatten(2).transpose(1, 2) + + if self.with_cls_token: + cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + + if latentT != self.latent_length or latentH != self.latent_size or latentW != self.latent_size: + pos_embed = resize_pos_embed( + self.pos_embed[:, 1:, :], + src_shape=(self.latent_length, self.latent_size, self.latent_size), + target_shape=(latentT, latentH, latentW), + ) + pos_embed = torch.cat((self.pos_embed[:, 0:1, :], pos_embed), dim=1) + else: + pos_embed = self.pos_embed + + x = x + pos_embed + x = self.pos_drop(x) + + for idx, blk in enumerate(self.blocks): + x = blk(x, feat_shape=(latentT, latentH, latentW)) + + x = self.norm(x) + x = self.last_layer(x) + + if self.with_cls_token: + x = x[:, 1:] # remove cls_token + + # B L C - > B , lT, lH, lW, zC + x = x.reshape(B, latentT, latentH, latentW, self.out_channels) + + # B , lT, lH, lW, zC -> B, zC, lT, lH, lW + x = x.permute(0, 4, 1, 2, 3) + if self.norm_code: + prev_dtype = x.dtype + x = x.float() + x = x / torch.norm(x, dim=1, keepdim=True) + x = x.to(prev_dtype) + return x + + def freeze_pretrain(self): + # Freeze all parameters + for param in self.parameters(): + param.requires_grad = False + + +################################################### +# ViTDecoder +################################################### +class ViTDecoder(nn.Module): + """Vision Transformer with support for patch or hybrid CNN input stage""" + + def __init__( + self, + video_size=256, + video_length=16, + patch_size=8, + patch_length=4, + in_chans=3, + z_chans=4, + double_z=True, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + with_cls_token=True, + norm_code=False, + ln_in_attn=False, + conv_last_layer=False, + use_rope=False, + use_final_proj=False, + ): + super().__init__() + + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + + self.latent_size = video_size // patch_size + self.latent_length = video_length // patch_length + self.patch_size = patch_size + self.patch_length = patch_length + + self.proj_in = nn.Linear(z_chans, embed_dim) + + num_patches = self.latent_size * self.latent_size * self.latent_length + + self.with_cls_token = with_cls_token + if with_cls_token: + self.cls_token_nums = 1 + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + else: + self.cls_token_nums = 0 + self.cls_token = None + + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.cls_token_nums, embed_dim)) + self.pos_drop = nn.Dropout(p=drop_rate) + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + self.blocks = nn.ModuleList( + [ + Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + ln_in_attn=ln_in_attn, + use_rope=use_rope, + ) + for i in range(depth) + ] + ) + self.norm = norm_layer(embed_dim) + + assert conv_last_layer == True, "Only support conv_last_layer=True" + + self.unpatch_channels = embed_dim // (patch_size * patch_size * patch_length) + self.final_proj = nn.Identity() + self.final_norm = nn.Identity() + + self.use_final_proj = use_final_proj + if self.use_final_proj: + self.unpatch_channels = 4 + self.final_proj = nn.Linear(embed_dim, self.unpatch_channels * (patch_size * patch_size * patch_length), bias=True) + self.final_norm = norm_layer(self.unpatch_channels * (patch_size * patch_size * patch_length)) + + self.last_layer = nn.Conv3d(in_channels=self.unpatch_channels, out_channels=3, kernel_size=3, stride=1, padding=1) + + trunc_normal_(self.pos_embed, std=0.02) + + if self.with_cls_token: + trunc_normal_(self.cls_token, std=0.02) + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay(self): + return {'pos_embed', 'cls_token'} + + def forward(self, x): + B, C, latentT, latentH, latentW = x.shape # x: (B, C, latentT, latentH, latenW) + x = x.permute(0, 2, 3, 4, 1) # x: (B, latentT, latentH, latenW, C) + + x = x.reshape(B, -1, C) + + x = self.proj_in(x) + + if self.with_cls_token: + cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + + if latentT != self.latent_length or latentH != self.latent_size or latentW != self.latent_size: + pos_embed = resize_pos_embed( + self.pos_embed[:, 1:, :], + src_shape=(self.latent_length, self.latent_size, self.latent_size), + target_shape=(latentT, latentH, latentW), + ) + pos_embed = torch.cat((self.pos_embed[:, 0:1, :], pos_embed), dim=1) + else: + pos_embed = self.pos_embed + + x = x + pos_embed + x = self.pos_drop(x) + + for idx, blk in enumerate(self.blocks): + x = blk(x, feat_shape=(latentT, latentH, latentW)) + + x = self.norm(x) + + if self.with_cls_token: + x = x[:, 1:] # remove cls_token + # B L C - > B, lT, lH, lW, pT, pH, pW, C + if self.use_final_proj: + x = self.final_proj(x) + x = self.final_norm(x) + x = x.reshape(B, latentT, latentH, latentW, self.patch_length, self.patch_size, self.patch_size, self.unpatch_channels) + x = rearrange(x, 'B lT lH lW pT pH pW C -> B C (lT pT) (lH pH) (lW pW)', C=self.unpatch_channels) + + x = self.last_layer(x) + return x + + +################################################### +# DiagonalGaussianDistribution +################################################### +class DiagonalGaussianDistribution(object): + def __init__(self, parameters, deterministic=False): + self.parameters = parameters + self.mean, self.logvar = torch.chunk(parameters, 2, dim=1) + self.logvar = torch.clamp(self.logvar, -30.0, 20.0) + self.deterministic = deterministic + self.std = torch.exp(0.5 * self.logvar) + self.var = torch.exp(self.logvar) + if self.deterministic: + self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device) + + def sample(self): + x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device) + return x + + def kl(self, other=None): + if self.deterministic: + return torch.Tensor([0.0]) + else: + if other is None: + return 0.5 * torch.sum(torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar, dim=[1, 2, 3]) + else: + return 0.5 * torch.sum( + torch.pow(self.mean - other.mean, 2) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar, + dim=[1, 2, 3], + ) + + def nll(self, sample, dims=[1, 2, 3]): + if self.deterministic: + return torch.Tensor([0.0]) + logtwopi = np.log(2.0 * np.pi) + return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var, dim=dims) + + def mode(self): + return self.mean diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b727dccf0a68d5bcbb9b32e5004d24f7df5599a --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .pipeline import MagiPipeline +from .video_generate import SampleTransport, find_dit_model + +__all__ = ["MagiPipeline", "SampleTransport", "find_dit_model"] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe1d944ee33cb54df75fc214c10611a7c2a7d2e4 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe9d4bcd1ddf3b85400b6113bc7dfbe84badf51c Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/entry.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/entry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e027bede5e7fb07224617d82481d03c0bf1ee34 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/entry.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/entry.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/entry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d65b27c47dc0e40986f94496417b888eefef7549 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/entry.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/flowcache.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/flowcache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..674ae0d77417b6648f9020a4481bfe373ba151af Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/flowcache.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/flowcache.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/flowcache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fbfe8058d5ce2ac4b8136779a212df4723fa63a Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/flowcache.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/pipeline.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/pipeline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bafd525be78a612f74f5b1b893703398f81a4f26 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/pipeline.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/pipeline.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/pipeline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f35f2ae572d94d671d71a74f327eeee435bd85b8 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/pipeline.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/prompt_process.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/prompt_process.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf7ebfe5d709024f6dfbc4b8f9bb03208e95dab9 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/prompt_process.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/teacache.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/teacache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cd0758ad833d0bea9d0ba3af7ec5cea7416886b Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/teacache.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/video_generate.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/video_generate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..011086173ea4cfa8b50638b5d797ea4350ce04af Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/video_generate.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/video_generate.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/video_generate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81f0ab34fee51ea282ee678b415541c872ea6514 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/video_generate.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/video_process.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/video_process.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92e7781974b928fbad455bd616b49483de6b28c8 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/__pycache__/video_process.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17422206ce2e373b9431d5ca3cd7d45f14083be7 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__init__.py @@ -0,0 +1,36 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Cache management module for MAGI inference. + +This module provides optimized implementations for: +- TeaCache: Full output reuse (all chunks together) +- ChunkWiseCache: Per-chunk output reuse (used in FlowCache) +- KVCacheCompressor: Dynamic KV cache compression +""" + +from .base import CacheStrategy, OutputCache, KVCompressor +from .cachereuse import TeaCache, ChunkWiseCache +from .kv_compressor import KVCacheCompressor +from .utils import generate_dynamic_kv_range + +__all__ = [ + "CacheStrategy", + "OutputCache", + "KVCompressor", + "TeaCache", + "ChunkWiseCache", + "generate_dynamic_kv_range", +] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..734f947e977a8d5a5c004cf7b8474e74e244ce76 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/base.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d37cab9e274f2bf60a7774b15b58350c9936ebdd Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/base.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/base.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f78ea8006b97acd54c5face1f47fb79d560a499d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/base.py @@ -0,0 +1,171 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Base classes for cache management strategies. +""" + +from abc import ABC, abstractmethod +from typing import Dict, Optional, Tuple +import torch + + +class CacheStrategy(ABC): + """ + Abstract base class for cache management strategies. + + All cache implementations should inherit from this class and implement + the required methods. + """ + + def __init__(self, enabled: bool = True): + """ + Initialize the cache strategy. + + Args: + enabled: Whether this cache strategy is enabled + """ + self.enabled = enabled + + @abstractmethod + def reset(self): + """ + Reset the cache state. + + This method should clear all internal state and prepare the cache + for a new inference run. + """ + pass + + def reset_if_enabled(self): + """Reset the cache if it is enabled.""" + if self.enabled: + self.reset() + + +class OutputCache(CacheStrategy): + """ + Abstract base class for output reuse strategies. + + Output caching strategies determine when model outputs can be reused + based on input similarity metrics. + """ + + @abstractmethod + def should_reuse( + self, + chunk_id: int, + step: int, + current_features: torch.Tensor, + **kwargs + ) -> bool: + """ + Determine whether the output for a chunk should be reused. + + Args: + chunk_id: The ID of the current chunk + step: The current denoising step + current_features: Feature tensor for the current input + **kwargs: Additional arguments specific to the implementation + + Returns: + True if the output should be reused, False otherwise + """ + pass + + @abstractmethod + def update_residual( + self, + chunk_id: int, + residual: torch.Tensor + ): + """ + Update the residual for a chunk. + + When outputs are reused, the residual from the previous step is + applied to the current input. + + Args: + chunk_id: The ID of the chunk + residual: The residual tensor to store + """ + pass + + @abstractmethod + def get_residual(self, chunk_id: int) -> Optional[torch.Tensor]: + """ + Get the stored residual for a chunk. + + Args: + chunk_id: The ID of the chunk + + Returns: + The residual tensor if available, None otherwise + """ + pass + + +class KVCompressor(CacheStrategy): + """ + Abstract base class for KV cache compression strategies. + + KV cache compression manages memory usage by selectively compressing + KV caches from completed chunks. + """ + + @abstractmethod + def should_compress( + self, + current_chunk_id: int, + cache_used: int, + cache_capacity: int, + **kwargs + ) -> bool: + """ + Determine whether KV cache compression should be triggered. + + Args: + current_chunk_id: The ID of the most recently completed chunk + cache_used: Current KV cache usage in tokens + cache_capacity: Total KV cache capacity in tokens + **kwargs: Additional arguments specific to the implementation + + Returns: + True if compression should be performed, False otherwise + """ + pass + + @abstractmethod + def compress( + self, + inference_params, + chunk_tracker, + clean_chunk_ids: list, + active_chunk_ids: list, + **kwargs + ) -> Dict[int, Tuple[int, int]]: + """ + Compress KV caches for specified chunks. + + Args: + inference_params: Inference parameters containing KV cache + chunk_tracker: Tracker managing chunk ranges + clean_chunk_ids: List of chunk IDs to compress + active_chunk_ids: List of chunk IDs to keep uncompressed + **kwargs: Additional arguments + + Returns: + Dictionary mapping chunk_id to (start, end) ranges after compression + """ + pass diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/cachereuse.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/cachereuse.py new file mode 100644 index 0000000000000000000000000000000000000000..43a9e61a175deb1567c293af749a99e2c759264f --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/cachereuse.py @@ -0,0 +1,602 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Cache reuse implementations for output optimization. + +This module provides two caching strategies: +- TeaCache: Full output reuse (all chunks together) +- ChunkWiseCache: Per-chunk output reuse (for FlowCache) +""" + +import json +import os + +from einops import rearrange +import torch +from typing import Dict, List, Optional, Tuple +from .base import OutputCache + + +class TeaCache(OutputCache): + """ + TeaCache implementation with full output reuse. + + This cache computes the relative L1 distance between current and previous + modulated inputs. When the accumulated distance is below threshold, the + output is reused and only the residual is applied. + + All chunks are treated as a single unit for reuse decisions. + + Attributes: + rel_l1_thresh: Threshold for relative L1 distance + warmup_steps: Number of warmup steps before reuse can happen + log: Whether to log reuse decisions + accumulated_rel_l1_distance: Accumulated relative L1 distance + previous_modulated_input: Previous input features + previous_residual: Previous residual for reuse + reuse_times: Number of times output was reused + previous_output: Output from previous stage + cnt: Current step counter + num_steps: Total number of steps + """ + + def __init__( + self, + rel_l1_thresh: float = 0.01, + warmup_steps: int = 0, + log: bool = False + ): + super().__init__(enabled=True) + self.rel_l1_thresh = rel_l1_thresh + self.warmup_steps = warmup_steps + self.log = log + + # State variables + self.accumulated_rel_l1_distance = 0.0 + self.previous_modulated_input = None + self.previous_residual = None + self.reuse_times = 0 + self.previous_output = None + self.cnt = 0 + self.num_steps = 0 + self.should_calc = True + + def reset(self): + """Reset all cache state.""" + self.accumulated_rel_l1_distance = 0.0 + self.previous_modulated_input = None + self.previous_residual = None + self.reuse_times = 0 + self.previous_output = None + self.cnt = 0 + self.should_calc = True + + def compute_feature_metric( + self, + x: torch.Tensor, + x_embedder, + x_rescale_factor: float, + half_channel_vae: bool, + params_dtype: torch.dtype + ) -> torch.Tensor: + """ + Compute feature metric from input tensor. + + Args: + x: Input tensor [N, C, T, H, W] + x_embedder: Model's x_embedder module + x_rescale_factor: Rescale factor for x + half_channel_vae: Whether VAE uses half channels + params_dtype: Model's parameter dtype for final conversion + + Returns: + Feature tensor of shape [(T*H*W), N, C] + """ + metric_x = x.clone() + metric_x = metric_x * x_rescale_factor + + if half_channel_vae: + assert metric_x.shape[1] == 16, "Expected 16 channels for half-channel VAE" + metric_x = torch.cat([metric_x, metric_x], dim=1) + + metric_x = metric_x.float() + metric_x = x_embedder(metric_x) + metric_x = metric_x.to(params_dtype) + metric_x = rearrange(metric_x, "N C T H W -> (T H W) N C").contiguous() + + return metric_x + + def should_reuse( + self, + chunk_id: int, + step: int, + current_features: torch.Tensor, + denoise_step_per_stage: int, + num_chunks_current: int, + num_chunks_previous: int, + **kwargs + ) -> bool: + """ + Determine whether to reuse output based on feature similarity. + + Args: + chunk_id: Current chunk ID (not used in simple mode) + step: Current denoising step + current_features: Current input features + denoise_step_per_stage: Steps per denoising stage + num_chunks_current: Number of chunks in current stage + num_chunks_previous: Number of chunks in previous stage + + Returns: + True if output should be reused, False if should calculate + """ + # Always calculate first and last steps, and during warmup + if self.cnt == 0 or self.cnt == self.num_steps - 1 or self.cnt < self.warmup_steps: + self.should_calc = True + self.accumulated_rel_l1_distance = 0 + if self.log: + print(f"Calculate output at step {self.cnt}") + return False + + # Compute feature difference + a1 = current_features.clone() + a2 = self.previous_modulated_input.clone() + + # Handle chunk count changes across stages + if self.cnt % denoise_step_per_stage == 0: + dim1 = a1.shape[0] + dim2 = a2.shape[0] + + if dim1 > dim2: + # Next stage has more chunks, truncate to match + a1 = a1[:dim2] + elif dim1 < dim2: + # Next stage has fewer chunks, take tail part + a2 = a2[-dim1:] + + # Compute relative L1 distance + rel_l1 = ((a1 - a2).abs().mean() / a2.abs().mean()).cpu().item() + self.accumulated_rel_l1_distance += rel_l1 + + # Decide whether to reuse + if self.accumulated_rel_l1_distance < self.rel_l1_thresh: + if self.cnt % denoise_step_per_stage == 0 and dim1 > dim2: + # Only calculate new chunk when crossing stage + self.should_calc = True + if self.log: + print(f"Partly reuse output at step {self.cnt}, only calculate new chunk") + return False + else: + # Full reuse + self.reuse_times += 1 + if self.log: + print(f"Reuse output at step {self.cnt}") + self.should_calc = False + return True + else: + # Threshold exceeded, recalculate + if self.log: + print(f"Calculate output at step {self.cnt}") + self.should_calc = True + self.accumulated_rel_l1_distance = 0 + return False + + def update_residual(self, chunk_id: int, residual: torch.Tensor): + """ + Update the residual for reuse. + + Args: + chunk_id: Chunk ID (not used in simple mode, residual applies to all) + residual: Residual tensor to store + """ + self.previous_residual = residual + + def get_residual(self, chunk_id: int) -> Optional[torch.Tensor]: + """ + Get the stored residual. + + Args: + chunk_id: Chunk ID (not used in simple mode) + + Returns: + The residual tensor or None + """ + return self.previous_residual + + def increment_step(self): + """Increment step counter and print statistics if done.""" + self.cnt += 1 + if self.cnt == self.num_steps: + print(f"Reuse output account for {self.reuse_times} / {self.num_steps} steps, " + f"ratio: {self.reuse_times / self.num_steps:.2%}") + self.cnt = 0 + + def store_previous_features(self, features: torch.Tensor): + """Store current features as previous for next step.""" + self.previous_modulated_input = features.clone() + + def get_previous_features(self) -> Optional[torch.Tensor]: + """Get the stored previous features.""" + return self.previous_modulated_input + + def prepare_for_next_stage(self): + """Store output for use in next stage.""" + pass # Handled in integrate_velocity + + +class ChunkWiseCache(OutputCache): + """ + Chunk-wise output cache implementation for FlowCache. + + This cache tracks reuse decisions separately for each chunk, allowing + finer-grained control over which chunks to skip. + + Attributes: + rel_l1_thresh: Threshold for relative L1 distance + warmup_steps: Number of warmup steps per chunk before reuse can happen + discard_nearly_clean_chunk: Whether to skip nearly-clean chunk + log: Whether to log reuse decisions + chunk_accumulated_rel_l1: Per-chunk accumulated L1 distance + chunk_reuse_flags: Per-chunk reuse flags for current step + prev_metric_chunks: Previous features per chunk + previous_residual: Per-chunk residuals + """ + + def __init__( + self, + rel_l1_thresh: float = 0.01, + warmup_steps: int = 0, + discard_nearly_clean_chunk: bool = False, + log: bool = False, + metric_stats_path: Optional[str] = None, + ): + super().__init__(enabled=True) + self.rel_l1_thresh = rel_l1_thresh + self.warmup_steps = warmup_steps + self.discard_nearly_clean_chunk = discard_nearly_clean_chunk + self.log = log + self.metric_stats_path = metric_stats_path + self.metric_records = [] + self.execution_records = [] + self.chunk_execution_counts: Dict[int, Dict[str, int]] = {} + + # State variables + self.chunk_accumulated_rel_l1: Dict[int, float] = {} + self.chunk_reuse_flags: Dict[int, bool] = {} + self.prev_metric_chunks: Dict[int, torch.Tensor] = {} + self.previous_residual: Dict[int, torch.Tensor] = {} + + self.cnt = 0 + self.num_steps = 0 + + def reset(self): + """Reset all cache state.""" + self.chunk_accumulated_rel_l1.clear() + self.chunk_reuse_flags.clear() + self.prev_metric_chunks.clear() + self.previous_residual.clear() + self.metric_records.clear() + self.execution_records.clear() + self.chunk_execution_counts.clear() + self.cnt = 0 + + def initialize_chunk_state(self, chunk_num: int): + """Initialize state for all chunks.""" + if len(self.chunk_accumulated_rel_l1) != chunk_num: + self.chunk_accumulated_rel_l1 = {i: 0.0 for i in range(chunk_num)} + self.previous_residual = {i: None for i in range(chunk_num)} + + # Reset reuse flags for each step + self.chunk_reuse_flags = {i: False for i in range(chunk_num)} + + def compute_feature_metric( + self, + x: torch.Tensor, + x_embedder, + x_rescale_factor: float, + half_channel_vae: bool, + chunk_token_nums: int, + params_dtype: torch.dtype, + offset: int = 0, + fwd_extra_1st_chunk: bool = False, + distill_nearly_clean_chunk: bool = False + ) -> Tuple[Dict[int, torch.Tensor], int]: + """ + Compute feature metric for each chunk. + + Following source code logic: + 1. Compute metric_x from input x + 2. Handle fwd_extra_1st_chunk: slice off first chunk if needed + 3. Handle distill_nearly_clean_chunk: slice off last chunk if needed + 4. Split into chunks + + Args: + x: Input tensor [N, C, T, H, W] + x_embedder: Model's x_embedder module + x_rescale_factor: Rescale factor for x + half_channel_vae: Whether VAE uses half channels + chunk_token_nums: Number of tokens per chunk + params_dtype: Model's parameter dtype for final conversion + offset: Offset for chunk_id (to match x_chunks indexing) + fwd_extra_1st_chunk: Whether to slice off first chunk (always False) + distill_nearly_clean_chunk: Whether to slice off last chunk + + Returns: + Tuple of (metric_chunks dict, num_chunks_for_x) + """ + from einops import rearrange + + # 1. Compute metric_x from input x + metric_x = x.clone() + metric_x = metric_x * x_rescale_factor + + if half_channel_vae: + assert metric_x.shape[1] == 16 + metric_x = torch.cat([metric_x, metric_x], dim=1) + + metric_x = metric_x.float() + metric_x = x_embedder(metric_x) + metric_x = metric_x.to(params_dtype) + metric_x = rearrange(metric_x, "N C T H W -> (T H W) N C").contiguous() + + # 2. Handle fwd_extra_1st_chunk: slice off first chunk if needed + # Note: fwd_extra_1st_chunk is always False in current implementation + if fwd_extra_1st_chunk: + metric_x = metric_x[chunk_token_nums:, :, :] + + # 3. Handle distill_nearly_clean_chunk: slice off last chunk if needed + if distill_nearly_clean_chunk: + metric_x = metric_x[:-chunk_token_nums, :, :] + + # 4. Split into chunks + assert metric_x.shape[0] % chunk_token_nums == 0 + num_chunks = metric_x.shape[0] // chunk_token_nums + + metric_chunks = {} + for i in range(num_chunks): + start = i * chunk_token_nums + end = start + chunk_token_nums + metric_chunks[offset + i] = metric_x[start:end] + + # Return num_chunks for x_chunks iteration (matching source code) + return metric_chunks, num_chunks + + def should_reuse( + self, + chunk_id: int, + step: int, + current_features: torch.Tensor, + chunk_denoise_count: Dict[int, int], + current_num_chunks: int, + previous_num_chunks: int, + **kwargs + ) -> bool: + """ + Determine whether to reuse output for a specific chunk. + + Args: + chunk_id: The chunk ID to check + step: Current denoising step + current_features: Current features for all chunks + chunk_denoise_count: Denoising steps completed per chunk + current_num_chunks: Number of chunks in current stage + previous_num_chunks: Number of chunks in previous stage + + Returns: + True if output should be reused, False otherwise + """ + # First and last steps always calculate + if self.cnt == 0 or self.cnt == self.num_steps - 1: + self.record_metric_decision(chunk_id, step, None, None, False, "first_or_last_step", **kwargs) + return False + + # Check if chunk exists in both current and previous + if chunk_id not in current_features or chunk_id not in self.prev_metric_chunks: + self.record_metric_decision(chunk_id, step, None, None, False, "missing_previous_features", **kwargs) + return False + + # Apply warmup: skip reuse during warmup period + if self._should_skip_reuse(chunk_id, chunk_denoise_count): + self.chunk_accumulated_rel_l1[chunk_id] = 0.0 + self.record_metric_decision(chunk_id, step, None, 0.0, False, "warmup", **kwargs) + return False + + # Compute relative L1 distance + curr_feat = current_features[chunk_id] + prev_feat = self.prev_metric_chunks[chunk_id] + + diff = (curr_feat - prev_feat).abs().mean() + denom = prev_feat.abs().mean() + 1e-8 + rel_l1 = (diff / denom).item() + delta_l1_norm = (curr_feat - prev_feat).abs().sum().item() + prev_feat_l1_norm = prev_feat.abs().sum().item() + rel_l1_ratio = delta_l1_norm / max(prev_feat_l1_norm, 1e-8) + + # Accumulate and check threshold + accumulated = self.chunk_accumulated_rel_l1[chunk_id] + rel_l1 + + if accumulated < self.rel_l1_thresh: + self.chunk_accumulated_rel_l1[chunk_id] = accumulated + self.chunk_reuse_flags[chunk_id] = True + self.record_metric_decision( + chunk_id, step, rel_l1, accumulated, True, "below_threshold", + delta_l1_norm=delta_l1_norm, + prev_feat_l1_norm=prev_feat_l1_norm, + rel_l1_ratio=rel_l1_ratio, + **kwargs, + ) + return True + else: + self.chunk_accumulated_rel_l1[chunk_id] = 0.0 + self.chunk_reuse_flags[chunk_id] = False + self.record_metric_decision( + chunk_id, step, rel_l1, accumulated, False, "threshold_exceeded", + delta_l1_norm=delta_l1_norm, + prev_feat_l1_norm=prev_feat_l1_norm, + rel_l1_ratio=rel_l1_ratio, + **kwargs, + ) + return False + + def record_metric_decision( + self, + chunk_id: int, + step: int, + rel_l1: Optional[float], + accumulated_rel_l1: Optional[float], + reused: bool, + decision_reason: str, + **kwargs + ): + if not self.metric_stats_path: + return + + chunk_offset = kwargs.get("chunk_offset", 0) + record = { + "infer_idx": kwargs.get("infer_idx"), + "cur_denoise_step": kwargs.get("cur_denoise_step", step), + "denoise_stage": kwargs.get("denoise_stage"), + "denoise_idx": kwargs.get("denoise_idx"), + "chunk_idx": chunk_id, + "generated_chunk_idx": chunk_id - chunk_offset, + "chunk_denoise_count": kwargs.get("chunk_denoise_count_value"), + "flowcache_rel_l1": rel_l1, + "flowcache_rel_l1_ratio": kwargs.get("rel_l1_ratio"), + "flowcache_delta_l1_norm": kwargs.get("delta_l1_norm"), + "flowcache_prev_feat_l1_norm": kwargs.get("prev_feat_l1_norm"), + "flowcache_accumulated_rel_l1": accumulated_rel_l1, + "rel_l1_thresh": self.rel_l1_thresh, + "reused": bool(reused), + "decision_reason": decision_reason, + } + self.metric_records.append(record) + + def record_actual_execution( + self, + chunk_id: int, + reused: bool, + **kwargs + ): + stats = self.chunk_execution_counts.setdefault( + chunk_id, + {"reuse_steps": 0, "compute_steps": 0, "total_steps": 0}, + ) + if reused: + stats["reuse_steps"] += 1 + else: + stats["compute_steps"] += 1 + stats["total_steps"] += 1 + + if not self.metric_stats_path: + return + + chunk_offset = kwargs.get("chunk_offset", 0) + self.execution_records.append({ + "infer_idx": kwargs.get("infer_idx"), + "cur_denoise_step": kwargs.get("cur_denoise_step"), + "denoise_stage": kwargs.get("denoise_stage"), + "denoise_idx": kwargs.get("denoise_idx"), + "chunk_idx": chunk_id, + "generated_chunk_idx": chunk_id - chunk_offset, + "reused": bool(reused), + "execution": "reuse" if reused else "compute", + }) + + def get_execution_summary(self): + summary = {} + for chunk_id, stats in sorted(self.chunk_execution_counts.items()): + total_steps = stats["total_steps"] + reuse_steps = stats["reuse_steps"] + compute_steps = stats["compute_steps"] + summary[str(chunk_id)] = { + "chunk_idx": chunk_id, + "reuse_steps": reuse_steps, + "compute_steps": compute_steps, + "total_steps": total_steps, + "reuse_rate": reuse_steps / total_steps if total_steps else 0.0, + "compute_rate": compute_steps / total_steps if total_steps else 0.0, + } + return summary + + def _should_skip_reuse( + self, + chunk_id: int, + chunk_denoise_count: Dict[int, int] + ) -> bool: + """ + Check if reuse should be skipped for this chunk. + + During warmup period, chunks are always recalculated. + + Args: + chunk_id: Chunk to check + chunk_denoise_count: Steps completed per chunk + + Returns: + True if should skip reuse (i.e., in warmup period) + """ + return chunk_denoise_count[chunk_id] < self.warmup_steps + + def update_residual(self, chunk_id: int, residual: torch.Tensor): + """Update the residual for a specific chunk.""" + self.previous_residual[chunk_id] = residual + + def get_residual(self, chunk_id: int) -> Optional[torch.Tensor]: + """Get the stored residual for a chunk.""" + return self.previous_residual.get(chunk_id) + + def store_previous_features(self, metric_chunks: Dict[int, torch.Tensor]): + """Store current features as previous for next step.""" + self.prev_metric_chunks = { + i: f.clone().detach() for i, f in metric_chunks.items() + } + + def increment_step(self): + """Increment step counter.""" + self.cnt += 1 + if self.cnt == self.num_steps: + self.cnt = 0 + + def set_total_steps(self, num_steps: int): + """Set total number of steps.""" + self.num_steps = num_steps + + def save_metric_stats(self): + if not self.metric_stats_path: + return + save_dir = os.path.dirname(self.metric_stats_path) + if save_dir: + os.makedirs(save_dir, exist_ok=True) + + payload = { + "description": ( + "FlowCache original per-chunk reuse metric. flowcache_rel_l1 = " + "mean(abs(x_embedder(X_t_current) - x_embedder(X_t_previous))) / " + "(mean(abs(x_embedder(X_t_previous))) + 1e-8). " + "flowcache_rel_l1_ratio = sum(abs(delta)) / sum(abs(previous_feature)); " + "flowcache_accumulated_rel_l1 is the accumulated value compared with rel_l1_thresh. " + "chunk_execution_summary is counted at the actual integrate step and includes every " + "per-chunk reuse or compute execution." + ), + "chunk_execution_summary": self.get_execution_summary(), + "execution_records": self.execution_records, + "records": self.metric_records, + } + if self.metric_stats_path.endswith((".pt", ".pth")): + torch.save(payload, self.metric_stats_path) + else: + with open(self.metric_stats_path, "w") as f: + json.dump(payload, f, indent=2) + print(f"Saved FlowCache metric stats to {self.metric_stats_path}") diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/kv_compressor.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/kv_compressor.py new file mode 100644 index 0000000000000000000000000000000000000000..7bd43d2b864f1f1f478542525bd2014c8c572772 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/kv_compressor.py @@ -0,0 +1,390 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +KV Cache Compression module. +""" + +import torch +from typing import Dict, List, Optional, Tuple, Any +from .base import KVCompressor +from .utils import ( + identify_compressible_chunks, + check_compress_condition, + get_latent_spatial_dims, +) + + +class KVCacheCompressor(KVCompressor): + """ + Manages KV cache compression for memory-efficient inference. + + This compressor identifies clean chunks (completed denoising) and compresses + their KV caches using the configured compression strategy (e.g., R1KV). + + Attributes: + total_cache_len: Total cache capacity in tokens + tokens_per_chunk: Number of tokens per chunk + budget_cache_len: Target cache size after compression + compression_config: Configuration for compression strategy + kv_compressed: Whether compression has been performed + chunk_query_states: Query states for each layer (used for compression) + """ + + def __init__( + self, + total_cache_len: int, + tokens_per_chunk: int, + budget_chunk_nums: int, + window_size: int = 4, + compression_config: Optional[Dict[str, Any]] = None + ): + """ + Initialize the KV cache compressor. + + Args: + total_cache_len: Total cache capacity in tokens + tokens_per_chunk: Number of tokens per chunk + budget_chunk_nums: Target number of chunks after compression + window_size: Window size for denoising stages + compression_config: Configuration for compression strategy + """ + super().__init__(enabled=True) + self.total_cache_len = total_cache_len + self.tokens_per_chunk = tokens_per_chunk + self.budget_cache_len = (budget_chunk_nums - 1) * tokens_per_chunk + self.window_size = window_size + self.compression_config = compression_config or {} + + self.kv_compressed = False + self.chunk_query_states: Dict[int, torch.Tensor] = {} + + def reset(self): + """Reset compression state.""" + self.kv_compressed = False + self.chunk_query_states.clear() + + def should_compress( + self, + tracker, + chunk_num: int, + chunk_start: int, + transport_input, + chunk_denoise_count: Dict[int, int], + **kwargs + ) -> bool: + """ + Check if compression should be triggered. + + Args: + tracker: ChunkKVRangeTracker instance + chunk_num: Total number of chunks + chunk_start: Current chunk being processed + transport_input: Transport input + chunk_denoise_count: Denoising steps per chunk + + Returns: + True if compression should be performed + """ + return check_compress_condition( + tracker=tracker, + total_cache_len=self.total_cache_len, + chunk_num=chunk_num, + chunk_start=chunk_start, + transport_input=transport_input, + chunk_denoise_count=chunk_denoise_count, + window_size=self.window_size + ) + + def compress( + self, + model, + inference_params, + tracker, + transport_input, + chunk_start: int, + chunk_denoise_count: Dict[int, int], + query_states_dict: Optional[Dict[int, torch.Tensor]] = None, + **kwargs + ) -> Dict[int, Tuple[int, int]]: + """ + Perform KV cache compression. + + Args: + model: DiT model with videodit_blocks + inference_params: Inference parameters containing KV cache + tracker: ChunkKVRangeTracker instance + transport_input: Transport input + chunk_start: Current chunk being processed + chunk_denoise_count: Denoising steps per chunk + + Returns: + Dictionary mapping chunk_id to (start, end) ranges after compression + """ + # Identify chunks to compress + chunk_offset = self._get_chunk_offset(transport_input) + clean_chunk_ids, active_chunk_ids = identify_compressible_chunks( + tracker=tracker, + chunk_start=chunk_start, + transport_input=transport_input, + chunk_denoise_count=chunk_denoise_count, + chunk_offset=chunk_offset + ) + + if len(clean_chunk_ids) < 2: + # Need at least 2 chunks to compress + return {} + + # Compress for each layer + final_chunk_ids = [] + final_lengths = [] + + for layer in model.videodit_blocks.layers: + if not hasattr(layer.self_attention, 'kv_cluster'): + continue + + # import pdb; pdb.set_trace() + layer_result = self._compress_layer( + layer=layer, + inference_params=inference_params, + tracker=tracker, + clean_chunk_ids=clean_chunk_ids, + active_chunk_ids=active_chunk_ids, + transport_input=transport_input, + query_states_dict=query_states_dict + ) + + # Store result from first layer for chunk metadata + if layer.self_attention.layer_number == 0: + final_chunk_ids = layer_result['chunk_ids'] + final_lengths = layer_result['lengths'] + + # Update tracker ranges (shared across layers) + new_ranges = self._compute_new_ranges( + final_chunk_ids, final_lengths + ) + tracker.update_ranges_after_compression(new_ranges) + + # Mark as compressed + self.kv_compressed = True + + return new_ranges + + def _compress_layer( + self, + layer, + inference_params, + tracker, + clean_chunk_ids: List[int], + active_chunk_ids: List[int], + transport_input, + query_states_dict: Optional[Dict[int, torch.Tensor]] = None + ) -> Dict[str, Any]: + """ + Compress KV cache for a single layer. + + Args: + layer: Transformer layer + inference_params: Inference parameters + tracker: ChunkKVRangeTracker + clean_chunk_ids: Chunks to compress + active_chunk_ids: Chunks to keep uncompressed + transport_input: Transport input + query_states_dict: Query states for each layer (from transport) + + Returns: + Dictionary with compression results + """ + kv_cluster = layer.self_attention.kv_cluster + layer_num = layer.self_attention.layer_number + + # Extract KV caches for clean chunks + clean_kv_list = [] + clean_lengths = [] + for cid in clean_chunk_ids: + s, e = tracker.get_range(cid) + chunk_kv = inference_params.key_value_memory_dict[layer_num][s:e, ...] + clean_kv_list.append(chunk_kv) + clean_lengths.append(e - s) + + # Concatenate and split into key and value + clean_kv = torch.cat(clean_kv_list, dim=0) + key_clean, value_clean = torch.chunk(clean_kv, 2, dim=-1) + + # Extract KV caches for active chunks + active_kv_list = [] + active_lengths = [] + for cid in active_chunk_ids: + s, e = tracker.get_range(cid) + chunk_kv = inference_params.key_value_memory_dict[layer_num][s:e, ...] + active_kv_list.append(chunk_kv) + active_lengths.append(e - s) + + # Get query states for compression + query_states = query_states_dict.get(layer_num) if query_states_dict else None + if query_states is None: + raise RuntimeError(f"Query states not available for layer {layer_num}") + + # Set compression budget + total_clean_tokens = sum(clean_lengths) + kv_cluster.budget = max( + total_clean_tokens - self.tokens_per_chunk, + self.tokens_per_chunk + ) + + # Get latent dimensions + H, W = get_latent_spatial_dims(transport_input, layer.model_config) + T = self.tokens_per_chunk // (H * W) + + # Perform compression + key_compressed, value_compressed, indices = kv_cluster.update_kv( + key_states=key_clean, + query_states=query_states, + value_states=value_clean, + clean_chunk_tokens=total_clean_tokens, + latent_size_t=T, + latent_size_h=H, + latent_size_w=W, + ) + + # Reassemble KV cache + final_kv_parts = [] + final_chunk_ids = [] + final_lengths = [] + + # Add compressed part + compressed_kv = torch.cat([key_compressed, value_compressed], dim=-1) + final_kv_parts.append(compressed_kv) + + # Compute compressed lengths per chunk + all_lengths_after_compress = self._compute_compressed_lengths( + indices, clean_chunk_ids, clean_lengths, total_clean_tokens + ) + final_chunk_ids.extend(clean_chunk_ids) + final_lengths.extend(all_lengths_after_compress) + + # Add active (uncompressed) chunks + for i, chunk_kv in enumerate(active_kv_list): + final_kv_parts.append(chunk_kv) + final_chunk_ids.append(active_chunk_ids[i]) + final_lengths.append(active_lengths[i]) + + # Concatenate and update KV cache + final_kv = torch.cat(final_kv_parts, dim=0) + total_kv_len = final_kv.size(0) + + inference_params.key_value_memory_dict[layer_num][:total_kv_len, ...] = final_kv + inference_params.key_value_memory_dict[layer_num][total_kv_len:, ...] = 0.0 + + return { + 'chunk_ids': final_chunk_ids, + 'lengths': final_lengths + } + + def _compute_compressed_lengths( + self, + indices: torch.Tensor, + clean_chunk_ids: List[int], + clean_lengths: List[int], + total_clean_tokens: int + ) -> List[int]: + """ + Compute the compressed length for each chunk. + + Args: + indices: Selected token indices [num_to_keep, num_kv_heads, head_dim] + clean_chunk_ids: IDs of chunks that were compressed + clean_lengths: Original lengths of compressed chunks + total_clean_tokens: Total tokens before compression + + Returns: + List of compressed lengths per chunk + """ + # TODO: This has an issue - different heads keep different ranges + # But it's fine since we attend to all previous chunks' KV cache + indices_1d = indices[:, 0, 0] # shape: (num_to_keep,) + + all_lengths_after_compress = [] + start_idx = 0 + + for chunk_len in clean_lengths: + end_idx = start_idx + chunk_len + # Count selected tokens in this chunk's range + mask = (indices_1d >= start_idx) & (indices_1d < min(end_idx, total_clean_tokens)) + kept_in_chunk = mask.sum().item() + all_lengths_after_compress.append(kept_in_chunk) + start_idx = end_idx + + return all_lengths_after_compress + + def _compute_new_ranges( + self, + chunk_ids: List[int], + lengths: List[int] + ) -> Dict[int, Tuple[int, int]]: + """ + Compute new chunk ranges after compression. + + Args: + chunk_ids: List of chunk IDs in order + lengths: Compressed lengths for each chunk + + Returns: + Dictionary mapping chunk_id to (start, end) range + """ + new_ranges = {} + current_start = 0 + + for cid, length in zip(chunk_ids, lengths): + new_end = current_start + length + new_ranges[cid] = (current_start, new_end) + current_start = new_end + + return new_ranges + + def _get_chunk_offset(self, transport_input) -> int: + """ + Get the number of prefix video chunks. + + Args: + transport_input: Transport input + + Returns: + Number of prefix video chunks + """ + if transport_input.prefix_video is not None: + return transport_input.prefix_video.size(2) // transport_input.chunk_width + return 0 + + def store_query_states(self, layer_num: int, query_states: torch.Tensor): + """ + Store query states for later compression. + + Args: + layer_num: Layer number + query_states: Query tensor to store + """ + self.chunk_query_states[layer_num] = query_states + + def get_query_states(self, layer_num: int) -> Optional[torch.Tensor]: + """ + Get stored query states for a layer. + + Args: + layer_num: Layer number + + Returns: + Query tensor or None if not available + """ + return self.chunk_query_states.get(layer_num) diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/utils.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7a83cf9781d9df9041cc5e225f0cc3d20810bbb2 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/utils.py @@ -0,0 +1,390 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Utility functions for cache management. +""" + +import math +import torch +from typing import Dict, List, Tuple, Optional, Any +from inference.common import PackedCrossAttnParams + + +def generate_dynamic_kv_range( + tracker, + current_chunk_id: int, + x_chunks_keys: List[int], + chunk_token_nums: int, + near_clean_chunk_idx: int = -1 +) -> torch.Tensor: + """ + Generate dynamic KV ranges for chunks after compression. + + This function computes the KV range each chunk should attend to, + taking into account the compressed KV cache layout. + + Args: + tracker: ChunkKVRangeTracker instance managing chunk ranges + current_chunk_id: The chunk being processed + x_chunks_keys: List of all chunk keys being processed + chunk_token_nums: Number of tokens per chunk + near_clean_chunk_idx: Index of the nearly-clean chunk (-1 if not present) + + Returns: + Tensor of shape [num_chunks, 2] with KV ranges for each chunk + """ + kv_ranges = [] + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + # Process normal chunks (excluding near_clean_chunk) + normal_chunks = [chunk_id for chunk_id in x_chunks_keys if chunk_id != near_clean_chunk_idx] + + for chunk_id in normal_chunks: + # Normal chunk: needs to see itself and all previous chunks + all_chunk_ids = tracker.get_all_chunk_ids() + list(normal_chunks) + chunks_to_include = [cid for cid in all_chunk_ids if cid <= chunk_id] + + # Calculate based on actual compressed ranges in tracker + total_tokens = 0 + for cid in chunks_to_include: + if cid in tracker.get_all_chunk_ids(): + # Use compressed actual range + s, e = tracker.get_range(cid) + total_tokens = max(total_tokens, e) + else: + # Newly entered chunk not yet registered, but size is known + total_tokens += chunk_token_nums + + range_start = 0 + range_end = total_tokens + kv_ranges.append([range_start, range_end]) + + # Handle near_clean_chunk (always last if present) + if near_clean_chunk_idx != -1: + # Calculate end position of last normal chunk + last_normal_chunk_end = 0 + all_chunk_ids = tracker.get_all_chunk_ids() + normal_chunks + for cid in all_chunk_ids: + if cid in tracker.get_all_chunk_ids(): + s, e = tracker.get_range(cid) + last_normal_chunk_end = max(last_normal_chunk_end, e) + else: + # Newly entered chunk not yet registered + last_normal_chunk_end += chunk_token_nums + + # near_clean_chunk range: (last_normal_chunk_end, last_normal_chunk_end + chunk_token_nums] + range_start = last_normal_chunk_end + range_end = last_normal_chunk_end + chunk_token_nums + kv_ranges.append([range_start, range_end]) + + return torch.tensor(kv_ranges, device=device, dtype=torch.int32) + + +def identify_compressible_chunks( + tracker, + chunk_start: int, + transport_input, + chunk_denoise_count: Dict[int, int], + chunk_offset: int = 0 +) -> Tuple[List[int], List[int]]: + """ + Identify which chunks can be compressed and which should remain active. + + A chunk can be compressed if: + - It's a prefix video chunk (always clean) + - It's a generated chunk that has completed all denoising steps + + Args: + tracker: ChunkKVRangeTracker instance + chunk_start: Current chunk being processed + transport_input: Transport input containing chunk info + chunk_denoise_count: Dictionary mapping chunk_id to denoising steps completed + chunk_offset: Number of prefix video chunks + + Returns: + Tuple of (clean_chunk_ids, active_chunk_ids) + """ + all_chunk_ids = tracker.get_all_chunk_ids() + + clean_chunks = [] + for cid in all_chunk_ids: + if cid < chunk_offset: + # Prefix video chunks are always clean + clean_chunks.append(cid) + elif cid <= chunk_start: + # Generated chunks need to check denoising completion + if chunk_denoise_count[cid] == transport_input.num_steps: + clean_chunks.append(cid) + + active_chunks = [cid for cid in all_chunk_ids if cid not in clean_chunks] + + return clean_chunks, active_chunks + + +def check_compress_condition( + tracker, + total_cache_len: int, + chunk_num: int, + chunk_start: int, + transport_input, + chunk_denoise_count: Dict[int, int], + window_size: int = 4 +) -> bool: + """ + Check if KV cache compression should be triggered. + + Compression is triggered when: + 1. Cache is full (next_free_idx >= total_cache_len) + 2. More chunks are yet to enter (registered_count < chunk_num) + 3. Next chunk is about to enter (last chunk's steps == num_steps/window_size) + + Args: + tracker: ChunkKVRangeTracker instance + total_cache_len: Total cache capacity in tokens + chunk_num: Total number of chunks + chunk_start: Current chunk being processed + transport_input: Transport input containing parameters + chunk_denoise_count: Dictionary mapping chunk_id to denoising steps + window_size: Window size for denoising stages (default: 4) + + Returns: + True if compression should be performed, False otherwise + """ + all_chunk_ids = tracker.get_all_chunk_ids() + if len(all_chunk_ids) == 0: + return False + + registered_chunk_count = len(all_chunk_ids) + cache_full = tracker.next_free_idx >= total_cache_len + has_more_chunks = registered_chunk_count < chunk_num + last_chunk_id = all_chunk_ids[-1] + + # Calculate steps per stage + steps_per_stage = transport_input.num_steps // window_size + next_chunk_will_enter = chunk_denoise_count[last_chunk_id] == steps_per_stage + + should_compress = cache_full and has_more_chunks and next_chunk_will_enter + return should_compress + + +def get_embedding_and_meta_with_chunk_info( + model_self, + x: torch.Tensor, + t: torch.Tensor, + y: torch.Tensor, + caption_dropout_mask, + xattn_mask, + kv_range: torch.Tensor, + **kwargs +) -> tuple: + """ + Compute embeddings and meta information with chunk-aware processing. + + This is a unified version of the get_embedding_and_meta function that + properly handles chunk-based processing with dynamic KV ranges. + + Args: + model_self: The DiT model instance + x: Input tensor [N, C, T, H, W] + t: Timestep tensor [N, range_num] + y: Text conditioning tensor + caption_dropout_mask: Dropout mask for captions + xattn_mask: Cross-attention mask + kv_range: KV range tensor + **kwargs: Additional arguments including: + - range_num: Total number of chunks + - denoising_range_num: Number of chunks being denoised + - slice_point: Starting chunk index + - start_chunk_id: First chunk to process + - end_chunk_id: Last chunk to process (exclusive) + - distill_nearly_clean_chunk: Whether to add nearly-clean chunk + - chunk_token_nums: Tokens per chunk + - chunk_width: Width of each chunk in frames + - num_steps: Total denoising steps + + Returns: + Tuple of (x, condition, condition_map, rope, y_xattn_flat, xattn_mask_cuda, + H, W, ardf_meta, cross_attn_params) + """ + # ========== Part 1: Embed x ========== + x = model_self.x_embedder(x) # [N, C, T, H, W] + batch_size, _, T, H, W = x.shape + + # Prepare necessary variables + range_num = kwargs["range_num"] + denoising_range_num = kwargs["denoising_range_num"] + slice_point = kwargs.get("slice_point", 0) + frame_in_range = T // denoising_range_num + + # distill_nearly_clean_chunk adds one extra chunk + T_total = (range_num + kwargs.get("distill_nearly_clean_chunk", False)) * frame_in_range + + # ========== Part 2: Compute rotary positional embedding ========== + rescale_factor = math.sqrt((H * W) / (16 * 16)) + rope = model_self.rope.get_embed( + shape=[T_total, H, W], + ref_feat_shape=[T_total, H / rescale_factor, W / rescale_factor] + ) + # Rope shape: (T*H*W, head_dim) - cut to current chunk range + rope = rope[ + kwargs["start_chunk_id"] * frame_in_range * H * W : + kwargs["end_chunk_id"] * frame_in_range * H * W + ] + + # ========== Part 3: Embed t ========== + assert t.shape[0] == batch_size, f"Invalid t shape: {t.shape[0]} != {batch_size}" + assert t.shape[1] == denoising_range_num, f"Invalid t shape: {t.shape[1]} != {denoising_range_num}" + + t_flat = t.flatten() # (N * denoising_range_num,) + t = model_self.t_embedder(t_flat) # (N, D) + + if model_self.engine_config.distill: + distill_dt_scalar = 2 + if kwargs["num_steps"] == 12: + base_chunk_step = 4 + distill_dt_factor = base_chunk_step / kwargs["distill_interval"] * distill_dt_scalar + else: + distill_dt_factor = kwargs["num_steps"] / 4 * distill_dt_scalar + + distill_dt = torch.ones_like(t_flat) * distill_dt_factor + distill_dt_embed = model_self.t_embedder(distill_dt) + t = t + distill_dt_embed + + t = t.reshape(batch_size, denoising_range_num, -1) # (N, range_num, D) + + # ========== Part 4: Embed y, prepare condition and y_xattn_flat ========== + y_xattn, y_adaln = model_self.y_embedder(y, model_self.training, caption_dropout_mask) + + assert xattn_mask is not None + xattn_mask = xattn_mask.squeeze(1).squeeze(1) + + # condition: (N, range_num, D) + y_adaln = y_adaln.squeeze(1) # (N, D) + condition = t + y_adaln.unsqueeze(1) + + assert condition.shape[0] == batch_size + assert condition.shape[1] == denoising_range_num + + seqlen_per_chunk = (T * H * W) // denoising_range_num + condition_map = torch.arange(batch_size * denoising_range_num, device=x.device) + condition_map = torch.repeat_interleave(condition_map, seqlen_per_chunk) + condition_map = condition_map.reshape(batch_size, -1).transpose(0, 1).contiguous() + + # y_xattn_flat: (total_token, D) + y_xattn_flat = torch.masked_select( + y_xattn.squeeze(1), + xattn_mask.unsqueeze(-1).bool() + ).reshape(-1, y_xattn.shape[-1]) + + xattn_mask_for_cuda_graph = None + + # ========== Part 5: Prepare cross_attn_params ========== + xattn_mask = xattn_mask.reshape(xattn_mask.shape[0], -1) + y_index = torch.sum(xattn_mask, dim=-1) + clip_token_nums = H * W * frame_in_range + + cu_seqlens_q = torch.Tensor( + [0] + ([clip_token_nums] * denoising_range_num * batch_size) + ).to(torch.int64).to(x.device) + cu_seqlens_k = torch.cat( + [y_index.new_tensor([0]), y_index] + ).to(torch.int64).to(x.device) + cu_seqlens_q = cu_seqlens_q.cumsum(-1).to(torch.int32) + cu_seqlens_k = cu_seqlens_k.cumsum(-1).to(torch.int32) + + assert cu_seqlens_q.shape == cu_seqlens_k.shape, \ + f"cu_seqlens_q.shape: {cu_seqlens_q.shape}, cu_seqlens_k.shape: {cu_seqlens_k.shape}" + + xattn_q_ranges = torch.cat( + [cu_seqlens_q[:-1].unsqueeze(1), cu_seqlens_q[1:].unsqueeze(1)], dim=1 + ) + xattn_k_ranges = torch.cat( + [cu_seqlens_k[:-1].unsqueeze(1), cu_seqlens_k[1:].unsqueeze(1)], dim=1 + ) + assert xattn_q_ranges.shape == xattn_k_ranges.shape, \ + f"xattn_q_ranges.shape: {xattn_q_ranges.shape}, xattn_k_ranges.shape: {xattn_k_ranges.shape}" + + cross_attn_params = PackedCrossAttnParams( + q_ranges=xattn_q_ranges, + kv_ranges=xattn_k_ranges, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=cu_seqlens_k, + max_seqlen_q=clip_token_nums, + max_seqlen_kv=model_self.caption_max_length, + ) + + # ========== Part 6: Prepare core_attn related q/kv range ========== + q_range = torch.cat( + [cu_seqlens_q[:-1].unsqueeze(1), cu_seqlens_q[1:].unsqueeze(1)], dim=1 + ) + flat_kv = torch.unique(kv_range, sorted=True) + max_seqlen_k = (flat_kv[-1] - flat_kv[0]).cpu().item() + + ardf_meta = dict( + clip_token_nums=clip_token_nums, + slice_point=slice_point, + range_num=range_num, + denoising_range_num=denoising_range_num, + q_range=q_range, + k_range=kv_range, + max_seqlen_q=clip_token_nums, + max_seqlen_k=max_seqlen_k, + ) + + return (x, condition, condition_map, rope, y_xattn_flat, + xattn_mask_for_cuda_graph, H, W, ardf_meta, cross_attn_params) + + +def compute_chunk_token_nums( + transport_input, + model_config, + chunk_width: int +) -> int: + """ + Calculate the number of tokens in one chunk. + + Args: + transport_input: Transport input containing latent dimensions + model_config: Model configuration + chunk_width: Number of frames per chunk + + Returns: + Number of tokens per chunk + """ + patch_size = model_config.patch_size + latent_h = transport_input.latent_size[3] // patch_size + latent_w = transport_input.latent_size[4] // patch_size + + return chunk_width * latent_h * latent_w + + +def get_latent_spatial_dims( + transport_input, + model_config +) -> Tuple[int, int]: + """ + Get the spatial dimensions of latent in patch units. + + Args: + transport_input: Transport input containing latent dimensions + model_config: Model configuration + + Returns: + Tuple of (height_patches, width_patches) + """ + patch_size = model_config.patch_size + h = transport_input.latent_size[3] // patch_size + w = transport_input.latent_size[4] // patch_size + return h, w diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/entry.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/entry.py new file mode 100644 index 0000000000000000000000000000000000000000..353b77d959dc64a99c49797f256c53c4d5e63020 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/entry.py @@ -0,0 +1,117 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import gc +import sys + +import torch + +from inference.pipeline import MagiPipeline + + +def parse_arguments(): + parser = argparse.ArgumentParser(description="Run MagiPipeline with different modes.") + parser.add_argument('--config_file', type=str, help='Path to the configuration file.') + parser.add_argument( + '--mode', type=str, choices=['t2v', 'i2v', 'v2v'], required=True, help='Mode to run: t2v, i2v, or v2v.' + ) + parser.add_argument('--prompt', type=str, required=True, help='Prompt for the pipeline.') + parser.add_argument('--image_path', type=str, help='Path to the image file (for i2v mode).') + parser.add_argument('--prefix_video_path', type=str, help='Path to the prefix video file (for v2v mode).') + parser.add_argument('--output_path', type=str, required=True, help='Path to save the output video.') + parser.add_argument( + '--residual_stats_path', + type=str, + help='Optional path to save per-chunk residual-difference norm stats as .json, .pt, or .pth.', + ) + parser.add_argument( + '--l1_rel_stats_path', + type=str, + help='Optional path to save per-chunk relative L1 change stats as .json, .pt, or .pth.', + ) + parser.add_argument( + '--token_l2_change_rate_stats_path', + type=str, + help='Optional path to save per-token L2 norm change-rate stats for one chunk as .json, .pt, or .pth.', + ) + parser.add_argument( + '--token_l2_change_rate_chunk_idx', + type=int, + default=0, + help='Generated chunk index used for per-token L2 norm change-rate analysis (default: 0).', + ) + parser.add_argument('--print_peak_memory', action='store_true', help='Print peak memory usage after pipeline completion.') + return parser.parse_args() + + +def main(): + args = parse_arguments() + + if args.print_peak_memory: + # Check if GPU is available and reset memory stats + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + device = torch.cuda.current_device() + print(f"Running on GPU: {torch.cuda.get_device_name(device)}") + print(f"GPU Memory before pipeline: {torch.cuda.memory_allocated(device) / 1024**3:.2f} GB allocated") + else: + print("CUDA not available, running on CPU") + + pipeline = MagiPipeline( + args.config_file, + residual_stats_path=args.residual_stats_path, + l1_rel_stats_path=args.l1_rel_stats_path, + token_l2_change_rate_stats_path=args.token_l2_change_rate_stats_path, + token_l2_change_rate_chunk_idx=args.token_l2_change_rate_chunk_idx, + ) + + if args.mode == 't2v': + pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) + elif args.mode == 'i2v': + if not args.image_path: + print("Error: --image_path is required for i2v mode.") + sys.exit(1) + pipeline.run_image_to_video(prompt=args.prompt, image_path=args.image_path, output_path=args.output_path) + elif args.mode == 'v2v': + if not args.prefix_video_path: + print("Error: --prefix_video_path is required for v2v mode.") + sys.exit(1) + pipeline.run_video_to_video(prompt=args.prompt, prefix_video_path=args.prefix_video_path, output_path=args.output_path) + + if args.print_peak_memory: + # Print peak memory usage after pipeline completion + if torch.cuda.is_available(): + peak_memory = torch.cuda.max_memory_allocated(device) / 1024**3 + current_memory = torch.cuda.memory_allocated(device) / 1024**3 + cached_memory = torch.cuda.memory_reserved(device) / 1024**3 + total_memory = torch.cuda.get_device_properties(device).total_memory / 1024**3 + + print("\n" + "="*50) + print("GPU Memory Usage Summary:") + print(f"Peak memory allocated: {peak_memory:.2f} GB") + print(f"Current memory allocated: {current_memory:.2f} GB") + print(f"Cached memory reserved: {cached_memory:.2f} GB") + print(f"Total GPU memory: {total_memory:.2f} GB") + print(f"Peak memory usage: {(peak_memory/total_memory)*100:.1f}%") + print("="*50) + + # Clear cache and show final memory + gc.collect() + torch.cuda.empty_cache() + final_memory = torch.cuda.memory_allocated(device) / 1024**3 + print(f"Memory after cache cleanup: {final_memory:.2f} GB") + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/flowcache.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/flowcache.py new file mode 100644 index 0000000000000000000000000000000000000000..bdc73d9cc68cb16da85a8c232011c7b9b20eeffe --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/flowcache.py @@ -0,0 +1,777 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +FlowCache implementation: Per-chunk output reuse + KV cache compression. + +This module provides FlowCache, which combines: +- ChunkWiseCache: Per-chunk output reuse for fine-grained control +- KVCacheCompressor: Dynamic KV cache compression for memory efficiency +""" + +import argparse +import gc +import os +import sys +import torch +from types import MethodType + +from inference.pipeline import MagiPipeline +from inference.pipeline.video_generate import SampleTransport, find_dit_model +from inference.pipeline.cache import ChunkWiseCache, KVCacheCompressor +from inference.pipeline.cache.utils import ( + generate_dynamic_kv_range, + get_embedding_and_meta_with_chunk_info, +) +from inference.pipeline.kvcompress import replace_magi +from inference.pipeline.kvcompress.utils import ChunkKVRangeTracker + + +def setup_flowcache( + rel_l1_thresh: float = 0.01, + warmup_steps: int = 0, + discard_nearly_clean_chunk: bool = False, + log: bool = False, + total_cache_chunk_nums: int = 5, + compress_kv_cache: bool = True, + metric_stats_path: str = None, +): + """ + Set up FlowCache with per-chunk reuse and KV compression. + + Args: + rel_l1_thresh: Relative L1 distance threshold for reuse + warmup_steps: Number of warmup steps per chunk before reuse can happen + discard_nearly_clean_chunk: Whether to skip nearly-clean chunk + log: Whether to log reuse decisions + total_cache_chunk_nums: Total number of chunks to cache + compress_kv_cache: Whether to enable KV cache compression + """ + # Create cache instance and attach to SampleTransport + SampleTransport.cache_reuse_manager = ChunkWiseCache( + rel_l1_thresh=rel_l1_thresh, + warmup_steps=warmup_steps, + discard_nearly_clean_chunk=discard_nearly_clean_chunk, + log=log, + metric_stats_path=metric_stats_path, + ) + + # Initialize compressor placeholder (will be created at runtime) + SampleTransport.kv_compress_manager = None + + # Monkey patch the SampleTransport methods + SampleTransport.forward_velocity = flowcache_forward_velocity + SampleTransport.integrate_velocity = flowcache_integrate_velocity + SampleTransport.total_cache_chunk_nums = total_cache_chunk_nums + SampleTransport.compress_kv_cache = compress_kv_cache + + +def flowcache_forward_velocity(self, infer_idx: int, cur_denoise_step: int) -> dict: + """ + Forward pass with per-chunk TeaCache and KV compression. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + + Returns: + Dictionary mapping chunk_id to velocity tensor + """ + # Get cache from class attribute + cache = SampleTransport.cache_reuse_manager + + # 1. Get current work status + x = self.xs[infer_idx] + transport_input = self.transport_inputs[infer_idx] + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + + # 2. Initialize KV cache tracking if needed + if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache: + total_cache_len = self.total_cache_chunk_nums * ( + self.chunk_width * + (transport_input.latent_size[3] // self.model_config.patch_size) * + (transport_input.latent_size[4] // self.model_config.patch_size) + ) + + if not hasattr(self.inference_params[infer_idx], 'kv_chunk_tracker'): + self.inference_params[infer_idx].kv_chunk_tracker = ChunkKVRangeTracker( + total_cache_len=total_cache_len, + clip_token_nums=chunk_token_nums, + max_batch_size=1 + ) + + if not hasattr(self, 'chunk_query_states'): + self.chunk_query_states = {} + + # 3. Initialize chunk state + cache.initialize_chunk_state(transport_input.chunk_num) + + # 4. Extract denoising status + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + self.current_chunk_offset = chunk_offset + + # 5. Prepare model kwargs + model_kwargs = dict( + chunk_width=self.chunk_width, + fwd_extra_1st_chunk=False, + num_steps=transport_input.num_steps + ) + if hasattr(self, "debug"): + model_kwargs["debug"] = self.debug + model_kwargs.update({ + "denoise_step_per_stage": denoise_step_per_stage, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx, + "chunk_num": transport_input.chunk_num + }) + + if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache: + model_kwargs.update({ + "compress_kv": True, + "total_cache_len": total_cache_len + }) + else: + model_kwargs["save_kvcache_every_forward"] = True + + if chunk_offset > 0 and cur_denoise_step == 0: + self.extract_prefix_video_feature( + infer_idx, transport_input.prefix_video, transport_input.y, chunk_offset, model_kwargs + ) + + # 6. Prepare inputs + x_chunk = x[:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width].clone() + y_chunk = transport_input.y[:, chunk_start:chunk_end] + mask_chunk = transport_input.emb_masks[:, chunk_start:chunk_end] + model_kwargs.update({ + "slice_point": chunk_start, + "range_num": chunk_end, + "denoising_range_num": chunk_end - chunk_start + }) + model_kwargs["chunk_token_nums"] = chunk_token_nums + + # 7. Prepare timesteps + denoise_step_of_each_chunk = self.get_denoise_step_of_each_chunk( + infer_idx, denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = t.unsqueeze(0).repeat(x_chunk.size(0), 1) + + # 8. Generate KV range + kv_range = self.generate_kvrange_for_denoising_video( + infer_idx=infer_idx, + slice_point=model_kwargs["slice_point"], + denoising_range_num=model_kwargs["denoising_range_num"], + denoise_step_of_each_chunk=denoise_step_of_each_chunk, + ) + + # 9. Pad prefix video if needed + if transport_input.prefix_video is not None: + x_chunk, t = self.try_pad_prefix_video( + infer_idx, x_chunk, t, prefix_video_start=model_kwargs["slice_point"] * self.chunk_width + ) + + # 10. Model forward + forward_fn = find_dit_model(self.model).forward_dispatcher + nearly_clean_chunk_t = t[0, int(model_kwargs["fwd_extra_1st_chunk"])].item() + model_kwargs["distill_nearly_clean_chunk"] = ( + nearly_clean_chunk_t > self.engine_config.distill_nearly_clean_chunk_threshold + ) + model_kwargs["distill_interval"] = self.time_interval[infer_idx][denoise_idx] + model_kwargs["total_num_steps"] = self.total_forward_step(infer_idx) + + # Initialize step counter + cache.set_total_steps(model_kwargs["total_num_steps"]) + + # Setup monkey-patched model forward + model = find_dit_model(self.model) + model.forward = MethodType(_create_flowcache_model_forward_fn(cache, self, infer_idx), model) + model.get_embedding_and_meta = MethodType(_new_get_embedding_and_meta, model) + + velocity = forward_fn( + x=x_chunk, + timestep=t, + y=y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + mask=mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + kv_range=kv_range, + inference_params=self.inference_params[infer_idx], + **model_kwargs, + ) + + self.x_chunks[infer_idx] = x_chunk + self.velocities[infer_idx] = velocity + return velocity + + +def _create_flowcache_model_forward_fn(cache: ChunkWiseCache, transport, infer_idx: int): + """ + Create a model forward function with per-chunk cache and KV compression logic. + + Args: + cache: ChunkWiseCache instance + transport: SampleTransport instance + infer_idx: Inference index + + Returns: + Model forward function + """ + @torch.no_grad() + def model_forward( + model_self, + x, + t, + y, + caption_dropout_mask=None, + xattn_mask=None, + kv_range=None, + inference_params=None, + **kwargs, + ) -> dict: + raw_x = x.clone() + + # 1. Compute feature metrics per chunk + # Following source code: compute metric_x first, handle slicing, then split + metric_chunks, num_chunks = cache.compute_feature_metric( + x=x, + x_embedder=model_self.x_embedder, + x_rescale_factor=model_self.model_config.x_rescale_factor, + half_channel_vae=model_self.model_config.half_channel_vae, + chunk_token_nums=kwargs["chunk_token_nums"], + params_dtype=model_self.model_config.params_dtype, + offset=kwargs['slice_point'], + fwd_extra_1st_chunk=kwargs.get("fwd_extra_1st_chunk", False), + distill_nearly_clean_chunk=kwargs.get("distill_nearly_clean_chunk", False) + ) + + # 2. Update kwargs + cache.total_num_steps = kwargs['total_num_steps'] + denoise_step_per_stage = kwargs['denoise_step_per_stage'] + kwargs['cur_denoise_step'] = cache.cnt + model_self.cur_denoise_step = cache.cnt + + # 3. Split x into chunks (using num_chunks from metric_x, matching source code) + chunk_width = kwargs["chunk_width"] + offset = kwargs['slice_point'] + x_chunks = {} + # Artifact chunks in x are not included - following source code comment + for i in range(num_chunks): + start_idx = i * chunk_width + end_idx = start_idx + chunk_width + x_chunks[offset + i] = x[:, :, start_idx:end_idx] + + # 4. Handle nearly clean chunk (artifact chunk) - add separately AFTER normal chunks + # Following source code logic + model_self.discard_nearly_clean_chunk = cache.discard_nearly_clean_chunk + near_clean_chunk_idx = -1 + if not cache.discard_nearly_clean_chunk and kwargs.get("distill_nearly_clean_chunk", False): + # Add artifact chunk - following source code comment + near_clean_chunk_idx = max(x_chunks.keys()) + 1 + model_self.near_clean_chunk_idx = near_clean_chunk_idx + x_chunks[near_clean_chunk_idx] = x[:, :, -chunk_width:] + + # 5. Determine which chunks to reuse + if cache.cnt != 0 and cache.cnt != cache.num_steps - 1: + current_num_chunks = len(metric_chunks) + previous_num_chunks = len(cache.prev_metric_chunks) + + common_keys = set(metric_chunks.keys()) & set(cache.prev_metric_chunks.keys()) + for i in sorted(common_keys): + should_reuse = cache.should_reuse( + chunk_id=i, + step=cache.cnt, + current_features=metric_chunks, + chunk_denoise_count=transport.chunk_denoise_count[infer_idx], + current_num_chunks=current_num_chunks, + previous_num_chunks=previous_num_chunks, + infer_idx=infer_idx, + cur_denoise_step=cache.cnt, + denoise_stage=kwargs.get("denoise_stage"), + denoise_idx=kwargs.get("denoise_idx"), + chunk_offset=getattr(transport, "current_chunk_offset", 0), + chunk_denoise_count_value=transport.chunk_denoise_count[infer_idx][i], + ) + cache.chunk_reuse_flags[i] = should_reuse + + # 6. Remove nearly clean chunk if first chunk can be reused + if cache.chunk_reuse_flags.get(kwargs["slice_point"], False) and near_clean_chunk_idx != -1: + x_chunks.pop(near_clean_chunk_idx, None) + + # 7. Store previous features + cache.store_previous_features(metric_chunks) + + # 8. Forward chunks that are not reused + current_infer_outputs = {} + + for i in sorted(x_chunks.keys()): + if i in cache.chunk_reuse_flags and cache.chunk_reuse_flags[i]: + continue + + x_i = x_chunks[i] + # Handle near_clean_chunk_idx: use last chunk of t, y, xattn_mask + if i == near_clean_chunk_idx: + t_i = t[:, -1:] + y_i = y[-1:] + xattn_mask_i = xattn_mask[-1:] + else: + t_i = t[:, i - offset:i - offset + 1] + y_i = y[i - offset:i - offset + 1] + xattn_mask_i = xattn_mask[i - offset:i - offset + 1] + + kwargs["start_chunk_id"] = i + kwargs["end_chunk_id"] = i + 1 + kwargs["denoising_range_num"] = 1 + + if i == near_clean_chunk_idx: + kwargs["distill_nearly_clean_chunk"] = True + else: + kwargs["distill_nearly_clean_chunk"] = False + + # Update KV range if compressed + if hasattr(transport, 'compress_kv_cache') and transport.compress_kv_cache: + if inference_params.kv_compressed: + kv_range = generate_dynamic_kv_range( + tracker=inference_params.kv_chunk_tracker, + current_chunk_id=i, + x_chunks_keys=list(x_chunks.keys()), + chunk_token_nums=kwargs["chunk_token_nums"], + near_clean_chunk_idx=near_clean_chunk_idx + ) + + kwargs["near_clean_chunk_idx"] = near_clean_chunk_idx + (processed_x, condition, condition_map, y_xattn_flat, rope, meta_args) = \ + model_self.forward_pre_process( + x_i, t_i, y_i, caption_dropout_mask, xattn_mask_i, kv_range, **kwargs + ) + + if not model_self.pre_process: + from inference.pipeline.parallelism import pp_scheduler + processed_x = pp_scheduler().recv_prev_data(processed_x.shape, processed_x.dtype) + model_self.videodit_blocks.set_input_tensor(processed_x) + else: + processed_x = processed_x.clone() + + try: + out = model_self.videodit_blocks.forward( + hidden_states=processed_x, + condition=condition, + condition_map=condition_map, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rope, + inference_params=inference_params, + meta_args=meta_args, + ) + except Exception as e: + import pdb; pdb.set_trace() + + # Store query states for compression + if hasattr(transport, 'compress_kv_cache') and transport.compress_kv_cache: + for layer in model_self.videodit_blocks.layers: + layer_num = layer.self_attention.layer_number + if hasattr(layer.self_attention, '_last_query'): + transport.chunk_query_states[layer_num] = layer.self_attention._last_query + + if not model_self.post_process: + from inference.pipeline.parallelism import pp_scheduler + pp_scheduler().isend_next(out) + + out = model_self.forward_post_process(out, meta_args) + current_infer_outputs[i] = out.clone().detach() + + return current_infer_outputs + + return model_forward + + +@torch.no_grad() +def _new_get_embedding_and_meta(model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs): + """Monkey-patched version of get_embedding_and_meta with chunk info.""" + return get_embedding_and_meta_with_chunk_info( + model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs + ) + + +def flowcache_integrate_velocity(self, infer_idx: int, cur_denoise_step: int): + """ + Integrate velocity with per-chunk cache residual handling and KV compression. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + """ + # Get cache from class attribute + cache = SampleTransport.cache_reuse_manager + + transport_input = self.transport_inputs[infer_idx] + x_chunk = self.x_chunks[infer_idx] + velocity = self.velocities[infer_idx] + chunk_denoise_count = self.chunk_denoise_count[infer_idx] + + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + + chunk_num = x_chunk.shape[2] // self.chunk_width + offset = chunk_start + ori_x_chunk = x_chunk.clone() + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + next_t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx + 1, has_clean_t=False + ) + x_embedder_before = None + x_embedder_after = None + x_embedder_chunk_width = None + need_embedder_stats = ( + (self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank()) + or (self.token_l2_norm_change_tracker.enabled and self.token_l2_norm_change_tracker.is_writer_rank()) + ) + if need_embedder_stats: + x_embedder_before, x_embedder_chunk_width = self.embed_x_for_l1_rel_stats(ori_x_chunk) + self.update_token_l2_norm_change_tracker( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + chunk_end=chunk_end, + x_embedder_before=x_embedder_before, + x_embedder_chunk_width=x_embedder_chunk_width, + timesteps=t, + ) + + # Split into chunks + x_chunks = {} + for i in range(chunk_num): + start_idx = i * self.chunk_width + end_idx = start_idx + self.chunk_width + x_chunks[offset + i] = x_chunk[:, :, start_idx:end_idx] + + # Integrate per chunk + for i in range(chunk_num): + chunk_id = offset + i + reused = cache.chunk_reuse_flags[chunk_id] + cache.record_actual_execution( + chunk_id=chunk_id, + reused=reused, + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + ) + if reused: + # Reuse: add residual + x_chunk[:, :, i * self.chunk_width:(i + 1) * self.chunk_width] += \ + cache.previous_residual[chunk_id] + else: + # Recalculate + assert chunk_id in velocity, f"Chunk {chunk_id} not in velocity outputs" + x_chunk[:, :, i * self.chunk_width:(i + 1) * self.chunk_width] = \ + self.integrate(x_chunks[chunk_id], velocity[chunk_id], self.ts[infer_idx], + denoise_step_per_stage, t_start, t_end, denoise_idx, i) + # Store residual + cache.previous_residual[chunk_id] = \ + x_chunk[:, :, i * self.chunk_width:(i + 1) * self.chunk_width] - \ + ori_x_chunk[:, :, i * self.chunk_width:(i + 1) * self.chunk_width] + + applied_residual = x_chunk - ori_x_chunk + self.residual_diff_tracker.update_residuals( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + residual=applied_residual, + timesteps=t, + chunk_width=self.chunk_width, + ) + if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank(): + x_embedder_after, _ = self.embed_x_for_l1_rel_stats(x_chunk) + self.l1_rel_change_tracker.update( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + x_before=ori_x_chunk, + x_after=x_chunk, + timesteps=t, + next_timesteps=next_t, + chunk_width=self.chunk_width, + x_embedder_before=x_embedder_before, + x_embedder_after=x_embedder_after, + x_embedder_chunk_width=x_embedder_chunk_width, + ) + + # Increment step counter + cache.increment_step() + + # Update chunk denoise count + for chunk_index in range(chunk_start, chunk_end): + chunk_denoise_count[chunk_index] += 1 + + self.xs[infer_idx][:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width] = x_chunk + self.chunk_denoise_count[infer_idx] = chunk_denoise_count + + # Check if KV compression is needed + if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache: + _check_and_compress_kv(self, infer_idx, chunk_start, transport_input) + + # Return clean chunk if ready + if chunk_denoise_count[chunk_start] == transport_input.num_steps: + return _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset) + + return None, None + + +def _check_and_compress_kv(self, infer_idx: int, chunk_start: int, transport_input): + """Check and perform KV cache compression if needed.""" + inference_params = self.inference_params[infer_idx] + tracker = inference_params.kv_chunk_tracker + + total_cache_len = self.total_cache_chunk_nums * ( + self.chunk_width * + (transport_input.latent_size[3] // self.model_config.patch_size) * + (transport_input.latent_size[4] // self.model_config.patch_size) + ) + + # Get or create compressor from class attribute + compressor = SampleTransport.kv_compress_manager + if compressor is None: + chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx)[1] + compressor = KVCacheCompressor( + total_cache_len=total_cache_len, + tokens_per_chunk=chunk_token_nums, + budget_chunk_nums=self.total_cache_chunk_nums - 1, + window_size=self.window_size + ) + SampleTransport.kv_compress_manager = compressor + + # Check if compression needed + if compressor.should_compress( + tracker=tracker, + chunk_num=transport_input.chunk_num, + chunk_start=chunk_start, + transport_input=transport_input, + chunk_denoise_count=self.chunk_denoise_count[infer_idx] + ): + compressor.compress( + model=find_dit_model(self.model), + inference_params=inference_params, + tracker=tracker, + transport_input=transport_input, + chunk_start=chunk_start, + chunk_denoise_count=self.chunk_denoise_count[infer_idx], + query_states_dict=self.chunk_query_states + ) + + +def _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset): + """Return the clean chunk if denoising is complete.""" + if transport_input.prefix_video is not None: + prefix_video_length = transport_input.prefix_video.size(2) + if (chunk_start + 1) * self.chunk_width <= prefix_video_length: + return None, None + + real_start = max(chunk_start * self.chunk_width, prefix_video_length) + + if chunk_start == 0 and prefix_video_length == 1: + real_start = 0 + + clean_chunk, _ = self.xs[infer_idx][:, :, real_start:(chunk_start + 1) * self.chunk_width].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + else: + clean_chunk, _ = self.xs[infer_idx][ + :, :, chunk_start * self.chunk_width:(chunk_start + 1) * self.chunk_width + ].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + + +def load_config(config_path: str) -> dict: + """Load configuration from JSON or YAML file.""" + _, ext = os.path.splitext(config_path) + with open(config_path, 'r') as f: + if ext == '.json': + import json + return json.load(f) + elif ext in ['.yaml', '.yml']: + import yaml + return yaml.safe_load(f) + else: + raise ValueError(f"Unsupported config file extension: {ext}") + + +def parse_arguments(): + """Parse command line arguments.""" + parser = argparse.ArgumentParser(description="Run MagiPipeline with FlowCache.") + parser.add_argument('--config_file', type=str, help='Path to the configuration file.') + parser.add_argument( + '--mode', type=str, choices=['t2v', 'i2v', 'v2v'], + required=True, help='Mode to run: t2v, i2v, or v2v.' + ) + parser.add_argument('--prompt', type=str, required=True, help='Prompt for the pipeline.') + parser.add_argument('--image_path', type=str, help='Path to the image file (for i2v mode).') + parser.add_argument('--prefix_video_path', type=str, help='Path to the prefix video file (for v2v mode).') + parser.add_argument('--output_path', type=str, required=True, help='Path to save the output video.') + parser.add_argument('--additional_config', type=str, help='Path to additional config file.') + parser.add_argument( + '--residual_stats_path', + type=str, + help='Optional path to save per-chunk residual-difference norm stats as .json, .pt, or .pth.', + ) + parser.add_argument( + '--l1_rel_stats_path', + type=str, + help='Optional path to save per-chunk relative L1 change stats as .json, .pt, or .pth.', + ) + parser.add_argument( + '--token_l2_change_rate_stats_path', + type=str, + help='Optional path to save per-token L2 norm change-rate stats for one chunk as .json, .pt, or .pth.', + ) + parser.add_argument( + '--token_l2_change_rate_chunk_idx', + type=int, + default=0, + help='Generated chunk index used for per-token L2 norm change-rate analysis (default: 0).', + ) + parser.add_argument( + '--flowcache_metric_stats_path', + type=str, + help='Optional path to save FlowCache original reuse metric stats as .json, .pt, or .pth.', + ) + parser.add_argument('--print_peak_memory', action='store_true', help='Print peak memory usage.') + + return parser.parse_args() + + +def main(): + """Main entry point.""" + args = parse_arguments() + + # Load additional config + if args.additional_config: + additional_config = load_config(args.additional_config) + print(f"Loading additional config: {additional_config}") + + for key, value in additional_config.items(): + setattr(args, key, value) + print(f"Added to args: {key} = {value}") + + # Handle parameter name compatibility + if hasattr(args, 'no_reuse_first_n_steps') and not hasattr(args, 'warmup_steps'): + args.warmup_steps = args.no_reuse_first_n_steps + if hasattr(args, 'no_reuse_mode'): + # no_reuse_mode is deprecated, ignore it + pass + else: + print("No additional config provided.") + + if args.print_peak_memory: + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + device = torch.cuda.current_device() + print(f"Running on GPU: {torch.cuda.get_device_name(device)}") + print(f"GPU Memory before pipeline: {torch.cuda.memory_allocated(device) / 1024**3:.2f} GB") + else: + print("CUDA not available, running on CPU") + + # Setup FlowCache + setup_flowcache( + rel_l1_thresh=args.rel_l1_thresh, + warmup_steps=args.warmup_steps, + discard_nearly_clean_chunk=args.discard_nearly_clean_chunk, + log=args.log, + total_cache_chunk_nums=args.total_cache_chunk_nums, + compress_kv_cache=args.compress_kv_cache, + metric_stats_path=args.flowcache_metric_stats_path, + ) + + # Setup KV compression in model + compression_config = { + "method_config": { + "compress_strategy": getattr(args, 'compress_strategy', 'token'), + "mix_lambda": getattr(args, 'mix_lambda', 0.07), + "query_granularity": getattr(args, 'query_granularity', 'chunk'), + "score_weighting_method": getattr(args, 'score_weighting_method', None) or 'no_weight', + "power": getattr(args, 'power', 3), + }, + } + replace_magi(compression_config) + + # Run pipeline + pipeline = MagiPipeline( + args.config_file, + residual_stats_path=args.residual_stats_path, + l1_rel_stats_path=args.l1_rel_stats_path, + token_l2_change_rate_stats_path=args.token_l2_change_rate_stats_path, + token_l2_change_rate_chunk_idx=args.token_l2_change_rate_chunk_idx, + ) + + if args.mode == 't2v': + pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) + elif args.mode == 'i2v': + if not args.image_path: + print("Error: --image_path is required for i2v mode.") + sys.exit(1) + pipeline.run_image_to_video(prompt=args.prompt, image_path=args.image_path, output_path=args.output_path) + elif args.mode == 'v2v': + if not args.prefix_video_path: + print("Error: --prefix_video_path is required for v2v mode.") + sys.exit(1) + pipeline.run_video_to_video( + prompt=args.prompt, prefix_video_path=args.prefix_video_path, output_path=args.output_path + ) + + if args.print_peak_memory: + if torch.cuda.is_available(): + peak_memory = torch.cuda.max_memory_allocated(device) / 1024**3 + current_memory = torch.cuda.memory_allocated(device) / 1024**3 + cached_memory = torch.cuda.memory_reserved(device) / 1024**3 + total_memory = torch.cuda.get_device_properties(device).total_memory / 1024**3 + + print("\n" + "=" * 50) + print("GPU Memory Usage Summary:") + print(f"Peak memory allocated: {peak_memory:.2f} GB") + print(f"Current memory allocated: {current_memory:.2f} GB") + print(f"Cached memory reserved: {cached_memory:.2f} GB") + print(f"Total GPU memory: {total_memory:.2f} GB") + print(f"Peak memory usage: {(peak_memory/total_memory)*100:.1f}%") + print("=" * 50) + + gc.collect() + torch.cuda.empty_cache() + final_memory = torch.cuda.memory_allocated(device) / 1024**3 + print(f"Memory after cache cleanup: {final_memory:.2f} GB") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/.DS_Store b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..81ddf723ab2ad7484c6b094f87561851f2a00842 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/.DS_Store differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__init__.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..271690aebf11d70f2405296aac31012d08bae88f --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__init__.py @@ -0,0 +1,9 @@ +""" +This package provides efficient decoding-time KV cache compression methods. +""" + +__version__ = "0.1.0" + +from .monkeypatch import replace_magi + +__all__ = ["replace_magi"] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/kv_compressor.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/kv_compressor.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd7a518cde39d1f61e9f83c159662b63c6ed759 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/kv_compressor.py @@ -0,0 +1,314 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import List +import os + +from inference.pipeline.kvcompress.utils import cal_similarity, compute_attention_scores + + +class KVCompressor: + def __init__( + self, + kernel_size=7, + mix_lambda=0.07, + compress_strategy="token", + query_granularity="chunk", + score_weighting_method="default", + power=3, + **kwargs, + ): + self.kernel_size = kernel_size + self.mix_lambda = mix_lambda + assert compress_strategy in ["token", "frame", "chunk"] + assert query_granularity in ["token", "frame", "chunk"] + self.compress_strategy = compress_strategy + self.query_granularity = query_granularity + self.score_weighting_method = score_weighting_method + self.power = power + + def update_kv( + # The passed kv is the kv cache of all chunks + self, + key_states, + query_states, + value_states, + clean_chunk_tokens, + latent_size_t, + latent_size_h, + latent_size_w + ): + if self.query_granularity == "token": + # Take 50 tokens + query_states = query_states[- 50 : ] + elif self.query_granularity == "frame": + query_states = query_states[- latent_size_h * latent_size_w : ] + elif self.query_granularity == "chunk": + pass + else: + raise ValueError("Invalid query granularity") + + if self.compress_strategy == "token": + return self.update_kv_token( + key_states, + query_states, + value_states, + clean_chunk_tokens, + each_chunk_tokens=latent_size_t * latent_size_h * latent_size_w, + ) + elif self.compress_strategy == "frame": + return self.update_kv_frame_chunk( + key_states, + query_states, + value_states, + clean_chunk_tokens, + together_size=latent_size_h * latent_size_w, + ) + elif self.compress_strategy == "chunk": + return self.update_kv_frame_chunk( + key_states, + query_states, + value_states, + clean_chunk_tokens, + together_size=latent_size_t * latent_size_h * latent_size_w, + ) + else: + raise ValueError("Invalid compress strategy") + + def update_kv_token( + self, + key_states, + query_states, + value_states, + clean_chunk_tokens, + each_chunk_tokens, + ): + each_chunk_tokens = int(each_chunk_tokens) + head_dim = query_states.shape[-1] + kv_cache_len = key_states.shape[0] + + attn_weights = compute_attention_scores(query_states, key_states[:clean_chunk_tokens]) + attn_weights_sum = ( + nn.functional.softmax( + attn_weights[:, :, : clean_chunk_tokens], + dim=-1, + dtype=torch.float32, + ) + .mean(dim=-2) + .to(query_states.dtype) + ) + + attn_cache = F.max_pool1d( + attn_weights_sum, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + stride=1, + ).to('cpu') + + similarity_cos = cal_similarity(key_states[:clean_chunk_tokens, :, :]).to('cpu') + + final_score = attn_cache * self.mix_lambda - similarity_cos * (1 - self.mix_lambda) + + # Ensure final score is non-negative for weighting + min_scores_per_head = final_score.min(dim=-1, keepdim=True).values # (num_kv_heads, 1) + final_score = final_score - min_scores_per_head + + # Note that final_score contains negative numbers + # Apply different weighting methods to final_score, relatively making tokens at later positions more likely to be selected + if self.score_weighting_method == "no_weight": + print("Using no weighting method") + pass + + elif self.score_weighting_method == "hard_code": + print("Using hard code weighting method") + final_score[:, :each_chunk_tokens] -= 1e6 + + elif self.score_weighting_method == "exponential": + print("Using exponential weighting method") + seq_len = final_score.shape[1] + positions = torch.arange(seq_len, dtype=torch.float32, device=final_score.device) / (seq_len - 1) if seq_len > 1 else torch.zeros(1) + decay_rate = 2.0 + # Normalize to [0.1, 1.0] range + exponential_values = 1 - torch.exp(-decay_rate * positions) + max_value = 1 - torch.exp(torch.tensor(-decay_rate, device=final_score.device)) # Value when positions=1 + weights = 0.1 + 0.9 * (exponential_values / max_value) + final_score = final_score * weights.unsqueeze(0) + + elif self.score_weighting_method == "polynomial": + print(f"Using polynomial weighting method, power={self.power}") + seq_len = final_score.shape[1] + positions = torch.arange(seq_len, dtype=torch.float32, device=final_score.device) / (seq_len - 1) if seq_len > 1 else torch.zeros(1) + # Normalize to [0.1, 1.0] range + weights = 0.1 + 0.9 * (positions ** self.power) + final_score = final_score * weights.unsqueeze(0) + elif self.score_weighting_method == "upper_convex_polynomial": + print(f"Using upper convex polynomial weighting method, power={self.power}") + seq_len = final_score.shape[1] + positions = torch.arange(seq_len, dtype=torch.float32, device=final_score.device) / (seq_len - 1) if seq_len > 1 else torch.zeros(1) + max_value = 2.0 + # Construct upper convex n-th degree polynomial: w(x) = max_value * (1 - (1-x)^n) + weights = max_value * (1 - (1 - positions) ** self.power) + final_score = final_score * weights.unsqueeze(0) + + elif self.score_weighting_method == "gaussian": + print("Using gaussian weighting method") + # Emphasize previous information more + seq_len = final_score.shape[1] + + positions = torch.arange(seq_len, dtype=torch.float32, device=final_score.device) + sigma = seq_len / 4.0 # ← Adjustable! Smaller values emphasize the beginning more + + gaussian_decay = torch.exp(-0.5 * (positions / sigma) ** 2) + min_decay = torch.exp(torch.tensor(-0.5 * ((seq_len - 1) / sigma) ** 2, device=final_score.device)) + + # Map [min_decay, 1.0] → [0.1, 1.0] + weights = 0.1 + 0.9 * ((gaussian_decay - min_decay) / (1.0 - min_decay)) + final_score = final_score * weights.unsqueeze(0) + else: + raise ValueError(f"Unknown score weighting method: {self.score_weighting_method}") + + # Calculate number of tokens to keep + num_to_keep = self.budget + + # Select top-k tokens + try: + indices = final_score.topk(num_to_keep, dim=-1).indices # shape: (num_kv_heads, num_to_keep) + del final_score + except RuntimeError: + import pdb; pdb.set_trace() + indices = indices.unsqueeze(-1).expand(-1, -1, head_dim).permute(1, 0, 2) # shape: (num_to_keep, num_kv_heads, head_dim) + + indices = indices.to(key_states.device) + + # Compress non-recent parts + k_past_compress = key_states[:clean_chunk_tokens, :, :].gather(dim=0, index=indices) + v_past_compress = value_states[:clean_chunk_tokens, :, :].gather(dim=0, index=indices) + k_cur = key_states[clean_chunk_tokens :, :, :] + v_cur = value_states[clean_chunk_tokens :, :, :] + + key_compress = torch.cat([k_past_compress, k_cur], dim=0) + value_compress = torch.cat([v_past_compress, v_cur], dim=0) + + return key_compress, value_compress, indices + + def update_kv_frame_chunk( + self, + key_states, + query_states, + value_states, + clean_chunk_tokens, + together_size, + ): + head_dim = query_states.shape[-1] + kv_cache_len = key_states.shape[0] + + # ========== Compression Logic ========== + + # Step 1: Compute attention weights + attn_weights = compute_attention_scores(query_states, key_states) + attn_weights_sum = ( + nn.functional.softmax( + attn_weights[:, :, : clean_chunk_tokens], + dim=-1, + dtype=torch.float32, + ) + .mean(dim=-2) # shape: (num_kv_heads, clean_chunk_tokens) + .to(query_states.dtype) + ) + + # Step 2: Pooling to get "importance" of each token + attn_cache = F.max_pool1d( + attn_weights_sum, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + stride=1, + ).to('cpu') # shape: (num_kv_heads, clean_chunk_tokens) + + # Step 3: Compute similarity between tokens + similarity_cos = cal_similarity(key_states[:clean_chunk_tokens, :, :]).to('cpu') + + # Step 4: Compute final score for each token + final_score_per_token = attn_cache * self.mix_lambda - similarity_cos * (1 - self.mix_lambda) + # shape: (num_kv_heads, clean_chunk_tokens) + + # ========== Frame-wise or Chunk-wise Aggregation ========== + # In the code below, chunk is also referred to as frame; they are conceptually consistent, just differing in how many tokens are aggregated into one frame/chunk + + assert clean_chunk_tokens % together_size == 0 + num_frames = clean_chunk_tokens // together_size + + # Reshape to (num_kv_heads, num_frames, together_size) + score_frames = final_score_per_token.view( + key_states.shape[1], num_frames, together_size + ) + + # Aggregate scores for each frame + frame_scores = score_frames.mean(dim=-1) # shape: (num_kv_heads, num_frames) + + # Calculate number of frames to keep + assert self.budget % together_size == 0 + num_frames_to_keep = self.budget // together_size + + # Select top-k frames for each head + frame_indices = frame_scores.topk(num_frames_to_keep, dim=-1).indices + # shape: (num_kv_heads, num_frames_to_keep) + + + # Convert frame_indices to token indices + # frame_indices: frame id selected by each head + + # offset: [0, 1, ..., together_size-1] + token_offsets = torch.arange(together_size, device=key_states.device) + frame_indices_expanded = frame_indices.unsqueeze(-1) * together_size + token_indices_per_head = frame_indices_expanded + token_offsets # shape: (num_heads, num_frames_to_keep, together_size) + token_indices_flat = token_indices_per_head.view(key_states.shape[1], -1) # (num_heads, K * together_size) + indices_gather = token_indices_flat.permute(1, 0).unsqueeze(-1).expand(-1, -1, head_dim) # shape: (kept_tokens, num_kv_heads, head_dim) + + # Gather from key/value + k_past_compress = key_states[:clean_chunk_tokens, :, :].gather(dim=0, index=indices_gather) + v_past_compress = value_states[:clean_chunk_tokens, :, :].gather(dim=0, index=indices_gather) + + # ========== Concatenate Recent Parts ========== + k_cur = key_states[clean_chunk_tokens:, :, :] + v_cur = value_states[clean_chunk_tokens:, :, :] + + key_compress = torch.cat([k_past_compress, k_cur], dim=0) + value_compress = torch.cat([v_past_compress, v_cur], dim=0) + + return key_compress, value_compress, indices_gather # token indices + + +def plot_tensor_values(tensor_1d: torch.Tensor, title: str = "Tensor Values", save_path: str = None, + xlabel: str = "Position", ylabel: str = "Value", figsize: tuple = (10, 6)): + try: + import matplotlib.pyplot as plt + import numpy as np + except ImportError: + print("Warning: matplotlib not available, skipping plot") + return + + # Ensure input is a 1D tensor + if tensor_1d.dim() != 1: + raise ValueError(f"Input tensor must be 1D, got {tensor_1d.dim()}D") + + # Convert to numpy array + values = tensor_1d.detach().cpu().float().numpy() + positions = np.arange(len(values)) + + # Create plot + plt.figure(figsize=figsize) + plt.plot(positions, values, 'b-', linewidth=2, markersize=4, alpha=0.8) + plt.xlabel(xlabel, fontsize=12) + plt.ylabel(ylabel, fontsize=12) + plt.title(title, fontsize=14) + + # Adjust layout + plt.tight_layout() + + # Save plot + if save_path is not None: + os.makedirs(os.path.dirname(save_path), exist_ok=True) + plt.savefig(save_path, dpi=100, bbox_inches='tight') + print(f"Plot saved to: {save_path}") + + plt.close() \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/modeling.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebec5d78478d33f86036559fd7c6f66b733ef65 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/modeling.py @@ -0,0 +1,54 @@ +import torch +from .kv_compressor import KVCompressor +from inference.model.dit.dit_module import CustomLayerNormLinear, FusedLayerNorm, PerChannelQuantizedFp8Linear, Attention +from inference.common import EngineConfig, InferenceParams, ModelConfig, ModelMetaArgs + +def MagiAttention_init( + self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int, compression_config: dict +): + Attention.__init__(self, model_config, engine_config, layer_number) + # super().__init__(model_config=model_config, engine_config=engine_config, layer_number=layer_number) + + # output 2x query, one for self-attn, one for cross-attn with condition + self.linear_qkv = CustomLayerNormLinear( + input_size=self.model_config.hidden_size, + output_size_q=self.query_projection_size, + output_size_kv=self.kv_projection_size, + layer_number=self.layer_number, + model_config=self.model_config, + engine_config=self.engine_config, + ) + + # kv from condition, e.g., caption + self.linear_kv_xattn = torch.nn.Linear( + int(self.model_config.hidden_size * self.model_config.xattn_cond_hidden_ratio), # 6144 + 2 * self.kv_projection_size, # 2048 + dtype=self.model_config.params_dtype, + bias=False, + ) + + # Output. + self.adapt_linear_quant = ( + self.engine_config.fp8_quant and self.layer_number != 0 and self.layer_number != model_config.num_layers - 1 + ) + submodules_linear_proj = PerChannelQuantizedFp8Linear if self.adapt_linear_quant else torch.nn.Linear + self.linear_proj = submodules_linear_proj( + 2 * self.query_projection_size, self.model_config.hidden_size, dtype=self.model_config.params_dtype, bias=False + ) + + self.q_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head) + self.q_layernorm_xattn = FusedLayerNorm( + model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head + ) + self.k_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head) + self.k_layernorm_xattn = FusedLayerNorm( + model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head + ) + + self.attn_weights_history = [] + + # =============== New logic start =============== + self.kv_cluster = KVCompressor( + **compression_config["method_config"] + ) + # =============== New logic end ================= \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/monkeypatch.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/monkeypatch.py new file mode 100644 index 0000000000000000000000000000000000000000..154d59435406156a93909fd3d015334e47b76dd3 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/monkeypatch.py @@ -0,0 +1,8 @@ +from .modeling import MagiAttention_init + +def replace_magi(compression_config): + from inference.model.dit import VideoDiTModel, FullyParallelAttention + def init_wrapper(self, model_config, engine_config, layer_number): + MagiAttention_init(self, model_config, engine_config, layer_number, compression_config) + + FullyParallelAttention.__init__ = init_wrapper \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/utils.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c5748d277836e2deb6bc4aaa503ccef829f58ee8 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/utils.py @@ -0,0 +1,208 @@ +import math +import torch +import time +import matplotlib.pyplot as plt +import numpy as np +from typing import List, Tuple, Dict + +################################################################# +###################### kv cache utilities ####################### +################################################################# + +def compute_attention_scores(query_states, key_states_cpu, pooling="max"): + """ + query_states: [q_len, q_heads, head_dim] on GPU + key_states_cpu: [kv_len, kv_heads, head_dim] on CPU + """ + + q_len, q_heads, head_dim = query_states.shape + kv_len, kv_heads, _ = key_states_cpu.shape + query_group_size = q_heads // kv_heads + + device = query_states.device # GPU + + # print(f"Before computing attention scores, GPU memory usage: {torch.cuda.memory_allocated() / 1024 ** 3:.1f} GB") + + if query_group_size == 1: + chunk_size = 12150 + + attn_weights = torch.empty(kv_heads, q_len, kv_len, device=device, dtype=query_states.dtype) + + for i in range(0, kv_len, chunk_size): + end_i = min(i + chunk_size, kv_len) + k_chunk = key_states_cpu[i:end_i].to(device) # Transfer small chunk to GPU + + attn_chunk = torch.bmm( + query_states.transpose(0, 1), # [kv_heads, q_len, head_dim] + k_chunk.transpose(1, 2) # [kv_heads, head_dim, chunk_size] + ) / math.sqrt(head_dim) # [kv_heads, q_len, chunk_size] + + attn_weights[:, :, i:end_i] = attn_chunk + del k_chunk, attn_chunk + + return attn_weights + + else: + # query_states: [q_len, q_heads, head_dim] -> reshape to group + # We group by query_group, but still compute key in chunks + query_states = query_states.view(q_len, kv_heads, query_group_size, head_dim) + # [q_len, kv_heads, g, head_dim] -> permute to [kv_heads, g, q_len, head_dim] + query_states = query_states.permute(1, 2, 0, 3).contiguous() # [kv_heads, g, q_len, head_dim] + + if pooling == "mean": + attn_weights_sum = None + count = 0 + elif pooling == "max": + attn_weights_max = None + else: + raise ValueError("Pooling method not supported") + + for g in range(query_group_size): + q_group = query_states[:, g, :, :] # [kv_heads, q_len, head_dim] + + chunk_size = 12150 + group_attn = torch.empty(kv_heads, q_len, kv_len, device=device, dtype=query_states.dtype) + + for i in range(0, kv_len, chunk_size): + end_i = min(i + chunk_size, kv_len) + k_chunk = key_states_cpu[i:end_i].to(device) # [chunk_size, kv_heads, head_dim] + k_chunk = k_chunk.permute(1, 2, 0) # [kv_heads, head_dim, chunk_size] + attn_chunk = torch.bmm(q_group, k_chunk) / math.sqrt(head_dim) + group_attn[:, :, i:end_i] = attn_chunk + del k_chunk, attn_chunk + + # Apply pooling over query_group_size dimension + if pooling == "mean": + if attn_weights_sum is None: + attn_weights_sum = group_attn + else: + attn_weights_sum += group_attn + count += 1 + elif pooling == "max": + if attn_weights_max is None: + attn_weights_max = group_attn + else: + attn_weights_max = torch.max(attn_weights_max, group_attn) + + del group_attn + + if pooling == "mean": + attn_weights = attn_weights_sum / count + del attn_weights_sum + elif pooling == "max": + attn_weights = attn_weights_max + del attn_weights_max + + return attn_weights + + +# def cal_similarity( +# key_states, +# ): +# # key_states shape: [kv_len, kv_heads, head_dim] +# start = time.time() +# k = key_states.permute(1, 0, 2).to('cuda') # shape: [kv_heads, kv_len, head_dim] +# num_heads = k.shape[0] + +# k_norm = k / (k.norm(dim=-1, keepdim=True) + 1e-8) +# similarity_cos = torch.matmul(k_norm, k_norm.transpose(-1, -2)).to('cpu') + +# for h in range(num_heads): +# similarity_cos[h].fill_diagonal_(0.0) + +# end = time.time() +# return similarity_cos.mean(dim=1).softmax(dim=-1) + + +def cal_similarity( + key_states, +): + # [kv_len, H, D] → [H, kv_len, D] + k = key_states.permute(1, 0, 2).to('cuda') + H, L, D = k.shape + + # L2 normalize each key vector per head + k_norm = k / (k.norm(dim=-1, keepdim=True) + 1e-8) # [H, L, D] + + # Step 1: Compute sum of all keys per head → [H, D] + k_sum = k_norm.sum(dim=1) # Σ_j k_j + + # Step 2: For each key i, compute k_i ⋅ (Σ_j k_j) → [H, L] + # That is: (k_norm @ k_sum.T) → use bmm for batch + # k_norm: [H, L, D], k_sum.unsqueeze(-1): [H, D, 1] → bmm → [H, L, 1] + dot_with_sum = torch.bmm(k_norm, k_sum.unsqueeze(-1)).squeeze(-1) # [H, L] + + # Step 3: Apply correction for diagonal (since cos(k_i, k_i) = 1 was included in sum) + # Original: fill_diagonal_(0) then mean(dim=1) ⇒ (total_sum - 1) / L + if L == 1: + mean_sim = torch.zeros(H, 1, device=k.device) # or handle specially + else: + mean_sim = (dot_with_sum - 1.0) / L # [H, L] ← strictly equivalent to original + + avg_sim = mean_sim + + # Step 5: Softmax → final importance-like distribution + result = avg_sim.softmax(dim=-1).to('cpu') # move small result to CPU + + return result + + +class ChunkKVRangeTracker: + def __init__(self, total_cache_len: int, clip_token_nums: int, max_batch_size: int): + self.total_cache_len = total_cache_len + self.clip_token_nums = clip_token_nums + self.max_batch_size = max_batch_size + self.tokens_per_chunk = clip_token_nums * max_batch_size + self.chunk_ranges: Dict[int, Tuple[int, int]] = {} # chunk_id -> (start, end) + self.next_free_idx = 0 # For sequential allocation when not compressed + self.registered_chunks_ordered: List[int] = [] # Maintain registration order for compression and concatenation + + def register_chunks(self, chunk_ids: List[int]): + """Batch register multiple chunks and allocate original space""" + for cid in chunk_ids: + if cid in self.chunk_ranges: + continue + start = self.next_free_idx + end = start + self.tokens_per_chunk + if end > self.total_cache_len: + import pdb; pdb.set_trace() + raise ValueError("KV cache is full") + self.chunk_ranges[cid] = (start, end) + self.registered_chunks_ordered.append(cid) + self.next_free_idx = end + + def get_range(self, chunk_id: int) -> Tuple[int, int]: + if chunk_id not in self.chunk_ranges: + raise KeyError(f"Chunk {chunk_id} not registered. Call register_chunks first.") + return self.chunk_ranges[chunk_id] + + def get_all_ranges_previous(self, current_chunk_ids: List[int]) -> List[Tuple[int, int]]: + # Get KV ranges of all previous chunks + ranges = [] + if len(current_chunk_ids) > 0: + min_chunk_id = min(current_chunk_ids) + for cid in self.registered_chunks_ordered: + if cid >= min_chunk_id: + continue + ranges.append(self.chunk_ranges[cid]) + else: + # To adapt to MAGI-1's original logic, should return ranges of all registered chunks + for cid in self.registered_chunks_ordered: + ranges.append(self.chunk_ranges[cid]) + return ranges + + def get_all_chunk_ids(self) -> List[int]: + return self.registered_chunks_ordered.copy() + + def update_ranges_after_compression(self, new_ranges: Dict[int, Tuple[int, int]]): + """Update each chunk's range based on actual compressed length""" + # Update chunk_ranges + for cid, (start, end) in new_ranges.items(): + if cid in self.chunk_ranges: + self.chunk_ranges[cid] = (start, end) + + # Update next_free_idx to maximum end + if new_ranges: + self.next_free_idx = max(end for start, end in new_ranges.values()) + else: + self.next_free_idx = 0 \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/memory_monitor.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/memory_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..9683d610e823b035b65281e81fdbdb1d1203833c --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/memory_monitor.py @@ -0,0 +1,195 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import time +from typing import List, Optional, Dict, Any +import logging + +class MemoryMonitor: + """ + Enhanced memory monitor for tracking tensor memory usage + """ + + def __init__(self, log_file: Optional[str] = None, enable_logging: bool = True): + self.log_file = log_file + self.enable_logging = enable_logging + self.peak_memory_usage = 0.0 + self.memory_history = [] + + # Setup logging + if self.enable_logging: + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file) if log_file else logging.StreamHandler(), + logging.StreamHandler() + ] + ) + self.logger = logging.getLogger(__name__) + + def get_tensor_memory_info(self, tensor_list: List[Any], unit: str = 'MB') -> Dict[str, Any]: + """ + Get detailed memory information for a list of tensors + """ + total_bytes = 0 + non_null_tensors = 0 + tensor_shapes = [] + tensor_devices = [] + + for i, t in enumerate(tensor_list): + if isinstance(t, torch.Tensor): + non_null_tensors += 1 + tensor_shapes.append(t.shape) + tensor_devices.append(str(t.device)) + + if t.is_cuda: + total_bytes += t.element_size() * t.numel() + else: + tensor_shapes.append(None) + tensor_devices.append(None) + + # Convert to requested unit + unit = unit.upper() + scale_dict = { + 'B': 1, + 'KB': 1024, + 'MB': 1024 ** 2, + 'GB': 1024 ** 3, + } + scale = scale_dict[unit] + + return { + 'total_memory_mb': total_bytes / scale, + 'total_memory_gb': total_bytes / (scale_dict['GB']), + 'total_elements': sum(t.numel() for t in tensor_list if isinstance(t, torch.Tensor) and t.is_cuda), + 'non_null_count': non_null_tensors, + 'total_count': len(tensor_list), + 'tensor_shapes': tensor_shapes, + 'tensor_devices': tensor_devices, + 'utilization_rate': non_null_tensors / len(tensor_list) if tensor_list else 0 + } + + def monitor_residual_memory(self, previous_residual: List[Any], + step: int, chunk_info: Optional[Dict] = None, + log_immediately: bool = True) -> Dict[str, Any]: + """ + Monitor memory usage of previous_residual specifically + """ + memory_info = self.get_tensor_memory_info(previous_residual, unit='MB') + memory_info['step'] = step + memory_info['timestamp'] = time.time() + + if chunk_info: + memory_info.update(chunk_info) + + # Track peak memory + if memory_info['total_memory_mb'] > self.peak_memory_usage: + self.peak_memory_usage = memory_info['total_memory_mb'] + memory_info['is_peak'] = True + else: + memory_info['is_peak'] = False + + # Store history + self.memory_history.append(memory_info) + + # Log if requested + if log_immediately and self.enable_logging: + self._log_memory_info(memory_info) + + return memory_info + + def _log_memory_info(self, memory_info: Dict[str, Any]): + """ + Log memory information in a formatted way + """ + msg = ( + f"Step {memory_info['step']:3d} | " + f"Residual Memory: {memory_info['total_memory_mb']:6.2f} MB | " + f"Tensors: {memory_info['non_null_count']:2d}/{memory_info['total_count']:2d} | " + f"Utilization: {memory_info['utilization_rate']*100:5.1f}%" + ) + + if memory_info['is_peak']: + msg += " | [NEW PEAK]" + + self.logger.info(msg) + + # Log detailed tensor shapes for debugging + if memory_info['non_null_count'] > 0: + shapes_str = ", ".join([str(s) for s in memory_info['tensor_shapes'] if s is not None]) + self.logger.debug(f" Tensor shapes: {shapes_str}") + + def get_memory_summary(self) -> Dict[str, Any]: + """ + Get summary of memory usage over time + """ + if not self.memory_history: + return {'error': 'No memory history available'} + + memory_values = [h['total_memory_mb'] for h in self.memory_history] + + return { + 'peak_memory_mb': max(memory_values), + 'average_memory_mb': sum(memory_values) / len(memory_values), + 'min_memory_mb': min(memory_values), + 'total_steps': len(self.memory_history), + 'peak_step': max(self.memory_history, key=lambda x: x['total_memory_mb'])['step'], + 'final_memory_mb': memory_values[-1] if memory_values else 0, + 'memory_growth': memory_values[-1] - memory_values[0] if len(memory_values) > 1 else 0 + } + + def save_memory_report(self, filename: str): + """ + Save detailed memory report to file + """ + import json + + summary = self.get_memory_summary() + report = { + 'summary': summary, + 'detailed_history': self.memory_history, + 'peak_memory_gb': self.peak_memory_usage / 1024 + } + + with open(filename, 'w') as f: + json.dump(report, f, indent=2, default=str) + + print(f"Memory report saved to: {filename}") + + def reset(self): + """ + Reset monitor state + """ + self.peak_memory_usage = 0.0 + self.memory_history = [] + +# Global monitor instance +_global_monitor = None + +def get_memory_monitor() -> MemoryMonitor: + """Get or create global memory monitor""" + global _global_monitor + if _global_monitor is None: + _global_monitor = MemoryMonitor() + return _global_monitor + +def monitor_residual_memory_step(previous_residual: List[Any], step: int, + chunk_info: Optional[Dict] = None) -> Dict[str, Any]: + """ + Convenience function to monitor a single step + """ + monitor = get_memory_monitor() + return monitor.monitor_residual_memory(previous_residual, step, chunk_info) \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..8caca9b6712ac62b47ea521702b10dbe477109a7 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py @@ -0,0 +1,82 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import torch +from typing import Optional + +from inference.common import MagiConfig, print_rank_0, set_random_seed +from inference.infra.distributed import dist_init +from inference.model.dit import get_dit + +from .prompt_process import get_txt_embeddings +from .video_generate import generate_per_chunk +from .video_process import post_chunk_process, process_image, process_prefix_video, save_video_to_disk + + +class MagiPipeline: + def __init__( + self, + config_path, + residual_stats_path: Optional[str] = None, + l1_rel_stats_path: Optional[str] = None, + token_l2_change_rate_stats_path: Optional[str] = None, + token_l2_change_rate_chunk_idx: int = 0, + ): + self.config = MagiConfig.from_json(config_path) + self.residual_stats_path = residual_stats_path + self.l1_rel_stats_path = l1_rel_stats_path + self.token_l2_change_rate_stats_path = token_l2_change_rate_stats_path + self.token_l2_change_rate_chunk_idx = token_l2_change_rate_chunk_idx + set_random_seed(self.config.runtime_config.seed) + dist_init(self.config) + print_rank_0(self.config) + + def run_text_to_video(self, prompt: str, output_path: str): + self._run(prompt, None, output_path) + + def run_image_to_video(self, prompt: str, image_path: str, output_path: str): + prefix_video = process_image(image_path, self.config) + self._run(prompt, prefix_video, output_path) + + def run_video_to_video(self, prompt: str, prefix_video_path: str, output_path: str): + prefix_video = process_prefix_video(prefix_video_path, self.config) + self._run(prompt, prefix_video, output_path) + + def _run(self, prompt: str, prefix_video: torch.Tensor, output_path: str): + caption_embs, emb_masks = get_txt_embeddings(prompt, self.config) # caption_embs: [1, 1, 800, 4096], emb_masks: [1, 800] + dit = get_dit(self.config) + videos = torch.cat( + [ + post_chunk_process(chunk, self.config) + for chunk in generate_per_chunk( + model=dit, + prefix_video=prefix_video, + caption_embs=caption_embs, + emb_masks=emb_masks, + residual_stats_path=self.residual_stats_path, + l1_rel_stats_path=self.l1_rel_stats_path, + token_l2_change_rate_stats_path=self.token_l2_change_rate_stats_path, + token_l2_change_rate_chunk_idx=self.token_l2_change_rate_chunk_idx, + ) + ], + dim=0, + ) + save_video_to_disk(videos, output_path, fps=self.config.runtime_config.fps) + + mem_allocated_gb = torch.cuda.max_memory_allocated() / 1024**3 + mem_reserved_gb = torch.cuda.max_memory_reserved() / 1024**3 + print_rank_0( + f"Finish MagiPipeline, max memory allocated: {mem_allocated_gb:.2f} GB, max memory reserved: {mem_reserved_gb:.2f} GB" + ) diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/prompt_process.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/prompt_process.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae9e712d6eee5616f13f29ee2711acb706d9ea3 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/prompt_process.py @@ -0,0 +1,209 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import gc +import os +from typing import List + +import numpy as np +import torch + +from inference.common import MagiConfig, env_is_true, magi_logger +from inference.infra.distributed import is_last_tp_cp_rank +from inference.infra.distributed import parallel_state as mpu +from inference.model.t5 import T5Embedder + +SPECIAL_TOKEN_PATH = os.getenv("SPECIAL_TOKEN_PATH", "example/assets/special_tokens.npz") +SPECIAL_TOKEN = np.load(SPECIAL_TOKEN_PATH) +CAPTION_TOKEN = torch.tensor(SPECIAL_TOKEN["caption_token"].astype(np.float16)) +LOGO_TOKEN = torch.tensor(SPECIAL_TOKEN["logo_token"].astype(np.float16)) +TRANS_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][:1].astype(np.float16)) +HQ_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][1:2].astype(np.float16)) +STATIC_FIRST_FRAMES_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][2:3].astype(np.float16)) # static first frames +DYNAMIC_FIRST_FRAMES_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][3:4].astype(np.float16)) # dynamic first frames +BORDERNESS_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][4:5].astype(np.float16)) +DURATION_TOKEN_LIST = [torch.tensor(SPECIAL_TOKEN["other_tokens"][i : i + 1].astype(np.float16)) for i in range(0 + 7, 8 + 7)] +THREE_D_MODEL_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][15:16].astype(np.float16)) +TWO_D_ANIME_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][16:17].astype(np.float16)) + +SPECIAL_TOKEN_DICT = { + "CAPTION_TOKEN": CAPTION_TOKEN, + "LOGO_TOKEN": LOGO_TOKEN, + "TRANS_TOKEN": TRANS_TOKEN, + "HQ_TOKEN": HQ_TOKEN, + "STATIC_FIRST_FRAMES_TOKEN": STATIC_FIRST_FRAMES_TOKEN, + "DYNAMIC_FIRST_FRAMES_TOKEN": DYNAMIC_FIRST_FRAMES_TOKEN, + "BORDERNESS_TOKEN": BORDERNESS_TOKEN, + "THREE_D_MODEL_TOKEN": THREE_D_MODEL_TOKEN, + "TWO_D_ANIME_TOKEN": TWO_D_ANIME_TOKEN, +} + +for i, token in enumerate(DURATION_TOKEN_LIST): + # DURATION_TOKEN_N represents N chunk(s) remain in the future + SPECIAL_TOKEN_DICT[f"DURATION_TOKEN_{i+1}"] = token + + +def pad_duration_token_keys(special_token_keys: List[str]) -> List[str]: + if "DURATION_TOKEN" in set(special_token_keys): + return special_token_keys + + if env_is_true("PAD_DURATION"): + return special_token_keys + ["DURATION_TOKEN"] + return special_token_keys + + +def get_special_token_keys() -> List[str]: + special_token_keys = [] + if env_is_true("PAD_STATIC"): + special_token_keys.append("STATIC_FIRST_FRAMES_TOKEN") + if env_is_true("PAD_DYNAMIC"): + special_token_keys.append("DYNAMIC_FIRST_FRAMES_TOKEN") + if env_is_true("PAD_BORDERNESS"): + special_token_keys.append("BORDERNESS_TOKEN") + if env_is_true("PAD_HQ"): + special_token_keys.append("HQ_TOKEN") + if env_is_true("PAD_THREE_D_MODEL"): + special_token_keys.append("THREE_D_MODEL_TOKEN") + if env_is_true("PAD_TWO_D_ANIME"): + special_token_keys.append("TWO_D_ANIME_TOKEN") + + special_token_keys = pad_duration_token_keys(special_token_keys) + return special_token_keys + + +def get_negative_special_token_keys() -> List[str]: + if env_is_true("NEG_PROMPT"): + return ["CAPTION_TOKEN", "LOGO_TOKEN", "TRANS_TOKEN", "BORDERNESS_TOKEN"] + return None + + +def _pad_special_token(special_token: torch.Tensor, txt_feat: torch.Tensor, attn_mask: torch.Tensor = None): + _device = txt_feat.device + _dtype = txt_feat.dtype + N, C, _, D = txt_feat.size() + txt_feat = torch.cat( + [special_token.unsqueeze(0).unsqueeze(0).to(_device).to(_dtype).expand(N, C, -1, D), txt_feat], dim=2 + )[:, :, :800, :] + if attn_mask is not None: + attn_mask = torch.cat([torch.ones(N, C, 1, dtype=_dtype, device=_device), attn_mask], dim=-1)[:, :, :800] + return txt_feat, attn_mask + + +def pad_special_token(special_token_keys: List[str], caption_embs: torch.Tensor, emb_masks: torch.Tensor): + device = f"cuda:{torch.cuda.current_device()}" + if not special_token_keys: + return caption_embs, emb_masks + for special_token_key in special_token_keys: + if special_token_key == "DURATION_TOKEN": + new_caption_embs, new_emb_masks = [], [] + num_chunks = caption_embs.size(1) + for i in range(num_chunks): + chunk_caption_embs, chunk_emb_masks = _pad_special_token( + DURATION_TOKEN_LIST[min(num_chunks - i - 1, 7)].to(device), + caption_embs[:, i : i + 1], + emb_masks[:, i : i + 1], + ) + new_caption_embs.append(chunk_caption_embs) + new_emb_masks.append(chunk_emb_masks) + caption_embs = torch.cat(new_caption_embs, dim=1) + emb_masks = torch.cat(new_emb_masks, dim=1) + else: + special_token = SPECIAL_TOKEN_DICT.get(special_token_key) + if special_token is not None: + caption_embs, emb_masks = _pad_special_token(special_token.to(device), caption_embs, emb_masks) + return caption_embs, emb_masks + + +_t5_cache = None + + +def _t5(model_cache_dir, model_device, model_max_length) -> T5Embedder: + global _t5_cache + if _t5_cache is None: + _t5_model = T5Embedder( + device=model_device, + local_cache=True, + cache_dir=model_cache_dir, + torch_dtype=torch.float, + model_max_length=model_max_length, + ) + if os.environ.get("OFFLOAD_T5_CACHE") == "true": + return _t5_model + _t5_cache = _t5_model + return _t5_cache + + +def prepare_prompt_embeddings(prompts: List[str], model_cache_dir, model_device, model_max_length): + magi_logger.info("Precompute validation prompt embeddings") + cur_rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0 + magi_logger.debug( + f"rank {cur_rank} memory allocated before precompute validation prompt embeddings: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {cur_rank} memory reserved before precompute validation prompt embeddings: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + + txt_embs = [] + for prompt in prompts: + with torch.no_grad(): + caption_embs, emb_masks = _t5(model_cache_dir, model_device, model_max_length).get_text_embeddings([prompt]) + caption_embs = caption_embs.float()[:, None] + txt_embs.append([caption_embs, emb_masks]) + magi_logger.debug(f"caption_embs.shape = {caption_embs.shape}") + magi_logger.debug(f"emb_masks.shape = {emb_masks.shape}") + + # put everything to CPU for future broadcast + txt_embs = [[x[0].cpu(), x[1].cpu()] for x in txt_embs] + + magi_logger.debug( + f"rank {cur_rank} memory allocated after precompute validation prompt embeddings: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {cur_rank} memory reserved after precompute validation prompt embeddings: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + gc.collect() + torch.cuda.empty_cache() + return txt_embs + + +def get_txt_embeddings(prompt: str, config: MagiConfig): + prompts = [prompt] + if not torch.distributed.is_initialized(): + txt_embs = prepare_prompt_embeddings( + prompts, + config.runtime_config.t5_pretrained, + config.runtime_config.t5_device, + config.model_config.caption_max_length, + ) + else: + if is_last_tp_cp_rank(): + txt_embs = prepare_prompt_embeddings( + prompts, + config.runtime_config.t5_pretrained, + config.runtime_config.t5_device, + config.model_config.caption_max_length, + ) + else: + txt_embs = [None] + src = mpu.get_tensor_model_parallel_last_rank(with_context_parallel=True) + group = mpu.get_tp_group(with_context_parallel=True) + torch.distributed.broadcast_object_list(txt_embs, src=src, group=group) + + # Only process one prompt + assert len(txt_embs) == 1 + caption_embs, emb_masks = txt_embs[0] + device = f"cuda:{torch.cuda.current_device()}" + caption_embs, emb_masks = caption_embs.to(device), emb_masks.to(device) + return caption_embs, emb_masks diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/teacache.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/teacache.py new file mode 100644 index 0000000000000000000000000000000000000000..fa45885f0b62ede240aee06417376f49eeb4e30d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/teacache.py @@ -0,0 +1,519 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +TeaCache implementation for full output reuse. + +This module provides TeaCache, which reuses all model outputs together when +the accumulated relative L1 distance is below threshold. +""" + +import argparse +import gc +import sys +import torch +from types import MethodType + +from inference.pipeline import MagiPipeline +from inference.pipeline.video_generate import SampleTransport, find_dit_model +from inference.pipeline.cache import TeaCache +from inference.pipeline.cache.utils import get_embedding_and_meta_with_chunk_info + + +def setup_teacache( + rel_l1_thresh: float = 0.01, + warmup_steps: int = 0, + log: bool = False +): + """ + Set up TeaCache for SampleTransport. + + Args: + rel_l1_thresh: Relative L1 distance threshold for reuse + warmup_steps: Number of warmup steps before reuse can happen + log: Whether to log reuse decisions + """ + # Create cache instance and attach to SampleTransport + SampleTransport.cache_reuse_manager = TeaCache( + rel_l1_thresh=rel_l1_thresh, + warmup_steps=warmup_steps, + log=log + ) + + # Monkey patch the SampleTransport methods + SampleTransport.forward_velocity = teacache_forward_velocity + SampleTransport.integrate_velocity = teacache_integrate_velocity + + +def teacache_forward_velocity(self, infer_idx: int, cur_denoise_step: int) -> torch.Tensor: + """ + Forward pass with TeaCache output reuse. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + + Returns: + Velocity tensor + """ + # Get cache from class attribute + teacache = SampleTransport.cache_reuse_manager + + # 1. Get current work status + x = self.xs[infer_idx] + transport_input = self.transport_inputs[infer_idx] + + # 2. Extract denoising status + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + + # 3. Prepare model kwargs + model_kwargs = dict( + chunk_width=self.chunk_width, + fwd_extra_1st_chunk=False, + num_steps=transport_input.num_steps + ) + model_kwargs.update({ + "denoise_step_per_stage": denoise_step_per_stage, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx + }) + + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + model_kwargs["chunk_token_nums"] = chunk_token_nums + model_kwargs["chunk_num"] = transport_input.chunk_num + model_kwargs["chunk_offset"] = chunk_offset + + if chunk_offset > 0 and cur_denoise_step == 0: + self.extract_prefix_video_feature( + infer_idx, transport_input.prefix_video, transport_input.y, chunk_offset, model_kwargs + ) + + # 4. Prepare inputs + x_chunk = x[:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width].clone() + y_chunk = transport_input.y[:, chunk_start:chunk_end] + mask_chunk = transport_input.emb_masks[:, chunk_start:chunk_end] + model_kwargs.update({ + "slice_point": chunk_start, + "range_num": chunk_end, + "denoising_range_num": chunk_end - chunk_start + }) + + # 5. Prepare timesteps + denoise_step_of_each_chunk = self.get_denoise_step_of_each_chunk( + infer_idx, denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = t.unsqueeze(0).repeat(x_chunk.size(0), 1) + + # 6. Generate KV range + kv_range = self.generate_kvrange_for_denoising_video( + infer_idx=infer_idx, + slice_point=model_kwargs["slice_point"], + denoising_range_num=model_kwargs["denoising_range_num"], + denoise_step_of_each_chunk=denoise_step_of_each_chunk, + ) + + # 7. Pad prefix video if needed + if transport_input.prefix_video is not None: + x_chunk, t = self.try_pad_prefix_video( + infer_idx, x_chunk, t, prefix_video_start=model_kwargs["slice_point"] * self.chunk_width + ) + + # 8. Model forward + forward_fn = find_dit_model(self.model).forward_dispatcher + nearly_clean_chunk_t = t[0, int(model_kwargs["fwd_extra_1st_chunk"])].item() + model_kwargs["distill_nearly_clean_chunk"] = ( + nearly_clean_chunk_t > self.engine_config.distill_nearly_clean_chunk_threshold + ) + model_kwargs["distill_interval"] = self.time_interval[infer_idx][denoise_idx] + model_kwargs["total_num_steps"] = self.total_forward_step(infer_idx) + + # Initialize TeaCache step counter + if teacache.cnt == 0 and teacache.num_steps == 0: + teacache.num_steps = model_kwargs["total_num_steps"] + + # Setup monkey-patched model forward + model = find_dit_model(self.model) + model.forward = MethodType(_create_model_forward_fn(teacache), model) + model.get_embedding_and_meta = MethodType(_new_get_embedding_and_meta, model) + + velocity = forward_fn( + x=x_chunk, + timestep=t, + y=y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + mask=mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + kv_range=kv_range, + inference_params=self.inference_params[infer_idx], + **model_kwargs, + ) + + self.x_chunks[infer_idx] = x_chunk + self.velocities[infer_idx] = velocity + return velocity + + +def _create_model_forward_fn(teacache: TeaCache): + """ + Create a model forward function with TeaCache logic. + + Args: + teacache: TeaCache instance + + Returns: + Model forward function + """ + @torch.no_grad() + def model_forward( + model_self, + x, + t, + y, + caption_dropout_mask=None, + xattn_mask=None, + kv_range=None, + inference_params=None, + **kwargs, + ) -> torch.Tensor: + raw_x = x.clone() + + # 1. Compute feature metric + metric_x = teacache.compute_feature_metric( + x=x, + x_embedder=model_self.x_embedder, + x_rescale_factor=model_self.model_config.x_rescale_factor, + half_channel_vae=model_self.model_config.half_channel_vae, + params_dtype=model_self.model_config.params_dtype + ) + + # 2. Update kwargs with TeaCache state + teacache.total_num_steps = kwargs['total_num_steps'] + denoise_step_per_stage = kwargs['denoise_step_per_stage'] + kwargs["start_chunk_id"] = kwargs['slice_point'] + kwargs["end_chunk_id"] = kwargs['range_num'] + kwargs['cur_denoise_step'] = teacache.cnt + model_self.cur_denoise_step = teacache.cnt + + if kwargs.get("distill_nearly_clean_chunk", False): + kwargs["end_chunk_id"] += 1 + + # Handle nearly clean chunk (not used in TeaCache) + if kwargs.get("fwd_extra_1st_chunk", False): + metric_x = metric_x[kwargs["chunk_token_nums"]:, :, :] + if kwargs.get("distill_nearly_clean_chunk", False): + metric_x = metric_x[:-kwargs["chunk_token_nums"], :, :] + + # 3. Check if should reuse or calculate + current_num_chunks = metric_x.shape[0] // kwargs["chunk_token_nums"] + previous_num_chunks = ( + teacache.previous_modulated_input.shape[0] // kwargs["chunk_token_nums"] + if teacache.previous_modulated_input is not None else 0 + ) + + should_reuse = teacache.should_reuse( + chunk_id=0, # Not used in TeaCache + step=teacache.cnt, + current_features=metric_x, + denoise_step_per_stage=denoise_step_per_stage, + num_chunks_current=current_num_chunks, + num_chunks_previous=previous_num_chunks + ) + + # 4. Handle partial reuse at stage boundary + if (not should_reuse and + teacache.cnt % denoise_step_per_stage == 0 and + current_num_chunks > previous_num_chunks and + teacache.accumulated_rel_l1_distance < teacache.rel_l1_thresh): + + # Only calculate new chunk + range_num = kwargs['range_num'] - kwargs['chunk_offset'] + if kwargs.get("distill_nearly_clean_chunk", False): + x = x[:, :, (range_num - 2) * kwargs['chunk_width']:(range_num - 1) * kwargs['chunk_width']] + y = y[range_num - 2:range_num - 1] + t = t[:, range_num - 2:range_num - 1] + xattn_mask = xattn_mask[range_num - 2:range_num - 1] + kwargs["start_chunk_id"] = kwargs['range_num'] - 2 + kwargs["end_chunk_id"] = kwargs['range_num'] - 1 + kwargs["denoising_range_num"] = 1 + model_self.discard_nearly_clean_chunk = True + else: + x = x[:, :, (range_num - 1) * kwargs['chunk_width']:range_num * kwargs['chunk_width']] + y = y[range_num - 1:range_num] + t = t[:, range_num - 1:range_num] + xattn_mask = xattn_mask[range_num - 1:range_num] + kwargs["start_chunk_id"] = kwargs['range_num'] - 1 + kwargs["denoising_range_num"] = 1 + + model_self.single_chunk_inference = True + model_self.denoising_range_num = kwargs["denoising_range_num"] + + # Store features for next step + teacache.store_previous_features(metric_x) + + # 5. Forward or reuse + if teacache.should_calc: + (x, condition, condition_map, y_xattn_flat, rope, meta_args) = model_self.forward_pre_process( + x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs + ) + + if not model_self.pre_process: + from inference.pipeline.parallelism import pp_scheduler + x = pp_scheduler().recv_prev_data(x.shape, x.dtype) + model_self.videodit_blocks.set_input_tensor(x) + else: + x = x.clone() + + x = model_self.videodit_blocks.forward( + hidden_states=x, + condition=condition, + condition_map=condition_map, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rope, + inference_params=inference_params, + meta_args=meta_args, + ) + + if not model_self.post_process: + from inference.pipeline.parallelism import pp_scheduler + pp_scheduler().isend_next(x) + + return model_self.forward_post_process(x, meta_args) + else: + # Reuse: return zeros (output not used) + return torch.zeros_like(raw_x) + + return model_forward + + +@torch.no_grad() +def _new_get_embedding_and_meta( + model_self, + x, + t, + y, + caption_dropout_mask, + xattn_mask, + kv_range, + **kwargs +): + """Monkey-patched version of get_embedding_and_meta with chunk info.""" + return get_embedding_and_meta_with_chunk_info( + model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs + ) + + +def teacache_integrate_velocity(self, infer_idx: int, cur_denoise_step: int): + """ + Integrate velocity with TeaCache residual handling. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + """ + # Get cache from class attribute + teacache = SampleTransport.cache_reuse_manager + + transport_input = self.transport_inputs[infer_idx] + x_chunk = self.x_chunks[infer_idx] + velocity = self.velocities[infer_idx] + chunk_denoise_count = self.chunk_denoise_count[infer_idx] + + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + + # Integrate with residual handling + ori_x_chunk = x_chunk.clone() + + if teacache.should_calc: + if velocity.shape[2] < x_chunk.shape[2]: + # Partial reuse: only last chunk was computed + t_num = x_chunk.shape[2] // self.chunk_width + x_chunk = x_chunk[:, :, -self.chunk_width:] + x_chunk = self.integrate( + x_chunk, velocity, self.ts[infer_idx], denoise_step_per_stage, + t_start, t_end, denoise_idx, delta_t_index=t_num - 1 + ) + # Concatenate with reused chunks + x_chunk = torch.cat([teacache.previous_output, x_chunk], dim=2) + else: + # Full calculation + x_chunk = self.integrate( + x_chunk, velocity, self.ts[infer_idx], denoise_step_per_stage, + t_start, t_end, denoise_idx + ) + + # Store residual for next step + teacache.update_residual(0, x_chunk - ori_x_chunk) + + # Store output for potential next stage reuse + if (teacache.cnt + 1) % denoise_step_per_stage == 0: + teacache.previous_output = x_chunk + else: + # Reuse: add residual to input + x_chunk = x_chunk + teacache.previous_residual[:, :, -x_chunk.shape[2]:] + + # Increment step counter + teacache.increment_step() + + # Update chunk denoise count + for chunk_index in range(chunk_start, chunk_end): + chunk_denoise_count[chunk_index] += 1 + + self.xs[infer_idx][:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width] = x_chunk + self.chunk_denoise_count[infer_idx] = chunk_denoise_count + + # Return clean chunk if ready + if chunk_denoise_count[chunk_start] == transport_input.num_steps: + return _return_clean_chunk( + self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset + ) + + return None, None + + +def _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset): + """ + Return the clean chunk if denoising is complete. + + Args: + self: SampleTransport instance + infer_idx: Inference index + transport_input: Transport input + chunk_start: Start chunk ID + chunk_end: End chunk ID + chunk_offset: Prefix video offset + + Returns: + Tuple of (clean_chunk, relative_chunk_id) or (None, None) + """ + if transport_input.prefix_video is not None: + prefix_video_length = transport_input.prefix_video.size(2) + if (chunk_start + 1) * self.chunk_width <= prefix_video_length: + return None, None + + real_start = max(chunk_start * self.chunk_width, prefix_video_length) + + # Keep the first 4-frames only for I2V Job + if chunk_start == 0 and prefix_video_length == 1: + real_start = 0 + + clean_chunk, _ = self.xs[infer_idx][:, :, real_start:(chunk_start + 1) * self.chunk_width].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + else: + clean_chunk, _ = self.xs[infer_idx][ + :, :, chunk_start * self.chunk_width:(chunk_start + 1) * self.chunk_width + ].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + + +def parse_arguments(): + """Parse command line arguments.""" + parser = argparse.ArgumentParser(description="Run MagiPipeline with TeaCache.") + parser.add_argument('--config_file', type=str, help='Path to the configuration file.') + parser.add_argument( + '--mode', type=str, choices=['t2v', 'i2v', 'v2v'], + required=True, help='Mode to run: t2v, i2v, or v2v.' + ) + parser.add_argument('--prompt', type=str, required=True, help='Prompt for the pipeline.') + parser.add_argument('--image_path', type=str, help='Path to the image file (for i2v mode).') + parser.add_argument('--prefix_video_path', type=str, help='Path to the prefix video file (for v2v mode).') + parser.add_argument('--output_path', type=str, required=True, help='Path to save the output video.') + parser.add_argument('--use_teacache', action='store_true', help='Whether to use TeaCache.') + parser.add_argument('--rel_l1_thresh', type=float, default=0.01, help='Relative L1 distance threshold.') + parser.add_argument('--warmup_steps', type=int, default=0, help='Number of warmup steps before reuse.') + parser.add_argument('--log', action='store_true', help='Whether to log TeaCache information.') + parser.add_argument('--print_peak_memory', action='store_true', help='Print peak memory usage.') + + return parser.parse_args() + + +def main(): + """Main entry point.""" + args = parse_arguments() + + if args.print_peak_memory: + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + device = torch.cuda.current_device() + print(f"Running on GPU: {torch.cuda.get_device_name(device)}") + print(f"GPU Memory before pipeline: {torch.cuda.memory_allocated(device) / 1024**3:.2f} GB") + else: + print("CUDA not available, running on CPU") + + print(f"TeaCache config: rel_l1_thresh={args.rel_l1_thresh}, " + f"warmup_steps={args.warmup_steps}") + + # Setup TeaCache + setup_teacache( + rel_l1_thresh=args.rel_l1_thresh, + warmup_steps=args.warmup_steps, + log=args.log + ) + + # Run pipeline + pipeline = MagiPipeline(args.config_file) + + if args.mode == 't2v': + pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) + elif args.mode == 'i2v': + if not args.image_path: + print("Error: --image_path is required for i2v mode.") + sys.exit(1) + pipeline.run_image_to_video(prompt=args.prompt, image_path=args.image_path, output_path=args.output_path) + elif args.mode == 'v2v': + if not args.prefix_video_path: + print("Error: --prefix_video_path is required for v2v mode.") + sys.exit(1) + pipeline.run_video_to_video( + prompt=args.prompt, prefix_video_path=args.prefix_video_path, output_path=args.output_path + ) + + if args.print_peak_memory: + if torch.cuda.is_available(): + peak_memory = torch.cuda.max_memory_allocated(device) / 1024**3 + current_memory = torch.cuda.memory_allocated(device) / 1024**3 + cached_memory = torch.cuda.memory_reserved(device) / 1024**3 + total_memory = torch.cuda.get_device_properties(device).total_memory / 1024**3 + + print("\n" + "=" * 50) + print("GPU Memory Usage Summary:") + print(f"Peak memory allocated: {peak_memory:.2f} GB") + print(f"Current memory allocated: {current_memory:.2f} GB") + print(f"Cached memory reserved: {cached_memory:.2f} GB") + print(f"Total GPU memory: {total_memory:.2f} GB") + print(f"Peak memory usage: {(peak_memory/total_memory)*100:.1f}%") + print("=" * 50) + + gc.collect() + torch.cuda.empty_cache() + final_memory = torch.cuda.memory_allocated(device) / 1024**3 + print(f"Memory after cache cleanup: {final_memory:.2f} GB") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/utils.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fe8bdcdc2227c22edf09514a25ac73f4f392b559 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/utils.py @@ -0,0 +1,21 @@ +import torch + +def get_tensors_memory_usage(tensor_list, unit='MB'): + total_bytes = 0 + for t in tensor_list: + if isinstance(t, torch.Tensor) and t.is_cuda: + total_bytes += t.element_size() * t.numel() + + unit = unit.upper() + scale_dict = { + 'B': 1, + 'KB': 1024, + 'MB': 1024 ** 2, + 'GB': 1024 ** 3, + } + + if unit not in scale_dict: + raise ValueError(f"Unsupported unit: {unit}. Use 'B', 'KB', 'MB', or 'GB'.") + + scale = scale_dict[unit] + return total_bytes / scale \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py new file mode 100644 index 0000000000000000000000000000000000000000..d44a8a05dc4905602a25eece9857a50b5ae2e33e --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py @@ -0,0 +1,1367 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import json +import math +import os +from collections import Counter +from dataclasses import dataclass, field +from queue import Queue +from typing import Dict, Generator, List, Optional, Tuple, Union +from types import MethodType + +import torch +import torch.distributed as dist +from tqdm import tqdm + +import inference.infra.distributed.parallel_state as mpu +from inference.common import InferenceParams, event_path_timer, print_rank_0 +from inference.infra.parallelism import pp_scheduler + +from .prompt_process import get_negative_special_token_keys, get_special_token_keys, pad_special_token + + +@dataclass(frozen=True) +class InferenceInput: + caption_embs: torch.Tensor + emb_masks: torch.Tensor + y: torch.Tensor + prefix_video: Union[torch.Tensor, None] + latent_size: Tuple[int] + t_schedule_config: Dict = field(default_factory=dict) + num_steps: int = None + vae_ckpt: str = None + task_idx_list: List[int] = None + report_chunk_num_list: List[int] = None + chunk_num: int = None + + +def _process_txt_embeddings( + caption_embs: torch.Tensor, emb_masks: torch.Tensor, null_emb: torch.Tensor, infer_chunk_num: int, clean_chunk_num: int +) -> Tuple[torch.Tensor, torch.Tensor]: + special_token_keys = get_special_token_keys() + print_rank_0(f"special_token = {list(special_token_keys)}") + + # denoise chunk with caption_embs + caption_embs = caption_embs.repeat(1, infer_chunk_num - clean_chunk_num, 1, 1) + emb_masks = emb_masks.unsqueeze(1).repeat(1, infer_chunk_num - clean_chunk_num, 1) + caption_embs, emb_masks = pad_special_token(special_token_keys, caption_embs, emb_masks) + + # clean chunk with null_emb + caption_embs = torch.cat([null_emb.repeat(1, clean_chunk_num, 1, 1), caption_embs], dim=1) + emb_masks = torch.cat( + [torch.zeros(1, clean_chunk_num, emb_masks.size(2), dtype=emb_masks.dtype, device=emb_masks.device), emb_masks], dim=1 + ) + return caption_embs, emb_masks + + +def _process_null_embeddings( + null_caption_embedding: torch.Tensor, null_emb_masks: torch.Tensor, infer_chunk_num: int +) -> Tuple[torch.Tensor, torch.Tensor]: + null_embs = null_caption_embedding.repeat(1, infer_chunk_num, 1, 1) + negative_special_token_keys = get_negative_special_token_keys() + if negative_special_token_keys: + null_embs, _ = pad_special_token(negative_special_token_keys, null_embs, None) + + null_token_length = 50 + null_emb_masks[:, :, :null_token_length] = 1 + null_emb_masks[:, :, null_token_length:] = 0 + + return null_embs, null_emb_masks + + +@torch.inference_mode() +def extract_feature_for_inference( + model: torch.nn.Module, prefix_video: torch.Tensor, caption_embs: torch.Tensor, emb_masks: torch.Tensor +) -> InferenceInput: + model_config = model.model_config + runtime_config = model.runtime_config + ### Prepare prefix video feature + clean_chunk_num = 0 + if prefix_video is not None: + clean_chunk_num = prefix_video.size(2) // runtime_config.chunk_width + infer_chunk_num = math.ceil( + (runtime_config.num_frames // runtime_config.temporal_downsample_factor * 1.0 + prefix_video.size(2)) + / runtime_config.chunk_width + ) + else: + infer_chunk_num = math.ceil( + (runtime_config.num_frames // runtime_config.temporal_downsample_factor * 1.0) / runtime_config.chunk_width + ) + + ### Prepare text feature + # [1, caption_max_length (800), hidden_size(4096)] + null_caption_embedding = model.y_embedder.null_caption_embedding.unsqueeze(0) + caption_embs, caption_emb_masks = _process_txt_embeddings( + caption_embs, emb_masks, null_caption_embedding, infer_chunk_num, clean_chunk_num + ) + null_emb_masks = torch.zeros_like(caption_emb_masks) + null_embs, null_emb_masks = _process_null_embeddings(null_caption_embedding, null_emb_masks, infer_chunk_num) + + if emb_masks.sum() == 0: + emb_masks = torch.cat([null_emb_masks, null_emb_masks], dim=0) + y = torch.cat([null_embs, null_embs]) + else: + emb_masks = torch.cat([caption_emb_masks, null_emb_masks], dim=0) + y = torch.cat([caption_embs, null_embs]) + + ### Prepare latent feature dims + in_channels = model_config.in_channels + if model_config.half_channel_vae: + in_channels = 16 + latent_size_t = infer_chunk_num * runtime_config.chunk_width + latent_size_h = runtime_config.video_size_h // 8 + latent_size_w = runtime_config.video_size_w // 8 + + return InferenceInput( + caption_embs=caption_embs, # [1, 4, 800, 4096] + emb_masks=emb_masks, # [2, 4, 800] + y=y, # [2, 4, 800, 4096] + prefix_video=prefix_video, + latent_size=(1, in_channels, latent_size_t, latent_size_h, latent_size_w), # NCTHW + t_schedule_config={}, + num_steps=runtime_config.num_steps, + task_idx_list=[0], + report_chunk_num_list=[infer_chunk_num - clean_chunk_num], + chunk_num=latent_size_t // runtime_config.chunk_width, + ) + + +# Example1: when chunk_num=8, window_size=8 +# clip_start: [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7] +# clip_end : [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8] +# t_start : [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7] +# t_end : [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8] + +# Example2: when chunk_num=8, window_size=4 +# clip_start: [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7] +# clip_end : [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8] +# t_start : [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3] +# t_end : [1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4] + +# Example3: when chunk_num=8, window_size=4, chunk_offset=2 +# clip_start: [2, 2, 2, 2, 3, 4, 5, 6, 7] +# clip_end : [3, 4, 5, 6, 7, 8, 8, 8, 8] +# t_start : [0, 0, 0, 0, 0, 0, 1, 2, 3] +# t_end : [1, 2, 3, 4, 4, 4, 4, 4, 4] + +# Example4: when chunk_num=8, window_size=1 +# clip_start: [0, 1, 2, 3, 4, 5, 6, 7] +# clip_end : [1, 2, 3, 4, 5, 6, 7, 8] +# t_start : [0, 0, 0, 0, 0, 0, 0, 0] +# t_end : [1, 1, 1, 1, 1, 1, 1, 1] + + +def generate_sequences(chunk_num, window_size, chunk_offset): + # Adjust range to include the offset + start_index = chunk_offset + end_index = chunk_num + window_size - 1 + + # Generate clip_start and clip_end + clip_start = [max(chunk_offset, i - window_size + 1) for i in range(start_index, end_index)] + clip_end = [min(chunk_num, i + 1) for i in range(start_index, end_index)] + + # Generate t_start and t_end + t_start = [max(0, i - chunk_num + 1) for i in range(start_index, end_index)] + t_end = [ + min(window_size, i - chunk_offset + 1) if i - chunk_offset < window_size else window_size + for i in range(start_index, end_index) + ] + + return clip_start, clip_end, t_start, t_end + + +def init_t(t_schedule_config: Union[Dict, None], num_steps: int, device: torch.device, shortcut_mode: str = ""): + """Init Timestep and Transform t""" + if num_steps == 12: + base_t = torch.linspace(0, 1, 4 + 1, device=device) / 4 + accu_num = torch.linspace(0, 1, 4 + 1, device=device) + if shortcut_mode == "16,16,8": + base_t = base_t[:3] + else: + base_t = torch.cat([base_t[:1], base_t[2:4]], dim=0) + t = torch.cat([base_t + accu for accu in accu_num], dim=0)[: (num_steps + 1)] + else: + t = torch.linspace(0, 1, num_steps + 1, device=device) + t_schedule_func = t_schedule_config.get("tSchedulerFunc", "sd3") + if t_schedule_func == "sd3": + + def t_resolution_transform(x, shift=3.0): + # sd3: with a **reverse** time-schedule (0: clean, 1: noise) + # ours (0: noise, 1: clean) + # https://github.com/Stability-AI/sd3-ref/blob/master/sd3_impls.py#L33 + assert shift >= 1.0, "shift should >=1" + shift_inv = 1.0 / shift + return shift_inv * x / (1 + (shift_inv - 1) * x) + + t = t**2 + shift = t_schedule_config.get("shift", 3.0) + t = t_resolution_transform(t, shift) + elif t_schedule_func == "square": + t = t**2 + elif t_schedule_func == "piecewise": + + def t_transform(x): + mask = x < 0.875 + x[mask] = x[mask] * (0.5 / 0.875) + x[~mask] = 0.5 + (x[~mask] - 0.875) * (0.5 / (1 - 0.875)) + return x + + t = t_transform(t) + else: # identity + pass + return t + + +def init_intervel(num_steps: int, device: torch.device, shortcut_mode: str = ""): + """Init intervel""" + base_intervel = torch.ones(num_steps, device=device) + if num_steps % 3 == 0: + repeat_times = num_steps // 3 + if shortcut_mode == "16,16,8": + base_intervel = torch.tensor([1, 1, 2] * repeat_times, device=device) + else: + base_intervel = torch.tensor([2, 1, 1] * repeat_times, device=device) + return base_intervel + + +@dataclass +class WorkStatus: + infer_idx: int + cur_denoise_step: int + + +class ResidualDiffTracker: + def __init__(self, save_path: Optional[str]): + self.save_path = save_path + self.prev_residuals = {} + self.prev_timesteps = {} + self.records = [] + + @property + def enabled(self) -> bool: + return bool(self.save_path) + + def is_writer_rank(self) -> bool: + return not dist.is_available() or not dist.is_initialized() or dist.get_rank() == 0 + + def update( + self, + infer_idx: int, + cur_denoise_step: int, + denoise_stage: int, + denoise_idx: int, + chunk_offset: int, + chunk_start: int, + x_chunk: torch.Tensor, + velocity: torch.Tensor, + timesteps: torch.Tensor, + chunk_width: int, + ) -> None: + residual = (velocity[0:1] - x_chunk[0:1]).detach() + self.update_residuals( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + residual=residual, + timesteps=timesteps, + chunk_width=chunk_width, + ) + + def update_residuals( + self, + infer_idx: int, + cur_denoise_step: int, + denoise_stage: int, + denoise_idx: int, + chunk_offset: int, + chunk_start: int, + residual: torch.Tensor, + timesteps: torch.Tensor, + chunk_width: int, + ) -> None: + if not self.enabled or not self.is_writer_rank(): + return + + residual = residual[0:1].detach() + timesteps = timesteps.detach() + assert residual.size(2) % chunk_width == 0 + chunk_num = residual.size(2) // chunk_width + assert timesteps.size(0) == chunk_num + residual = residual.reshape(residual.size(0), residual.size(1), chunk_num, chunk_width, *residual.shape[3:]) + + for local_chunk_idx in range(chunk_num): + chunk_idx = chunk_start + local_chunk_idx + key = (infer_idx, chunk_idx) + cur_residual = residual[:, :, local_chunk_idx].clone() + cur_timestep = float(timesteps[local_chunk_idx].item()) + + if key in self.prev_residuals: + prev_residual = self.prev_residuals[key] + diff_norm = torch.linalg.vector_norm(cur_residual.float() - prev_residual.float()).item() + residual_norm = torch.linalg.vector_norm(cur_residual.float()).item() + self.records.append( + { + "infer_idx": infer_idx, + "cur_denoise_step": cur_denoise_step, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx, + "chunk_idx": chunk_idx, + "generated_chunk_idx": chunk_idx - chunk_offset, + "prev_timestep": self.prev_timesteps[key], + "timestep": cur_timestep, + "residual_diff_norm": diff_norm, + "residual_norm": residual_norm, + } + ) + + self.prev_residuals[key] = cur_residual + self.prev_timesteps[key] = cur_timestep + + def save(self) -> None: + if not self.enabled or not self.is_writer_rank(): + return + save_dir = os.path.dirname(self.save_path) + if save_dir: + os.makedirs(save_dir, exist_ok=True) + + payload = { + "description": ( + "Per-chunk norm of residual differences across denoise timesteps. " + "For vanilla MAGI residual = velocity - x; for FlowCache residual = X_next - X_t." + ), + "records": self.records, + } + if self.save_path.endswith((".pt", ".pth")): + torch.save(payload, self.save_path) + else: + with open(self.save_path, "w") as f: + json.dump(payload, f, indent=2) + print_rank_0(f"Saved residual diff stats to {self.save_path}") + + +class L1RelChangeTracker: + def __init__(self, save_path: Optional[str], eps: float = 1e-6): + self.save_path = save_path + self.eps = eps + self.records = [] + + @property + def enabled(self) -> bool: + return bool(self.save_path) + + def is_writer_rank(self) -> bool: + return not dist.is_available() or not dist.is_initialized() or dist.get_rank() == 0 + + def update( + self, + infer_idx: int, + cur_denoise_step: int, + denoise_stage: int, + denoise_idx: int, + chunk_offset: int, + chunk_start: int, + x_before: torch.Tensor, + x_after: torch.Tensor, + timesteps: torch.Tensor, + next_timesteps: torch.Tensor, + chunk_width: int, + x_embedder_before: Optional[torch.Tensor] = None, + x_embedder_after: Optional[torch.Tensor] = None, + x_embedder_chunk_width: Optional[int] = None, + ) -> None: + if not self.enabled or not self.is_writer_rank(): + return + + x_before = x_before[0:1].detach() + x_after = x_after[0:1].detach() + timesteps = timesteps.detach() + next_timesteps = next_timesteps.detach() + assert x_before.size(2) == x_after.size(2) + assert x_before.size(2) % chunk_width == 0 + chunk_num = x_before.size(2) // chunk_width + assert timesteps.size(0) == chunk_num + assert next_timesteps.size(0) == chunk_num + + x_before = x_before.reshape(x_before.size(0), x_before.size(1), chunk_num, chunk_width, *x_before.shape[3:]) + x_after = x_after.reshape(x_after.size(0), x_after.size(1), chunk_num, chunk_width, *x_after.shape[3:]) + + x_embedder_before_by_chunk = None + x_embedder_after_by_chunk = None + if x_embedder_before is not None and x_embedder_after is not None and x_embedder_chunk_width is not None: + x_embedder_before = x_embedder_before[0:1].detach() + x_embedder_after = x_embedder_after[0:1].detach() + assert x_embedder_before.size(2) == x_embedder_after.size(2) + assert x_embedder_before.size(2) % x_embedder_chunk_width == 0 + assert x_embedder_before.size(2) // x_embedder_chunk_width == chunk_num + x_embedder_before_by_chunk = x_embedder_before.reshape( + x_embedder_before.size(0), + x_embedder_before.size(1), + chunk_num, + x_embedder_chunk_width, + *x_embedder_before.shape[3:], + ) + x_embedder_after_by_chunk = x_embedder_after.reshape( + x_embedder_after.size(0), + x_embedder_after.size(1), + chunk_num, + x_embedder_chunk_width, + *x_embedder_after.shape[3:], + ) + + for local_chunk_idx in range(chunk_num): + chunk_idx = chunk_start + local_chunk_idx + cur_x = x_before[:, :, local_chunk_idx].float() + next_x = x_after[:, :, local_chunk_idx].float() + delta = next_x - cur_x + denom = cur_x.abs().clamp_min(self.eps) + + l1_rel = (delta.abs() / denom).mean().item() + delta_l1_norm = delta.abs().sum().item() + x_l1_norm = cur_x.abs().sum().item() + l1_rel_ratio = delta_l1_norm / max(x_l1_norm, self.eps) + + self.records.append( + { + "infer_idx": infer_idx, + "cur_denoise_step": cur_denoise_step, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx, + "chunk_idx": chunk_idx, + "generated_chunk_idx": chunk_idx - chunk_offset, + "timestep": float(timesteps[local_chunk_idx].item()), + "next_timestep": float(next_timesteps[local_chunk_idx].item()), + "l1_rel": l1_rel, + "l1_rel_ratio": l1_rel_ratio, + "delta_l1_norm": delta_l1_norm, + "x_l1_norm": x_l1_norm, + } + ) + + if x_embedder_before_by_chunk is not None and x_embedder_after_by_chunk is not None: + cur_x_embedder = x_embedder_before_by_chunk[:, :, local_chunk_idx].float() + next_x_embedder = x_embedder_after_by_chunk[:, :, local_chunk_idx].float() + x_embedder_delta = next_x_embedder - cur_x_embedder + x_embedder_denom = cur_x_embedder.abs().clamp_min(self.eps) + x_embedder_l1_rel = (x_embedder_delta.abs() / x_embedder_denom).mean().item() + x_embedder_delta_l1_norm = x_embedder_delta.abs().sum().item() + x_embedder_l1_norm = cur_x_embedder.abs().sum().item() + x_embedder_l1_rel_ratio = x_embedder_delta_l1_norm / max(x_embedder_l1_norm, self.eps) + + self.records[-1].update( + { + "x_embedder_l1_rel": x_embedder_l1_rel, + "x_embedder_l1_rel_ratio": x_embedder_l1_rel_ratio, + "x_embedder_delta_l1_norm": x_embedder_delta_l1_norm, + "x_embedder_x_l1_norm": x_embedder_l1_norm, + } + ) + + def save(self) -> None: + if not self.enabled or not self.is_writer_rank(): + return + save_dir = os.path.dirname(self.save_path) + if save_dir: + os.makedirs(save_dir, exist_ok=True) + + payload = { + "description": ( + "Per-chunk relative L1 change across MAGI denoise steps. MAGI timesteps increase from noise " + "to clean, so next_timestep is the cleaner step. l1_rel = mean(abs((X_next - X_t) / " + "(abs(X_t) + eps))). x_embedder_* fields apply the same computation after DiT x_embedder." + ), + "eps": self.eps, + "records": self.records, + } + if self.save_path.endswith((".pt", ".pth")): + torch.save(payload, self.save_path) + else: + with open(self.save_path, "w") as f: + json.dump(payload, f, indent=2) + print_rank_0(f"Saved L1 relative change stats to {self.save_path}") + + +class TokenL2NormChangeRateTracker: + """Track per-token L2 norm change rates within a target generated chunk.""" + + def __init__( + self, + save_path: Optional[str], + target_generated_chunk_idx: int = 0, + eps: float = 1e-8, + ): + self.save_path = save_path + self.target_generated_chunk_idx = target_generated_chunk_idx + self.eps = eps + self.prev_norms: Optional[torch.Tensor] = None + self.change_rate_sums: Optional[torch.Tensor] = None + self.change_rate_counts: Optional[torch.Tensor] = None + self.token_shape: Optional[Tuple[int, int, int]] = None + self.step_records = [] + + @property + def enabled(self) -> bool: + return bool(self.save_path) + + def is_writer_rank(self) -> bool: + return not dist.is_available() or not dist.is_initialized() or dist.get_rank() == 0 + + def update_from_embedder( + self, + infer_idx: int, + cur_denoise_step: int, + denoise_stage: int, + denoise_idx: int, + chunk_offset: int, + chunk_start: int, + chunk_end: int, + x_embedder: torch.Tensor, + x_embedder_chunk_width: int, + timestep: Optional[float] = None, + ) -> None: + if not self.enabled or not self.is_writer_rank(): + return + + target_chunk_idx = chunk_offset + self.target_generated_chunk_idx + if not (chunk_start <= target_chunk_idx < chunk_end): + return + + x_embedder = x_embedder[0:1].detach() + chunk_num = x_embedder.size(2) // x_embedder_chunk_width + assert x_embedder.size(2) % x_embedder_chunk_width == 0 + assert chunk_num == chunk_end - chunk_start + + local_chunk_idx = target_chunk_idx - chunk_start + x_embedder_by_chunk = x_embedder.reshape( + x_embedder.size(0), + x_embedder.size(1), + chunk_num, + x_embedder_chunk_width, + *x_embedder.shape[3:], + ) + chunk_tokens = x_embedder_by_chunk[:, :, local_chunk_idx].float() + token_norms = torch.linalg.vector_norm(chunk_tokens, dim=1).flatten() + + if self.token_shape is None: + self.token_shape = tuple(chunk_tokens.shape[2:]) + elif tuple(chunk_tokens.shape[2:]) != self.token_shape: + raise ValueError( + f"Token shape changed from {self.token_shape} to {tuple(chunk_tokens.shape[2:])}" + ) + + if self.prev_norms is None: + self.prev_norms = token_norms.clone() + self.change_rate_sums = torch.zeros_like(token_norms) + self.change_rate_counts = torch.zeros_like(token_norms) + return + + if token_norms.numel() != self.prev_norms.numel(): + raise ValueError( + f"Token count changed from {self.prev_norms.numel()} to {token_norms.numel()}" + ) + + denom = token_norms.clamp_min(self.eps) + change_rates = (token_norms - self.prev_norms) / denom + self.change_rate_sums += change_rates + self.change_rate_counts += 1 + self.prev_norms = token_norms.clone() + + self.step_records.append( + { + "infer_idx": infer_idx, + "cur_denoise_step": cur_denoise_step, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx, + "chunk_idx": target_chunk_idx, + "generated_chunk_idx": self.target_generated_chunk_idx, + "timestep": timestep, + "mean_change_rate": float(change_rates.mean().item()), + "std_change_rate": float(change_rates.std(unbiased=False).item()), + } + ) + + def save(self) -> None: + if not self.enabled or not self.is_writer_rank(): + return + if self.change_rate_sums is None or self.change_rate_counts is None: + print_rank_0(f"No token L2 norm change-rate stats collected for chunk {self.target_generated_chunk_idx}") + return + + valid = self.change_rate_counts > 0 + mean_change_rates = torch.zeros_like(self.change_rate_sums) + mean_change_rates[valid] = self.change_rate_sums[valid] / self.change_rate_counts[valid] + + token_entries = [] + if self.token_shape is not None: + t_size, h_size, w_size = self.token_shape + for token_idx, value in enumerate(mean_change_rates.tolist()): + t_idx = token_idx // (h_size * w_size) + rem = token_idx % (h_size * w_size) + h_idx = rem // w_size + w_idx = rem % w_size + token_entries.append( + { + "token_idx": token_idx, + "t": t_idx, + "h": h_idx, + "w": w_idx, + "mean_change_rate": value, + "num_transitions": int(self.change_rate_counts[token_idx].item()), + } + ) + else: + token_entries = [ + { + "token_idx": token_idx, + "mean_change_rate": value, + "num_transitions": int(self.change_rate_counts[token_idx].item()), + } + for token_idx, value in enumerate(mean_change_rates.tolist()) + ] + + save_dir = os.path.dirname(self.save_path) + if save_dir: + os.makedirs(save_dir, exist_ok=True) + + payload = { + "description": ( + "Per-token mean L2 norm change rate inside one generated chunk. " + "For each patch-embedded token, channel L2 norm is computed first, then " + "change_rate_t = (norm_t - norm_{t-1}) / norm_t at each denoise transition. " + "mean_change_rate averages these transitions over the full denoising process." + ), + "target_generated_chunk_idx": self.target_generated_chunk_idx, + "eps": self.eps, + "token_shape": list(self.token_shape) if self.token_shape is not None else None, + "num_tokens": len(token_entries), + "num_transitions_per_token": int(self.change_rate_counts.max().item()) if valid.any() else 0, + "step_records": self.step_records, + "tokens": token_entries, + "mean_change_rates": mean_change_rates.tolist(), + } + if self.save_path.endswith((".pt", ".pth")): + torch.save(payload, self.save_path) + else: + with open(self.save_path, "w") as f: + json.dump(payload, f, indent=2) + print_rank_0(f"Saved token L2 norm change-rate stats to {self.save_path}") + + +def find_dit_model(model): + if hasattr(model, "y_embedder"): + return model + if hasattr(model, "module"): + return find_dit_model(model.module) + raise ValueError("Cannot find the real model") + + +class SampleTransport: + def __init__( + self, + model: torch.nn.Module, + transport_inputs: List[InferenceInput], + device: torch.device, + residual_stats_path: Optional[str] = None, + l1_rel_stats_path: Optional[str] = None, + token_l2_change_rate_stats_path: Optional[str] = None, + token_l2_change_rate_chunk_idx: int = 0, + ): + # ========= Input Tensor ========= + self.model = model + self.transport_inputs = transport_inputs + self.device = device + + # ========= Init Global Members ========= + self.model_config = model.model_config + self.runtime_config = model.runtime_config + self.engine_config = model.engine_config + self.chunk_width = self.runtime_config.chunk_width + self.window_size = self.runtime_config.window_size + self.residual_diff_tracker = ResidualDiffTracker(residual_stats_path or os.getenv("MAGI_RESIDUAL_STATS_PATH")) + self.l1_rel_change_tracker = L1RelChangeTracker(l1_rel_stats_path or os.getenv("MAGI_L1_REL_STATS_PATH")) + self.token_l2_norm_change_tracker = TokenL2NormChangeRateTracker( + token_l2_change_rate_stats_path or os.getenv("MAGI_TOKEN_L2_CHANGE_RATE_STATS_PATH"), + target_generated_chunk_idx=token_l2_change_rate_chunk_idx, + ) + + # ========= Init Batched Inputs and Work Queue ========= + self.work_queue = Queue() + self.chunk_denoise_count: List[Counter] = [] + self.ts: List[torch.Tensor] = [] + self.time_interval: List[torch.Tensor] = [] + self.xs: List[torch.Tensor] = [] + self.x_chunks: List[torch.Tensor] = [] + self.velocities: List[torch.Tensor] = [] + self.time_record: List[tqdm] = [] + self.inference_params: List[InferenceParams] = [] + self.init_work_queue() + + def init_work_queue(self) -> None: + shortcut_mode = self.engine_config.shortcut_mode + if mpu.get_pp_world_size() > 1: + if len(self.transport_inputs) == 1: + print_rank_0("Warning: For better performance, please use multiple inputs for PP>1") + else: + assert len(self.transport_inputs) == 1, "Only support single input for PP=1" + + for idx, tran_input in enumerate(self.transport_inputs): + self.work_queue.put(WorkStatus(infer_idx=idx, cur_denoise_step=0)) + + self.chunk_denoise_count.append(Counter()) + self.ts.append( + init_t(tran_input.t_schedule_config, tran_input.num_steps, self.device, shortcut_mode=shortcut_mode) + ) + self.time_interval.append(init_intervel(tran_input.num_steps, self.device, shortcut_mode=shortcut_mode)) + self.x_chunks.append(None) + self.velocities.append(None) + + if torch.distributed.get_rank() == 0: + report_chunk_num = sum( + dict( + zip(self.transport_inputs[idx].task_idx_list, self.transport_inputs[idx].report_chunk_num_list) + ).values() + ) + + progress_bar = tqdm(total=report_chunk_num, desc=f"InferBatch {idx}") + self.time_record.append(progress_bar) + + print_rank_0(f"transport_inputs len: {len(self.transport_inputs)}") + x = torch.randn(*tran_input.latent_size, device=self.device) # NCTHW + x = torch.cat([x, x], 0) # [2 * N, C, T, H, W] + self.xs.append(x) + + max_sequence_length = ( + x.shape[2] * (x.shape[3] // self.model_config.patch_size) * (x.shape[4] // self.model_config.patch_size) + ) + self.inference_params.append(InferenceParams(max_batch_size=1, max_sequence_length=max_sequence_length)) + + def append_dims(self, x, target_dims): + """Appends dimensions to the end of a tensor until it has target_dims dimensions.""" + dims_to_append = target_dims - x.ndim + if dims_to_append < 0: + raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less") + return x[(...,) + (None,) * dims_to_append] + + def embed_x_for_l1_rel_stats(self, x: torch.Tensor) -> Tuple[torch.Tensor, int]: + dit_model = find_dit_model(self.model) + x_embedder_chunk_width = self.chunk_width // dit_model.model_config.t_patch_size + assert self.chunk_width % dit_model.model_config.t_patch_size == 0 + + x = x[0:1] * dit_model.model_config.x_rescale_factor + if dit_model.model_config.half_channel_vae: + assert x.shape[1] == 16 + x = torch.cat([x, x], dim=1) + x = x.float() + with torch.no_grad(): + x = dit_model.x_embedder(x) + return x, x_embedder_chunk_width + + def update_token_l2_norm_change_tracker( + self, + infer_idx: int, + cur_denoise_step: int, + denoise_stage: int, + denoise_idx: int, + chunk_offset: int, + chunk_start: int, + chunk_end: int, + x_embedder_before: torch.Tensor, + x_embedder_chunk_width: int, + timesteps: torch.Tensor, + ) -> None: + tracker = self.token_l2_norm_change_tracker + if not tracker.enabled or not tracker.is_writer_rank(): + return + + target_chunk_idx = chunk_offset + tracker.target_generated_chunk_idx + if not (chunk_start <= target_chunk_idx < chunk_end): + return + + local_chunk_idx = target_chunk_idx - chunk_start + timestep = float(timesteps[local_chunk_idx].item()) if timesteps.numel() > local_chunk_idx else None + tracker.update_from_embedder( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + chunk_end=chunk_end, + x_embedder=x_embedder_before, + x_embedder_chunk_width=x_embedder_chunk_width, + timestep=timestep, + ) + + def get_timestep( + self, + t_total: torch.Tensor, + denoise_step_per_stage: int, + start: int, + end: int, + denoise_idx: int, + has_clean_t: bool = False, + ) -> torch.Tensor: + """Const Method""" + t_index = [] + for i in range(start, end): + t_index.append(i * denoise_step_per_stage + denoise_idx) + t_index.reverse() + # t_index is the timestep + timestep = t_total[t_index] + if has_clean_t: + ones = torch.ones(1, device=self.device) * self.runtime_config.clean_t + timestep = torch.cat([ones, timestep], 0) + return timestep + + def get_denoise_step_of_each_chunk( + self, + infer_idx: int, + denoise_step_per_stage: int, + t_start: int, + t_end: int, + denoise_idx: int, + has_clean_t: bool = False, + ): + denoise_step_of_each_chunk = [] + for i in range(t_start, t_end): + denoise_step_of_each_chunk.append(i * denoise_step_per_stage + denoise_idx) + denoise_step_of_each_chunk.reverse() + if has_clean_t: + denoise_step_of_each_chunk = [self.transport_inputs[infer_idx].num_steps] + denoise_step_of_each_chunk + return denoise_step_of_each_chunk + + def get_batch_size_and_chunk_token_nums(self, infer_idx: int): + """Const Method""" + batch_size = 1 + # T H W + chunk_token_nums = ( + self.chunk_width + * (self.transport_inputs[infer_idx].latent_size[3] // self.model_config.patch_size) + * (self.transport_inputs[infer_idx].latent_size[4] // self.model_config.patch_size) + ) + return batch_size, chunk_token_nums + + def generate_kvrange_for_prefix_video(self, infer_idx: int, range_num: int): + """Const Method""" + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + if self.runtime_config.clean_chunk_kvrange != -1: + prev_chunk_num = self.runtime_config.clean_chunk_kvrange + elif len(self.runtime_config.noise2clean_kvrange) > 0: + prev_chunk_num = self.runtime_config.noise2clean_kvrange[-1] + else: + prev_chunk_num = 8 + + k_chunk_end = torch.linspace(1, range_num, steps=range_num).reshape((range_num, 1)) + k_chunk_start = torch.clamp(k_chunk_end - prev_chunk_num, min=0).reshape((range_num, 1)) + k_chunk_range = torch.concat([k_chunk_start, k_chunk_end], dim=1) + k_batch_range = ( + torch.concat([k_chunk_range + i * range_num for i in range(batch_size)], dim=0).to(torch.int32).to(self.device) + ) + return k_batch_range * chunk_token_nums + + def extract_prefix_video_feature( + self, infer_idx: int, prefix_video: torch.Tensor, y: torch.Tensor, chunk_offset: int, model_kwargs: dict + ): + """Non-Const Method""" + print_rank_0(f"extract clean feature for prefix video, chunk_offset: {chunk_offset}") + + x_chunk = prefix_video[:, :, : chunk_offset * self.chunk_width] + x_chunk = torch.cat([x_chunk, x_chunk], 0) # [2 * N, C, T, H, W] + + # clean feature without y embedding + null_y_chunk = self.transport_inputs[infer_idx].y[1:2, :chunk_offset] + null_y_chunk = torch.cat([null_y_chunk, null_y_chunk], 0) + mask_chunk = self.transport_inputs[infer_idx].emb_masks[1:2, :chunk_offset] + mask_chunk = torch.cat([mask_chunk, mask_chunk], 0) + + null_y_chunk_flatten = null_y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1) + mask_chunk_flatten = mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1) + + t = torch.ones(chunk_offset, device=self.device) * self.runtime_config.clean_t + t = t.unsqueeze(0).repeat(x_chunk.size(0), 1) + + fwd_model_kwargs = model_kwargs.copy() + fwd_model_kwargs.update( + { + "slice_point": 0, + "range_num": chunk_offset, + "denoising_range_num": chunk_offset, + "fwd_extra_1st_chunk": False, + "extract_prefix_video_feature": True, + } + ) + + # Adapt to chunkwise forward + fwd_model_kwargs["start_chunk_id"] = 0 + fwd_model_kwargs["end_chunk_id"] = chunk_offset + fwd_model_kwargs["chunk_num"] = self.transport_inputs[infer_idx].chunk_num + + kv_range = self.generate_kvrange_for_prefix_video(infer_idx, chunk_offset) + + forward_fn = find_dit_model(self.model).forward_dispatcher + fwd_model_kwargs["distill_interval"] = self.time_interval[infer_idx][0] + forward_fn( + x=x_chunk, + timestep=t, + y=null_y_chunk_flatten, + mask=mask_chunk_flatten, + kv_range=kv_range, + inference_params=self.inference_params[infer_idx], + **fwd_model_kwargs, + ) # for kv cache + + def try_pad_prefix_video( + self, infer_idx: int, x_chunk: torch.Tensor, t: torch.Tensor, prefix_video_start: int + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Non-Const Method""" + prefix_length = self.transport_inputs[infer_idx].prefix_video.size(2) + + if prefix_length <= prefix_video_start: + return x_chunk, t + + padding_length = min(prefix_length - prefix_video_start, x_chunk.size(2)) + prefix_video_end = prefix_video_start + padding_length + ret = x_chunk.clone() + ret[:, :, :padding_length] = self.transport_inputs[infer_idx].prefix_video[:, :, prefix_video_start:prefix_video_end] + + num_clean_t = (prefix_length - prefix_video_start) // self.chunk_width + if num_clean_t > 0: + t[:, :num_clean_t] = 1.0 + return ret, t + + def generate_default_kvrange(self, infer_idx: int, slice_point: int, denoising_range_num: int) -> torch.Tensor: + """Const Method""" + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + range_num = slice_point + denoising_range_num + + k_chunk_end = torch.linspace(slice_point + 1, range_num, steps=denoising_range_num).reshape((denoising_range_num, 1)) + k_chunk_start = torch.Tensor([0] * denoising_range_num).reshape((denoising_range_num, 1)) + k_chunk_range = torch.concat([k_chunk_start, k_chunk_end], dim=1) + k_batch_range = ( + torch.concat([k_chunk_range + i * range_num for i in range(batch_size)], dim=0).to(torch.int32).to(self.device) + ) + return k_batch_range * chunk_token_nums + + def generate_noise2clean_kvrange( + self, + infer_idx: int, + slice_point: int, + denoising_range_num: int, + noise2clean_kvrange: List[int], + clean_chunk_kvrange: int, + denoise_step_of_each_chunk: List[int], + ) -> torch.Tensor: + """Const Method""" + assert len(denoise_step_of_each_chunk) == denoising_range_num + assert len(noise2clean_kvrange) > 0 + + if clean_chunk_kvrange == -1: + clean_chunk_kvrange = noise2clean_kvrange[-1] + num_steps = self.transport_inputs[infer_idx].num_steps + assert num_steps % len(noise2clean_kvrange) == 0 + denoise_step_per_stage = num_steps // len(noise2clean_kvrange) + denoise_kv_range = [] + for cur_chunk_denoise_step in denoise_step_of_each_chunk: + if cur_chunk_denoise_step == num_steps: + denoise_kv_range.append(clean_chunk_kvrange) + else: + denoise_kv_range.append(noise2clean_kvrange[cur_chunk_denoise_step // denoise_step_per_stage]) + + range_num = slice_point + denoising_range_num + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + k_ranges = [] + for i in range(batch_size): + k_batch_start = i * range_num + for j in range(denoising_range_num): + k_chunk_end = slice_point + j + 1 + k_chunk_start = max(0, k_chunk_end - denoise_kv_range[j]) + k_ranges.append( + torch.Tensor( + [(k_batch_start + k_chunk_start) * chunk_token_nums, (k_batch_start + k_chunk_end) * chunk_token_nums] + ) + .reshape(1, 2) + .to(self.device) + ) + k_range = torch.concat(k_ranges, dim=0).to(torch.int32).to(self.device) + return k_range + + def generate_kvrange_for_denoising_video( + self, infer_idx: int, slice_point: int, denoising_range_num: int, denoise_step_of_each_chunk: List[int] + ) -> torch.Tensor: + """Const Method""" + noise2clean_kvrange = self.runtime_config.noise2clean_kvrange + clean_chunk_kvrange = self.runtime_config.clean_chunk_kvrange + if len(noise2clean_kvrange) == 0: + k_range = self.generate_default_kvrange(infer_idx, slice_point, denoising_range_num) + else: + k_range = self.generate_noise2clean_kvrange( + infer_idx, + slice_point, + denoising_range_num, + noise2clean_kvrange, + clean_chunk_kvrange, + denoise_step_of_each_chunk, + ) + return k_range + + def integrate( + self, + x_chunk: torch.Tensor, + velocity: torch.Tensor, + t_total: torch.Tensor, + denoise_step_per_stage: int, + t_start: int, + t_end: int, + i: int, + delta_t_index: int = None, + ) -> torch.Tensor: + """Non-Const Method""" + t_before = self.get_timestep(t_total, denoise_step_per_stage, t_start, t_end, i) + t_after = self.get_timestep(t_total, denoise_step_per_stage, t_start, t_end, i + 1) + delta_t = t_after - t_before + N, C, T, H, W = x_chunk.shape + x_chunk = x_chunk.reshape(N, C, -1, self.chunk_width, H, W) + velocity = velocity.reshape(N, C, -1, self.chunk_width, H, W) + + if x_chunk.size(2) < delta_t.size(0) and delta_t_index is not None: + delta_t = delta_t[delta_t_index:delta_t_index+1] + + assert x_chunk.size(2) == delta_t.size(0) + x_chunk = x_chunk + velocity * delta_t.reshape(1, 1, -1, 1, 1, 1) + x_chunk = x_chunk.reshape(N, C, T, H, W) + return x_chunk + + def generate_denoise_status_and_sequences( + self, infer_idx: int, cur_denoise_step: int + ) -> Tuple[Tuple[int, int, int], Tuple[int, int, int, int, int]]: + """Const Method""" + chunk_offset = 0 + if self.transport_inputs[infer_idx].prefix_video is not None: + chunk_offset = self.transport_inputs[infer_idx].prefix_video.size(2) // self.chunk_width + + transport_input = self.transport_inputs[infer_idx] + denoise_step_per_stage = transport_input.num_steps // self.window_size + denoise_stage, denoise_idx = (cur_denoise_step // denoise_step_per_stage, cur_denoise_step % denoise_step_per_stage) + chunk_start_s, chunk_end_s, t_start_s, t_end_s = generate_sequences( + transport_input.chunk_num, self.window_size, chunk_offset + ) + chunk_start, chunk_end, t_start, t_end = ( + chunk_start_s[denoise_stage], + chunk_end_s[denoise_stage], + t_start_s[denoise_stage], + t_end_s[denoise_stage], + ) + return (denoise_step_per_stage, denoise_stage, denoise_idx), (chunk_offset, chunk_start, chunk_end, t_start, t_end) + + def total_forward_step(self, infer_idx: int) -> int: + denoise_step_per_stage = self.transport_inputs[infer_idx].num_steps // self.window_size + + chunk_offset = 0 + if self.transport_inputs[infer_idx].prefix_video is not None: + chunk_offset = self.transport_inputs[infer_idx].prefix_video.size(2) // self.chunk_width + + total_forward_step = denoise_step_per_stage * ( + self.transport_inputs[infer_idx].chunk_num + self.window_size - 1 - chunk_offset + ) + return total_forward_step + + def forward_velocity(self, infer_idx: int, cur_denoise_step: int) -> torch.Tensor: + # 1. Get current work status + x = self.xs[infer_idx] + transport_input = self.transport_inputs[infer_idx] + + # 2. Extract prefix video KV cache + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + + model_kwargs = dict(chunk_width=self.chunk_width, fwd_extra_1st_chunk=False, num_steps=transport_input.num_steps) + model_kwargs.update( + {"denoise_step_per_stage": denoise_step_per_stage, "denoise_stage": denoise_stage, "denoise_idx": denoise_idx + }) + + if chunk_offset > 0 and cur_denoise_step == 0: + self.extract_prefix_video_feature( + infer_idx, transport_input.prefix_video, transport_input.y, chunk_offset, model_kwargs + ) + + # 3. Prepare inputs + x_chunk = x[:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width].clone() + y_chunk = transport_input.y[:, chunk_start:chunk_end] + mask_chunk = transport_input.emb_masks[:, chunk_start:chunk_end] + model_kwargs.update( + {"slice_point": chunk_start, "range_num": chunk_end, "denoising_range_num": chunk_end - chunk_start} + ) + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + model_kwargs["chunk_token_nums"] = chunk_token_nums + model_kwargs["start_chunk_id"] = chunk_start + model_kwargs["end_chunk_id"] = chunk_end + + # 4. Forward clean chunk and get clean kv + fwd_extra_1st_chunk = chunk_start > chunk_offset and denoise_idx == 0 + if fwd_extra_1st_chunk: + clean_x = x[:, :, (chunk_start - 1) * self.chunk_width : chunk_start * self.chunk_width].clone() + x_chunk = torch.cat([clean_x, x_chunk], dim=2) + + # Clean feature without y embedding + y_chunk = torch.cat([transport_input.y[1:2, 0:1].expand(y_chunk.size(0), -1, -1, -1), y_chunk], dim=1) + mask_chunk = torch.cat([transport_input.emb_masks[1:2, 1:2].expand(mask_chunk.size(0), -1, -1), mask_chunk], dim=1) + + model_kwargs["slice_point"] = chunk_start - 1 + model_kwargs["denoising_range_num"] = chunk_end - chunk_start + 1 + model_kwargs["fwd_extra_1st_chunk"] = True + + # 5. Prepare inputs + y_chunk_flatten = y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1) + mask_chunk_flatten = mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1) + + denoise_step_of_each_chunk = self.get_denoise_step_of_each_chunk( + infer_idx, denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=fwd_extra_1st_chunk + ) + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=fwd_extra_1st_chunk + ) + t = t.unsqueeze(0).repeat(x_chunk.size(0), 1) + + kv_range = self.generate_kvrange_for_denoising_video( + infer_idx=infer_idx, + slice_point=model_kwargs["slice_point"], + denoising_range_num=model_kwargs["denoising_range_num"], + denoise_step_of_each_chunk=denoise_step_of_each_chunk, + ) + + # 6. Padding prefix video + if transport_input.prefix_video is not None: + x_chunk, t = self.try_pad_prefix_video( + infer_idx, x_chunk, t, prefix_video_start=model_kwargs["slice_point"] * self.chunk_width + ) + + # 7. Model forward + forward_fn = find_dit_model(self.model).forward_dispatcher + nearly_clean_chunk_t = t[0, int(model_kwargs["fwd_extra_1st_chunk"])].item() + model_kwargs["distill_nearly_clean_chunk"] = ( + nearly_clean_chunk_t > self.engine_config.distill_nearly_clean_chunk_threshold + ) + model_kwargs["distill_interval"] = self.time_interval[infer_idx][denoise_idx] + model_kwargs["total_num_steps"] = self.total_forward_step(infer_idx) + + if model_kwargs.get("distill_nearly_clean_chunk", False): + model_kwargs["end_chunk_id"] += 1 + model_kwargs["chunk_num"] = transport_input.chunk_num + + velocity = forward_fn( + x=x_chunk, + timestep=t, + y=y_chunk_flatten, + mask=mask_chunk_flatten, + kv_range=kv_range, + inference_params=self.inference_params[infer_idx], + **model_kwargs, + ) + + self.x_chunks[infer_idx] = x_chunk + self.velocities[infer_idx] = velocity + return velocity + + def integrate_velocity(self, infer_idx: int, cur_denoise_step: int): + transport_input = self.transport_inputs[infer_idx] + x_chunk = self.x_chunks[infer_idx] + velocity = self.velocities[infer_idx] + chunk_denoise_count = self.chunk_denoise_count[infer_idx] + + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + fwd_extra_1st_chunk = chunk_start > chunk_offset and denoise_idx == 0 + + # 8. Remove clean chunk + if fwd_extra_1st_chunk: + x_chunk = x_chunk[:, :, self.chunk_width :] + velocity = velocity[:, :, self.chunk_width :] + + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=fwd_extra_1st_chunk + ) + if fwd_extra_1st_chunk: + t = t[1:] + self.residual_diff_tracker.update( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + x_chunk=x_chunk, + velocity=velocity, + timesteps=t, + chunk_width=self.chunk_width, + ) + next_t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx + 1, has_clean_t=fwd_extra_1st_chunk + ) + if fwd_extra_1st_chunk: + next_t = next_t[1:] + x_before_integrate = x_chunk + x_embedder_before = None + x_embedder_after = None + x_embedder_chunk_width = None + need_embedder_stats = ( + (self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank()) + or (self.token_l2_norm_change_tracker.enabled and self.token_l2_norm_change_tracker.is_writer_rank()) + ) + if need_embedder_stats: + x_embedder_before, x_embedder_chunk_width = self.embed_x_for_l1_rel_stats(x_before_integrate) + self.update_token_l2_norm_change_tracker( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + chunk_end=chunk_end, + x_embedder_before=x_embedder_before, + x_embedder_chunk_width=x_embedder_chunk_width, + timesteps=t, + ) + + # 9. Walk and integrate + x_chunk = self.integrate(x_chunk, velocity, self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx) + if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank(): + x_embedder_after, _ = self.embed_x_for_l1_rel_stats(x_chunk) + self.l1_rel_change_tracker.update( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + x_before=x_before_integrate, + x_after=x_chunk, + timesteps=t, + next_timesteps=next_t, + chunk_width=self.chunk_width, + x_embedder_before=x_embedder_before, + x_embedder_after=x_embedder_after, + x_embedder_chunk_width=x_embedder_chunk_width, + ) + + # 10. chunk denoise count + for chunk_index in range(chunk_start, chunk_end): + chunk_denoise_count[chunk_index] += 1 + self.xs[infer_idx][:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width] = x_chunk + self.chunk_denoise_count[infer_idx] = chunk_denoise_count + + # 11. Return clean chunk + if chunk_denoise_count[chunk_start] == transport_input.num_steps: + if transport_input.prefix_video is not None: + prefix_video_length = transport_input.prefix_video.size(2) + if (chunk_start + 1) * self.chunk_width <= prefix_video_length: + return None, None + + real_start = max(chunk_start * self.chunk_width, prefix_video_length) + + # Keep the first 4-frames only for I2V Job + if chunk_start == 0 and prefix_video_length == 1: + real_start = 0 + + clean_chunk, _ = self.xs[infer_idx][:, :, real_start : (chunk_start + 1) * self.chunk_width].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + else: + clean_chunk, _ = self.xs[infer_idx][ + :, :, chunk_start * self.chunk_width : (chunk_start + 1) * self.chunk_width + ].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + return None, None + + def walk(self): + event_path_timer().synced_record("begin_walk") + infer_batch_size = len(self.transport_inputs) + for infer_idx in range(infer_batch_size): + velocity = self.forward_velocity(infer_idx, 0) + + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_first_stage(): + pp_scheduler().queue_irecv_prev(velocity.shape, velocity.dtype) + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_last_stage(): + pp_scheduler().isend_next(velocity) + + while not self.work_queue.empty(): + work_status: WorkStatus = self.work_queue.get() + + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_first_stage(): + self.velocities[work_status.infer_idx] = pp_scheduler().queue_irecv_prev_data() + + clean_chunk, chunk_idx = self.integrate_velocity(work_status.infer_idx, work_status.cur_denoise_step) + if clean_chunk is not None: + if torch.distributed.get_rank() == 0: + self.time_record[work_status.infer_idx].update(1) + yield work_status.infer_idx, chunk_idx, clean_chunk + + if work_status.cur_denoise_step + 1 == self.total_forward_step(work_status.infer_idx): + if torch.distributed.get_rank() == 0: + self.time_record[work_status.infer_idx].close() + continue + self.work_queue.put(WorkStatus(infer_idx=work_status.infer_idx, cur_denoise_step=work_status.cur_denoise_step + 1)) + velocity = self.forward_velocity(work_status.infer_idx, work_status.cur_denoise_step + 1) + + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_first_stage(): + pp_scheduler().queue_irecv_prev(velocity.shape, velocity.dtype) + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_last_stage(): + pp_scheduler().isend_next(velocity) + + +def generate_per_chunk( + model: torch.nn.Module, + prefix_video: torch.Tensor, + caption_embs: torch.Tensor, + emb_masks: torch.Tensor, + residual_stats_path: Optional[str] = None, + l1_rel_stats_path: Optional[str] = None, + token_l2_change_rate_stats_path: Optional[str] = None, + token_l2_change_rate_chunk_idx: int = 0, +) -> Generator[Tuple[int, int, int, int, int, torch.Tensor], None, None]: + print_rank_0("Begin to generate per chunk") + device = f"cuda:{torch.cuda.current_device()}" + transport_inputs: InferenceInput = extract_feature_for_inference(model, prefix_video, caption_embs, emb_masks) + sample_transport = SampleTransport( + model=model, + transport_inputs=[transport_inputs], + device=device, + residual_stats_path=residual_stats_path, + l1_rel_stats_path=l1_rel_stats_path, + token_l2_change_rate_stats_path=token_l2_change_rate_stats_path, + token_l2_change_rate_chunk_idx=token_l2_change_rate_chunk_idx, + ) + for _, _, chunk in sample_transport.walk(): + yield chunk + sample_transport.residual_diff_tracker.save() + sample_transport.l1_rel_change_tracker.save() + sample_transport.token_l2_norm_change_tracker.save() + cache_reuse_manager = getattr(SampleTransport, "cache_reuse_manager", None) + if cache_reuse_manager is not None and hasattr(cache_reuse_manager, "save_metric_stats"): + cache_reuse_manager.save_metric_stats() + dist.barrier(device_ids=[torch.cuda.current_device()]) + gc.collect() + torch.cuda.empty_cache() diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_process.py b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_process.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd5b7f9bd7495f83091b6e011c657a7244e1bfa --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_process.py @@ -0,0 +1,400 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import os +import tempfile + +import ffmpeg +import torch +from einops import rearrange + +import inference.infra.distributed.parallel_state as mpu +from inference.common import MagiConfig, magi_logger +from inference.model.vae import AutoModel, DiagonalGaussianDistribution, VideoTokenizerABC + + +############################################ +# VaeHelper +########################################### +class SingletonMeta(type): + """ + Singleton metaclass + """ + + _instances = {} + + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = super().__call__(*args, **kwargs) + return cls._instances[cls] + + +class VaeHelper(metaclass=SingletonMeta): + def __init__(self): + # Initialize cache dict + if not hasattr(self, "vae_cache_dict"): + self.vae_cache_dict = {} + + @staticmethod + def get_vae(vae_ckpt: str) -> VideoTokenizerABC: + """ + Load a pretrained VAE model. + + Args: + vae_ckpt (str): Path to the pretrained VAE checkpoint. + + Returns: + VideoTokenizerABC: Pretrained VAE model. + """ + vae_helper = VaeHelper() + + if vae_ckpt not in vae_helper.vae_cache_dict: + vae = AutoModel.from_pretrained(vae_ckpt) + vae.encode = vae_helper.patch_vae_encode.__get__(vae) + vae.cuda() + vae.eval() + vae.bfloat16() + if os.environ.get("OFFLOAD_VAE_CACHE") == "true": + return vae + vae_helper.vae_cache_dict[vae_ckpt] = vae + return vae_helper.vae_cache_dict[vae_ckpt] + + @staticmethod + @torch.no_grad() + def patch_vae_encode(vae: callable, x: torch.Tensor) -> torch.Tensor: + """ + Encode the input video. + + Args: + x (torch.Tensor): Input video tensor with shape (N, C, T, H, W). + sample_posterior (bool): Whether to sample from the posterior. + + Returns: + torch.Tensor: Encoded tensor with additional information. + """ + if not isinstance(x, torch.Tensor): + raise TypeError(f"Expected input x to be torch.Tensor, but got {type(x)}.") + if len(x.shape) != 5: + raise ValueError(f"Expected input tensor x to have shape (N, C, T, H, W), but got {x.shape}.") + + if not hasattr(vae, "encoder") or not callable(vae.encoder): + raise AttributeError("Encoder is not defined or callable. Please initialize 'self.encoder'.") + + # for setting vae encoding to deterministic + N, C, T, H, W = x.shape + if T == 1: + x = x.expand(-1, -1, 4, -1, -1) + x = vae.encoder(x) + posterior = DiagonalGaussianDistribution(x) + z = posterior.mode() + + return z[:, :, :1, :, :].type(x.dtype) + else: + x = vae.encoder(x) + posterior = DiagonalGaussianDistribution(x) + z = posterior.mode() + + return z.type(x.dtype) + + @staticmethod + def encode( + video: torch.Tensor, + vae: VideoTokenizerABC, + tile_sample_min_length: int = 16, + tile_sample_min_height: int = 256, + tile_sample_min_width: int = 256, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + allow_spatial_tiling: bool = True, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> torch.Tensor: + """ + Encode the input tensor. + Args: + video (torch.Tensor): Input tensor with shape (N, T, C, H, W). + vae (VideoTokenizerABC): Pretrained VAE model. + tile_sample_min_length (int): Minimum length of the tile sample. + tile_sample_min_height (int): Minimum height of the tile sample. + tile_sample_min_width (int): Minimum width of the tile sample. + spatial_tile_overlap_factor (float): Spatial tile overlap factor. + allow_spatial_tiling (bool): Allow spatial tiling. + parallel_group (ProcessGroup): Distributed encoding group. + Returns: + torch.Tensor: Encoded tensor. + """ + assert video.dim() == 5, f"Expected input tensor to have shape (N, T, C, H, W), but got {video.shape}." + video = video.cuda() + video = (video / 127.5) - 1.0 + video = video.bfloat16() + moments = vae.tiled_encode_3d( + video, + tile_sample_min_length=tile_sample_min_length, + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + allow_spatial_tiling=allow_spatial_tiling, + parallel_group=parallel_group, + ) + + return moments + + @staticmethod + def decode( + chunk: torch.Tensor, + vae: VideoTokenizerABC, + tile_sample_min_height: int = 256, + tile_sample_min_width: int = 256, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + tile_sample_min_length: int = 16, + allow_spatial_tiling: bool = True, + uint8_output: bool = True, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> torch.Tensor: + """ + Decode the input tensor. + Args: + chunk (torch.Tensor): Input tensor with shape (N, C, T, H, W). + vae (VideoTokenizerABC): Pretrained VAE model. + tile_sample_min_length (int): Minimum length of the tile sample. + tile_sample_min_height (int): Minimum height of the tile sample. + tile_sample_min_width (int): Minimum width of the tile sample. + spatial_tile_overlap_factor (float): Spatial tile overlap factor. + temporal_tile_overlap_factor (float): Temporal tile overlap factor. + allow_spatial_tiling (bool): Allow spatial tiling. + uint8_output (bool): Whether to output uint8 tensor. + parallel_group (ProcessGroup): Distributed decoding group. + Returns: + torch.Tensor: Decoded tensor. + """ + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + chunk = vae.tiled_decode_3d( + chunk, + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + tile_sample_min_length=tile_sample_min_length, + allow_spatial_tiling=allow_spatial_tiling, + parallel_group=parallel_group, + ) + chunk = rearrange(chunk, "b c t h w -> (b t) c h w") + if uint8_output: + chunk = (chunk * 127.5) + 127.5 + chunk = chunk.clamp(0, 255) + chunk = chunk.type(torch.uint8) + return chunk + + +############################################ +# Process to get prefix video +########################################### + + +def ffmpeg_i2v(image_path, w=384, h=224, aspect_policy="fit"): + r = ffmpeg.input("pipe:0", format="image2pipe") + if aspect_policy == "crop": + r = r.filter("scale", w, h, force_original_aspect_ratio="increase").filter("crop", w, h) + elif aspect_policy == "pad": + r = r.filter("scale", w, h, force_original_aspect_ratio="decrease").filter( + "pad", w, h, "(ow-iw)/2", "(oh-ih)/2", color="black" + ) + elif aspect_policy == "fit": + r = r.filter("scale", w, h) + else: + magi_logger.warning(f"Unknown aspect policy: {aspect_policy}, using fit as fallback") + r = r.filter("scale", w, h) + image_byte = open(image_path, "rb").read() + try: + out, _ = r.output("pipe:", format="rawvideo", pix_fmt="rgb24", vframes=1).run( + input=image_byte, capture_stdout=True, capture_stderr=True + ) + except ffmpeg.Error as e: + print(f"Error occurred: {e.stderr.decode()}") + raise e + + video = torch.frombuffer(out, dtype=torch.uint8).view(1, h, w, 3) + return video + + +def ffmpeg_v2v(video_path, fps, w=384, h=224, prefix_frame=None, prefix_video_max_chunk=5): + if video_path is None: + return None + out, _ = ( + ffmpeg.input(video_path, ss=0, format="mp4") + .filter("fps", fps=fps) + .filter("scale", w, h) + .output("pipe:", format="rawvideo", pix_fmt="rgb24", nostdin=None) + .run(capture_stdout=True, capture_stderr=True) + ) + + video = torch.frombuffer(out, dtype=torch.uint8).view(-1, h, w, 3) + + if prefix_frame is not None: + return video[:prefix_frame] + else: + num_frames_to_read = video.shape[0] + if num_frames_to_read < fps: + clip_length = 1 + else: + PREFIX_VIDEO_MAX_FRAMES = prefix_video_max_chunk * fps + clip_length = min(num_frames_to_read // fps * fps, PREFIX_VIDEO_MAX_FRAMES) + return video[-clip_length:] + + +def save_video_to_disk(video: torch.Tensor, save_path: str, fps: int) -> bytes: + # TCHW -> THWC + video = video.permute(0, 2, 3, 1).cpu().numpy() + _, H, W, _ = video.shape + with tempfile.NamedTemporaryFile(delete=False) as temp_file: + temp_file.write(video.tobytes()) + temp_file.flush() + temp_file_path = temp_file.name + + try: + output, err = ( + ffmpeg + .input(temp_file_path, format="rawvideo", pix_fmt="rgb24", s=f"{W}x{H}", r=fps) + .output(save_path, format='mp4', vcodec='libx264', pix_fmt='yuv420p') + .overwrite_output() + .run(capture_stdout=True, capture_stderr=True) + ) + print("✅ Video saved successfully.") + except ffmpeg.Error as e: + stderr_output = e.stderr.decode('utf8') if e.stderr else "No stderr output" + print("❌ FFmpeg Error:") + print("="*60) + print(stderr_output) + print("="*60) + raise RuntimeError("Failed to encode video with FFmpeg") from e + + os.remove(temp_file_path) + return output + + os.remove(temp_file_path) + return output + + +def encode_prefix_video(prefix_video, fps, vae_ckpt, scale_factor, parallel_group): + if prefix_video is None: + return None + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory allocated before vae encode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory reserved before vae encode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + + # THWC -> NCTHW + prefix_video = prefix_video.permute(3, 0, 1, 2).unsqueeze(0) + magi_logger.debug(f"prefix_video.shape: {prefix_video.shape}") + vae_model = VaeHelper.get_vae(vae_ckpt) + tile_sample_min_length = fps // 2 + prefix_video = VaeHelper.encode( + prefix_video, + vae_model, + tile_sample_min_height=256, + tile_sample_min_width=256, + spatial_tile_overlap_factor=0.25, + temporal_tile_overlap_factor=0, + tile_sample_min_length=tile_sample_min_length, + allow_spatial_tiling=True, + parallel_group=parallel_group, + ) + prefix_video = prefix_video * scale_factor + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory allocated after vae encode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory reserved after vae encode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + return prefix_video + + +def process_image(image_path: str, config: MagiConfig) -> torch.Tensor: + prefix_video = ffmpeg_i2v(image_path, w=config.runtime_config.video_size_w, h=config.runtime_config.video_size_h) + prefix_video = encode_prefix_video( + prefix_video, + config.runtime_config.fps, + config.runtime_config.vae_pretrained, + config.runtime_config.scale_factor, + parallel_group=mpu.get_tp_group(with_context_parallel=True), + ) + return prefix_video + + +def process_prefix_video(prefix_video_path: str, config: MagiConfig) -> torch.Tensor: + prefix_video = ffmpeg_v2v( + prefix_video_path, + fps=config.runtime_config.fps, + prefix_frame=None, # Modified + w=config.runtime_config.video_size_w, + h=config.runtime_config.video_size_h, + ) + prefix_video = encode_prefix_video( + prefix_video, + config.runtime_config.fps, + config.runtime_config.vae_pretrained, + config.runtime_config.scale_factor, + parallel_group=mpu.get_tp_group(with_context_parallel=True), + ) + return prefix_video + + +############################################ +# Process to get final video +############################################ +def decode_chunk(chunk, vae_ckpt, scale_factor, tile_sample_min_length, parallel_group): + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory allocated before vae decode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory reserved before vae decode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + + vae_model = VaeHelper.get_vae(vae_ckpt) + decoded_chunk = VaeHelper.decode( + chunk / scale_factor, + vae_model, + tile_sample_min_height=256, + tile_sample_min_width=256, + spatial_tile_overlap_factor=0.25, + temporal_tile_overlap_factor=0, + tile_sample_min_length=tile_sample_min_length, + allow_spatial_tiling=True, + parallel_group=parallel_group, + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory allocated after vae decode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory reserved after vae decode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + return decoded_chunk + + +def post_chunk_process(chunk: torch.Tensor, config: MagiConfig): + tile_sample_min_length = config.runtime_config.fps // 2 + chunk = decode_chunk( + chunk, + config.runtime_config.vae_pretrained, + config.runtime_config.scale_factor, + tile_sample_min_length, + parallel_group=mpu.get_tp_group(with_context_parallel=True), + ) + gc.collect() + torch.cuda.empty_cache() + return chunk diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/logs/flowcache_vbench_20260520_103113.log b/FlowCache/FlowCache4MAGI-1-dev-V2/logs/flowcache_vbench_20260520_103113.log new file mode 100644 index 0000000000000000000000000000000000000000..67a33fb8d698a434ef4d04234b9a39ac77df4f55 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/logs/flowcache_vbench_20260520_103113.log @@ -0,0 +1,181 @@ +🚀 Starting multi-GPU benchmark sampling +🔢 Total dimensions to process: 3 +📋 Dimensions: overall_consistency subject_consistency scene +🔍 Processing dimension: overall_consistency +Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp +Total samples: 93 +GPUs: [0] +Output: outputs/vbench/videos/overall_consistency +Config: config/sample/vbench.json +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W520 10:31:24.093345214 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-05-20 10:31:24,656 - INFO] Initialize torch distribution and model parallel successfully +[2026-05-20 10:31:24,656 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False)) +[2026-05-20 10:31:24,657 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +KV cache compression is enabled. +Processing 93 samples. +[GPU 0] Assigned 93 samples +[GPU 0] Loading model... +[GPU 0] Model loaded. +[GPU 0] Generating T2V: 'Close up of grapes on a rotating table.' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/overall_consistency/Close up of grapes on a rotating table.-0.mp4 + Loading checkpoint shards: 0%| | 0/2 [00:00 + [ + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk + for _, _, chunk in sample_transport.walk(): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1079, in walk + velocity = self.forward_velocity(infer_idx, 0) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 93, in flowcache_forward_velocity + cache = SampleTransport.cache_reuse_manager +AttributeError: type object 'SampleTransport' has no attribute 'cache_reuse_manager' + InferBatch 0: 0%| | 0/10 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +KV cache compression is enabled. +Processing 72 samples. +[GPU 0] Assigned 72 samples +[GPU 0] Loading model... +[GPU 0] Model loaded. +[GPU 0] Generating T2V: 'a person swimming in ocean' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/subject_consistency/a person swimming in ocean-0.mp4 + Loading checkpoint shards: 0%| | 0/2 [00:00 + [ + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk + for _, _, chunk in sample_transport.walk(): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1079, in walk + velocity = self.forward_velocity(infer_idx, 0) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 93, in flowcache_forward_velocity + cache = SampleTransport.cache_reuse_manager +AttributeError: type object 'SampleTransport' has no attribute 'cache_reuse_manager' + InferBatch 0: 0%| | 0/10 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +KV cache compression is enabled. +Processing 86 samples. +[GPU 0] Assigned 86 samples +[GPU 0] Loading model... +[GPU 0] Model loaded. +[GPU 0] Generating T2V: 'alley' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/scene/alley-0.mp4 + Loading checkpoint shards: 0%| | 0/2 [00:00 + [ + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk + for _, _, chunk in sample_transport.walk(): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1079, in walk + velocity = self.forward_velocity(infer_idx, 0) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 93, in flowcache_forward_velocity + cache = SampleTransport.cache_reuse_manager +AttributeError: type object 'SampleTransport' has no attribute 'cache_reuse_manager' + InferBatch 0: 0%| | 0/10 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +KV cache compression is enabled. +Processing 93 samples. +[GPU 0] Assigned 93 samples +[GPU 0] Loading model... +[GPU 0] Model loaded. +[GPU 0] Generating T2V: 'Close up of grapes on a rotating table.' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/overall_consistency/Close up of grapes on a rotating table.-0.mp4 + Loading checkpoint shards: 0%| | 0/2 [00:00 + [ + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk + for _, _, chunk in sample_transport.walk(): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1092, in walk + clean_chunk, chunk_idx = self.integrate_velocity(work_status.infer_idx, work_status.cur_denoise_step) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 530, in flowcache_integrate_velocity + _check_and_compress_kv(self, infer_idx, chunk_start, transport_input) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 570, in _check_and_compress_kv + compressor.compress( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 158, in compress + layer_result = self._compress_layer( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 251, in _compress_layer + key_compressed, value_compressed, indices = kv_cluster.update_kv( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 52, in update_kv + return self.update_kv_token( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 168, in update_kv_token + raise ValueError(f"Unknown score weighting method: {self.score_weighting_method}") +ValueError: Unknown score weighting method: None +✅ Completed: overall_consistency +--- +🔍 Processing dimension: subject_consistency +Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp +Total samples: 72 +GPUs: [0] +Output: outputs/vbench/videos/subject_consistency +Config: config/sample/vbench.json +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W520 12:22:42.069407203 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-05-20 12:22:42,624 - INFO] Initialize torch distribution and model parallel successfully +[2026-05-20 12:22:42,624 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False)) +[2026-05-20 12:22:42,625 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +KV cache compression is enabled. +Processing 72 samples. +[GPU 0] Assigned 72 samples +[GPU 0] Loading model... +[GPU 0] Model loaded. +[GPU 0] Generating T2V: 'a person swimming in ocean' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/subject_consistency/a person swimming in ocean-0.mp4 + Loading checkpoint shards: 0%| | 0/2 [00:00 + [ + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk + for _, _, chunk in sample_transport.walk(): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1092, in walk + clean_chunk, chunk_idx = self.integrate_velocity(work_status.infer_idx, work_status.cur_denoise_step) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 530, in flowcache_integrate_velocity + _check_and_compress_kv(self, infer_idx, chunk_start, transport_input) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 570, in _check_and_compress_kv + compressor.compress( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 158, in compress + layer_result = self._compress_layer( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 251, in _compress_layer + key_compressed, value_compressed, indices = kv_cluster.update_kv( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 52, in update_kv + return self.update_kv_token( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 168, in update_kv_token + raise ValueError(f"Unknown score weighting method: {self.score_weighting_method}") +ValueError: Unknown score weighting method: None +✅ Completed: subject_consistency +--- +🔍 Processing dimension: scene +Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp +Total samples: 86 +GPUs: [0] +Output: outputs/vbench/videos/scene +Config: config/sample/vbench.json +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W520 12:25:23.550998312 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-05-20 12:25:23,106 - INFO] Initialize torch distribution and model parallel successfully +[2026-05-20 12:25:23,106 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False)) +[2026-05-20 12:25:23,106 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +KV cache compression is enabled. +Processing 86 samples. +[GPU 0] Assigned 86 samples +[GPU 0] Loading model... +[GPU 0] Model loaded. +[GPU 0] Generating T2V: 'alley' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/scene/alley-0.mp4 + Loading checkpoint shards: 0%| | 0/2 [00:00 + [ + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk + for _, _, chunk in sample_transport.walk(): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1092, in walk + clean_chunk, chunk_idx = self.integrate_velocity(work_status.infer_idx, work_status.cur_denoise_step) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 530, in flowcache_integrate_velocity + _check_and_compress_kv(self, infer_idx, chunk_start, transport_input) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 570, in _check_and_compress_kv + compressor.compress( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 158, in compress + layer_result = self._compress_layer( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 251, in _compress_layer + key_compressed, value_compressed, indices = kv_cluster.update_kv( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 52, in update_kv + return self.update_kv_token( + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 168, in update_kv_token + raise ValueError(f"Unknown score weighting method: {self.score_weighting_method}") +ValueError: Unknown score weighting method: None +✅ Completed: scene +--- +🎉 All sampling tasks completed. diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/logs/flowcache_vbench_20260520_124220.log b/FlowCache/FlowCache4MAGI-1-dev-V2/logs/flowcache_vbench_20260520_124220.log new file mode 100644 index 0000000000000000000000000000000000000000..3bf572cf9e35fa88c0769e929178f570e1ca0fb0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/logs/flowcache_vbench_20260520_124220.log @@ -0,0 +1,195 @@ +🚀 Starting multi-GPU benchmark sampling +🔢 Total dimensions to process: 3 +📋 Dimensions: overall_consistency subject_consistency scene +🔍 Processing dimension: overall_consistency +Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp +Total samples: 93 +GPUs: [0] +Output: outputs/vbench/videos/overall_consistency +Config: config/sample/vbench.json +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W520 12:42:27.778130826 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-05-20 12:42:27,333 - INFO] Initialize torch distribution and model parallel successfully +[2026-05-20 12:42:27,333 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False)) +[2026-05-20 12:42:27,333 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +KV cache compression is enabled. +Processing 93 samples. +[GPU 0] Assigned 93 samples +[GPU 0] Loading model... +[GPU 0] Model loaded. +[GPU 0] Generating T2V: 'Close up of grapes on a rotating table.' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/overall_consistency/Close up of grapes on a rotating table.-0.mp4 + Loading checkpoint shards: 0%| | 0/2 [00:00 /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/overall_consistency/Turtle swimming in ocean.-0.mp4 + Loading checkpoint shards: 0%| | 0/2 [00:00 + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock +ModuleNotFoundError: No module named 'flashinfer' +ModuleNotFoundError: No module named 'flashinfer' + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in + main() + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main + raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}") +RuntimeError: 4 worker process(es) failed with exit codes: [1, 1, 1, 1] +✅ Completed: overall_consistency +--- +🔍 Processing dimension: subject_consistency +Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp +Total samples: 72 +GPUs: [0, 1, 2, 3] +Output: outputs/vbench/videos/subject_consistency +Config: config/sample/vbench.json +Process Process-3: +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Process Process-1: +Process Process-2: +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Process Process-4: +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in + main() + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main + raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}") +RuntimeError: 4 worker process(es) failed with exit codes: [1, 1, 1, 1] +✅ Completed: subject_consistency +--- +🔍 Processing dimension: scene +Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp +Total samples: 86 +GPUs: [0, 1, 2, 3] +Output: outputs/vbench/videos/scene +Config: config/sample/vbench.json +Process Process-4: +Process Process-2: +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Process Process-3: +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Process Process-1: +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in + main() + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main + raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}") +RuntimeError: 4 worker process(es) failed with exit codes: [1, 1, 1, 1] +✅ Completed: scene +--- +🎉 All sampling tasks completed. diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/logs/flowcache_vbench_20260521_034016.log b/FlowCache/FlowCache4MAGI-1-dev-V2/logs/flowcache_vbench_20260521_034016.log new file mode 100644 index 0000000000000000000000000000000000000000..a7d8287831102bdaa380a517d59d1c6fa78104db --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/logs/flowcache_vbench_20260521_034016.log @@ -0,0 +1,109 @@ +🚀 Starting multi-GPU benchmark sampling +🔢 Total dimensions to process: 3 +📋 Dimensions: overall_consistency subject_consistency scene +🔍 Processing dimension: overall_consistency +Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp +Total samples: 93 +GPUs: [0] +Output: outputs/vbench/videos/overall_consistency +Config: config/sample/vbench.json +Process Process-1: +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in + main() + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main + raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}") +RuntimeError: 1 worker process(es) failed with exit codes: [1] +✅ Completed: overall_consistency +--- +🔍 Processing dimension: subject_consistency +Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp +Total samples: 72 +GPUs: [0] +Output: outputs/vbench/videos/subject_consistency +Config: config/sample/vbench.json +Process Process-1: +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in + main() + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main + raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}") +RuntimeError: 1 worker process(es) failed with exit codes: [1] +✅ Completed: subject_consistency +--- +🔍 Processing dimension: scene +Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp +Total samples: 86 +GPUs: [0] +Output: outputs/vbench/videos/scene +Config: config/sample/vbench.json +Process Process-1: +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap + self.run() + File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run + self._target(*self._args, **self._kwargs) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process + configure_reuse_strategy(config) + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy + from inference.pipeline.video_generate import SampleTransport + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in + from .pipeline import MagiPipeline + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in + from inference.model.dit import get_dit + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in + from .dit_model import get_dit, VideoDiTModel + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in + from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in + import flashinfer +ModuleNotFoundError: No module named 'flashinfer' +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in + main() + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main + raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}") +RuntimeError: 1 worker process(es) failed with exit codes: [1] +✅ Completed: scene +--- +🎉 All sampling tasks completed. diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/metric.sh b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/metric.sh new file mode 100644 index 0000000000000000000000000000000000000000..c513748df78937d28806c827ef746c56b1f94684 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/metric.sh @@ -0,0 +1,5 @@ +export CUDA_VISIBLE_DEVICES=3 + +python tools/video_metrics.py \ +--original_video "/path/to/original_video.mp4" \ +--generated_video "/path/to/generated_video.mp4" \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/tools/plot_l1_rel.py b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/plot_l1_rel.py new file mode 100644 index 0000000000000000000000000000000000000000..b117dbc6d97323a0ad71303b700f2cc251773257 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/plot_l1_rel.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 + +import argparse +import json +from collections import defaultdict +from pathlib import Path +from typing import Dict, List, Optional, Set, Tuple + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + + +def parse_int_list(value: Optional[str]) -> Optional[Set[int]]: + if not value: + return None + return {int(item.strip()) for item in value.split(",") if item.strip()} + + +def load_l1_rel_records(json_path: Path) -> List[dict]: + with json_path.open("r") as f: + payload = json.load(f) + if isinstance(payload, list): + return payload + if isinstance(payload, dict) and isinstance(payload.get("records"), list): + return payload["records"] + raise ValueError(f"Cannot find records in {json_path}") + + +def collect_by_chunk(records: List[dict], chunk_ids: Optional[Set[int]], max_chunks: Optional[int]) -> Dict[int, List[dict]]: + chunks = defaultdict(list) + for record in records: + chunk_idx = int(record["chunk_idx"]) + if chunk_ids is not None and chunk_idx not in chunk_ids: + continue + chunks[chunk_idx].append(record) + + chunks = dict(sorted(chunks.items())) + if max_chunks is not None: + chunks = dict(list(chunks.items())[:max_chunks]) + return chunks + + +def plot_l1_rel( + chunks: Dict[int, List[dict]], + output_path: Path, + x_field: str, + y_field: str, + reverse_x: bool, + title: Optional[str], + figsize: Tuple[float, float], + dpi: int, +) -> None: + fig, ax = plt.subplots(figsize=figsize) + + for chunk_idx, records in chunks.items(): + points = [] + for record in records: + if x_field not in record or y_field not in record: + continue + if record[x_field] is None or record[y_field] is None: + continue + points.append((float(record[x_field]), float(record[y_field]))) + if not points: + continue + + points.sort(key=lambda item: item[0]) + xs, ys = zip(*points) + ax.plot(xs, ys, marker="o", linewidth=1.6, markersize=3, label=f"chunk {chunk_idx}") + + ax.set_xlabel(x_field) + ax.set_ylabel(y_field) + ax.set_title(title or f"{y_field} by timestep") + ax.grid(True, alpha=0.3) + if reverse_x: + ax.invert_xaxis() + ax.legend(loc="best", fontsize="small", ncols=2) + fig.tight_layout() + + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=dpi) + plt.close(fig) + + +def parse_arguments(): + parser = argparse.ArgumentParser(description="Plot per-chunk MAGI relative L1 change curves.") + parser.add_argument("json_path", type=Path, help="Path to L1 relative change JSON saved by --l1_rel_stats_path.") + parser.add_argument("-o", "--output", type=Path, help="Output image path. Defaults to _plot.png.") + parser.add_argument("--chunks", type=str, help="Comma-separated chunk_idx list to plot, for example: 0,1,2.") + parser.add_argument("--max-chunks", type=int, help="Plot at most this many chunks after filtering.") + parser.add_argument( + "--x-field", + choices=["timestep", "next_timestep", "cur_denoise_step", "denoise_idx"], + default="next_timestep", + help="Record field used for the x axis. next_timestep is the cleaner MAGI step.", + ) + parser.add_argument( + "--y-field", + choices=[ + "l1_rel", + "l1_rel_ratio", + "delta_l1_norm", + "x_l1_norm", + "x_embedder_l1_rel", + "x_embedder_l1_rel_ratio", + "x_embedder_delta_l1_norm", + "x_embedder_x_l1_norm", + "flowcache_rel_l1", + "flowcache_rel_l1_ratio", + "flowcache_delta_l1_norm", + "flowcache_prev_feat_l1_norm", + "flowcache_accumulated_rel_l1", + "rel_l1_thresh", + ], + default="l1_rel", + help="Record field used for the y axis.", + ) + parser.add_argument("--reverse-x", action="store_true", help="Reverse the x axis.") + parser.add_argument("--title", type=str, help="Figure title.") + parser.add_argument("--figsize", type=str, default="10,6", help="Figure size as width,height.") + parser.add_argument("--dpi", type=int, default=160, help="Output image DPI.") + return parser.parse_args() + + +def main(): + args = parse_arguments() + output_path = args.output or args.json_path.with_name(f"{args.json_path.stem}_plot.png") + figsize = [float(part.strip()) for part in args.figsize.split(",")] + if len(figsize) != 2: + raise ValueError("--figsize must be formatted as width,height") + + records = load_l1_rel_records(args.json_path) + chunks = collect_by_chunk(records, parse_int_list(args.chunks), args.max_chunks) + if not chunks: + raise ValueError("No records matched the requested chunks.") + + plot_l1_rel( + chunks=chunks, + output_path=output_path, + x_field=args.x_field, + y_field=args.y_field, + reverse_x=args.reverse_x, + title=args.title, + figsize=(figsize[0], figsize[1]), + dpi=args.dpi, + ) + print(f"Saved plot to {output_path}") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/tools/plot_residual_norms.py b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/plot_residual_norms.py new file mode 100644 index 0000000000000000000000000000000000000000..600e0c35144bca5f6cdc48e6c4e2098972e358ff --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/plot_residual_norms.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 + +import argparse +import json +from collections import defaultdict +from pathlib import Path +from typing import Dict, List, Optional, Set, Tuple + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + + +def parse_int_list(value: Optional[str]) -> Optional[Set[int]]: + if not value: + return None + return {int(item.strip()) for item in value.split(",") if item.strip()} + + +def load_records(json_path: Path) -> List[dict]: + with json_path.open("r") as f: + payload = json.load(f) + if isinstance(payload, list): + return payload + if isinstance(payload, dict) and isinstance(payload.get("records"), list): + return payload["records"] + raise ValueError(f"Cannot find records in {json_path}") + + +def group_records(records: List[dict], chunk_ids: Optional[Set[int]], max_chunks: Optional[int]) -> Dict[int, List[dict]]: + grouped = defaultdict(list) + for record in records: + chunk_idx = int(record["chunk_idx"]) + if chunk_ids is not None and chunk_idx not in chunk_ids: + continue + grouped[chunk_idx].append(record) + + grouped = dict(sorted(grouped.items())) + if max_chunks is not None: + grouped = dict(list(grouped.items())[:max_chunks]) + return grouped + + +def build_plot( + grouped_records: Dict[int, List[dict]], + output_path: Path, + x_field: str, + y_field: str, + title: Optional[str], + reverse_x: bool, + figsize: Tuple[float, float], + dpi: int, +) -> None: + fig, ax = plt.subplots(figsize=figsize) + + for chunk_idx, records in grouped_records.items(): + points = [] + for record in records: + if x_field not in record or y_field not in record: + continue + if record[x_field] is None or record[y_field] is None: + continue + points.append((float(record[x_field]), float(record[y_field]))) + if not points: + continue + + points.sort(key=lambda item: item[0]) + xs, ys = zip(*points) + ax.plot(xs, ys, marker="o", linewidth=1.6, markersize=3, label=f"chunk {chunk_idx}") + + ax.set_xlabel(x_field) + ax.set_ylabel(y_field) + ax.set_title(title or f"{y_field} by timestep") + ax.grid(True, alpha=0.3) + if reverse_x: + ax.invert_xaxis() + ax.legend(loc="best", fontsize="small", ncols=2) + fig.tight_layout() + + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=dpi) + plt.close(fig) + + +def parse_arguments(): + parser = argparse.ArgumentParser(description="Plot per-chunk residual norm curves from MAGI residual stats JSON.") + parser.add_argument("json_path", type=Path, help="Path to residual stats JSON saved by --residual_stats_path.") + parser.add_argument( + "-o", + "--output", + type=Path, + help="Output image path. Defaults to _residual_norms.png.", + ) + parser.add_argument("--chunks", type=str, help="Comma-separated chunk_idx list to plot, for example: 0,1,2.") + parser.add_argument("--max-chunks", type=int, help="Plot at most this many chunks after filtering.") + parser.add_argument( + "--x-field", + choices=["timestep", "cur_denoise_step", "denoise_idx"], + default="timestep", + help="Record field used for the x axis.", + ) + parser.add_argument( + "--y-field", + choices=["residual_norm", "residual_diff_norm"], + default="residual_norm", + help="Record field used for the y axis.", + ) + parser.add_argument("--reverse-x", action="store_true", help="Reverse the x axis.") + parser.add_argument("--title", type=str, help="Figure title.") + parser.add_argument("--figsize", type=str, default="10,6", help="Figure size as width,height.") + parser.add_argument("--dpi", type=int, default=160, help="Output image DPI.") + return parser.parse_args() + + +def main(): + args = parse_arguments() + output_path = args.output or args.json_path.with_name(f"{args.json_path.stem}_residual_norms.png") + figsize_parts = [float(part.strip()) for part in args.figsize.split(",")] + if len(figsize_parts) != 2: + raise ValueError("--figsize must be formatted as width,height") + + records = load_records(args.json_path) + grouped_records = group_records(records, parse_int_list(args.chunks), args.max_chunks) + if not grouped_records: + raise ValueError("No records matched the requested chunks.") + + build_plot( + grouped_records=grouped_records, + output_path=output_path, + x_field=args.x_field, + y_field=args.y_field, + title=args.title, + reverse_x=args.reverse_x, + figsize=(figsize_parts[0], figsize_parts[1]), + dpi=args.dpi, + ) + print(f"Saved plot to {output_path}") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/tools/plot_token_l2_change_rate_density.py b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/plot_token_l2_change_rate_density.py new file mode 100644 index 0000000000000000000000000000000000000000..ec17bef39b5c65f86105968c1af7cc1c8be209d9 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/plot_token_l2_change_rate_density.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 + +import argparse +import json +from pathlib import Path +from typing import List + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np + + +def load_mean_change_rates(json_path: Path) -> List[float]: + with json_path.open("r") as f: + payload = json.load(f) + + if isinstance(payload, dict) and isinstance(payload.get("mean_change_rates"), list): + rates = payload["mean_change_rates"] + elif isinstance(payload, dict) and isinstance(payload.get("tokens"), list): + rates = [float(item["mean_change_rate"]) for item in payload["tokens"]] + else: + raise ValueError(f"Cannot find per-token mean change rates in {json_path}") + + rates = [float(value) for value in rates if np.isfinite(value)] + if not rates: + raise ValueError(f"No valid mean change rates found in {json_path}") + return rates + + +def plot_density( + rates: List[float], + output_path: Path, + bins: int, + chunk_idx: int, +) -> None: + fig, ax = plt.subplots(figsize=(8, 5)) + ax.hist(rates, bins=bins, density=True, color="#4C78A8", alpha=0.85, edgecolor="white", linewidth=0.5) + ax.set_xlabel("Mean L2 norm change rate") + ax.set_ylabel("Density") + ax.set_title(f"Chunk {chunk_idx} token heterogeneity (n={len(rates)} tokens)") + ax.grid(True, alpha=0.25, linestyle="--", linewidth=0.5) + fig.tight_layout() + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=160) + plt.close(fig) + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Plot per-token mean L2 norm change-rate density for one chunk." + ) + parser.add_argument( + "json_path", + type=Path, + help="Path to token L2 change-rate stats JSON saved by --token_l2_change_rate_stats_path.", + ) + parser.add_argument("-o", "--output", type=Path, required=True, help="Output image path.") + parser.add_argument("--bins", type=int, default=50, help="Number of histogram bins.") + parser.add_argument( + "--chunk-idx", + type=int, + default=None, + help="Chunk index for plot title. Defaults to target_generated_chunk_idx in JSON.", + ) + args = parser.parse_args() + + with args.json_path.open("r") as f: + payload = json.load(f) + chunk_idx = args.chunk_idx + if chunk_idx is None: + chunk_idx = int(payload.get("target_generated_chunk_idx", 0)) + + rates = load_mean_change_rates(args.json_path) + plot_density(rates, args.output, bins=args.bins, chunk_idx=chunk_idx) + print(f"Saved density plot to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/tools/video_metrics.py b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/video_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..3873573d52ac923c98523b5ebff648f00c9287c6 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/video_metrics.py @@ -0,0 +1,108 @@ +import os +import cv2 +import argparse +import torch +import lpips +import numpy as np +from tqdm import tqdm +from torchmetrics.image import StructuralSimilarityIndexMeasure + +def load_video_frames(path, resize_to=None): + """ + Load all frames from a video file as a list of HxWx3 uint8 arrays. + Optionally resize each frame to `resize_to` (w, h). + """ + + cap = cv2.VideoCapture(path) + frames = [] + while True: + ret, img = cap.read() + if not ret: + break + if resize_to is not None: + img = cv2.resize(img, resize_to) + frames.append(np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), axis=0)) + cap.release() + return np.concatenate(frames) + + +def compute_video_metrics(frames_gt, frames_gen, + device, ssim_metric, lpips_fn): + """ + Compute PSNR, SSIM, LPIPS for two lists of frames (uint8 BGR). + All computations on `device`. + Returns (psnr, ssim, lpips) scalars. + """ + # ensure same frame count + # convert to tensors [N,3,H,W], normalize to [0,1] + gt_t = torch.from_numpy(frames_gt).float().to(device).permute(0, 3, 1, 2).div_(255).contiguous() + + gen_t = torch.from_numpy(frames_gen).float().to(device).permute(0, 3, 1, 2).div_(255).contiguous() + + # PSNR (data_range=1.0): -10 * log10(mse) + mse = torch.mean((gt_t - gen_t) ** 2) + psnr = -10.0 * torch.log10(mse) + + # SSIM: returns average over batch + ssim_val = ssim_metric(gen_t, gt_t) + + # LPIPS: expects [-1,1] + with torch.no_grad(): + lpips_val = lpips_fn(gt_t * 2.0 - 1.0, gen_t * 2.0 - 1.0).mean() + + return psnr.item(), ssim_val.item(), lpips_val.item() + + +def main(): + parser = argparse.ArgumentParser( + description="Compute PSNR/SSIM/LPIPS on GPU for two folders of .mp4 videos" + ) + parser.add_argument("--original_video", required=True, + help="ground-truth .mp4 videos") + parser.add_argument("--generated_video", required=True, + help="generated .mp4 videos") + parser.add_argument("--device", default="cuda", + help="Torch device, e.g. 'cuda' or 'cpu'") + parser.add_argument("--lpips_net", default="alex", choices=["alex", "vgg"], + help="Backbone for LPIPS") + args = parser.parse_args() + + device = torch.device(args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu") + # instantiate metrics on device + ssim_metric = StructuralSimilarityIndexMeasure(data_range=1.0).to(device) + lpips_fn = lpips.LPIPS(net=args.lpips_net, spatial=True).to(device) + + # gather .mp4 filenames + gt_files = args.original_video + gen_set = args.generated_video + + psnrs, ssims, lpips_vals = [], [], [] + for fname in tqdm([gt_files], desc="Videos"): + path_gt = gt_files + path_gen = gen_set + + # load frames; resize generated to match GT dimensions + frames_gt = load_video_frames(path_gt) + frames_gen = load_video_frames(path_gen) + + res = compute_video_metrics(frames_gt, frames_gen, + device, ssim_metric, lpips_fn) + if res is None: + continue + p, s, l = res + psnrs.append(p) + ssims.append(s) + lpips_vals.append(l) + + if not psnrs: + print("No valid videos processed.") + return + + print("\n=== Overall Averages ===") + print(f"Average PSNR : {np.mean(psnrs):.2f} dB") + print(f"Average SSIM : {np.mean(ssims):.4f}") + print(f"Average LPIPS: {np.mean(lpips_vals):.4f}") + + +if __name__ == "__main__": + main() \ No newline at end of file