File size: 9,906 Bytes
2bfd19c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | #!/usr/bin/env bash
# Hyperparameter sweep for dev3 (MotionCache) and dev4 (MotionDetailCache).
set -euo pipefail
GPU_ID="${CUDA_VISIBLE_DEVICES:-1}"
SWEEP_FRAMES="${SWEEP_FRAMES:-120}"
PROMPT="${PROMPT:-a woman dancing.}"
BASELINE="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/a_woman_dancing_2026-05-19_09-49-14/output_2026-05-19_09-49-14.mp4"
FLOWCACHE_ROOT="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev3-motion"
DETAIL_ROOT="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail"
SWEEP_ROOT="${SWEEP_ROOT:-$FLOWCACHE_ROOT/outputs/hparam_sweep_$(date +%Y%m%d_%H%M%S)}"
REPORT_DIR="$SWEEP_ROOT/report"
mkdir -p "$REPORT_DIR"
export MASTER_ADDR=localhost
export CUDA_VISIBLE_DEVICES="$GPU_ID"
export PYTHONPATH="${FLOWCACHE_ROOT}:${DETAIL_ROOT}:${PYTHONPATH:-}"
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
if [ -z "${CONDA_DEFAULT_ENV:-}" ] || [ "${CONDA_DEFAULT_ENV}" != "magi" ]; then
# shellcheck disable=SC1091
source "${HOME}/miniforge3/etc/profile.d/conda.sh" 2>/dev/null || source "${HOME}/anaconda3/etc/profile.d/conda.sh"
conda activate magi
fi
ensure_numpy_compat() {
if ! python3 - <<'PY'
import numpy as np
major = int(np.__version__.split(".")[0])
raise SystemExit(0 if major < 2 else 1)
PY
then
echo "Fixing numpy for transformers (found incompatible version)..."
pip install -q "numpy>=1.24,<2.0"
fi
}
ensure_numpy_compat
make_runtime_config() {
local dst="$1" frames="$2"
python3 - "$dst" "$frames" <<'PY'
import json, sys
dst, frames = sys.argv[1], int(sys.argv[2])
src = "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev3-motion/config/single_run/flowcache_t2v.json"
with open(src) as f:
cfg = json.load(f)
cfg["runtime_config"]["num_frames"] = frames
with open(dst, "w") as f:
json.dump(cfg, f, indent=4)
PY
}
RUNTIME_CFG="$SWEEP_ROOT/runtime_${SWEEP_FRAMES}f.json"
make_runtime_config "$RUNTIME_CFG" "$SWEEP_FRAMES"
echo "Sweep output: $SWEEP_ROOT (num_frames=$SWEEP_FRAMES, GPU=$GPU_ID, host=$(hostname))"
RESULTS_CSV="$REPORT_DIR/results.csv"
echo "variant,version,tau,alpha,detail_alpha,detail_window,combine_mode,detail_lambda,psnr_db,ssim,black_ratio,reuse_rate_pct,wall_sec,peak_gb,video_path,log_path" > "$RESULTS_CSV"
run_one() {
local version="$1" run_id="$2" yaml_path="$3" root_dir="$4"
local exp_dir="$SWEEP_ROOT/${version}_${run_id}"
mkdir -p "$exp_dir"
local out="$exp_dir/output.mp4"
local log="$exp_dir/infer.log"
local metric="$exp_dir/metrics.json"
local t0 t1 elapsed
export MASTER_PORT=$((6000 + RANDOM % 500))
if [ "$root_dir" = "$DETAIL_ROOT" ]; then
export PYTHONPATH="${DETAIL_ROOT}:${FLOWCACHE_ROOT}:${PYTHONPATH:-}"
else
export PYTHONPATH="${FLOWCACHE_ROOT}:${DETAIL_ROOT}:${PYTHONPATH:-}"
fi
echo ""
echo "========== [$version] $run_id =========="
t0=$(date +%s)
set +e
(
cd "$root_dir"
python3 inference/pipeline/motioncache.py \
--config_file "$RUNTIME_CFG" \
--mode t2v \
--prompt "$PROMPT" \
--output_path "$out" \
--additional_config "$yaml_path" \
--motioncache_metric_stats_path "$metric" \
2>&1 | tee "$log"
)
local rc=${PIPESTATUS[0]}
set -e
t1=$(date +%s)
elapsed=$((t1 - t0))
if [ ! -f "$out" ] || [ "$rc" -ne 0 ]; then
echo "FAILED: $run_id (rc=$rc, no video)"
return 1
fi
eval_out=$(python3 "$FLOWCACHE_ROOT/tools/eval_run.py" \
--baseline "$BASELINE" \
--generated "$out" \
--log "$log" \
--metric "$metric" 2>/dev/null || true)
PSNR="NA"; SSIM="NA"; BLACK="NA"; REUSE="NA"; PEAK="NA"
while IFS='=' read -r k v; do
case "$k" in PSNR) PSNR="$v" ;; SSIM) SSIM="$v" ;; BLACK) BLACK="$v" ;; REUSE) REUSE="$v" ;; PEAK) PEAK="$v" ;; esac
done <<< "$eval_out"
echo "$run_id,$version,$TAU,$ALPHA,$DETAIL_ALPHA,$DETAIL_WINDOW,$COMBINE,$DETAIL_LAM,$PSNR,$SSIM,$BLACK,$REUSE,$elapsed,$PEAK,$out,$log" >> "$RESULTS_CSV"
echo " PSNR=${PSNR}dB reuse=${REUSE}% time=${elapsed}s"
}
write_yaml() {
local path="$1"
shift
python3 - "$path" "$@" <<'PY'
import sys, yaml
path = sys.argv[1]
params = {}
for kv in sys.argv[2:]:
k, v = kv.split("=", 1)
if v.lower() in ("true", "false"):
params[k] = v.lower() == "true"
elif v.replace(".", "", 1).isdigit():
params[k] = float(v) if "." in v else int(v)
else:
params[k] = v
base = {
"warmup_steps": 5,
"phase1_steps": 9,
"alpha": 0.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": False,
"print_peak_memory": True,
}
base.update(params)
with open(path, "w") as f:
yaml.dump(base, f, default_flow_style=False)
PY
}
# ---------- Phase 1: dev3 tau sweep ----------
BEST_DEV3_TAU="0.015"
for tau in 0.010 0.012 0.015 0.018 0.020 0.025 0.030; do
y="$SWEEP_ROOT/dev3_tau${tau}.yaml"
write_yaml "$y" "rel_l1_thresh=$tau"
export TAU="$tau" ALPHA="0.5" DETAIL_ALPHA="" DETAIL_WINDOW="" COMBINE="" DETAIL_LAM=""
run_one "dev3" "tau${tau}" "$y" "$FLOWCACHE_ROOT" || true
done
BEST_DEV3_TAU=$(python3 - "$RESULTS_CSV" <<'PY'
import csv, sys
rows = [r for r in csv.DictReader(open(sys.argv[1])) if r["version"] == "dev3" and r["psnr_db"] not in ("NA", "")]
if not rows:
print("0.015")
else:
def score(r):
psnr = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0
reuse = float(r["reuse_rate_pct"] or 0)
return psnr + 0.02 * reuse
print(max(rows, key=score)["tau"])
PY
)
echo "Best dev3 tau from sweep: $BEST_DEV3_TAU"
# ---------- Phase 2: dev4 detail sweep ----------
for spec in \
"max|3|0.5|0.5" \
"max|5|0.5|0.5" \
"max|3|0.4|0.5" \
"max|3|0.6|0.5" \
"blend|3|0.5|0.3" \
"blend|3|0.5|0.5" \
"blend|3|0.5|0.7" \
"product|3|0.5|0.5" \
"product|5|0.5|0.5"; do
IFS='|' read -r mode win da lam <<< "$spec"
rid="tau${BEST_DEV3_TAU}_${mode}_w${win}_da${da}_lam${lam}"
y="$SWEEP_ROOT/dev4_${rid}.yaml"
write_yaml "$y" \
"rel_l1_thresh=$BEST_DEV3_TAU" \
"detail_alpha=$da" \
"detail_window_size=$win" \
"weight_combine_mode=$mode" \
"detail_lambda=$lam"
export TAU="$BEST_DEV3_TAU" ALPHA="0.5" DETAIL_ALPHA="$da" DETAIL_WINDOW="$win" COMBINE="$mode" DETAIL_LAM="$lam"
run_one "dev4" "$rid" "$y" "$DETAIL_ROOT" || true
done
# ---------- Phase 3: 240-frame validation ----------
RUNTIME_CFG="$SWEEP_ROOT/runtime_240f.json"
make_runtime_config "$RUNTIME_CFG" 240
echo "Full validation at 240 frames..."
DEV3_COUNT=$(python3 - "$RESULTS_CSV" <<'PY'
import csv, sys
print(sum(1 for r in csv.DictReader(open(sys.argv[1])) if r["version"] == "dev3" and r["psnr_db"] not in ("NA", "")))
PY
)
DEV4_COUNT=$(python3 - "$RESULTS_CSV" <<'PY'
import csv, sys
print(sum(1 for r in csv.DictReader(open(sys.argv[1])) if r["version"] == "dev4" and r["psnr_db"] not in ("NA", "")))
PY
)
if [ "$DEV3_COUNT" -gt 0 ]; then
BEST_DEV3_ID=$(python3 - "$RESULTS_CSV" <<'PY'
import csv, sys
rows = [r for r in csv.DictReader(open(sys.argv[1])) if r["version"] == "dev3" and r["psnr_db"] not in ("NA", "")]
def score(r):
psnr = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0
return psnr + 0.02 * float(r["reuse_rate_pct"] or 0)
print(max(rows, key=score)["variant"])
PY
)
y3="$SWEEP_ROOT/dev3_${BEST_DEV3_ID}_full.yaml"
write_yaml "$y3" "rel_l1_thresh=${BEST_DEV3_TAU}"
export TAU="$BEST_DEV3_TAU" ALPHA="0.5" DETAIL_ALPHA="" DETAIL_WINDOW="" COMBINE="" DETAIL_LAM=""
run_one "dev3_full" "${BEST_DEV3_ID}_240f" "$y3" "$FLOWCACHE_ROOT" || true
fi
if [ "$DEV4_COUNT" -gt 0 ]; then
read -r y4 da dw cm dl BEST_DEV4_ID <<< "$(python3 - "$RESULTS_CSV" "$SWEEP_ROOT" "$BEST_DEV3_TAU" <<'PY'
import csv, sys, yaml, os
csv_path, sweep_root, tau = sys.argv[1:4]
rows = [r for r in csv.DictReader(open(csv_path)) if r["version"] == "dev4" and r["psnr_db"] not in ("NA", "")]
def score(r):
psnr = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0
return psnr + 0.02 * float(r["reuse_rate_pct"] or 0)
row = max(rows, key=score)
y = {
"rel_l1_thresh": float(tau),
"warmup_steps": 5, "phase1_steps": 9, "alpha": 0.5,
"detail_alpha": float(row["detail_alpha"]),
"detail_window_size": int(float(row["detail_window"])),
"weight_combine_mode": row["combine_mode"],
"detail_lambda": float(row["detail_lambda"]),
"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": False, "print_peak_memory": True,
}
path = os.path.join(sweep_root, f"dev4_{row['variant']}_full.yaml")
with open(path, "w") as f:
yaml.dump(y, f, default_flow_style=False)
print(path, row["detail_alpha"], row["detail_window"], row["combine_mode"], row["detail_lambda"], row["variant"])
PY
)"
export TAU="$BEST_DEV3_TAU" ALPHA="0.5" DETAIL_ALPHA="$da" DETAIL_WINDOW="$dw" COMBINE="$cm" DETAIL_LAM="$dl"
run_one "dev4_full" "${BEST_DEV4_ID}_240f" "$y4" "$DETAIL_ROOT" || true
fi
python3 "$FLOWCACHE_ROOT/tools/generate_comparison_report.py" \
--results "$RESULTS_CSV" \
--baseline "$BASELINE" \
--output "$REPORT_DIR/comparison_report.md" \
--sweep_dir "$SWEEP_ROOT"
echo ""
echo "Sweep complete."
echo " CSV: $RESULTS_CSV"
echo " Report: $REPORT_DIR/comparison_report.md"
|