Spaces:
Running
Running
Download tools/evaluate.py from setariaa/next-gpt-lite: direct link, hf CLI and curl.
- Browser
- Download file 6.26 kB
-
https://huggingface.co/spaces/setariaa/next-gpt-lite/resolve/main/tools/evaluate.py
- Command line
-
hf download hf://spaces/setariaa/next-gpt-lite/tools/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/spaces/setariaa/next-gpt-lite/resolve/main/tools/evaluate.py
6.26 kB
| """Evaluate the trained NExT-GPT-lite system and save machine-readable evidence. | |
| Metrics | |
| captioning : BLEU-4 and CLIPScore on held-out images/audio (stage-1 ability) | |
| generation : CLIPScore (image) / CLAP score (audio) of decoded media vs. the prompt | |
| modality switch : accuracy of emitting the requested signal token for T->M instructions | |
| All raw generations are stored under results/samples/ so the report can quote them. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import pathlib | |
| import sys | |
| ROOT = pathlib.Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT)) | |
| import numpy as np # noqa: E402 | |
| import torch # noqa: E402 | |
| from PIL import Image # noqa: E402 | |
| from transformers import CLIPModel, CLIPProcessor # noqa: E402 | |
| from nextgpt_lite.config import CKPT, DATA, RESULTS, CLIP_REPO, model_path # noqa: E402 | |
| from nextgpt_lite.eval import bleu, clap_score, clip_score # noqa: E402 | |
| from nextgpt_lite.model import NextGPTLite # noqa: E402 | |
| FEAT = DATA / "features" | |
| SAMPLES = RESULTS / "samples" | |
| def load_model(stage3: bool = True) -> NextGPTLite: | |
| model = NextGPTLite(load_decoders=True) | |
| s3 = CKPT / "stage3" | |
| if stage3 and (s3 / "adapter").exists(): | |
| model.llm.load_lora(s3 / "adapter") | |
| model.load_projections(str(s3 / "projections.pt")) | |
| elif (CKPT / "stage2_image.pt").exists(): | |
| model.load_projections(str(CKPT / "stage2_image.pt")) | |
| audio_ckpt = CKPT / "audio_decoder.pt" | |
| if audio_ckpt.exists(): | |
| model.audio_decoder.load_state_dict(torch.load(audio_ckpt, map_location=model.device)) | |
| model.eval() | |
| return model | |
| def caption_eval(model, split: str, modality: str, limit: int) -> dict: | |
| from nextgpt_lite.constants import MODALITY_EN | |
| d = np.load(FEAT / f"{modality}_{split}.npz", allow_pickle=True) | |
| captions = [str(c) for c in d["captions"]][:limit] | |
| feats = torch.from_numpy(d["features"][:limit]).float() | |
| preds = [] | |
| prompt = {"image": "请描述这张图片。", "audio": "请描述这段音频。"}[modality] | |
| for i in range(len(captions)): | |
| res = model.chat([{"role": "user", "content": prompt}], modality=modality, | |
| features=feats[i].unsqueeze(0), max_new_tokens=32) | |
| preds.append(res.text) | |
| score = bleu(preds, captions) | |
| out = {"n": len(preds), "bleu4": score, "preds": preds, "refs": captions} | |
| if modality == "image": | |
| # CLIPScore of the *real* test image vs. the caption the model wrote for it | |
| clip = CLIPModel.from_pretrained(model_path(CLIP_REPO)).to(model.device).eval() | |
| proc = CLIPProcessor.from_pretrained(model_path(CLIP_REPO)) | |
| images = [] | |
| for i in range(min(len(preds), 60)): | |
| p = SAMPLES / f"test_image_{i}.jpg" | |
| if p.exists(): | |
| images.append(Image.open(p).convert("RGB")) | |
| if images: | |
| out["caption_clipscore"] = clip_score(clip, proc, images, preds[: len(images)], model.device) | |
| return out | |
| def generation_eval(model, split: str, modality: str, limit: int, steps: int) -> dict: | |
| d = np.load(FEAT / f"{modality}_{split}.npz", allow_pickle=True) | |
| captions = [str(c) for c in d["captions"]][:limit] | |
| conds = torch.from_numpy(np.stack([d["target"][i] for i in range(limit)])).float() | |
| if modality == "image": | |
| clip = CLIPModel.from_pretrained(model_path(CLIP_REPO)).to(model.device).eval() | |
| proc = CLIPProcessor.from_pretrained(model_path(CLIP_REPO)) | |
| images = [] | |
| for i in range(limit): | |
| c = conds[i:i + 1].unsqueeze(1) | |
| arr = model.image_decoder.decode(c, steps=steps, size=256, seed=i)[0] | |
| images.append(Image.fromarray(arr)) | |
| if i < 8: | |
| Image.fromarray(arr).save(SAMPLES / f"gen_image_{split}_{i}.png") | |
| score = clip_score(clip, proc, images, captions, model.device) | |
| return {"n": limit, "clipscore": score, "captions": captions} | |
| wavs = [] | |
| for i in range(limit): | |
| c = conds[i:i + 1] | |
| wav = model.audio_decoder.frontend.to_waveform(model.audio_decoder.sample(c, steps=50, seed=i)) | |
| wavs.append(wav[0].cpu()) | |
| if i < 8: | |
| import soundfile as sf | |
| sf.write(SAMPLES / f"gen_audio_{split}_{i}.wav", wav[0].cpu().numpy(), 22050) | |
| score = clap_score(model.encoders.audio, wavs, captions, model.device) | |
| return {"n": limit, "clapscore": score, "captions": captions} | |
| def modality_switch_eval(model, modality: str, limit: int) -> dict: | |
| prompts = { | |
| "image": ["请生成一张图片:{c}", "帮我画一幅图,内容是:{c}", "Generate an image of {c}"], | |
| "audio": ["请生成一段音频:{c}", "Generate a sound clip of {c}"], | |
| "video": ["请生成一段视频:{c}"], | |
| }[modality] | |
| captions = [str(c) for c in np.load(FEAT / "image_test.npz", allow_pickle=True)["captions"][:limit]] | |
| ok = [] | |
| for i, cap in enumerate(captions): | |
| p = prompts[i % len(prompts)].format(c=cap) | |
| res = model.chat([{"role": "user", "content": p}], max_new_tokens=12) | |
| ok.append(modality in res.modalities) | |
| return {"n": len(ok), "accuracy": float(np.mean(ok)), "hits": int(sum(ok))} | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--limit", type=int, default=100) | |
| ap.add_argument("--image-steps", type=int, default=4) | |
| args = ap.parse_args() | |
| SAMPLES.mkdir(parents=True, exist_ok=True) | |
| model = load_model() | |
| out = {} | |
| out["caption_image"] = caption_eval(model, "test", "image", args.limit) | |
| out["caption_audio"] = caption_eval(model, "test", "audio", min(args.limit, 100)) | |
| out["gen_image"] = generation_eval(model, "test", "image", min(args.limit, 50), args.image_steps) | |
| out["gen_audio"] = generation_eval(model, "test", "audio", min(args.limit, 50), 50) | |
| for mod in ("image", "audio", "video"): | |
| out[f"switch_{mod}"] = modality_switch_eval(model, mod, 30) | |
| (RESULTS / "eval.json").write_text(json.dumps(out, indent=2, ensure_ascii=False), encoding="utf-8") | |
| print(json.dumps({k: {kk: vv for kk, vv in v.items() if kk not in ("preds", "refs", "captions")} | |
| for k, v in out.items()}, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |