next-gpt-lite / tools /prepare_data.py
setariaa's picture
Code + report (attempt 1)
0b0e1c1 verified
Raw History Blame Contribute Delete
8.02 kB
"""Precompute frozen-encoder features, caption embeddings and log-mels.
Stage 1/2 train only projection layers, so the frozen encoders are run once over the
training data instead of every step. This mirrors NExT-GPT's ``process_embeddings.py``,
which precomputes caption embeddings for the decoder-side alignment.
Outputs (under data/features/):
image_{train,val,test}.npz : features (N,50,768) fp16, target (N,768) CLIP-text mean,
captions (N,) primary caption
audio_{train,val,test}.npz : features (N,T,768) fp16, target (N,512) CLAP-text,
mel (N,64,216) fp16, captions (N,)
captions_{split}.json : all reference captions per sample (for evaluation)
"""
from __future__ import annotations
import argparse
import io
import json
import pathlib
import numpy as np
import torch
from PIL import Image
ROOT = pathlib.Path(__file__).resolve().parents[1]
import sys
sys.path.insert(0, str(ROOT))
from nextgpt_lite.config import CLAP_REPO, CLIP_REPO, SD_REPO, model_path, pick_device # noqa: E402
from nextgpt_lite.decoders.audio import MelFrontend # noqa: E402
from nextgpt_lite.decoders.image import ImageDecoder # noqa: E402
from nextgpt_lite.encoders import CLAPAudioEncoder, CLIPVisionEncoder # noqa: E402
CACHE = ROOT / ".cache"
FEAT = ROOT / "data" / "features"
SAMPLES = ROOT / "data" / "samples"
def iter_rows(paths):
import pyarrow.parquet as pq
for p in paths:
pf = pq.ParquetFile(p)
for batch in pf.iter_batches(batch_size=32):
for row in batch.to_pylist():
yield row
def load_image(value):
if isinstance(value, dict) and value.get("bytes"):
return Image.open(io.BytesIO(value["bytes"])).convert("RGB")
if isinstance(value, dict) and value.get("path"):
return Image.open(value["path"]).convert("RGB")
if isinstance(value, (bytes, bytearray)):
return Image.open(io.BytesIO(value)).convert("RGB")
raise ValueError(f"unsupported image field: {type(value)}")
def load_audio(value, sample_rate=22050):
import soundfile as sf
if isinstance(value, dict):
if value.get("array") is not None:
arr = np.asarray(value["array"], dtype=np.float32)
sr = int(value.get("sampling_rate", sample_rate))
elif value.get("bytes"):
arr, sr = sf.read(io.BytesIO(value["bytes"]), dtype="float32")
elif value.get("path"):
arr, sr = sf.read(value["path"], dtype="float32")
else:
raise ValueError("empty audio field")
else:
arr, sr = sf.read(io.BytesIO(value), dtype="float32")
if arr.ndim > 1:
arr = arr.mean(1)
return torch.from_numpy(arr).float(), sr
def caption_of(row):
caps = []
for k, v in row.items():
if k.startswith("caption") and isinstance(v, str) and v.strip():
caps.append(v.strip())
if not caps:
for k in ("text", "sentence", "description"):
if isinstance(row.get(k), str):
caps.append(row[k].strip())
return caps
def build_images(files, out_split, clip, sd, device):
feats, targets, captions, all_caps = [], [], [], []
for i, row in enumerate(iter_rows(files)):
img = load_image(row.get("image") or row.get("img"))
caps = caption_of(row)
if not caps:
continue
primary = caps[0]
feats.append(clip(clip.preprocess(img).to(device)).half().cpu().numpy()[0])
targets.append(sd.encode_caption([primary]).cpu().numpy()[0])
captions.append(primary)
all_caps.append(caps)
if i < 6:
img.save(SAMPLES / f"image_{out_split}_{i}.jpg")
if out_split == "test" and i < 60:
img.save(SAMPLES / f"test_image_{i}.jpg")
if i % 500 == 0:
print(f" image {out_split} {i}", flush=True)
np.savez_compressed(FEAT / f"image_{out_split}.npz", features=np.stack(feats),
target=np.stack(targets), captions=np.array(captions))
(ROOT / "data" / f"captions_{out_split}.json").write_text(
json.dumps(all_caps, ensure_ascii=False), encoding="utf-8")
print(f"image_{out_split}: {len(feats)} samples", flush=True)
def build_audio(rows, out_split, clap, mel_frontend, device, batch_size: int = 24):
feats, targets, mels, captions = [], [], [], []
import torchaudio
for start in range(0, len(rows), batch_size):
chunk = rows[start: start + batch_size]
clap_wavs, mel_wavs, caps = [], [], []
for row, cap in chunk:
arr, sr = load_audio(row.get("audio"))
clap_wavs.append(torchaudio.functional.resample(arr, sr, clap.sample_rate) if sr != clap.sample_rate else arr)
mel_wavs.append(torchaudio.functional.resample(arr, sr, 22050) if sr != 22050 else arr)
caps.append(cap)
inputs = clap.processor(audio=[w.numpy() for w in clap_wavs], sampling_rate=clap.sample_rate,
return_tensors="pt", padding=True)
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
out = clap.model.audio_model(**inputs)
last = out.last_hidden_state
if last.dim() == 4:
last = last.flatten(2).transpose(1, 2)
feats.append(last.half().cpu().numpy())
targets.append(clap.text_embed(caps).cpu().numpy())
mel = mel_frontend(torch.stack(mel_wavs).to(device))
mels.append(mel.half().cpu().numpy())
captions.extend(caps)
print(f" audio {out_split} {start + len(chunk)}/{len(rows)}", flush=True)
np.savez_compressed(FEAT / f"audio_{out_split}.npz", features=np.concatenate(feats),
target=np.concatenate(targets), mel=np.concatenate(mels),
captions=np.array(captions))
print(f"audio_{out_split}: {len(captions)} samples", flush=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--device", default=None)
ap.add_argument("--only", choices=["image", "audio", "all"], default="all")
args = ap.parse_args()
FEAT.mkdir(parents=True, exist_ok=True)
SAMPLES.mkdir(parents=True, exist_ok=True)
device = torch.device(args.device) if args.device else pick_device()
if args.only in ("image", "all"):
clip = CLIPVisionEncoder(model_path(CLIP_REPO)).to(device).eval()
sd = ImageDecoder(model_path(SD_REPO), dtype=torch.float32, device=str(device))
f8k = CACHE / "jxie--flickr8k" / "data"
build_images([f8k / "train-00000-of-00002-2f8f6bfa852eac4b.parquet",
f8k / "train-00001-of-00002-2173151d8cd6c7fb.parquet"], "train", clip, sd, device)
build_images([f8k / "validation-00000-of-00001-7025a2b596f14b7b.parquet"], "val", clip, sd, device)
build_images([f8k / "test-00000-of-00001-42a2661d12c73e48.parquet"], "test", clip, sd, device)
if args.only in ("audio", "all"):
clap = CLAPAudioEncoder(model_path(CLAP_REPO)).to(device).eval()
mel_frontend = MelFrontend().to(device)
esc = CACHE / "ashraq--esc50" / "data"
rows = list(iter_rows([esc / "train-00000-of-00002-2f1ab7b824ec751f.parquet",
esc / "train-00001-of-00002-27425e5c1846b494.parquet"]))
items = []
for row in rows:
cat = row.get("category") or row.get("label") or "sound"
cap = f"the sound of {str(cat).replace('_', ' ')}"
items.append((row, cap))
import random
rng = random.Random(0)
rng.shuffle(items)
n = len(items)
train, rest = items[: int(n * 0.8)], items[int(n * 0.8):]
val, test = rest[: len(rest) // 2], rest[len(rest) // 2:]
build_audio(train, "train", clap, mel_frontend, device)
build_audio(val, "val", clap, mel_frontend, device)
build_audio(test, "test", clap, mel_frontend, device)
if __name__ == "__main__":
main()