| |
| """ |
| 定位 POS noise 不导致性能下降的原因(用代码证据)。 |
| |
| 做两件事: |
| 1) 统计不同 pos_noise_ratio 下 noun_mask/verb_mask 的有效覆盖率(相对 LLaMA token mask)。 |
| 2) 对同一批样本,在相同 ckpt 下比较关键输出是否变化(binding_score / delta_s / saliency_scores / out_class)。 |
| """ |
| import argparse |
| import json |
| import os |
| from pathlib import Path |
|
|
| import numpy as np |
| import torch |
|
|
|
|
| def load_jsonl(path: Path, limit=None): |
| items = [] |
| with path.open("r", encoding="utf-8") as f: |
| for i, line in enumerate(f): |
| if limit is not None and i >= limit: |
| break |
| line = line.strip() |
| if not line: |
| continue |
| items.append(json.loads(line)) |
| return items |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--ckpt", required=True) |
| ap.add_argument("--config", default="data/MR_16.py") |
| ap.add_argument("--device", type=int, default=0) |
| ap.add_argument("--eval_path", default="data/highlight_val_release.jsonl") |
| ap.add_argument("--v_feat_dirs", default="/home/szha0669/myproject/FlashVTG/features/qvhighlight_6b") |
| ap.add_argument("--t_feat_dir", default="/home/szha0669/myproject/FlashVTG/features/qvhighlight_llama_text_feature") |
| ap.add_argument("--a_feat_dir", default="/home/szha0669/myproject/FlashVTG/features/qvhighlight/slowfast_features") |
| ap.add_argument("--n", type=int, default=64, help="number of samples to probe") |
| ap.add_argument("--ratios", default="0.0,0.2,0.5,1.0") |
| args = ap.parse_args() |
|
|
| |
| root = Path(__file__).resolve().parent.parent |
| os.environ["PYTHONPATH"] = f"{root}:{root/'FlashVTG'}:" + os.environ.get("PYTHONPATH", "") |
|
|
| from FlashVTG.config import TestOptions |
| from FlashVTG.model import build_model1 |
| from FlashVTG.start_end_dataset import StartEndDataset, start_end_collate, prepare_batch_inputs |
|
|
| dev = torch.device(f"cuda:{args.device}" if torch.cuda.is_available() else "cpu") |
|
|
| |
| ckpt = torch.load(args.ckpt, map_location="cpu", weights_only=False) |
| opt = ckpt["opt"] |
| opt.device = dev |
| opt.resume = args.ckpt |
| model, _ = build_model1(opt) |
| model.load_state_dict(ckpt["model"], strict=False) |
| model.to(dev).eval() |
| print("=== FDIM/ISA key args (from ckpt opt) ===") |
| for k in ["use_fdim", "fdim_inject_h", "fdim_proposal_alpha", "fdim_topk_ratio", "fdim_threshold", "fdim_gating_mode"]: |
| print(f"{k} = {getattr(opt, k, None)}") |
|
|
| ratios = [float(x) for x in args.ratios.split(",")] |
| |
| datasets = {} |
| for r in ratios: |
| datasets[r] = StartEndDataset( |
| dset_name=opt.dset_name, |
| data_path=args.eval_path, |
| v_feat_dirs=[args.v_feat_dirs], |
| q_feat_dir=args.t_feat_dir, |
| q_feat_type=opt.q_feat_type, |
| max_q_l=opt.max_q_l, |
| max_v_l=opt.max_v_l, |
| ctx_mode=opt.ctx_mode, |
| data_ratio=1.0, |
| normalize_v=True, |
| normalize_t=True, |
| clip_len=opt.clip_length, |
| max_windows=opt.max_windows, |
| load_labels=True, |
| span_loss_type=opt.span_loss_type, |
| txt_drop_ratio=0, |
| dset_domain=getattr(opt, "dset_domain", None), |
| a_feat_dir=args.a_feat_dir, |
| pos_noise_ratio=r, |
| ) |
|
|
| |
| idxs = list(range(min(args.n, len(datasets[ratios[0]])))) |
|
|
| def stats_for_ratio(r: float): |
| ds = datasets[r] |
| noun_cover = [] |
| verb_cover = [] |
| noun_any = 0 |
| verb_any = 0 |
|
|
| |
| return dict(noun_cover=noun_cover, verb_cover=verb_cover, noun_any=noun_any, verb_any=verb_any) |
|
|
| |
| outs = {} |
| mask_stats = {} |
|
|
| for r in ratios: |
| ds = datasets[r] |
| bs = [] |
| noun_cover = [] |
| verb_cover = [] |
| noun_any = 0 |
| verb_any = 0 |
| for idx in idxs: |
| sample = ds[idx] |
| batch = start_end_collate([sample]) |
| meta = batch[0][0] |
| model_inputs, _ = prepare_batch_inputs(batch[1], dev, non_blocking=False, batch_meta=batch[0]) |
|
|
| src_txt_mask = model_inputs["src_txt_mask"][0].bool().detach().cpu().numpy() |
| L_txt = int(src_txt_mask.shape[0]) |
| n_txt = int(src_txt_mask.sum()) |
|
|
| noun_m = model_inputs.get("noun_mask", None) |
| verb_m = model_inputs.get("verb_mask", None) |
| if noun_m is None or verb_m is None: |
| noun_cover.append(0.0) |
| verb_cover.append(0.0) |
| else: |
| noun_vec = noun_m[0].bool().detach().cpu().numpy()[:L_txt] |
| verb_vec = verb_m[0].bool().detach().cpu().numpy()[:L_txt] |
| noun_any += int(noun_vec.any()) |
| verb_any += int(verb_vec.any()) |
| noun_cover.append(float((noun_vec & src_txt_mask).sum()) / max(n_txt, 1)) |
| verb_cover.append(float((verb_vec & src_txt_mask).sum()) / max(n_txt, 1)) |
|
|
| with torch.no_grad(): |
| out = model(**model_inputs, targets={"label": batch[0]}) |
| |
| def _get(name): |
| v = out.get(name, None) |
| if v is None: |
| return None |
| if isinstance(v, torch.Tensor): |
| return v[0].detach().float().cpu().numpy() |
| return v |
|
|
| bs.append( |
| dict( |
| qid=meta.get("qid"), |
| sal=_get("saliency_scores"), |
| cls=_get("out_class"), |
| bind=_get("binding_score"), |
| delta=_get("delta_s"), |
| gate=_get("binding_gate"), |
| prop_gate=_get("proposal_gate_mask"), |
| prop_bind=_get("proposal_binding"), |
| ) |
| ) |
| outs[r] = bs |
| mask_stats[r] = dict( |
| noun_any=noun_any, |
| verb_any=verb_any, |
| noun_cover=float(np.mean(noun_cover)), |
| verb_cover=float(np.mean(verb_cover)), |
| ) |
|
|
| |
| base_r = ratios[0] |
| diffs = {} |
| for r in ratios[1:]: |
| sal_l1 = [] |
| cls_l1 = [] |
| bind_l1 = [] |
| delta_l1 = [] |
| for b0, b1 in zip(outs[base_r], outs[r]): |
| def l1(a, b): |
| if a is None or b is None: |
| return None |
| n = min(len(a), len(b)) |
| return float(np.mean(np.abs(a[:n] - b[:n]))) |
| sal_l1.append(l1(b0["sal"], b1["sal"]) or 0.0) |
| if b0["cls"] is not None and b1["cls"] is not None: |
| |
| c0 = b0["cls"].reshape(-1) |
| c1 = b1["cls"].reshape(-1) |
| cls_l1.append(l1(c0, c1) or 0.0) |
| else: |
| cls_l1.append(0.0) |
| bind_l1.append(l1(b0["bind"], b1["bind"]) or 0.0) |
| delta_l1.append(l1(b0["delta"], b1["delta"]) or 0.0) |
| diffs[r] = dict( |
| sal_l1=float(np.mean(sal_l1)), |
| cls_l1=float(np.mean(cls_l1)), |
| bind_l1=float(np.mean(bind_l1)), |
| delta_l1=float(np.mean(delta_l1)), |
| ) |
|
|
| print("=== POS mask coverage (mean over sampled items) ===") |
| for r in ratios: |
| s = mask_stats[r] |
| print(f"ratio={r:.1f} noun_any={s['noun_any']}/{len(idxs)} verb_any={s['verb_any']}/{len(idxs)} " |
| f"noun_cover={s['noun_cover']:.3f} verb_cover={s['verb_cover']:.3f}") |
|
|
| def agg_gate(arrs): |
| arrs = [a for a in arrs if a is not None] |
| if not arrs: |
| return None |
| x = np.concatenate([a.reshape(-1) for a in arrs], axis=0) |
| return dict(mean=float(x.mean()), p50=float(np.percentile(x, 50)), p90=float(np.percentile(x, 90)), max=float(x.max())) |
|
|
| print("\n=== binding_gate stats (all positions concatenated) ===") |
| for r in ratios: |
| gates = [b["gate"] for b in outs[r]] |
| s = agg_gate(gates) |
| print(f"ratio={r:.1f} gate_stats={s}") |
|
|
| print("\n=== proposal_gate_mask stats (fraction selected) ===") |
| for r in ratios: |
| pg = [b['prop_gate'] for b in outs[r]] |
| pg = [a for a in pg if a is not None] |
| if not pg: |
| print(f"ratio={r:.1f} proposal_gate_mask=None") |
| continue |
| |
| frac = [float(a.reshape(-1).mean()) for a in pg] |
| print(f"ratio={r:.1f} selected_frac_mean={float(np.mean(frac)):.4f} selected_frac_p50={float(np.percentile(frac,50)):.4f}") |
|
|
| print("\n=== proposal_binding stats (all proposals concatenated) ===") |
| for r in ratios: |
| pb = [b['prop_bind'] for b in outs[r]] |
| s = agg_gate(pb) |
| print(f"ratio={r:.1f} proposal_binding_stats={s}") |
|
|
| print("\n=== Output mean |L1| vs ratio=%.1f (mean over sampled items) ===" % base_r) |
| for r in ratios[1:]: |
| d = diffs[r] |
| print(f"ratio={r:.1f} sal_l1={d['sal_l1']:.6f} cls_l1={d['cls_l1']:.6f} " |
| f"bind_l1={d['bind_l1']:.6f} delta_l1={d['delta_l1']:.6f}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|