Download tools/probe.py from hyper88/Parallax-1.3B-preview: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/hyper88/Parallax-1.3B-preview/resolve/main/tools/probe.py
- Command line
-
hf download hf://hyper88/Parallax-1.3B-preview/tools/probe.py
-
curl -L -o probe.py https://huggingface.co/hyper88/Parallax-1.3B-preview/resolve/main/tools/probe.py
10.2 kB
| #!/usr/bin/env python3 | |
| # Copyright 2026 The Parallax Authors. Licensed under the Apache License, Version 2.0. | |
| """Zero-training probes on the frozen generator. | |
| long roll out far past the training horizon with a sliding cache and report how frame | |
| statistics move over time, for each cache update mode | |
| recall let early frames fall out of a small cache, then load them back from the pool and | |
| measure whether the following frames move towards them (they do not have to: the | |
| frozen model was never trained with retrieved context) | |
| Both write contact sheets and a JSON report. Pixels come from the fast decoder. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import torch | |
| import torch.nn.functional as F | |
| ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| sys.path.insert(0, ROOT) | |
| sys.path.insert(0, os.path.join(ROOT, "tools")) | |
| import infer_realtime as ir # noqa: E402 | |
| from gpu_tools import psnr, sheet # noqa: E402 | |
| def load(a): | |
| from safetensors.torch import load_file | |
| dev, dt = torch.device(a.device), torch.bfloat16 | |
| cfg = ir.DiTConfig() | |
| dit = ir.load_generator(a.checkpoint, cfg, dev, dt) | |
| bank = load_file(a.bank) | |
| refiner = ir.load_refiner(a.refiner, cfg, dev, dt) if a.refiner else None | |
| decoder = ir.PixelDecoder() | |
| decoder.load_taehv(torch.load(a.decoder, map_location="cpu", weights_only=True)) | |
| decoder = decoder.to(device=dev, dtype=dt).eval() | |
| pe = lambda i: bank["embeds"][bank["offsets"][i]:bank["offsets"][i + 1]][None].to(device=dev, dtype=dt) | |
| return dev, dt, cfg, dit, refiner, decoder, pe | |
| def noise_stream(seed, hw, dev, dt): | |
| g = torch.Generator().manual_seed(seed) | |
| return lambda: torch.randn(1, 16, *hw, generator=g).to(device=dev, dtype=dt) | |
| def decode(decoder, zs): | |
| decoder.reset() | |
| return torch.cat([decoder(z) for z in zs]).float() # [T, 3, H, W] | |
| def nearest_psnr(frames, refs, width=208): | |
| """Mean over `frames` of the PSNR to the closest of `refs`, at reduced resolution (tolerates small shifts).""" | |
| small = lambda x: F.interpolate(x.float(), size=(int(width * x.shape[-2] / x.shape[-1]), width), mode="bilinear", antialias=True) | |
| a, b = small(frames), small(refs) | |
| mse = (a[:, None] - b[None]).pow(2).mean(dim=(2, 3, 4)) # [n_frames, n_refs] | |
| return float((10 * torch.log10(1.0 / mse.clamp_min(1e-12))).amax(dim=1).mean()) | |
| def frame_stats(px): | |
| """Per-frame scalars that drift when a rollout degrades: brightness, colourfulness, fine detail, motion.""" | |
| lum = px.mean(dim=1) | |
| dif = (lum[1:] - lum[:-1]).abs().mean(dim=(1, 2)) # change from the previous frame: falls to zero if the video freezes | |
| motion = torch.cat([dif[:1], dif]) if px.shape[0] > 1 else torch.zeros(px.shape[0], dtype=px.dtype, device=px.device) | |
| sat = px.amax(dim=1) - px.amin(dim=1) | |
| lap = F.conv2d(lum[:, None], torch.tensor([[[[0, 1, 0], [1, -4, 1], [0, 1, 0]]]], dtype=px.dtype, device=px.device)) | |
| return dict(brightness=lum.mean(dim=(1, 2)).tolist(), saturation=sat.mean(dim=(1, 2)).tolist(), detail=lap.abs().mean(dim=(1, 2, 3)).tolist(), | |
| motion=motion.tolist()) | |
| def cmd_long(a): | |
| dev, dt, cfg, dit, refiner, decoder, pe = load(a) | |
| hw = (a.height // 8, a.width // 8) | |
| os.makedirs(a.out, exist_ok=True) | |
| report = [] | |
| for pi in a.indices: | |
| rows = [] | |
| for mode in a.modes.split(","): | |
| eng = ir.StreamEngine(dit, ir.EngineConfig(slots=a.slots, sink=a.sink, cache_update=mode), hw, refiner=refiner) | |
| eng.set_prompt(pe(pi)) | |
| nz = noise_stream(a.seed + pi, hw, dev, dt) | |
| zs = [] | |
| for _ in range(a.frames): | |
| n_re = len(eng.cfg.first_steps if eng.empty() else eng.cfg.steps) - 1 | |
| zs.append(eng.step(nz(), renoise=[nz() for _ in range(n_re)])) | |
| px = decode(decoder, zs) | |
| st = frame_stats(px) | |
| n = px.shape[0] | |
| seg = lambda xs, lo, hi: sum(xs[lo:hi]) / max(1, hi - lo) | |
| first = slice(4, 4 + 16) # second half of the first second: the model's steady start | |
| rec = dict(prompt=pi, mode=mode, latent_frames=a.frames, pixel_frames=n, slots=a.slots, sink=a.sink) | |
| for k, xs in st.items(): | |
| rec[f"{k}_start"] = round(seg(xs, first.start, first.stop), 4) | |
| rec[f"{k}_end"] = round(seg(xs, n - 16, n), 4) | |
| rec[f"{k}_ratio"] = round(rec[f"{k}_end"] / max(rec[f"{k}_start"], 1e-6), 3) | |
| zl = torch.cat(zs).float() | |
| rec["latent_std_start"], rec["latent_std_end"] = round(float(zl[1:5].std()), 4), round(float(zl[-4:].std()), 4) | |
| report.append(rec) | |
| print(json.dumps(rec), flush=True) | |
| rows.append(px[torch.linspace(0, n - 1, a.cols).round().long()]) | |
| del eng | |
| open(os.path.join(a.out, f"long_{pi:04d}.jpg"), "wb").write(sheet(rows, a.thumb)) | |
| json.dump(report, open(os.path.join(a.out, "long.json"), "w"), indent=1) | |
| VARIANTS = ("no_retrieval", "native_time", "same_index", "contiguous") | |
| def cmd_recall(a): | |
| dev, dt, cfg, dit, refiner, decoder, pe = load(a) | |
| hw = (a.height // 8, a.width // 8) | |
| os.makedirs(a.out, exist_ok=True) | |
| early = list(range(a.early_start, a.early_start + a.retrieved)) | |
| report = [] | |
| for pi in a.indices: | |
| outs = {} | |
| for variant in VARIANTS: | |
| eng = ir.StreamEngine(dit, ir.EngineConfig(slots=a.window + a.retrieved, retrieved=a.retrieved, cache_update=a.mode), hw, refiner=refiner) | |
| eng.set_prompt(pe(pi)) | |
| nz = noise_stream(a.seed + pi, hw, dev, dt) | |
| zs = [] | |
| for f in range(a.frames): | |
| if f >= a.recall_at and variant != "no_retrieval": | |
| # native_time: keys keep the frame index they were generated with (far in the past) | |
| # same_index: all recalled frames share one index, just before the oldest frame of the window | |
| # contiguous: recalled frames take consecutive indices that end just before the window | |
| oldest = eng.frame - (a.window - 1) # index of the oldest frame the window will hold | |
| if variant == "native_time": | |
| idx = None | |
| elif variant == "same_index": | |
| idx = oldest - 1 | |
| else: | |
| idx = [oldest - len(early) + j for j in range(len(early))] | |
| if variant != "native_time": | |
| eng.load_retrieved([]) # keys are baked per load: reload with the current offset | |
| eng.load_retrieved(early, as_index=idx) | |
| n_re = len(eng.cfg.first_steps if eng.empty() else eng.cfg.steps) - 1 | |
| zs.append(eng.step(nz(), renoise=[nz() for _ in range(n_re)])) | |
| outs[variant] = (torch.cat(zs).float(), decode(decoder, zs)) | |
| del eng | |
| zb, pb = outs["no_retrieval"] | |
| # latent frame i >= 1 decodes to pixel frames 1 + 4 (i - 1) .. 4 i | |
| ref = pb[1 + 4 * (early[0] - 1):4 * early[-1] + 1] # pixel frames of the recalled latent frames | |
| tail = slice(1 + 4 * (a.recall_at + 2 - 1), None) # frames generated after recall started (skip two latent frames) | |
| rec = dict(prompt=pi, window=a.window, retrieved=a.retrieved, recalled_frames=early, recall_at=a.recall_at, frames=a.frames, mode=a.mode) | |
| for variant, (z, p) in outs.items(): | |
| rec[f"psnr_to_recalled_{variant}"] = round(nearest_psnr(p[tail], ref), 2) | |
| rec[f"psnr_to_previous_window_{variant}"] = round(nearest_psnr(p[tail], pb[1 + 4 * (a.recall_at - 4):1 + 4 * (a.recall_at - 1)]), 2) | |
| rec[f"latent_cos_to_recalled_{variant}"] = round(float(F.cosine_similarity(z[a.recall_at + 2:].mean(0).flatten(), zb[early].mean(0).flatten(), dim=0)), 4) | |
| rec[f"detail_{variant}"] = round(sum(frame_stats(p[tail])["detail"]) / max(1, p[tail].shape[0]), 4) | |
| rec["same_before_recall"] = bool(torch.equal(outs["no_retrieval"][0][:a.recall_at], outs["native_time"][0][:a.recall_at])) | |
| report.append(rec) | |
| print(json.dumps(rec), flush=True) | |
| n = pb.shape[0] | |
| pick = torch.linspace(0, n - 1, a.cols).round().long() | |
| if pi < a.indices[0] + 4: | |
| open(os.path.join(a.out, f"recall_{pi:04d}.jpg"), "wb").write(sheet([outs[v][1][pick] for v in VARIANTS], a.thumb)) | |
| json.dump(report, open(os.path.join(a.out, "recall.json"), "w"), indent=1) | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| for name in ("long", "recall"): | |
| p = sub.add_parser(name) | |
| p.add_argument("--checkpoint", required=True) | |
| p.add_argument("--bank", required=True) | |
| p.add_argument("--decoder", required=True) | |
| p.add_argument("--refiner") | |
| p.add_argument("--out", required=True) | |
| p.add_argument("--indices", type=int, nargs="+", default=[0, 1, 2]) | |
| p.add_argument("--height", type=int, default=480) | |
| p.add_argument("--width", type=int, default=832) | |
| p.add_argument("--cols", type=int, default=8) | |
| p.add_argument("--thumb", type=int, default=156) | |
| p.add_argument("--seed", type=int, default=0) | |
| p.add_argument("--device", default="cuda") | |
| if name == "long": | |
| p.add_argument("--modes", default="clean") | |
| p.add_argument("--frames", type=int, default=75) | |
| p.add_argument("--slots", type=int, default=21) | |
| p.add_argument("--sink", type=int, default=0) | |
| else: | |
| p.add_argument("--mode", default="clean") | |
| p.add_argument("--frames", type=int, default=36) | |
| p.add_argument("--window", type=int, default=8) | |
| p.add_argument("--retrieved", type=int, default=3) | |
| p.add_argument("--early-start", type=int, default=1) | |
| p.add_argument("--recall-at", type=int, default=24) | |
| a = ap.parse_args() | |
| (cmd_long if a.cmd == "long" else cmd_recall)(a) | |
| if __name__ == "__main__": | |
| main() | |