File size: 9,641 Bytes
d2b26ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env bash
# dev6 AdaptiveDetailCache hyperparameter sweep + dev4 vs dev6 @240f comparison.
set -eo 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"
DEV3="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev3-motion"
DEV4="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail"
DEV6="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev6-adaptive"
SWEEP_ROOT="${SWEEP_ROOT:-$DEV6/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 PAD_HQ=1 PAD_DURATION=1
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
export OFFLOAD_T5_CACHE=true OFFLOAD_VAE_CACHE=true

set +u
source "${HOME}/miniforge3/etc/profile.d/conda.sh" 2>/dev/null || source "${HOME}/anaconda3/etc/profile.d/conda.sh"
conda activate magi
python3 -c "import numpy as np; exit(0 if int(np.__version__.split('.')[0])<2 else 1)" || pip install -q "numpy>=1.24,<2.0"
set -u

make_runtime() {
    python3 - "$1" "$2" <<'PY'
import json, sys
with open("/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev6-adaptive/config/single_run/flowcache_t2v.json") as f:
    cfg = json.load(f)
cfg["runtime_config"]["num_frames"] = int(sys.argv[2])
with open(sys.argv[1], "w") as f:
    json.dump(cfg, f, indent=4)
PY
}

write_yaml() {
    python3 - "$1" "${@:2}" <<'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 = {
    "rel_l1_thresh": 0.012,
    "warmup_steps": 5,
    "phase1_steps": 9,
    "alpha": 0.5,
    "detail_alpha": 0.5,
    "detail_window_size": 3,
    "detail_lambda": 0.3,
    "weight_combine_mode": "blend",
    "use_adaptive_tau": True,
    "discard_nearly_clean_chunk": True,
    "compress_kv_cache": True,
    "total_cache_chunk_nums": 5,
    "log": False,
    "print_peak_memory": True,
}
base.update(params)
with open(path, "w") as f:
    yaml.dump(base, f, default_flow_style=False)
PY
}

RESULTS="$REPORT_DIR/results.csv"
echo "variant,version,frames,beta,tau_min,tau_max,psnr_db,ssim,black_ratio,reuse_rate_pct,wall_sec,peak_gb,video_path,log_path,config" > "$RESULTS"

run_one() {
    local version="$1" root="$2" yaml="$3" tag="$4" frames="$5"
    local beta="${6:-}" tmin="${7:-}" tmax="${8:-}"
    local runtime="$SWEEP_ROOT/runtime_${frames}f.json"
    make_runtime "$runtime" "$frames"
    local edir="$SWEEP_ROOT/${version}_${tag}_${frames}f"
    mkdir -p "$edir"
    local out="$edir/output.mp4" log="$edir/infer.log" metric="$edir/metrics.json"
    export MASTER_PORT=$((6400 + RANDOM % 300))
    if [ "$root" = "$DEV6" ]; then
        export PYTHONPATH="${DEV6}:${DEV4}:${DEV3}"
    elif [ "$root" = "$DEV4" ]; then
        export PYTHONPATH="${DEV4}:${DEV3}"
    else
        export PYTHONPATH="${DEV3}:${DEV4}"
    fi
    echo "========== $version / $tag @ ${frames}f (GPU=$GPU_ID) =========="
    local t0=$(date +%s)
    set +e
    ( cd "$root" && python3 inference/pipeline/motioncache.py \
        --config_file "$runtime" --mode t2v --prompt "$PROMPT" \
        --output_path "$out" --additional_config "$yaml" \
        --motioncache_metric_stats_path "$metric" 2>&1 | tee "$log" )
    local rc=${PIPESTATUS[0]}; set -e
    local t1=$(date +%s)
    [ -f "$out" ] && [ "$rc" -eq 0 ] || { echo "FAILED $tag rc=$rc"; return 1; }
    eval_out=$(python3 "$DEV3/tools/eval_run.py" --baseline "$BASELINE" --generated "$out" --log "$log" --metric "$metric")
    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 "$tag,$version,$frames,$beta,$tmin,$tmax,$PSNR,$SSIM,$BLACK,$REUSE,$((t1-t0)),$PEAK,$out,$log,$yaml" >> "$RESULTS"
    echo "  PSNR=${PSNR}dB reuse=${REUSE}% time=$((t1-t0))s"
}

echo "dev6 adaptive sweep @${SWEEP_FRAMES}f -> $SWEEP_ROOT (host=$(hostname), GPU=$GPU_ID)"

# dev4 fixed baseline @120f for reference
run_one dev4 "$DEV4" "$DEV4/yaml_config/single_run/motiondetail_config_best.yaml" best "$SWEEP_FRAMES" "" "" "" || true

# dev6 adaptive grid @120f
for beta in 0.5 0.8 1.2; do
    for pair in "0.008:0.020" "0.010:0.018" "0.006:0.024" "0.009:0.015"; do
        IFS=':' read -r tmin tmax <<< "$pair"
        tag="b${beta}_min${tmin}_max${tmax}"
        y="$SWEEP_ROOT/dev6_${tag}.yaml"
        write_yaml "$y" \
            "adaptive_tau_beta=$beta" \
            "adaptive_tau_min=$tmin" \
            "adaptive_tau_max=$tmax"
        run_one dev6 "$DEV6" "$y" "$tag" "$SWEEP_FRAMES" "$beta" "$tmin" "$tmax" || true
    done
done

BEST_YAML=$(python3 - "$RESULTS" "$DEV6/yaml_config/single_run/adaptive_config_best.yaml" <<'PY'
import csv, sys, yaml, os
csv_path, default_yaml = sys.argv[1:3]
rows = [r for r in csv.DictReader(open(csv_path))
        if r["version"] == "dev6" and r["frames"] == "120" and r["psnr_db"] not in ("NA", "")]
if not rows:
    print(default_yaml)
    raise SystemExit(0)

def score(r):
    p = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0
    return p + 0.02 * float(r["reuse_rate_pct"] or 0) - 0.0001 * float(r["wall_sec"] or 0)

best = max(rows, key=score)
src = best["config"]
with open(src) as f:
    cfg = yaml.safe_load(f)
with open(default_yaml, "w") as f:
    yaml.dump(cfg, f, default_flow_style=False)
print(src)
print(f"BEST_TAG={best['variant']}", file=sys.stderr)
print(f"BEST_PSNR={best['psnr_db']}", file=sys.stderr)
PY
)

BEST_TAG=$(python3 - "$RESULTS" <<'PY'
import csv, sys
rows = [r for r in csv.DictReader(open(sys.argv[1]))
        if r["version"] == "dev6" and r["frames"] == "120" and r["psnr_db"] not in ("NA", "")]
def score(r):
    p = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0
    return p + 0.02 * float(r["reuse_rate_pct"] or 0) - 0.0001 * float(r["wall_sec"] or 0)
print(max(rows, key=score)["variant"] if rows else "default")
PY
)

echo "Best dev6 @120f: $BEST_TAG -> $BEST_YAML"

# 240f validation
run_one dev4 "$DEV4" "$DEV4/yaml_config/single_run/motiondetail_config_best.yaml" best 240 "" "" "" || true
run_one dev6 "$DEV6" "$BEST_YAML" "${BEST_TAG}_best" 240 \
    "$(python3 -c "import yaml; print(yaml.safe_load(open('$BEST_YAML'))['adaptive_tau_beta'])")" \
    "$(python3 -c "import yaml; print(yaml.safe_load(open('$BEST_YAML'))['adaptive_tau_min'])")" \
    "$(python3 -c "import yaml; print(yaml.safe_load(open('$BEST_YAML'))['adaptive_tau_max'])")" || true

python3 - "$RESULTS" "$REPORT_DIR/comparison_dev4_dev6.md" "$BEST_TAG" "$BEST_YAML" <<'PY'
import csv, sys
from datetime import datetime

csv_path, md_path, best_tag, best_yaml = sys.argv[1:5]
rows = [r for r in csv.DictReader(open(csv_path)) if r["psnr_db"] not in ("NA", "")]

def score(r):
    p = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0
    return p + 0.02 * float(r["reuse_rate_pct"] or 0) - 0.0001 * float(r["wall_sec"] or 0)

dev6_120 = sorted([r for r in rows if r["version"] == "dev6" and r["frames"] == "120"], key=score, reverse=True)
dev4_120 = [r for r in rows if r["version"] == "dev4" and r["frames"] == "120"]
dev4_240 = [r for r in rows if r["version"] == "dev4" and r["frames"] == "240"]
dev6_240 = [r for r in rows if r["version"] == "dev6" and r["frames"] == "240"]

lines = [
    "# dev4 fixed vs dev6 adaptive 超参对比报告",
    "",
    f"生成时间: {datetime.now():%Y-%m-%d %H:%M:%S}",
    "",
    f"Sweep 目录: `{csv_path.replace('/report/results.csv', '')}`",
    "",
    "## 评分方法",
    "",
    "score = PSNR + 0.02 × reuse_rate(%) − 0.0001 × wall_time(s)",
    "",
    f"## dev6 最优 @120f: `{best_tag}`",
    "",
    f"配置: `{best_yaml}`",
    "",
    "## dev6 120f sweep 全部结果",
    "",
    "| variant | β | τ_min | τ_max | PSNR | reuse% | time(s) | score |",
    "|---------|---|-------|-------|------|--------|---------|-------|",
]
for r in dev6_120:
    lines.append(
        f"| {r['variant']} | {r['beta']} | {r['tau_min']} | {r['tau_max']} | "
        f"{r['psnr_db']} dB | {r['reuse_rate_pct']} | {r['wall_sec']} | {score(r):.3f} |"
    )

if dev4_120:
    r = dev4_120[0]
    lines += [
        "",
        "## dev4 fixed baseline @120f",
        "",
        f"- PSNR: **{r['psnr_db']} dB**, reuse: {r['reuse_rate_pct']}%, time: {r['wall_sec']}s",
    ]

lines += [
    "",
    "## 240f 全分辨率验证",
    "",
    "| version | variant | PSNR | reuse% | time(s) |",
    "|---------|---------|------|--------|---------|",
]
for r in dev4_240 + dev6_240:
    lines.append(f"| {r['version']} | {r['variant']} | {r['psnr_db']} dB | {r['reuse_rate_pct']} | {r['wall_sec']} |")

if dev4_240 and dev6_240:
    p4 = float(dev4_240[0]["psnr_db"])
    p6 = float(dev6_240[0]["psnr_db"])
    lines += [
        "",
        "## 结论",
        "",
        f"- dev4 @240f: {p4:.4f} dB",
        f"- dev6 @240f: {p6:.4f} dB",
        f"- dev6 vs dev4: **{p6 - p4:+.4f} dB**",
    ]

with open(md_path, "w") as f:
    f.write("\n".join(lines) + "\n")
print(f"Report: {md_path}")
PY

echo "Done. Report: $REPORT_DIR/comparison_dev4_dev6.md"
cat "$REPORT_DIR/comparison_dev4_dev6.md"