234 lines
8.8 KiB
Python
234 lines
8.8 KiB
Python
#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python
|
|
"""
|
|
[REF2VA STEP1 共識檢查] 同源參考圖的 result1_ref_*.pt 多數決驗證
|
|
================================================================
|
|
同一張參考圖 (相同 image bytes + 相同 metadata) 的 result1_ref_{idx}.pt
|
|
理論上應一致。step1 已做 VAE 去重 (同圖 + 同參數只編一次, 冷啟動首次
|
|
encode 燃燒), 所以同源檔案應 bit 相同; 但歷史檔案 / 不同版本 step1
|
|
產出的檔案仍可能離群, 故仍需本檢查:
|
|
|
|
三階段判定 (使用者指定):
|
|
1) 階段 1 binary cmp: 對同組 (相同參考圖 + 相同參數) 檔案做內容摘要分組
|
|
(zip 各 entry payload md5 — torch.save 的 .data/serialization_id 是
|
|
每次存檔的隨機 UUID, 整檔 md5 會誤判), 有明確多數 (>50%) →
|
|
少數派視為異常, 刪除。
|
|
2) 階段 2 內容檢查: 無明確多數時 (內容摘要全不同 / 平分), 載入 tensor:
|
|
硬門檻 = NaN/Inf / shape 不一致; 軟門檻 = 對同組 anchor 中位數的
|
|
最大偏差 > max(8*baseline, 3.0) → 離群, 刪除。
|
|
3) 階段 3: 離群者超過多數派 (無法決定誰是好的) → 全部刪除 + exit 11。
|
|
重跑 step1 後再檢查, 仍失敗 → 準備重跑整批。
|
|
|
|
刪除異常檔後, 重跑 ref2va_step1.py 會因既有檔跳過、只補跑被刪的 task。
|
|
|
|
用法:
|
|
python ref2va_check_refs.py # 檢查 (可刪除異常檔), 見 exit code
|
|
python ref2va_check_refs.py --dry-run # 只報告不刪除
|
|
|
|
Exit codes:
|
|
0 = 全部健康 (或本次刪除後已無異常, 應重跑 step1 再驗證)
|
|
10 = 發現並刪除異常檔 → 請重跑 ref2va_step1.py 再檢查
|
|
11 = 無多數且離群 > 多數派 (無法決定) → 已刪除該組全部檔案, 需重跑
|
|
12 = 無法判定 / 組內檔案不足 → 需重跑
|
|
"""
|
|
import hashlib
|
|
import importlib.util
|
|
import os
|
|
import sys
|
|
import torch
|
|
|
|
# ── 與 ref2va_step1.py 相同的 snap 邏輯 (noise full_t 依此決定, 需一致) ──
|
|
TIME_DIV, TIME_REM = 17, 5
|
|
REF_VIDEO_SHORT_EDGE = 768
|
|
REF_VIDEO_MAX_PIXELS = 768 * 1344
|
|
|
|
|
|
def snap_num_frames(nf):
|
|
if nf % TIME_DIV == TIME_REM:
|
|
return nf
|
|
return (nf - TIME_REM + TIME_DIV - 1) // TIME_DIV * TIME_DIV + TIME_REM
|
|
|
|
|
|
def load_config():
|
|
config_path = os.path.join(os.getcwd(), "config.py")
|
|
if not os.path.exists(config_path):
|
|
print(f">> [Error] 找不到 {config_path}, 請 cd 到專案目錄。")
|
|
sys.exit(1)
|
|
spec = importlib.util.spec_from_file_location("config", config_path)
|
|
config = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(config)
|
|
return config
|
|
|
|
|
|
def img_bytes(block):
|
|
img = block.get("prepared_image")
|
|
try:
|
|
return img.tobytes()
|
|
except Exception:
|
|
return str(img).encode("utf-8")
|
|
|
|
|
|
def meta_repr(block):
|
|
return repr(sorted((k, v) for k, v in block.items() if k != "prepared_image"))
|
|
|
|
|
|
def anchor_stats(a):
|
|
f = a.float()
|
|
return (
|
|
int(torch.isnan(f).sum()),
|
|
int(torch.isinf(f).sum()),
|
|
float(f.std().item()),
|
|
float(f.abs().max().item()),
|
|
)
|
|
|
|
|
|
def group_key(task, data):
|
|
"""同一參考圖 + 同一編碼參數 → 同組 (理論上應一致)。"""
|
|
imgs = hashlib.md5()
|
|
meta = hashlib.md5()
|
|
for b in data.get("ref_blocks", []):
|
|
imgs.update(img_bytes(b))
|
|
meta.update(meta_repr(b).encode("utf-8"))
|
|
# 1) 先算 nf → 2) 再算 full_t (與 step1 process 內 noise shape 一致):
|
|
# full_t = video_latents.shape[2] + 影像 block 數 = lt + len(blocks)。
|
|
# (nf 與 lt 一一同價, 一併入 key 只是讓除錯時直觀)
|
|
nf = snap_num_frames(task.num_frames)
|
|
lt = data.get("video_latent_shape", [0, 0, 0, 0, 0])[2]
|
|
full_t = lt + len(data.get("ref_blocks", []))
|
|
return (
|
|
imgs.hexdigest(),
|
|
meta.hexdigest(),
|
|
task.width,
|
|
task.height,
|
|
nf,
|
|
full_t,
|
|
getattr(task, "ref_image_short_edge", 2048),
|
|
REF_VIDEO_SHORT_EDGE,
|
|
REF_VIDEO_MAX_PIXELS,
|
|
)
|
|
|
|
|
|
def content_digest(f):
|
|
"""內容摘要 (決定性, 與檔名/序列化 UUID 無關):
|
|
zip: 每個 entry 的 name + payload md5; 舊格式: 整檔 md5。
|
|
torch.save 的 .data/serialization_id 是每次存檔的隨機 UUID,
|
|
直接 md5 整檔會因此誤判 → 必須比 payload 內容。"""
|
|
import zipfile
|
|
h = hashlib.md5()
|
|
try:
|
|
with zipfile.ZipFile(f) as z:
|
|
for i in sorted(z.infolist(), key=lambda x: x.filename):
|
|
h.update(i.filename.encode("utf-8"))
|
|
h.update(hashlib.md5(z.read(i.filename)).hexdigest().encode("ascii"))
|
|
return "zip:" + h.hexdigest()
|
|
except zipfile.BadZipFile:
|
|
return "raw:" + hashlib.md5(open(f, "rb").read()).hexdigest()
|
|
|
|
|
|
def check_group(gidx):
|
|
"""回傳 (outlier_ids, reason)。無異常 → ([], '')。"""
|
|
files = {i: f"result1_ref_{i}.pt" for i in gidx}
|
|
hashes = {i: content_digest(files[i]) for i in gidx}
|
|
|
|
# ── 階段 1: binary cmp (內容摘要分組: zip payload md5, 免 UUID 誤判) ──
|
|
groups = {}
|
|
for i, h in hashes.items():
|
|
groups.setdefault(h, []).append(i)
|
|
sizes = sorted(groups.values(), key=len, reverse=True)
|
|
n = len(gidx)
|
|
if len(sizes[0]) * 2 > n and len(sizes) > 1:
|
|
majority = set(sizes[0])
|
|
return (set(gidx) - majority, "binary (內容摘要) 少數派")
|
|
|
|
# ── 階段 2: 內容檢查 (載入 tensor) ──
|
|
data = {i: torch.load(files[i], map_location="cpu", weights_only=False) for i in gidx}
|
|
|
|
# 2a. 硬門檻: shape
|
|
shapes = {i: tuple(data[i]["ref_visual_anchor"].shape) for i in gidx}
|
|
if len(set(shapes.values())) > 1:
|
|
bad = [i for i in gidx if shapes[i] != shapes[max(gidx)]]
|
|
return (bad, f"anchor shape 不一致: {shapes}")
|
|
|
|
# 2b. 硬門檻: NaN / Inf
|
|
stats = {i: anchor_stats(data[i]["ref_visual_anchor"]) for i in gidx}
|
|
bad = [i for i in gidx if stats[i][0] or stats[i][1]]
|
|
if bad:
|
|
return (bad, f"NaN/Inf: {[(i, stats[i][:2]) for i in bad]}")
|
|
|
|
# 2c. 軟門檻: 對組內 anchor 中位數的偏差
|
|
med = None
|
|
for i in gidx:
|
|
med = data[i]["ref_visual_anchor"].clone() if med is None else torch.stack(
|
|
[med, data[i]["ref_visual_anchor"]]
|
|
).mean(dim=0)
|
|
diffs = {i: (data[i]["ref_visual_anchor"].float() - med.float()).abs().max().item() for i in gidx}
|
|
ordered = sorted(diffs.values())
|
|
baseline = ordered[min(1, len(ordered) - 1)] # 多數派互差 (N=2 時取 0)
|
|
thr = max(baseline * 8.0, 3.0)
|
|
outliers = [i for i in gidx if diffs[i] > thr]
|
|
if outliers:
|
|
return (outliers,
|
|
f"anchor 偏差離群 (thr={thr:.2f}, baseline={baseline:.4f}): "
|
|
f"{[(i, round(diffs[i], 3)) for i in outliers]}")
|
|
return ([], "")
|
|
|
|
|
|
def main():
|
|
dry = "--dry-run" in sys.argv
|
|
config = load_config()
|
|
enabled = [i for i, t in config.TASK_REGISTRY.items() if t.enabled]
|
|
print(f">> [CHECK] enabled tasks: {enabled}")
|
|
|
|
groups = {}
|
|
missing = []
|
|
for idx in enabled:
|
|
f = f"result1_ref_{idx}.pt"
|
|
if not os.path.exists(f):
|
|
missing.append(idx)
|
|
continue
|
|
data = torch.load(f, map_location="cpu", weights_only=False)
|
|
groups.setdefault(group_key(config.TASK_REGISTRY[idx], data), []).append(idx)
|
|
|
|
if missing:
|
|
print(f">> [WARN] 尚無檔案 (未跑 step1?): {missing} → 先跑 step1。")
|
|
sys.exit(0 if not groups else 10)
|
|
|
|
total_bad = 0
|
|
undecided = 0
|
|
for key, gidx in groups.items():
|
|
if len(gidx) == 1:
|
|
print(f">> [GROUP {gidx[0]}] 單檔組, 無同儕可比較 (跳過)。")
|
|
continue
|
|
outliers, reason = check_group(gidx)
|
|
if not outliers:
|
|
print(f">> [GROUP {sorted(gidx)}] ✓ 一致 ({len(gidx)} 檔)。")
|
|
continue
|
|
majority_ok = len(outliers) * 2 <= len(gidx)
|
|
if not majority_ok:
|
|
undecided += 1
|
|
print(f">> [GROUP {sorted(gidx)}] ✗ 無法決定: {reason} (離群 {sorted(outliers)} "
|
|
f">= 多數) → 刪除整組 {sorted(gidx)} 重跑。")
|
|
else:
|
|
print(f">> [GROUP {sorted(gidx)}] ✗ 異常: {reason} → 刪除 {sorted(outliers)}。")
|
|
for i in (outliers if majority_ok else gidx):
|
|
f = f"result1_ref_{i}.pt"
|
|
if dry:
|
|
print(f" [dry-run] 將刪除 {f}")
|
|
else:
|
|
os.remove(f)
|
|
print(f" 已刪除 {f}")
|
|
total_bad += len(outliers if majority_ok else gidx)
|
|
|
|
if undecided:
|
|
print(f"\n>> [CHECK] 無法判定 (exit 11): 已刪除整組, 重跑 step1 後再檢查。")
|
|
sys.exit(11)
|
|
if total_bad:
|
|
print(f"\n>> [CHECK] 發現 {total_bad} 個異常檔 (exit 10): 請重跑 ref2va_step1.py "
|
|
f"(會跳過既有檔, 只補跑被刪的)。")
|
|
sys.exit(10)
|
|
print(f"\n>> [CHECK] 全部健康 (exit 0)。")
|
|
sys.exit(0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|