Cccccz commited on
Commit
d2b26ce
·
verified ·
1 Parent(s): 34c65dc

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/flowcache_t2v.sh +119 -0
  2. FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/flowcache_v2v.sh +51 -0
  3. FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/historycache_t2v.sh +22 -0
  4. FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/motioncache_t2v.sh +122 -0
  5. FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/motiondetail_t2v.sh +120 -0
  6. FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/teacache_t2v.sh +50 -0
  7. FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/teacache_v2v.sh +52 -0
  8. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/sample/flowcache_physicsiq.yaml +36 -0
  9. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/sample/flowcache_vbench.yaml +36 -0
  10. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/sample/teacache_physicsiq.yaml +23 -0
  11. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/sample/teacache_vbench.yaml +26 -0
  12. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/config.yaml +15 -0
  13. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/history_anchor0.5.yaml +25 -0
  14. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/history_decay0.5.yaml +25 -0
  15. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/history_decay0.85.yaml +25 -0
  16. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/history_streak0.35.yaml +25 -0
  17. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/historycache_config.yaml +29 -0
  18. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/historycache_config_best.yaml +29 -0
  19. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motioncache_config.yaml +19 -0
  20. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motioncache_config_fast.yaml +19 -0
  21. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motioncache_phase1_only.yaml +19 -0
  22. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motiondetail_config.yaml +25 -0
  23. FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motiondetail_config_best.yaml +13 -0
  24. FlowCache/FlowCache4MAGI-1-dev6-adaptive/config/sample/physicsiq.json +81 -0
  25. FlowCache/FlowCache4MAGI-1-dev6-adaptive/config/sample/vbench.json +81 -0
  26. FlowCache/FlowCache4MAGI-1-dev6-adaptive/config/single_run/flowcache_t2v.json +81 -0
  27. FlowCache/FlowCache4MAGI-1-dev6-adaptive/config/single_run/flowcache_v2v.json +86 -0
  28. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/__init__.py +0 -0
  29. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/__pycache__/__init__.cpython-310.pyc +0 -0
  30. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__init__.py +37 -0
  31. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/__init__.cpython-310.pyc +0 -0
  32. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/common_utils.cpython-310.pyc +0 -0
  33. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/config.cpython-310.pyc +0 -0
  34. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/dataclass.cpython-310.pyc +0 -0
  35. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/logger.cpython-310.pyc +0 -0
  36. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/timer.cpython-310.pyc +0 -0
  37. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/common_utils.py +42 -0
  38. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/config.py +180 -0
  39. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/dataclass.py +100 -0
  40. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/logger.py +51 -0
  41. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/timer.py +85 -0
  42. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/checkpoint/__init__.py +17 -0
  43. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc +0 -0
  44. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc +0 -0
  45. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/checkpoint/checkpointing.py +180 -0
  46. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/__init__.py +73 -0
  47. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc +0 -0
  48. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc +0 -0
  49. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc +0 -0
  50. FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/dist_utils.py +92 -0
FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/flowcache_t2v.sh ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ export MASTER_ADDR=localhost
16
+ export MASTER_PORT=6005
17
+ export GPUS_PER_NODE=1
18
+ export NNODES=1
19
+ export WORLD_SIZE=1
20
+ export CUDA_VISIBLE_DEVICES=0
21
+
22
+ export PAD_HQ=1
23
+ export PAD_DURATION=1
24
+
25
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
26
+ export OFFLOAD_T5_CACHE=true
27
+ export OFFLOAD_VAE_CACHE=true
28
+ export TORCH_CUDA_ARCH_LIST="8.9;9.0"
29
+
30
+ set -euo pipefail
31
+
32
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
33
+ MAGI_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
34
+ cd "$MAGI_ROOT"
35
+
36
+ PROMPT="${PROMPT:-a woman dancing.}"
37
+ TIMESTAMP="${RUN_ID:-$(date "+%Y-%m-%d_%H-%M-%S")}"
38
+ PROMPT_DIR_NAME="${PROMPT_DIR_NAME:-$(python3 - "$PROMPT" <<'PY'
39
+ import re
40
+ import sys
41
+ import unicodedata
42
+
43
+ prompt = unicodedata.normalize("NFKC", sys.argv[1]).strip()
44
+ prompt = re.sub(r"[\\/:\*\?\"<>\|\x00-\x1f]+", "_", prompt)
45
+ prompt = re.sub(r"\s+", "_", prompt)
46
+ prompt = prompt.strip("._")
47
+ print((prompt or "prompt")[:120])
48
+ PY
49
+ )}"
50
+ OUTPUT_ROOT="${OUTPUT_ROOT:-outputs}"
51
+ EXP_DIR="${RUN_DIR:-$OUTPUT_ROOT/${PROMPT_DIR_NAME}_$TIMESTAMP}"
52
+ mkdir -p "$EXP_DIR"
53
+
54
+ OUTPUT_PATH="${OUTPUT_PATH:-$EXP_DIR/output_$TIMESTAMP.mp4}"
55
+ RESIDUAL_JSON="${RESIDUAL_JSON:-$EXP_DIR/residual_stats_$TIMESTAMP.json}"
56
+ RESIDUAL_PNG="${RESIDUAL_PNG:-$EXP_DIR/residual_norms_$TIMESTAMP.png}"
57
+ L1_REL_JSON="${L1_REL_JSON:-$EXP_DIR/l1_rel_stats_$TIMESTAMP.json}"
58
+ L1_REL_PNG="${L1_REL_PNG:-$EXP_DIR/l1_rel_$TIMESTAMP.png}"
59
+ L1_REL_RATIO_PNG="${L1_REL_RATIO_PNG:-$EXP_DIR/l1_rel_ratio_$TIMESTAMP.png}"
60
+ X_EMBEDDER_L1_REL_PNG="${X_EMBEDDER_L1_REL_PNG:-$EXP_DIR/x_embedder_l1_rel_$TIMESTAMP.png}"
61
+ X_EMBEDDER_L1_REL_RATIO_PNG="${X_EMBEDDER_L1_REL_RATIO_PNG:-$EXP_DIR/x_embedder_l1_rel_ratio_$TIMESTAMP.png}"
62
+ FLOWCACHE_METRIC_JSON="${FLOWCACHE_METRIC_JSON:-$EXP_DIR/flowcache_metric_stats_$TIMESTAMP.json}"
63
+ FLOWCACHE_REL_L1_PNG="${FLOWCACHE_REL_L1_PNG:-$EXP_DIR/flowcache_rel_l1_$TIMESTAMP.png}"
64
+ FLOWCACHE_REL_L1_RATIO_PNG="${FLOWCACHE_REL_L1_RATIO_PNG:-$EXP_DIR/flowcache_rel_l1_ratio_$TIMESTAMP.png}"
65
+ FLOWCACHE_ACCUMULATED_REL_L1_PNG="${FLOWCACHE_ACCUMULATED_REL_L1_PNG:-$EXP_DIR/flowcache_accumulated_rel_l1_$TIMESTAMP.png}"
66
+ LOG_FILE="${LOG_FILE:-$EXP_DIR/infer_$TIMESTAMP.log}"
67
+
68
+ export PYTHONPATH="$MAGI_ROOT:${PYTHONPATH:-}"
69
+ python3 inference/pipeline/flowcache.py \
70
+ --config_file config/single_run/flowcache_t2v.json \
71
+ --mode t2v \
72
+ --prompt "$PROMPT" \
73
+ --output_path "$OUTPUT_PATH" \
74
+ --additional_config yaml_config/single_run/config.yaml \
75
+ --residual_stats_path "$RESIDUAL_JSON" \
76
+ --l1_rel_stats_path "$L1_REL_JSON" \
77
+ --flowcache_metric_stats_path "$FLOWCACHE_METRIC_JSON" \
78
+ 2>&1 | tee "$LOG_FILE"
79
+
80
+ python3 tools/plot_residual_norms.py "$RESIDUAL_JSON" -o "$RESIDUAL_PNG"
81
+ python3 tools/plot_l1_rel.py "$L1_REL_JSON" -o "$L1_REL_PNG"
82
+ python3 tools/plot_l1_rel.py "$L1_REL_JSON" --y-field l1_rel_ratio -o "$L1_REL_RATIO_PNG"
83
+ python3 tools/plot_l1_rel.py "$L1_REL_JSON" --y-field x_embedder_l1_rel -o "$X_EMBEDDER_L1_REL_PNG"
84
+ python3 tools/plot_l1_rel.py "$L1_REL_JSON" --y-field x_embedder_l1_rel_ratio -o "$X_EMBEDDER_L1_REL_RATIO_PNG"
85
+ python3 tools/plot_l1_rel.py "$FLOWCACHE_METRIC_JSON" --x-field cur_denoise_step --y-field flowcache_rel_l1 -o "$FLOWCACHE_REL_L1_PNG"
86
+ 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"
87
+ 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"
88
+
89
+ python3 - "$FLOWCACHE_METRIC_JSON" <<'PY'
90
+ import json
91
+ import sys
92
+
93
+ with open(sys.argv[1], "r") as f:
94
+ payload = json.load(f)
95
+
96
+ summary = payload.get("chunk_execution_summary", {})
97
+ print("FlowCache actual execution summary:")
98
+ for chunk_id in sorted(summary, key=lambda value: int(value)):
99
+ item = summary[chunk_id]
100
+ print(
101
+ " chunk {chunk_idx}: reuse={reuse_steps}, compute={compute_steps}, "
102
+ "total={total_steps}, reuse_rate={reuse_rate:.2%}".format(**item)
103
+ )
104
+ PY
105
+
106
+ echo "Done."
107
+ echo " log: $LOG_FILE"
108
+ echo " video: $OUTPUT_PATH"
109
+ echo " residual json: $RESIDUAL_JSON"
110
+ echo " residual plot: $RESIDUAL_PNG"
111
+ echo " L1 rel json: $L1_REL_JSON"
112
+ echo " L1 rel plot: $L1_REL_PNG"
113
+ echo " L1 rel ratio plot: $L1_REL_RATIO_PNG"
114
+ echo " x_embedder L1 rel plot: $X_EMBEDDER_L1_REL_PNG"
115
+ echo " x_embedder L1 rel ratio plot: $X_EMBEDDER_L1_REL_RATIO_PNG"
116
+ echo " FlowCache metric json: $FLOWCACHE_METRIC_JSON"
117
+ echo " FlowCache rel L1 plot: $FLOWCACHE_REL_L1_PNG"
118
+ echo " FlowCache rel L1 ratio plot: $FLOWCACHE_REL_L1_RATIO_PNG"
119
+ echo " FlowCache accumulated rel L1 plot: $FLOWCACHE_ACCUMULATED_REL_L1_PNG"
FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/flowcache_v2v.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ export MASTER_ADDR=localhost
16
+ export MASTER_PORT=6001
17
+ export GPUS_PER_NODE=1
18
+ export NNODES=1
19
+ export WORLD_SIZE=1
20
+ export CUDA_VISIBLE_DEVICES=7
21
+
22
+ export PAD_HQ=1
23
+ export PAD_DURATION=1
24
+
25
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
26
+ export OFFLOAD_T5_CACHE=true
27
+ export OFFLOAD_VAE_CACHE=true
28
+ export TORCH_CUDA_ARCH_LIST="8.9;9.0"
29
+
30
+ MAGI_ROOT=$(git rev-parse --show-toplevel)
31
+
32
+
33
+ OUTPUT_NAME=flowcache
34
+ TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S")
35
+ EXP_DIR="/path/to/output/magi/${TIMESTAMP}_${OUTPUT_NAME}"
36
+ mkdir -p "$EXP_DIR"
37
+
38
+ LOG_FILE="$EXP_DIR/log_${TIMESTAMP}.log"
39
+ OUTPUT_PATH="$EXP_DIR/output.mp4"
40
+
41
+ export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH"
42
+ python3 inference/pipeline/flowcache.py \
43
+ --config_file config/single_run/flowcache_v2v.json \
44
+ --mode v2v \
45
+ --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." \
46
+ --prefix_video_path "/path/to/physicsiq/conditioning_video.mp4" \
47
+ --output_path $OUTPUT_PATH \
48
+ --additional_config addconfig/config.yaml \
49
+ 2>&1 | tee $LOG_FILE
50
+
51
+ # a cat sitting on the grass
FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/historycache_t2v.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ export MASTER_ADDR=localhost
3
+ export MASTER_PORT=6010
4
+ export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-1}"
5
+ set -euo pipefail
6
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7
+ MAGI_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
8
+ cd "$MAGI_ROOT"
9
+ source "${HOME}/miniforge3/etc/profile.d/conda.sh" 2>/dev/null || source "${HOME}/anaconda3/etc/profile.d/conda.sh"
10
+ conda activate magi
11
+ HISTORYCACHE_CONFIG="${HISTORYCACHE_CONFIG:-yaml_config/single_run/historycache_config.yaml}"
12
+ RUN_ID="${RUN_ID:-$(date +%Y%m%d_%H%M%S)}"
13
+ EXP_DIR="${RUN_DIR:-outputs/a_woman_dancing_historycache_$RUN_ID}"
14
+ mkdir -p "$EXP_DIR"
15
+ export PYTHONPATH="$MAGI_ROOT:$(dirname "$MAGI_ROOT")/FlowCache4MAGI-1-dev4-detail:$(dirname "$MAGI_ROOT")/FlowCache4MAGI-1-dev3-motion"
16
+ python3 inference/pipeline/motioncache.py \
17
+ --config_file config/single_run/flowcache_t2v.json \
18
+ --mode t2v --prompt "${PROMPT:-a woman dancing.}" \
19
+ --output_path "$EXP_DIR/output_$RUN_ID.mp4" \
20
+ --additional_config "$HISTORYCACHE_CONFIG" \
21
+ --motioncache_metric_stats_path "$EXP_DIR/metrics_$RUN_ID.json" \
22
+ 2>&1 | tee "$EXP_DIR/infer_$RUN_ID.log"
FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/motioncache_t2v.sh ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ export MASTER_ADDR=localhost
16
+ export MASTER_PORT=6006
17
+ export GPUS_PER_NODE=1
18
+ export NNODES=1
19
+ export WORLD_SIZE=1
20
+ export CUDA_VISIBLE_DEVICES=0
21
+
22
+ export PAD_HQ=1
23
+ export PAD_DURATION=1
24
+
25
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
26
+ export OFFLOAD_T5_CACHE=true
27
+ export OFFLOAD_VAE_CACHE=true
28
+ export TORCH_CUDA_ARCH_LIST="8.9;9.0"
29
+
30
+ set -euo pipefail
31
+
32
+ # MAGI inference requires the `magi` conda environment (flashinfer, etc.)
33
+ if [ -z "${CONDA_DEFAULT_ENV:-}" ] || [ "${CONDA_DEFAULT_ENV}" != "magi" ]; then
34
+ if [ -f "${HOME}/miniforge3/etc/profile.d/conda.sh" ]; then
35
+ # shellcheck disable=SC1091
36
+ source "${HOME}/miniforge3/etc/profile.d/conda.sh"
37
+ conda activate magi
38
+ elif [ -f "${HOME}/anaconda3/etc/profile.d/conda.sh" ]; then
39
+ # shellcheck disable=SC1091
40
+ source "${HOME}/anaconda3/etc/profile.d/conda.sh"
41
+ conda activate magi
42
+ fi
43
+ fi
44
+
45
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
46
+ MAGI_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
47
+ cd "$MAGI_ROOT"
48
+
49
+ PROMPT="${PROMPT:-a woman dancing.}"
50
+ TIMESTAMP="${RUN_ID:-$(date "+%Y-%m-%d_%H-%M-%S")}"
51
+ PROMPT_DIR_NAME="${PROMPT_DIR_NAME:-$(python3 - "$PROMPT" <<'PY'
52
+ import re
53
+ import sys
54
+ import unicodedata
55
+
56
+ prompt = unicodedata.normalize("NFKC", sys.argv[1]).strip()
57
+ prompt = re.sub(r"[\\/:\*\?\"<>\|\x00-\x1f]+", "_", prompt)
58
+ prompt = re.sub(r"\s+", "_", prompt)
59
+ prompt = prompt.strip("._")
60
+ print((prompt or "prompt")[:120])
61
+ PY
62
+ )}"
63
+ OUTPUT_ROOT="${OUTPUT_ROOT:-outputs}"
64
+ EXP_DIR="${RUN_DIR:-$OUTPUT_ROOT/${PROMPT_DIR_NAME}_motioncache_$TIMESTAMP}"
65
+ mkdir -p "$EXP_DIR"
66
+
67
+ MOTIONCACHE_CONFIG="${MOTIONCACHE_CONFIG:-yaml_config/single_run/motioncache_config.yaml}"
68
+
69
+ OUTPUT_PATH="${OUTPUT_PATH:-$EXP_DIR/output_$TIMESTAMP.mp4}"
70
+ RESIDUAL_JSON="${RESIDUAL_JSON:-$EXP_DIR/residual_stats_$TIMESTAMP.json}"
71
+ RESIDUAL_PNG="${RESIDUAL_PNG:-$EXP_DIR/residual_norms_$TIMESTAMP.png}"
72
+ L1_REL_JSON="${L1_REL_JSON:-$EXP_DIR/l1_rel_stats_$TIMESTAMP.json}"
73
+ L1_REL_PNG="${L1_REL_PNG:-$EXP_DIR/l1_rel_$TIMESTAMP.png}"
74
+ MOTIONCACHE_METRIC_JSON="${MOTIONCACHE_METRIC_JSON:-$EXP_DIR/motioncache_metric_stats_$TIMESTAMP.json}"
75
+ LOG_FILE="${LOG_FILE:-$EXP_DIR/infer_$TIMESTAMP.log}"
76
+
77
+ export PYTHONPATH="$MAGI_ROOT:${PYTHONPATH:-}"
78
+ python3 inference/pipeline/motioncache.py \
79
+ --config_file config/single_run/flowcache_t2v.json \
80
+ --mode t2v \
81
+ --prompt "$PROMPT" \
82
+ --output_path "$OUTPUT_PATH" \
83
+ --additional_config "$MOTIONCACHE_CONFIG" \
84
+ --residual_stats_path "$RESIDUAL_JSON" \
85
+ --l1_rel_stats_path "$L1_REL_JSON" \
86
+ --motioncache_metric_stats_path "$MOTIONCACHE_METRIC_JSON" \
87
+ 2>&1 | tee "$LOG_FILE"
88
+
89
+ if [ ! -f "$OUTPUT_PATH" ]; then
90
+ echo "ERROR: inference failed, output video not found: $OUTPUT_PATH"
91
+ exit 1
92
+ fi
93
+
94
+ if [ -f "$RESIDUAL_JSON" ]; then
95
+ python3 tools/plot_residual_norms.py "$RESIDUAL_JSON" -o "$RESIDUAL_PNG"
96
+ fi
97
+ if [ -f "$L1_REL_JSON" ]; then
98
+ python3 tools/plot_l1_rel.py "$L1_REL_JSON" -o "$L1_REL_PNG"
99
+ fi
100
+
101
+ python3 - "$MOTIONCACHE_METRIC_JSON" <<'PY'
102
+ import json
103
+ import sys
104
+
105
+ with open(sys.argv[1], "r") as f:
106
+ payload = json.load(f)
107
+
108
+ print("MotionCache hyperparameters:", payload.get("hyperparameters", {}))
109
+ summary = payload.get("chunk_execution_summary", {})
110
+ print("MotionCache execution summary:")
111
+ for chunk_id in sorted(summary, key=lambda value: int(value)):
112
+ item = summary[chunk_id]
113
+ print(
114
+ " chunk {chunk_idx}: reuse={reuse_steps}, compute={compute_steps}, "
115
+ "total={total_steps}, reuse_rate={reuse_rate:.2%}".format(**item)
116
+ )
117
+ PY
118
+
119
+ echo "Done."
120
+ echo " log: $LOG_FILE"
121
+ echo " video: $OUTPUT_PATH"
122
+ echo " motioncache metric json: $MOTIONCACHE_METRIC_JSON"
FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/motiondetail_t2v.sh ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the License.
13
+
14
+ export MASTER_ADDR=localhost
15
+ export MASTER_PORT=6007
16
+ export GPUS_PER_NODE=1
17
+ export NNODES=1
18
+ export WORLD_SIZE=1
19
+ export CUDA_VISIBLE_DEVICES=0
20
+
21
+ export PAD_HQ=1
22
+ export PAD_DURATION=1
23
+
24
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
25
+ export OFFLOAD_T5_CACHE=true
26
+ export OFFLOAD_VAE_CACHE=true
27
+ export TORCH_CUDA_ARCH_LIST="8.9;9.0"
28
+
29
+ set -euo pipefail
30
+
31
+ if [ -z "${CONDA_DEFAULT_ENV:-}" ] || [ "${CONDA_DEFAULT_ENV}" != "magi" ]; then
32
+ if [ -f "${HOME}/miniforge3/etc/profile.d/conda.sh" ]; then
33
+ # shellcheck disable=SC1091
34
+ source "${HOME}/miniforge3/etc/profile.d/conda.sh"
35
+ conda activate magi
36
+ elif [ -f "${HOME}/anaconda3/etc/profile.d/conda.sh" ]; then
37
+ # shellcheck disable=SC1091
38
+ source "${HOME}/anaconda3/etc/profile.d/conda.sh"
39
+ conda activate magi
40
+ fi
41
+ fi
42
+
43
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
44
+ MAGI_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
45
+ cd "$MAGI_ROOT"
46
+
47
+ PROMPT="${PROMPT:-a woman dancing.}"
48
+ TIMESTAMP="${RUN_ID:-$(date "+%Y-%m-%d_%H-%M-%S")}"
49
+ PROMPT_DIR_NAME="${PROMPT_DIR_NAME:-$(python3 - "$PROMPT" <<'PY'
50
+ import re
51
+ import sys
52
+ import unicodedata
53
+
54
+ prompt = unicodedata.normalize("NFKC", sys.argv[1]).strip()
55
+ prompt = re.sub(r"[\\/:\*\?\"<>\|\x00-\x1f]+", "_", prompt)
56
+ prompt = re.sub(r"\s+", "_", prompt)
57
+ prompt = prompt.strip("._")
58
+ print((prompt or "prompt")[:120])
59
+ PY
60
+ )}"
61
+ OUTPUT_ROOT="${OUTPUT_ROOT:-outputs}"
62
+ EXP_DIR="${RUN_DIR:-$OUTPUT_ROOT/${PROMPT_DIR_NAME}_motiondetail_$TIMESTAMP}"
63
+ mkdir -p "$EXP_DIR"
64
+
65
+ MOTIONDETAIL_CONFIG="${MOTIONDETAIL_CONFIG:-yaml_config/single_run/motiondetail_config.yaml}"
66
+
67
+ OUTPUT_PATH="${OUTPUT_PATH:-$EXP_DIR/output_$TIMESTAMP.mp4}"
68
+ RESIDUAL_JSON="${RESIDUAL_JSON:-$EXP_DIR/residual_stats_$TIMESTAMP.json}"
69
+ RESIDUAL_PNG="${RESIDUAL_PNG:-$EXP_DIR/residual_norms_$TIMESTAMP.png}"
70
+ L1_REL_JSON="${L1_REL_JSON:-$EXP_DIR/l1_rel_stats_$TIMESTAMP.json}"
71
+ L1_REL_PNG="${L1_REL_PNG:-$EXP_DIR/l1_rel_$TIMESTAMP.png}"
72
+ METRIC_JSON="${METRIC_JSON:-$EXP_DIR/motiondetail_metric_stats_$TIMESTAMP.json}"
73
+ LOG_FILE="${LOG_FILE:-$EXP_DIR/infer_$TIMESTAMP.log}"
74
+
75
+ export PYTHONPATH="$MAGI_ROOT:${PYTHONPATH:-}"
76
+ python3 inference/pipeline/motioncache.py \
77
+ --config_file config/single_run/flowcache_t2v.json \
78
+ --mode t2v \
79
+ --prompt "$PROMPT" \
80
+ --output_path "$OUTPUT_PATH" \
81
+ --additional_config "$MOTIONDETAIL_CONFIG" \
82
+ --residual_stats_path "$RESIDUAL_JSON" \
83
+ --l1_rel_stats_path "$L1_REL_JSON" \
84
+ --motioncache_metric_stats_path "$METRIC_JSON" \
85
+ 2>&1 | tee "$LOG_FILE"
86
+
87
+ if [ ! -f "$OUTPUT_PATH" ]; then
88
+ echo "ERROR: inference failed, output video not found: $OUTPUT_PATH"
89
+ exit 1
90
+ fi
91
+
92
+ if [ -f "$RESIDUAL_JSON" ]; then
93
+ python3 tools/plot_residual_norms.py "$RESIDUAL_JSON" -o "$RESIDUAL_PNG"
94
+ fi
95
+ if [ -f "$L1_REL_JSON" ]; then
96
+ python3 tools/plot_l1_rel.py "$L1_REL_JSON" -o "$L1_REL_PNG"
97
+ fi
98
+
99
+ python3 - "$METRIC_JSON" <<'PY'
100
+ import json
101
+ import sys
102
+
103
+ with open(sys.argv[1], "r") as f:
104
+ payload = json.load(f)
105
+
106
+ print("MotionDetailCache hyperparameters:", payload.get("hyperparameters", {}))
107
+ summary = payload.get("chunk_execution_summary", {})
108
+ print("MotionDetailCache execution summary:")
109
+ for chunk_id in sorted(summary, key=lambda value: int(value)):
110
+ item = summary[chunk_id]
111
+ print(
112
+ " chunk {chunk_idx}: reuse={reuse_steps}, compute={compute_steps}, "
113
+ "total={total_steps}, reuse_rate={reuse_rate:.2%}".format(**item)
114
+ )
115
+ PY
116
+
117
+ echo "Done."
118
+ echo " log: $LOG_FILE"
119
+ echo " video: $OUTPUT_PATH"
120
+ echo " metric json: $METRIC_JSON"
FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/teacache_t2v.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ export MASTER_ADDR=localhost
16
+ export MASTER_PORT=6002
17
+ export GPUS_PER_NODE=1
18
+ export NNODES=1
19
+ export WORLD_SIZE=1
20
+ export CUDA_VISIBLE_DEVICES=2
21
+
22
+ export PAD_HQ=1
23
+ export PAD_DURATION=1
24
+
25
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
26
+ export OFFLOAD_T5_CACHE=true
27
+ export OFFLOAD_VAE_CACHE=true
28
+ export TORCH_CUDA_ARCH_LIST="8.9;9.0"
29
+
30
+ MAGI_ROOT=$(git rev-parse --show-toplevel)
31
+
32
+
33
+ OUTPUT_NAME=allreuse
34
+ TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S")
35
+ EXP_DIR="/path/to/output/magi/${TIMESTAMP}_${OUTPUT_NAME}"
36
+ mkdir -p "$EXP_DIR"
37
+
38
+ LOG_FILE="$EXP_DIR/log_${TIMESTAMP}.log"
39
+ exec > >(tee -a "$LOG_FILE") 2>&1
40
+ OUTPUT_PATH="$EXP_DIR/output.mp4"
41
+
42
+ export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH"
43
+ python3 inference/pipeline/teacache_all.py \
44
+ --rel_l1_thresh 0.01 \
45
+ --warmup_steps 5 \
46
+ --config_file config/single_run/flowcache_t2v.json \
47
+ --mode t2v \
48
+ --prompt "A fantasy landscape" \
49
+ --log \
50
+ --output_path $OUTPUT_PATH \
FlowCache/FlowCache4MAGI-1-dev5-history/scripts/single_run/teacache_v2v.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ export MASTER_ADDR=localhost
16
+ export MASTER_PORT=6012
17
+ export GPUS_PER_NODE=1
18
+ export NNODES=1
19
+ export WORLD_SIZE=1
20
+ export CUDA_VISIBLE_DEVICES=1
21
+ export CUDA_HOME="/usr/local/cuda-12.1"
22
+
23
+ export PAD_HQ=1
24
+ export PAD_DURATION=1
25
+
26
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
27
+ export OFFLOAD_T5_CACHE=true
28
+ export OFFLOAD_VAE_CACHE=true
29
+ export TORCH_CUDA_ARCH_LIST="8.9;9.0"
30
+
31
+ MAGI_ROOT=$(git rev-parse --show-toplevel)
32
+
33
+
34
+ OUTPUT_NAME=allreuse
35
+ TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S")
36
+ EXP_DIR="/path/to/output/magi/${TIMESTAMP}_${OUTPUT_NAME}"
37
+ mkdir -p "$EXP_DIR"
38
+
39
+ LOG_FILE="$EXP_DIR/log_${TIMESTAMP}.log"
40
+ exec > >(tee -a "$LOG_FILE") 2>&1
41
+ OUTPUT_PATH="$EXP_DIR/output.mp4"
42
+
43
+ export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH"
44
+ python3 inference/pipeline/teacache_all.py \
45
+ --rel_l1_thresh 0.01 \
46
+ --warmup_steps 5 \
47
+ --config_file config/single_run/all_reuse.json \
48
+ --mode v2v \
49
+ --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." \
50
+ --prefix_video_path "/path/to/physicsiq/conditioning_video.mp4" \
51
+ --output_path $OUTPUT_PATH \
52
+ --log \
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/sample/flowcache_physicsiq.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FlowCache PhysicsIQ configuration file
2
+ # Usage: bash scripts/sample/flowcache_physicsiq.sh <path_to_this_yaml>
3
+
4
+ # Basic configuration
5
+ benchmark: physicsiq
6
+ config_file: config/sample/5s_physicsiq.json
7
+
8
+ # GPU configuration
9
+ gpus: all
10
+
11
+ # PhysicsIQ dataset configuration
12
+ physicsiq_data_dir: /path/to/physicsiq
13
+
14
+ # Output path configuration
15
+ base_save_path: /path/to/output/physicsiq
16
+
17
+ # Reuse strategy configuration
18
+ reuse_strategy: chunkwise
19
+ rel_l1_thresh: 0.01
20
+ warmup_steps: 5
21
+
22
+ # KV cache compression configuration
23
+ compress_kv_cache: true
24
+ total_cache_chunk_nums: 6
25
+ compress_strategy: token
26
+ query_granularity: token
27
+ mix_lambda: 0.07
28
+ score_weighting_method: no_weight
29
+ power: 3
30
+
31
+ # Sampling range control
32
+ start: 150
33
+ end: 200
34
+
35
+ # Log configuration
36
+ log: false
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/sample/flowcache_vbench.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FlowCache VBench configuration file
2
+ # Usage: bash scripts/sample/flowcache_vbench.sh <path_to_this_yaml>
3
+
4
+ # Basic configuration
5
+ benchmark: vbench
6
+ config_file: config/sample/vbench.json
7
+
8
+ # GPU configuration
9
+ gpus: all
10
+
11
+ # VBench dataset configuration
12
+ vbench_prompt_dir: downloads/vbench/prompts_per_dimension
13
+
14
+ # Dimension configuration (specify the current dimension to process)
15
+ dimension: overall_consistency # Options: subject_consistency, scene, object_class, multiple_objects, color, spatial_relationship, temporal_style, human_action, temporal_flickering, appearance_style
16
+
17
+ # Output path configuration
18
+ base_save_path: outputs/vbench
19
+
20
+ # Reuse strategy configuration
21
+ reuse_strategy: chunkwise
22
+ rel_l1_thresh: 0.01
23
+ warmup_steps: 5
24
+
25
+ # KV cache compression configuration
26
+ compress_kv_cache: true
27
+ total_cache_chunk_nums: 6
28
+ budget_cache_chunk_nums: 1
29
+ compress_strategy: token
30
+ query_granularity: chunk
31
+ mix_lambda: 0.07
32
+ score_weighting_method: no_weight
33
+ discard_nearly_clean_chunk: true
34
+
35
+ # Log configuration
36
+ log: false
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/sample/teacache_physicsiq.yaml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TeaCache PhysicsIQ configuration file
2
+ # Usage: bash scripts/sample/teacache_physicsiq.sh <path_to_this_yaml>
3
+
4
+ # Basic configuration
5
+ benchmark: physicsiq
6
+ config_file: config/sample/5s_physicsiq.json
7
+
8
+ # GPU configuration
9
+ gpus: all
10
+
11
+ # PhysicsIQ dataset configuration
12
+ physicsiq_data_dir: /path/to/physicsiq
13
+
14
+ # Output path configuration
15
+ base_save_path: /path/to/output/physicsiq
16
+
17
+ # Reuse strategy configuration
18
+ reuse_strategy: all
19
+ rel_l1_thresh: 0.01
20
+ warmup_steps: 5
21
+
22
+ # Log configuration
23
+ log: false
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/sample/teacache_vbench.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TeaCache VBench configuration file
2
+ # Usage: bash scripts/sample/teacache_vbench.sh <path_to_this_yaml>
3
+
4
+ # Basic configuration
5
+ benchmark: vbench
6
+ config_file: config/sample/vbench.json
7
+
8
+ # GPU configuration
9
+ gpus: all
10
+
11
+ # VBench dataset configuration
12
+ vbench_prompt_dir: downloads/vbench/prompts_per_dimension
13
+
14
+ # Dimension configuration (specify the current dimension to process)
15
+ dimension: overall_consistency # Options: subject_consistency, scene, object_class, multiple_objects, color, spatial_relationship, temporal_style, human_action, temporal_flickering, appearance_style
16
+
17
+ # Output path configuration
18
+ base_save_path: /path/to/output/vbench
19
+
20
+ # Reuse strategy configuration
21
+ reuse_strategy: all
22
+ rel_l1_thresh: 0.01
23
+ warmup_steps: 5
24
+
25
+ # Log configuration
26
+ log: false
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/config.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ rel_l1_thresh: 0.015
2
+ warmup_steps: 5
3
+ discard_nearly_clean_chunk: true
4
+
5
+ compress_kv_cache: true
6
+ total_cache_chunk_nums: 5
7
+ compress_strategy: token
8
+ mix_lambda: 0.07
9
+ query_granularity: frame
10
+ score_weighting_method: no_weight
11
+ power: 3
12
+
13
+ log: true
14
+ print_peak_memory: true
15
+ debug: false
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/history_anchor0.5.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ alpha: 0.5
2
+ compress_kv_cache: true
3
+ compress_strategy: token
4
+ detail_alpha: 0.5
5
+ detail_lambda: 0.3
6
+ detail_window_size: 3
7
+ discard_nearly_clean_chunk: true
8
+ history_anchor_alpha: 0.5
9
+ history_anchor_horizon: 3
10
+ history_anchor_lambda: 0.5
11
+ history_decay: 0.7
12
+ history_streak_gamma: 0.2
13
+ history_streak_len: 5
14
+ log: false
15
+ mix_lambda: 0.07
16
+ phase1_steps: 9
17
+ power: 3
18
+ print_peak_memory: true
19
+ query_granularity: frame
20
+ rel_l1_thresh: 0.012
21
+ score_weighting_method: no_weight
22
+ total_cache_chunk_nums: 5
23
+ use_history_cache: true
24
+ warmup_steps: 5
25
+ weight_combine_mode: blend
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/history_decay0.5.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ alpha: 0.5
2
+ compress_kv_cache: true
3
+ compress_strategy: token
4
+ detail_alpha: 0.5
5
+ detail_lambda: 0.3
6
+ detail_window_size: 3
7
+ discard_nearly_clean_chunk: true
8
+ history_anchor_alpha: 0.5
9
+ history_anchor_horizon: 3
10
+ history_anchor_lambda: 0.3
11
+ history_decay: 0.5
12
+ history_streak_gamma: 0.2
13
+ history_streak_len: 5
14
+ log: false
15
+ mix_lambda: 0.07
16
+ phase1_steps: 9
17
+ power: 3
18
+ print_peak_memory: true
19
+ query_granularity: frame
20
+ rel_l1_thresh: 0.012
21
+ score_weighting_method: no_weight
22
+ total_cache_chunk_nums: 5
23
+ use_history_cache: true
24
+ warmup_steps: 5
25
+ weight_combine_mode: blend
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/history_decay0.85.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ alpha: 0.5
2
+ compress_kv_cache: true
3
+ compress_strategy: token
4
+ detail_alpha: 0.5
5
+ detail_lambda: 0.3
6
+ detail_window_size: 3
7
+ discard_nearly_clean_chunk: true
8
+ history_anchor_alpha: 0.5
9
+ history_anchor_horizon: 3
10
+ history_anchor_lambda: 0.3
11
+ history_decay: 0.85
12
+ history_streak_gamma: 0.2
13
+ history_streak_len: 5
14
+ log: false
15
+ mix_lambda: 0.07
16
+ phase1_steps: 9
17
+ power: 3
18
+ print_peak_memory: true
19
+ query_granularity: frame
20
+ rel_l1_thresh: 0.012
21
+ score_weighting_method: no_weight
22
+ total_cache_chunk_nums: 5
23
+ use_history_cache: true
24
+ warmup_steps: 5
25
+ weight_combine_mode: blend
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/history_streak0.35.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ alpha: 0.5
2
+ compress_kv_cache: true
3
+ compress_strategy: token
4
+ detail_alpha: 0.5
5
+ detail_lambda: 0.3
6
+ detail_window_size: 3
7
+ discard_nearly_clean_chunk: true
8
+ history_anchor_alpha: 0.5
9
+ history_anchor_horizon: 3
10
+ history_anchor_lambda: 0.3
11
+ history_decay: 0.7
12
+ history_streak_gamma: 0.35
13
+ history_streak_len: 5
14
+ log: false
15
+ mix_lambda: 0.07
16
+ phase1_steps: 9
17
+ power: 3
18
+ print_peak_memory: true
19
+ query_granularity: frame
20
+ rel_l1_thresh: 0.012
21
+ score_weighting_method: no_weight
22
+ total_cache_chunk_nums: 5
23
+ use_history_cache: true
24
+ warmup_steps: 5
25
+ weight_combine_mode: blend
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/historycache_config.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dev5 HistoryAwareCache — inherits dev4 best + AR history (MVP)
2
+ rel_l1_thresh: 0.012
3
+ warmup_steps: 5
4
+ phase1_steps: 9
5
+ alpha: 0.5
6
+
7
+ detail_alpha: 0.5
8
+ detail_window_size: 3
9
+ detail_lambda: 0.3
10
+ weight_combine_mode: blend
11
+
12
+ use_history_cache: true
13
+ history_decay: 0.7
14
+ history_anchor_horizon: 3
15
+ history_streak_len: 5
16
+ history_anchor_lambda: 0.3
17
+ history_streak_gamma: 0.2
18
+ history_anchor_alpha: 0.5
19
+
20
+ discard_nearly_clean_chunk: true
21
+ compress_kv_cache: true
22
+ total_cache_chunk_nums: 5
23
+ compress_strategy: token
24
+ mix_lambda: 0.07
25
+ query_granularity: frame
26
+ score_weighting_method: no_weight
27
+ power: 3
28
+ log: false
29
+ print_peak_memory: true
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/historycache_config_best.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dev5 HistoryAwareCache — inherits dev4 best + AR history (MVP)
2
+ rel_l1_thresh: 0.012
3
+ warmup_steps: 5
4
+ phase1_steps: 9
5
+ alpha: 0.5
6
+
7
+ detail_alpha: 0.5
8
+ detail_window_size: 3
9
+ detail_lambda: 0.3
10
+ weight_combine_mode: blend
11
+
12
+ use_history_cache: true
13
+ history_decay: 0.7
14
+ history_anchor_horizon: 3
15
+ history_streak_len: 5
16
+ history_anchor_lambda: 0.3
17
+ history_streak_gamma: 0.2
18
+ history_anchor_alpha: 0.5
19
+
20
+ discard_nearly_clean_chunk: true
21
+ compress_kv_cache: true
22
+ total_cache_chunk_nums: 5
23
+ compress_strategy: token
24
+ mix_lambda: 0.07
25
+ query_granularity: frame
26
+ score_weighting_method: no_weight
27
+ power: 3
28
+ log: false
29
+ print_peak_memory: true
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motioncache_config.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionCache hyperparameters for MAGI-1 (Appendix C)
2
+ rel_l1_thresh: 0.015
3
+ warmup_steps: 5
4
+ phase1_steps: 9
5
+ alpha: 0.5
6
+
7
+ discard_nearly_clean_chunk: true
8
+
9
+ compress_kv_cache: true
10
+ total_cache_chunk_nums: 5
11
+ compress_strategy: token
12
+ mix_lambda: 0.07
13
+ query_granularity: frame
14
+ score_weighting_method: no_weight
15
+ power: 3
16
+
17
+ log: true
18
+ print_peak_memory: true
19
+ debug: false
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motioncache_config_fast.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionCache-fast: higher threshold for more aggressive skipping
2
+ rel_l1_thresh: 0.025
3
+ warmup_steps: 5
4
+ phase1_steps: 9
5
+ alpha: 0.5
6
+
7
+ discard_nearly_clean_chunk: true
8
+
9
+ compress_kv_cache: true
10
+ total_cache_chunk_nums: 5
11
+ compress_strategy: token
12
+ mix_lambda: 0.07
13
+ query_granularity: frame
14
+ score_weighting_method: no_weight
15
+ power: 3
16
+
17
+ log: true
18
+ print_peak_memory: true
19
+ debug: false
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motioncache_phase1_only.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionCache with phase2 disabled (K=64, always chunk-wise = FlowCache equivalent)
2
+ rel_l1_thresh: 0.015
3
+ warmup_steps: 5
4
+ phase1_steps: 64
5
+ alpha: 0.5
6
+
7
+ discard_nearly_clean_chunk: true
8
+
9
+ compress_kv_cache: true
10
+ total_cache_chunk_nums: 5
11
+ compress_strategy: token
12
+ mix_lambda: 0.07
13
+ query_granularity: frame
14
+ score_weighting_method: no_weight
15
+ power: 3
16
+
17
+ log: false
18
+ print_peak_memory: true
19
+ debug: false
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motiondetail_config.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionDetailCache: MotionCache + spatial detail variance (dev4)
2
+ rel_l1_thresh: 0.015
3
+ warmup_steps: 5
4
+ phase1_steps: 9
5
+ alpha: 0.5
6
+
7
+ # Detail metric: local latent spatial variance
8
+ detail_alpha: 0.5
9
+ detail_window_size: 3
10
+ detail_lambda: 0.5
11
+ weight_combine_mode: max # max | product | blend
12
+
13
+ discard_nearly_clean_chunk: true
14
+
15
+ compress_kv_cache: true
16
+ total_cache_chunk_nums: 5
17
+ compress_strategy: token
18
+ mix_lambda: 0.07
19
+ query_granularity: frame
20
+ score_weighting_method: no_weight
21
+ power: 3
22
+
23
+ log: true
24
+ print_peak_memory: true
25
+ debug: false
FlowCache/FlowCache4MAGI-1-dev5-history/yaml_config/single_run/motiondetail_config_best.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ alpha: 0.5
2
+ compress_kv_cache: true
3
+ detail_alpha: 0.5
4
+ detail_lambda: 0.3
5
+ detail_window_size: 3
6
+ discard_nearly_clean_chunk: true
7
+ log: true
8
+ phase1_steps: 9
9
+ print_peak_memory: true
10
+ rel_l1_thresh: 0.012
11
+ total_cache_chunk_nums: 5
12
+ warmup_steps: 5
13
+ weight_combine_mode: blend
FlowCache/FlowCache4MAGI-1-dev6-adaptive/config/sample/physicsiq.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_config": {
3
+ "model_name": "videodit_ardf",
4
+ "num_layers": 34,
5
+ "hidden_size": 3072,
6
+ "ffn_hidden_size": 12288,
7
+ "num_attention_heads": 24,
8
+ "num_query_groups": 8,
9
+ "kv_channels": 128,
10
+ "layernorm_epsilon": 1e-06,
11
+ "apply_layernorm_1p": true,
12
+ "x_rescale_factor": 1,
13
+ "half_channel_vae": false,
14
+ "params_dtype": "torch.bfloat16",
15
+ "patch_size": 2,
16
+ "t_patch_size": 1,
17
+ "in_channels": 16,
18
+ "out_channels": 16,
19
+ "cond_hidden_ratio": 0.25,
20
+ "caption_channels": 4096,
21
+ "caption_max_length": 800,
22
+ "xattn_cond_hidden_ratio": 1.0,
23
+ "cond_gating_ratio": 1.0,
24
+ "gated_linear_unit": false
25
+ },
26
+ "runtime_config": {
27
+ "cfg_number": 1,
28
+ "cfg_t_range": [
29
+ 0.0,
30
+ 0.0217,
31
+ 0.1,
32
+ 0.3,
33
+ 0.999
34
+ ],
35
+ "prev_chunk_scales": [
36
+ 1.5,
37
+ 1.5,
38
+ 1.5,
39
+ 1.0,
40
+ 1.0
41
+ ],
42
+ "text_scales": [
43
+ 7.5,
44
+ 7.5,
45
+ 7.5,
46
+ 0.0,
47
+ 0.0
48
+ ],
49
+ "noise2clean_kvrange": [],
50
+ "clean_chunk_kvrange": 1,
51
+ "clean_t": 0.9999,
52
+ "seed": 1234,
53
+ "num_frames": 120,
54
+ "video_size_h": 720,
55
+ "video_size_w": 1280,
56
+ "num_steps": 64,
57
+ "window_size": 4,
58
+ "fps": 24,
59
+ "chunk_width": 6,
60
+ "load": "./downloads/4.5B_distill",
61
+ "t5_pretrained": "./downloads/t5_pretrained",
62
+ "t5_device": "cuda",
63
+ "vae_pretrained": "./downloads/vae",
64
+ "scale_factor": 0.18215,
65
+ "temporal_downsample_factor": 4
66
+ },
67
+ "engine_config": {
68
+ "distributed_backend": "nccl",
69
+ "distributed_timeout_minutes": 15,
70
+ "pp_size": 1,
71
+ "cp_size": 1,
72
+ "cp_strategy": "none",
73
+ "ulysses_overlap_degree": 1,
74
+ "fp8_quant": false,
75
+ "distill_nearly_clean_chunk_threshold": 0.3,
76
+ "shortcut_mode": "8,16,16",
77
+ "distill": true,
78
+ "kv_offload": true,
79
+ "enable_cuda_graph": false
80
+ }
81
+ }
FlowCache/FlowCache4MAGI-1-dev6-adaptive/config/sample/vbench.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_config": {
3
+ "model_name": "videodit_ardf",
4
+ "num_layers": 34,
5
+ "hidden_size": 3072,
6
+ "ffn_hidden_size": 12288,
7
+ "num_attention_heads": 24,
8
+ "num_query_groups": 8,
9
+ "kv_channels": 128,
10
+ "layernorm_epsilon": 1e-06,
11
+ "apply_layernorm_1p": true,
12
+ "x_rescale_factor": 1,
13
+ "half_channel_vae": false,
14
+ "params_dtype": "torch.bfloat16",
15
+ "patch_size": 2,
16
+ "t_patch_size": 1,
17
+ "in_channels": 16,
18
+ "out_channels": 16,
19
+ "cond_hidden_ratio": 0.25,
20
+ "caption_channels": 4096,
21
+ "caption_max_length": 800,
22
+ "xattn_cond_hidden_ratio": 1.0,
23
+ "cond_gating_ratio": 1.0,
24
+ "gated_linear_unit": false
25
+ },
26
+ "runtime_config": {
27
+ "cfg_number": 1,
28
+ "cfg_t_range": [
29
+ 0.0,
30
+ 0.0217,
31
+ 0.1,
32
+ 0.3,
33
+ 0.999
34
+ ],
35
+ "prev_chunk_scales": [
36
+ 1.5,
37
+ 1.5,
38
+ 1.5,
39
+ 1.0,
40
+ 1.0
41
+ ],
42
+ "text_scales": [
43
+ 7.5,
44
+ 7.5,
45
+ 7.5,
46
+ 0.0,
47
+ 0.0
48
+ ],
49
+ "noise2clean_kvrange": [],
50
+ "clean_chunk_kvrange": 1,
51
+ "clean_t": 0.9999,
52
+ "seed": 1234,
53
+ "num_frames": 240,
54
+ "video_size_h": 720,
55
+ "video_size_w": 720,
56
+ "num_steps": 16,
57
+ "window_size": 4,
58
+ "fps": 24,
59
+ "chunk_width": 6,
60
+ "load": "./downloads/4.5B_distill",
61
+ "t5_pretrained": "./downloads/t5_pretrained",
62
+ "t5_device": "cuda",
63
+ "vae_pretrained": "./downloads/vae",
64
+ "scale_factor": 0.18215,
65
+ "temporal_downsample_factor": 4
66
+ },
67
+ "engine_config": {
68
+ "distributed_backend": "nccl",
69
+ "distributed_timeout_minutes": 15,
70
+ "pp_size": 1,
71
+ "cp_size": 1,
72
+ "cp_strategy": "none",
73
+ "ulysses_overlap_degree": 1,
74
+ "fp8_quant": false,
75
+ "distill_nearly_clean_chunk_threshold": 0.3,
76
+ "shortcut_mode": "8,16,16",
77
+ "distill": true,
78
+ "kv_offload": true,
79
+ "enable_cuda_graph": false
80
+ }
81
+ }
FlowCache/FlowCache4MAGI-1-dev6-adaptive/config/single_run/flowcache_t2v.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_config": {
3
+ "model_name": "videodit_ardf",
4
+ "num_layers": 34,
5
+ "hidden_size": 3072,
6
+ "ffn_hidden_size": 12288,
7
+ "num_attention_heads": 24,
8
+ "num_query_groups": 8,
9
+ "kv_channels": 128,
10
+ "layernorm_epsilon": 1e-06,
11
+ "apply_layernorm_1p": true,
12
+ "x_rescale_factor": 1,
13
+ "half_channel_vae": false,
14
+ "params_dtype": "torch.bfloat16",
15
+ "patch_size": 2,
16
+ "t_patch_size": 1,
17
+ "in_channels": 16,
18
+ "out_channels": 16,
19
+ "cond_hidden_ratio": 0.25,
20
+ "caption_channels": 4096,
21
+ "caption_max_length": 800,
22
+ "xattn_cond_hidden_ratio": 1.0,
23
+ "cond_gating_ratio": 1.0,
24
+ "gated_linear_unit": false
25
+ },
26
+ "runtime_config": {
27
+ "cfg_number": 1,
28
+ "cfg_t_range": [
29
+ 0.0,
30
+ 0.0217,
31
+ 0.1,
32
+ 0.3,
33
+ 0.999
34
+ ],
35
+ "prev_chunk_scales": [
36
+ 1.5,
37
+ 1.5,
38
+ 1.5,
39
+ 1.0,
40
+ 1.0
41
+ ],
42
+ "text_scales": [
43
+ 7.5,
44
+ 7.5,
45
+ 7.5,
46
+ 0.0,
47
+ 0.0
48
+ ],
49
+ "noise2clean_kvrange": [],
50
+ "clean_chunk_kvrange": 1,
51
+ "clean_t": 0.9999,
52
+ "seed": 1234,
53
+ "num_frames": 240,
54
+ "video_size_h": 720,
55
+ "video_size_w": 720,
56
+ "num_steps": 64,
57
+ "window_size": 4,
58
+ "fps": 24,
59
+ "chunk_width": 6,
60
+ "load": "./downloads/4.5B_distill",
61
+ "t5_pretrained": "./downloads/t5_pretrained",
62
+ "t5_device": "cuda",
63
+ "vae_pretrained": "./downloads/vae",
64
+ "scale_factor": 0.18215,
65
+ "temporal_downsample_factor": 4
66
+ },
67
+ "engine_config": {
68
+ "distributed_backend": "nccl",
69
+ "distributed_timeout_minutes": 15,
70
+ "pp_size": 1,
71
+ "cp_size": 1,
72
+ "cp_strategy": "none",
73
+ "ulysses_overlap_degree": 1,
74
+ "fp8_quant": false,
75
+ "distill_nearly_clean_chunk_threshold": 0.3,
76
+ "shortcut_mode": "8,16,16",
77
+ "distill": true,
78
+ "kv_offload": false,
79
+ "enable_cuda_graph": false
80
+ }
81
+ }
FlowCache/FlowCache4MAGI-1-dev6-adaptive/config/single_run/flowcache_v2v.json ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_config": {
3
+ "model_name": "videodit_ardf",
4
+ "num_layers": 34,
5
+ "hidden_size": 3072,
6
+ "ffn_hidden_size": 12288,
7
+ "num_attention_heads": 24,
8
+ "num_query_groups": 8,
9
+ "kv_channels": 128,
10
+ "layernorm_epsilon": 1e-06,
11
+ "apply_layernorm_1p": true,
12
+ "x_rescale_factor": 1,
13
+ "half_channel_vae": false,
14
+ "params_dtype": "torch.bfloat16",
15
+ "patch_size": 2,
16
+ "t_patch_size": 1,
17
+ "in_channels": 16,
18
+ "out_channels": 16,
19
+ "cond_hidden_ratio": 0.25,
20
+ "caption_channels": 4096,
21
+ "caption_max_length": 800,
22
+ "xattn_cond_hidden_ratio": 1.0,
23
+ "cond_gating_ratio": 1.0,
24
+ "gated_linear_unit": false
25
+ },
26
+ "runtime_config": {
27
+ "cfg_number": 1,
28
+ "cfg_t_range": [
29
+ 0.0,
30
+ 0.0217,
31
+ 0.1,
32
+ 0.3,
33
+ 0.999
34
+ ],
35
+ "prev_chunk_scales": [
36
+ 1.5,
37
+ 1.5,
38
+ 1.5,
39
+ 1.0,
40
+ 1.0
41
+ ],
42
+ "text_scales": [
43
+ 7.5,
44
+ 7.5,
45
+ 7.5,
46
+ 0.0,
47
+ 0.0
48
+ ],
49
+ "noise2clean_kvrange": [
50
+ 5,
51
+ 4,
52
+ 3,
53
+ 2
54
+ ],
55
+ "clean_chunk_kvrange": 1,
56
+ "clean_t": 0.9999,
57
+ "seed": 1234,
58
+ "num_frames": 120,
59
+ "video_size_h": 720,
60
+ "video_size_w": 1280,
61
+ "num_steps": 8,
62
+ "window_size": 4,
63
+ "fps": 24,
64
+ "chunk_width": 6,
65
+ "load": "./downloads/4.5B_distill",
66
+ "t5_pretrained": "./downloads/t5_pretrained",
67
+ "t5_device": "cuda",
68
+ "vae_pretrained": "./downloads/vae",
69
+ "scale_factor": 0.18215,
70
+ "temporal_downsample_factor": 4
71
+ },
72
+ "engine_config": {
73
+ "distributed_backend": "nccl",
74
+ "distributed_timeout_minutes": 15,
75
+ "pp_size": 1,
76
+ "cp_size": 1,
77
+ "cp_strategy": "none",
78
+ "ulysses_overlap_degree": 1,
79
+ "fp8_quant": false,
80
+ "distill_nearly_clean_chunk_threshold": 0.3,
81
+ "shortcut_mode": "8,16,16",
82
+ "distill": true,
83
+ "kv_offload": false,
84
+ "enable_cuda_graph": false
85
+ }
86
+ }
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/__init__.py ADDED
File without changes
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (198 Bytes). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .common_utils import divide, env_is_true, set_random_seed
16
+ from .config import EngineConfig, MagiConfig, ModelConfig, RuntimeConfig
17
+ from .dataclass import InferenceParams, ModelMetaArgs, PackedCoreAttnParams, PackedCrossAttnParams
18
+ from .logger import magi_logger, print_per_rank, print_rank_0
19
+ from .timer import event_path_timer
20
+
21
+ __all__ = [
22
+ "MagiConfig",
23
+ "ModelConfig",
24
+ "EngineConfig",
25
+ "RuntimeConfig",
26
+ "magi_logger",
27
+ "print_per_rank",
28
+ "print_rank_0",
29
+ "event_path_timer",
30
+ "divide",
31
+ "env_is_true",
32
+ "set_random_seed",
33
+ "PackedCoreAttnParams",
34
+ "PackedCrossAttnParams",
35
+ "ModelMetaArgs",
36
+ "InferenceParams",
37
+ ]
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (774 Bytes). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/common_utils.cpython-310.pyc ADDED
Binary file (1.05 kB). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/config.cpython-310.pyc ADDED
Binary file (6.43 kB). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/dataclass.cpython-310.pyc ADDED
Binary file (3.18 kB). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/logger.cpython-310.pyc ADDED
Binary file (1.27 kB). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/__pycache__/timer.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/common_utils.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import random
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+
22
+ def env_is_true(env_name: str) -> bool:
23
+ return str(os.environ.get(env_name, "0")).lower() in {"1", "true", "yes", "y", "on", "enabled"}
24
+
25
+
26
+ def divide(numerator, denominator):
27
+ assert numerator % denominator == 0, "{} is not divisible by {}".format(numerator, denominator)
28
+ return numerator // denominator
29
+
30
+
31
+ def set_random_seed(seed):
32
+ """Set random seed.
33
+
34
+ Args:
35
+ seed (int): Seed to be used.
36
+ """
37
+ assert seed is not None, "Please provide a seed in config.json"
38
+ random.seed(seed)
39
+ np.random.seed(seed)
40
+ torch.manual_seed(seed)
41
+ torch.cuda.manual_seed_all(seed)
42
+ return seed
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/config.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import dataclasses
16
+ import json
17
+ import os
18
+
19
+ import torch
20
+
21
+
22
+ @dataclasses.dataclass
23
+ class ModelConfig:
24
+ model_name: str
25
+
26
+ # Transformer
27
+ num_layers: int = None # Number of transformer layers.
28
+ hidden_size: int = None # Transformer hidden size.
29
+ ffn_hidden_size: int = None # Transformer Feed-Forward Network hidden size
30
+ num_attention_heads: int = None # Number of transformer attention heads.
31
+ num_query_groups: int = 1 # Number of query groups, which used for GQA
32
+ kv_channels: int = None # Projection weights dimension in multi-head attention
33
+ layernorm_epsilon: float = 1e-6 # Epsilon for layer norm and RMS norm.
34
+ apply_layernorm_1p: bool = False # Adjust LayerNorm weights which improves numerical stability.
35
+ x_rescale_factor: float = 1.0
36
+ half_channel_vae: bool = False
37
+ params_dtype: torch.dtype = None
38
+
39
+ # Embedding
40
+ patch_size: int = 2 # (latent) patch size for DiT patch embedding layer
41
+ t_patch_size: int = 1 # (latent) patch size for t dim patch embedding layer
42
+ in_channels: int = 4 # latent input channel for DiT
43
+ out_channels: int = 4 # latent output channel for DiT
44
+ cond_hidden_ratio: float = 0.25
45
+ caption_channels: int = 4096
46
+ caption_max_length: int = 800
47
+ xattn_cond_hidden_ratio: float = 1.0
48
+ cond_gating_ratio: float = 1.0
49
+ gated_linear_unit: bool = False
50
+
51
+
52
+ @dataclasses.dataclass
53
+ class RuntimeConfig:
54
+ # Inference settings such as cfg, kv range, clean t, etc.
55
+ cfg_number: int = None # Number of CFG
56
+ cfg_t_range: list = dataclasses.field(
57
+ default_factory=lambda: [0, 0.0217, 0.1000, 0.3, 0.999]
58
+ ) # CFG t-range of each scales
59
+ prev_chunk_scales: list = dataclasses.field(
60
+ default_factory=lambda: [1.5, 1.5, 1.5, 1.5, 1.5]
61
+ ) # CFG scales of previous chunks
62
+ text_scales: list = dataclasses.field(default_factory=lambda: [7.5, 7.5, 7.5, 7.5, 7.5]) # CFG scales of text
63
+
64
+ noise2clean_kvrange: list = dataclasses.field(default_factory=list) # Range of kv for noise2clean chunks
65
+ clean_chunk_kvrange: int = -1 # Range of kv for clean chunks
66
+ clean_t: float = 1.0 # timestep for clean chunks
67
+
68
+ # Video settings
69
+ seed: int = 1234 # Random seed used for python, numpy, pytorch, and cuda.
70
+ num_frames: int = 128
71
+ video_size_h: int = None
72
+ video_size_w: int = None
73
+ num_steps: int = 64 # Number of steps for the diffusion model
74
+ window_size: int = 4 # Window size for the diffusion model
75
+ fps: int = 24 # Frames per second
76
+ chunk_width: int = 6 # Clip width for the diffusion model
77
+
78
+ # Checkpoint, includes t5, vae, dit, etc.
79
+ t5_pretrained: str = None # Path to load pretrained T5 model.
80
+ t5_device: str = "cuda" # Device for T5 model to run on.
81
+ vae_pretrained: str = None # Path to load pretrained VAE model.
82
+ scale_factor: float = 0.18215 # Scale factor for the vae
83
+ temporal_downsample_factor: int = 4 # Temporal downsample factor for the vae
84
+ load: str = None # Directory containing a model checkpoint.
85
+
86
+
87
+ @dataclasses.dataclass
88
+ class EngineConfig:
89
+ # Parallism strategy
90
+ distributed_backend: str = "nccl" # Choices: ["nccl", "gloo"]
91
+ distributed_timeout_minutes: int = 10 # Timeout minutes for torch.distributed.
92
+ pp_size: int = 1 # Degree of pipeline model parallelism.
93
+ cp_size: int = 1 # Degree of context parallelism.
94
+ cp_strategy: str = "none" # Choices: ["none", "cp_ulysses", "cp_shuffle_overlap"]
95
+ ulysses_overlap_degree: int = 1 # Overlap degree for Ulysses
96
+
97
+ # Quantization
98
+ fp8_quant: bool = False # Enable 8-bit floating point quantization for model weights.
99
+
100
+ # Distillation
101
+ distill_nearly_clean_chunk_threshold: float = 0.3 # Threshold for distilling nearly clean chunks
102
+ shortcut_mode: str = "8,16,16" # Parameters for shortcut mode
103
+ distill: bool = False # Use distill mode
104
+
105
+ # Optimization
106
+ kv_offload: bool = False # Use kv-offload algorithm
107
+ enable_cuda_graph: bool = False # Enable CUDA graph for video generation
108
+
109
+
110
+ @dataclasses.dataclass
111
+ class MagiConfig:
112
+ model_config: ModelConfig
113
+ runtime_config: RuntimeConfig
114
+ engine_config: EngineConfig
115
+
116
+ @classmethod
117
+ def _check_missing_fields(cls, config_dict: dict, required_fields: list):
118
+ actual_fields = set(config_dict.keys())
119
+ missing_fields = set(required_fields) - actual_fields
120
+ if missing_fields:
121
+ raise ValueError(f"Missing fields in the configuration file: {', '.join(missing_fields)}")
122
+
123
+ @classmethod
124
+ def _create_nested_config(cls, config_dict: dict, config_name: str, config_cls):
125
+ nested_config_dict = config_dict.get(config_name, {})
126
+ cls._check_missing_fields(nested_config_dict, config_cls.__dataclass_fields__.keys())
127
+ return config_cls(**nested_config_dict)
128
+
129
+ @classmethod
130
+ def _create_config_from_dict(cls, config_dict: dict):
131
+ cls._check_missing_fields(config_dict, cls.__dataclass_fields__.keys())
132
+
133
+ # Create nested configs
134
+ model_config = cls._create_nested_config(config_dict, "model_config", ModelConfig)
135
+ runtime_config = cls._create_nested_config(config_dict, "runtime_config", RuntimeConfig)
136
+ engine_config = cls._create_nested_config(config_dict, "engine_config", EngineConfig)
137
+
138
+ return cls(model_config=model_config, runtime_config=runtime_config, engine_config=engine_config)
139
+
140
+ @classmethod
141
+ def from_json(cls, json_path: str):
142
+ def simple_json_decoder(dct):
143
+ dtype_map = {"torch.bfloat16": torch.bfloat16, "torch.float16": torch.float16, "torch.float32": torch.float32}
144
+ if 'params_dtype' in dct:
145
+ dct['params_dtype'] = dtype_map[dct['params_dtype']]
146
+ return dct
147
+
148
+ with open(json_path, "r") as f:
149
+ config_dict = json.load(f, object_hook=simple_json_decoder)
150
+ magi_config = cls._create_config_from_dict(config_dict)
151
+
152
+ def post_validation(magi_config):
153
+ if magi_config.engine_config.fp8_quant or magi_config.engine_config.distill:
154
+ assert (
155
+ magi_config.runtime_config.cfg_number == 1
156
+ ), "Please set `cfg_number: 1` in config.json for distill or quant model"
157
+ else:
158
+ assert magi_config.runtime_config.cfg_number == 3, "Please set `cfg_number: 3` in config.json for base model"
159
+
160
+ post_validation(magi_config)
161
+
162
+ return magi_config
163
+
164
+ def to_json(self, json_path: str):
165
+ class SimpleJSONEncoder(json.JSONEncoder):
166
+ def default(self, obj):
167
+ if isinstance(obj, torch.dtype):
168
+ return str(obj)
169
+ return super().default(obj)
170
+
171
+ # Ensure the directory exists
172
+ os.makedirs(os.path.dirname(json_path), exist_ok=True)
173
+
174
+ config_dict = {
175
+ "model_config": dataclasses.asdict(self.model_config),
176
+ "runtime_config": dataclasses.asdict(self.runtime_config),
177
+ "engine_config": dataclasses.asdict(self.engine_config),
178
+ }
179
+ with open(json_path, "w") as f:
180
+ json.dump(config_dict, f, indent=4, cls=SimpleJSONEncoder)
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/dataclass.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass
16
+ from typing import List, Optional
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class PackedCoreAttnParams:
24
+ # Packed sequence parameters for core_attn
25
+ q_range: torch.Tensor
26
+ k_range: torch.Tensor
27
+ np_q_range: np.ndarray
28
+ np_k_range: np.ndarray
29
+ max_seqlen_q: int
30
+ max_seqlen_k: int
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class PackedCrossAttnParams:
35
+ # Packed sequence parameters for cross_attn
36
+ q_ranges: torch.Tensor = None
37
+ kv_ranges: torch.Tensor = None
38
+ cu_seqlens_q: torch.Tensor = None
39
+ cu_seqlens_kv: torch.Tensor = None
40
+ max_seqlen_q: int = None
41
+ max_seqlen_kv: int = None
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class ModelMetaArgs:
46
+ H: int
47
+ W: int
48
+ cp_pad_size: int
49
+ cp_split_sizes: List[int]
50
+ slice_point: int
51
+ denoising_range_num: int
52
+ range_num: int
53
+ extract_prefix_video_feature: bool
54
+ fwd_extra_1st_chunk: bool
55
+ distill_nearly_clean_chunk: bool
56
+ clip_token_nums: int
57
+ enable_cuda_graph: bool
58
+ core_attn_params: PackedCoreAttnParams
59
+ cross_attn_params: PackedCrossAttnParams
60
+ timestep: torch.Tensor
61
+ get_attn_weights_layer_num: int
62
+ save_kvcache_every_forward: bool
63
+ cur_denoise_step: int
64
+ # Includes all chunks of the current sequence
65
+ start_chunk_id: int
66
+ end_chunk_id: int
67
+ compress_kv: bool # use kv cache compression or not
68
+ total_cache_len: int
69
+ budget_cache_len: int
70
+ chunk_num: int
71
+ debug: bool
72
+ near_clean_chunk_idx: int
73
+ # MotionCache sparse forward (Phase 2): gather active tokens only
74
+ sparse_active_indices: Optional[torch.Tensor] = None
75
+ sparse_total_tokens: int = 0
76
+
77
+ class InferenceParams:
78
+ """Inference parameters that are passed to the main model in order
79
+ to efficienly calculate and store the context during inference."""
80
+
81
+ def __init__(self, max_batch_size, max_sequence_length):
82
+ self.max_sequence_length = max_sequence_length
83
+ self.max_batch_size = max_batch_size
84
+ self.sequence_len_offset = 0
85
+ self.key_value_memory_dict = {}
86
+ self.update_kv_cache = False
87
+
88
+ self.kv_compressed = False
89
+
90
+ def swap_key_value_dict(self, batch_idx):
91
+ "swap between batches"
92
+ if len(self.key_value_memory_dict) == 0:
93
+ raise ValueError("should not swap when dict in empty")
94
+
95
+ for layer_number in self.key_value_memory_dict.keys():
96
+ inference_key_memory, inference_value_memory = self.key_value_memory_dict[layer_number]
97
+ assert len(batch_idx) == inference_key_memory.shape[1] # make sure batch size is the same
98
+ new_inference_key_memory = inference_key_memory[:, batch_idx]
99
+ new_inference_value_memory = inference_value_memory[:, batch_idx]
100
+ self.key_value_memory_dict[layer_number] = (new_inference_key_memory, new_inference_value_memory)
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/logger.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+
17
+ import torch
18
+
19
+
20
+ class GlobalLogger:
21
+ _logger = None
22
+
23
+ @classmethod
24
+ def get_logger(cls, name=__name__, level=logging.INFO):
25
+ if cls._logger is None:
26
+ cls._logger = logging.getLogger("magi_logger")
27
+ cls._logger.setLevel(logging.INFO)
28
+
29
+ cls._logger.propagate = False
30
+ cls._logger.handlers.clear()
31
+ formatter = logging.Formatter("[%(asctime)s - %(levelname)s] %(message)s")
32
+ handler = logging.StreamHandler()
33
+ handler.setFormatter(formatter)
34
+ cls._logger.addHandler(handler)
35
+
36
+ return cls._logger
37
+
38
+
39
+ magi_logger = GlobalLogger.get_logger()
40
+
41
+
42
+ def print_per_rank(message):
43
+ magi_logger.info(message)
44
+
45
+
46
+ def print_rank_0(message):
47
+ if torch.distributed.is_initialized():
48
+ if torch.distributed.get_rank() == 0:
49
+ magi_logger.info(message)
50
+ else:
51
+ magi_logger.info(message)
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/common/timer.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from datetime import datetime
16
+
17
+ import torch
18
+
19
+ from .logger import print_rank_0
20
+
21
+
22
+ class EventPathTimer:
23
+ """
24
+ A lightweight class for recording time without any distributed barrier.
25
+
26
+ This class allows for recording elapsed time between events without requiring
27
+ synchronization across distributed processes. It maintains the previous message
28
+ and time to calculate the duration between consecutive records.
29
+ """
30
+
31
+ def __init__(self):
32
+ """
33
+ Initialize the EventPathTimer.
34
+
35
+ This constructor sets the previous message and time to None, preparing
36
+ the instance for recording events.
37
+ """
38
+ self.prev_message: str = None
39
+ self.prev_time: datetime = None
40
+
41
+ def reset(self):
42
+ """
43
+ Reset the recorded message and time.
44
+
45
+ This method clears the previous message and time, allowing for a fresh
46
+ start in recording new events.
47
+ """
48
+ self.prev_message = None
49
+ self.prev_time = None
50
+
51
+ def synced_record(self, message):
52
+ """
53
+ Record the current time with a message.
54
+
55
+ Args:
56
+ message (str): A message to log along with the current time.
57
+
58
+ This method synchronizes the CUDA operations, records the current time,
59
+ and calculates the elapsed time since the last recorded message, if any.
60
+ It then logs the elapsed time along with the previous and current messages.
61
+ """
62
+ torch.cuda.synchronize()
63
+ current_time = datetime.now()
64
+ if self.prev_message is not None:
65
+ print_rank_0(
66
+ f"\nTime Elapsed: [{current_time - self.prev_time}] From [{self.prev_message} ({self.prev_time})] To [{message} ({current_time})]"
67
+ )
68
+ self.prev_message = message
69
+ self.prev_time = current_time
70
+
71
+
72
+ _GLOBAL_LIGHT_TIMER = EventPathTimer()
73
+
74
+
75
+ def event_path_timer() -> EventPathTimer:
76
+ """Get the current EventPathTimer instance.
77
+
78
+ Returns:
79
+ EventPathTimer: The current EventPathTimer instance.
80
+
81
+ Raises:
82
+ AssertionError: If the EventPathTimer has not been initialized.
83
+ """
84
+ assert _GLOBAL_LIGHT_TIMER is not None, "light time recorder is not initialized"
85
+ return _GLOBAL_LIGHT_TIMER
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/checkpoint/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .checkpointing import load_checkpoint
16
+
17
+ __all__ = ["load_checkpoint"]
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (290 Bytes). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc ADDED
Binary file (5.38 kB). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/checkpoint/checkpointing.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import io
16
+ import json
17
+ import os
18
+ import re
19
+ import subprocess
20
+ from collections import OrderedDict
21
+ from concurrent.futures import ThreadPoolExecutor
22
+ from datetime import datetime
23
+
24
+ import numpy as np
25
+ import torch
26
+ import torch.distributed
27
+ from safetensors.torch import load as load_from_bytes
28
+ from safetensors.torch import load_file
29
+ from tqdm.auto import tqdm
30
+
31
+ import inference.infra.distributed.parallel_state as mpu
32
+ from inference.common import EngineConfig, ModelConfig, RuntimeConfig, print_per_rank, print_rank_0
33
+
34
+
35
+ def _load_shard(shard_path, param_names, num_threads=None):
36
+ zstd_path = shard_path + ".zst"
37
+ if os.path.exists(zstd_path):
38
+ start_time = datetime.now()
39
+ print_per_rank(f"Decompressing {zstd_path} with {num_threads} threads")
40
+ cmd = ["zstd", "-d"]
41
+ if num_threads:
42
+ cmd.extend(["-T", str(num_threads)])
43
+
44
+ process = subprocess.Popen(cmd + ["-c", zstd_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1)
45
+
46
+ decompressed_data = process.stdout.read()
47
+ process.stdout.close()
48
+
49
+ retcode = process.wait()
50
+ if retcode != 0:
51
+ raise RuntimeError(f"Decompression failed: {process.stderr.read().decode()}")
52
+ print_per_rank(
53
+ f"Decompressed {zstd_path} with {num_threads} threads, duration: {(datetime.now() - start_time).total_seconds()}s"
54
+ )
55
+
56
+ buffer = io.BytesIO(decompressed_data)
57
+ start_time = datetime.now()
58
+ print_per_rank(f"Loading {shard_path} from zstd file, start time: {start_time}")
59
+ weights = load_from_bytes(buffer.getvalue())
60
+ print_per_rank(f"Loaded {shard_path} from zstd file, duration: {(datetime.now() - start_time).total_seconds()}s")
61
+ buffer.close()
62
+ else:
63
+ weights = load_file(shard_path)
64
+
65
+ return {name: weights[name] for name in param_names}
66
+
67
+
68
+ def load_sharded_safetensors_parallel_with_progress(checkpoint_dir):
69
+ index_path = os.path.join(checkpoint_dir, "model.safetensors.index.json")
70
+ if not os.path.exists(index_path):
71
+ model_file_path = os.path.join(checkpoint_dir, "model.safetensors")
72
+ state_dict = load_file(model_file_path)
73
+ return state_dict
74
+
75
+ with open(index_path, "r") as f:
76
+ index = json.load(f)
77
+
78
+ state_dict = {}
79
+ shard_map = {}
80
+
81
+ # Group parameters by shard file
82
+ for param_name, shard_file in index["weight_map"].items():
83
+ shard_path = os.path.join(checkpoint_dir, shard_file)
84
+ if shard_path not in shard_map:
85
+ shard_map[shard_path] = []
86
+ shard_map[shard_path].append(param_name)
87
+
88
+ # Load shards in parallel with a progress bar
89
+ with ThreadPoolExecutor() as executor:
90
+ futures = {
91
+ executor.submit(_load_shard, shard_path, param_names): shard_path for shard_path, param_names in shard_map.items()
92
+ }
93
+ pbar = tqdm(futures, desc="Loading shards", total=len(futures))
94
+ for future in pbar:
95
+ result = future.result()
96
+ state_dict.update(result)
97
+
98
+ return state_dict
99
+
100
+
101
+ def unwrap_model(model):
102
+ return_list = True
103
+ if not isinstance(model, list):
104
+ model = [model]
105
+ return_list = False
106
+ unwrapped_model = []
107
+ for model_module in model:
108
+ while hasattr(model_module, "module"):
109
+ model_module = model_module.module
110
+ unwrapped_model.append(model_module)
111
+ if not return_list:
112
+ return unwrapped_model[0]
113
+ return unwrapped_model
114
+
115
+
116
+ def _split_state_dict_for_pp(weight_dict: OrderedDict, model_config: ModelConfig):
117
+ num_layers = model_config.num_layers
118
+ partition = mpu.get_pp_world_size()
119
+
120
+ ## use partition and num_layers to get current rank layer order
121
+ layers_for_each_stage = np.array_split(range(num_layers), partition)
122
+ current_stage = mpu.get_pp_rank()
123
+ allow_layer_num = layers_for_each_stage[current_stage]
124
+ layer_offset = allow_layer_num[0]
125
+ new_weight_dict = {}
126
+ for k, v in weight_dict.items():
127
+ if "videodit_blocks.layers" in k:
128
+ layer_num = int(re.search(r"videodit_blocks\.layers\.(\d+)", k).group(1))
129
+ if layer_num not in allow_layer_num:
130
+ continue
131
+ ## replace the old key name by new layer number
132
+ new_layer_num = layer_num - layer_offset
133
+ new_k = k.replace(f"videodit_blocks.layers.{layer_num}", f"videodit_blocks.layers.{new_layer_num}")
134
+ new_weight_dict[new_k] = v
135
+ else:
136
+ new_weight_dict[k] = v
137
+ return new_weight_dict
138
+
139
+
140
+ def load_state_dict(runtime_config: RuntimeConfig, engine_config: EngineConfig):
141
+ load_dir = runtime_config.load
142
+
143
+ default_subdir = "inference_weight"
144
+ if engine_config.fp8_quant:
145
+ default_subdir = f"{default_subdir}.fp8"
146
+ if engine_config.distill:
147
+ default_subdir = f"{default_subdir}.distill"
148
+ inference_weight_dir = os.path.join(load_dir, default_subdir)
149
+
150
+ print_rank_0(f"load {default_subdir} weight from {inference_weight_dir}")
151
+ assert (
152
+ os.path.exists(inference_weight_dir) and len(os.listdir(inference_weight_dir)) > 0
153
+ ), f"Ckpt directory {inference_weight_dir} does not exist or empty. If you are using fp8_quant, please run calibration first."
154
+ state_dict = load_sharded_safetensors_parallel_with_progress(inference_weight_dir)
155
+ return state_dict
156
+
157
+
158
+ def load_checkpoint(model):
159
+ state_dict = load_state_dict(model.runtime_config, model.engine_config)
160
+
161
+ model = unwrap_model(model)
162
+ # if we use pipeline parallelism, we need to load the state dict for each stage
163
+ # as it always record layer from 0 -> num_layers//pipeline_parallel_size
164
+ # so we need to choose correct layer weight when load_state_dict
165
+ if mpu.get_pp_world_size() > 1:
166
+ state_dict = _split_state_dict_for_pp(state_dict, model.model_config)
167
+
168
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False, assign=True)
169
+ model.cuda(torch.cuda.current_device()) # bottleneck for loading
170
+
171
+ if mpu.get_pp_world_size() > 1:
172
+ rank_msg = f"CP_rank={mpu.get_cp_rank()} PP_rank={mpu.get_pp_rank()}"
173
+ print_per_rank(
174
+ 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"""
175
+ )
176
+ else:
177
+ print_rank_0(f"Load Weight Missing Keys: {missing_keys}")
178
+ print_rank_0(f"Load Weight Unexpected Keys: {unexpected_keys}")
179
+
180
+ return model
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/__init__.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .dist_utils import dist_init, get_device, get_world_size, is_last_rank, is_last_tp_cp_rank
16
+ from .parallel_state import (
17
+ destroy_model_parallel,
18
+ get_cp_group,
19
+ get_cp_rank,
20
+ get_cp_world_size,
21
+ get_dp_group,
22
+ get_dp_group_gloo,
23
+ get_dp_rank,
24
+ get_dp_world_size,
25
+ get_pipeline_model_parallel_first_rank,
26
+ get_pipeline_model_parallel_last_rank,
27
+ get_pipeline_model_parallel_next_rank,
28
+ get_pipeline_model_parallel_prev_rank,
29
+ get_pp_group,
30
+ get_pp_rank,
31
+ get_pp_world_size,
32
+ get_tensor_model_parallel_last_rank,
33
+ get_tensor_model_parallel_ranks,
34
+ get_tensor_model_parallel_src_rank,
35
+ get_tp_group,
36
+ get_tp_rank,
37
+ get_tp_world_size,
38
+ is_initialized,
39
+ is_pipeline_first_stage,
40
+ is_pipeline_last_stage,
41
+ )
42
+
43
+ __all__ = [
44
+ "dist_init",
45
+ "is_initialized",
46
+ "get_tp_group",
47
+ "get_pp_group",
48
+ "get_dp_group",
49
+ "get_dp_group_gloo",
50
+ "get_cp_group",
51
+ "get_tp_world_size",
52
+ "get_pp_world_size",
53
+ "get_dp_world_size",
54
+ "get_cp_world_size",
55
+ "get_tp_rank",
56
+ "get_pp_rank",
57
+ "get_dp_rank",
58
+ "get_cp_rank",
59
+ "is_pipeline_first_stage",
60
+ "is_pipeline_last_stage",
61
+ "get_tensor_model_parallel_src_rank",
62
+ "get_tensor_model_parallel_ranks",
63
+ "get_tensor_model_parallel_last_rank",
64
+ "get_pipeline_model_parallel_first_rank",
65
+ "get_pipeline_model_parallel_last_rank",
66
+ "get_pipeline_model_parallel_next_rank",
67
+ "get_pipeline_model_parallel_prev_rank",
68
+ "destroy_model_parallel",
69
+ "is_last_rank",
70
+ "is_last_tp_cp_rank",
71
+ "get_world_size",
72
+ "get_device",
73
+ ]
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.32 kB). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc ADDED
Binary file (2.52 kB). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc ADDED
Binary file (21.5 kB). View file
 
FlowCache/FlowCache4MAGI-1-dev6-adaptive/inference/infra/distributed/dist_utils.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 SandAI. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ from datetime import timedelta
17
+
18
+ import torch
19
+
20
+ import inference.infra.distributed.parallel_state as mpu
21
+ from inference.common import print_rank_0
22
+ from inference.infra.parallelism.pipeline_parallel import init_pp_scheduler
23
+
24
+ from . import parallel_state as mpu
25
+
26
+
27
+ def dist_init(config):
28
+ """Initialize torch.distributed and core model parallel."""
29
+
30
+ assert torch.cuda.is_available()
31
+ device_count = torch.cuda.device_count()
32
+ if torch.distributed.is_initialized():
33
+ print_rank_0("Torch distribution already initialized, skipping initialization ...")
34
+ else:
35
+ rank = int(os.getenv("RANK", "0"))
36
+ world_size = int(os.getenv("WORLD_SIZE", "1"))
37
+ # Manually set the device ids.
38
+ if device_count > 0:
39
+ device = rank % device_count
40
+ torch.cuda.set_device(device)
41
+ # Call the init process
42
+ torch.distributed.init_process_group(
43
+ backend=config.engine_config.distributed_backend,
44
+ world_size=world_size,
45
+ rank=rank,
46
+ timeout=timedelta(minutes=config.engine_config.distributed_timeout_minutes),
47
+ )
48
+ assert config.engine_config.cp_size * config.engine_config.pp_size == torch.distributed.get_world_size()
49
+ if device_count > 0:
50
+ if mpu.model_parallel_is_initialized():
51
+ print_rank_0("Model parallel is already initialized")
52
+ else:
53
+ mpu.initialize_model_parallel(
54
+ cp_size=config.engine_config.cp_size,
55
+ pp_size=config.engine_config.pp_size,
56
+ nccl_communicator_config_path=None,
57
+ distributed_timeout_minutes=config.engine_config.distributed_timeout_minutes,
58
+ order="tp-cp-pp-dp",
59
+ )
60
+ if mpu.get_pp_world_size() > 1:
61
+ init_pp_scheduler()
62
+ print_rank_0("Initialize torch distribution and model parallel successfully")
63
+
64
+
65
+ def is_last_rank():
66
+ return torch.distributed.get_rank() == (torch.distributed.get_world_size() - 1)
67
+
68
+
69
+ def is_last_tp_cp_rank():
70
+ return mpu.get_tp_rank(with_context_parallel=True) == mpu.get_tp_world_size(with_context_parallel=True) - 1
71
+
72
+
73
+ def get_world_size():
74
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
75
+ world_size = torch.distributed.get_world_size()
76
+ else:
77
+ world_size = 1
78
+ return world_size
79
+
80
+
81
+ def get_device(local_rank=None):
82
+ backend = torch.distributed.get_backend()
83
+ if backend == "nccl":
84
+ if local_rank is None:
85
+ device = torch.device("cuda")
86
+ else:
87
+ device = torch.device(f"cuda:{local_rank}")
88
+ elif backend == "gloo":
89
+ device = torch.device("cpu")
90
+ else:
91
+ raise RuntimeError
92
+ return device