File size: 5,099 Bytes
0a2c21d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#!/usr/bin/env python3
import argparse
from pathlib import Path

import numpy as np
import torch
from diffusers.models import AutoencoderKLWan
from PIL import Image, ImageDraw, ImageFont

from helios.utils.token_dynamics_debug import token_rect_on_image, token_yx_from_index


def parse_tokens(value: str, grid_w: int):
    tokens = []
    for item in value.split(","):
        item = item.strip()
        if not item:
            continue
        if ":" in item:
            y, x = item.split(":", 1)
            tokens.append(int(y) * grid_w + int(x))
        else:
            tokens.append(int(item))
    return tokens


def decode_latent_frame(vae, latent_frame: torch.Tensor, latents_mean, latents_std):
    latent = latent_frame.unsqueeze(0).unsqueeze(2).to(vae.dtype)
    latent = latent / latents_std + latents_mean
    with torch.no_grad():
        video = vae.decode(latent, return_dict=False)[0]
    frame = video[0, :, 0].float().permute(1, 2, 0).cpu().numpy()
    frame = np.clip((frame + 1.0) / 2.0, 0.0, 1.0)
    return (frame * 255.0).astype(np.uint8)


def to_pil(image_np: np.ndarray) -> Image.Image:
    return Image.fromarray(image_np)


def draw_token_pair(
    history_img: Image.Image,
    noise_img: Image.Image,
    noise_idx: int,
    hist_idx: int,
    score: float,
    grid_h: int,
    grid_w: int,
) -> Image.Image:
    ny, nx = token_yx_from_index(noise_idx, grid_w)
    hy, hx = token_yx_from_index(hist_idx, grid_w)

    hh, hw = history_img.height, history_img.width
    nh, nw = noise_img.height, noise_img.width

    hx0, hy0, hw_box, hh_box = token_rect_on_image(hy, hx, hh, hw, grid_h, grid_w)
    nx0, ny0, nw_box, nh_box = token_rect_on_image(ny, nx, nh, nw, grid_h, grid_w)

    canvas = Image.new("RGB", (hw + nw, max(hh, nh)))
    canvas.paste(history_img, (0, 0))
    canvas.paste(noise_img, (hw, 0))

    draw = ImageDraw.Draw(canvas)
    hist_rect = [hx0, hy0, hx0 + hw_box, hy0 + hh_box]
    noise_rect = [hw + nx0, ny0, hw + nx0 + nw_box, ny0 + nh_box]

    draw.rectangle(hist_rect, outline=(0, 255, 255), width=3)
    draw.rectangle(noise_rect, outline=(0, 255, 0), width=3)

    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 14)
    except OSError:
        font = ImageFont.load_default()

    draw.text((hx0 + 2, max(0, hy0 - 16)), f"hist ({hy},{hx}) cos={score:.3f}", fill=(0, 255, 255), font=font)
    draw.text((hw + nx0 + 2, max(0, ny0 - 16)), f"noise ({ny},{nx})", fill=(0, 255, 0), font=font)

    return canvas


def main():
    parser = argparse.ArgumentParser(
        description="Save one left-right image per noise token: history frame | noise frame 0."
    )
    parser.add_argument("input", help="token_dynamics_*.pt artifact")
    parser.add_argument("--model-path", default="./checkpoints/Helios-Base")
    parser.add_argument("--output-dir", default=None)
    parser.add_argument(
        "--tokens",
        default="",
        help='Optional subset: comma-separated token ids or "y:x" pairs. Default: all noise tokens.',
    )
    parser.add_argument("--stride", type=int, default=1, help="Use every N-th token when --tokens is empty.")
    args = parser.parse_args()

    artifact = torch.load(args.input, map_location="cpu")
    if artifact.get("noise_latent_frame") is None or artifact.get("history_latent_frame") is None:
        raise RuntimeError(
            "Artifact has no latent frames (expected fully denoised frames saved after chunk sampling). "
            "Re-run inference with updated _DEV3 debug code."
        )

    output_dir = Path(args.output_dir or Path(args.input).parent)
    output_dir.mkdir(parents=True, exist_ok=True)
    stem = Path(args.input).stem

    grid_h, grid_w = artifact["grid"]
    grid_tokens = grid_h * grid_w
    match_indices = artifact["match_indices"].long()
    match_scores = artifact["match_scores"].float()

    if args.tokens.strip():
        tokens = parse_tokens(args.tokens, grid_w)
    else:
        tokens = list(range(0, grid_tokens, args.stride))

    vae = AutoencoderKLWan.from_pretrained(args.model_path, subfolder="vae", torch_dtype=torch.float32)
    latents_mean = torch.tensor(vae.config.latents_mean).view(vae.config.z_dim, 1, 1)
    latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(vae.config.z_dim, 1, 1)

    history_img = to_pil(decode_latent_frame(vae, artifact["history_latent_frame"], latents_mean, latents_std))
    noise_img = to_pil(decode_latent_frame(vae, artifact["noise_latent_frame"], latents_mean, latents_std))

    pair_dir = output_dir / f"{stem}_match_frames"
    pair_dir.mkdir(parents=True, exist_ok=True)

    for noise_idx in tokens:
        hist_idx = int(match_indices[noise_idx].item())
        score = float(match_scores[noise_idx].item())
        ny, nx = token_yx_from_index(noise_idx, grid_w)
        canvas = draw_token_pair(history_img, noise_img, noise_idx, hist_idx, score, grid_h, grid_w)
        out = pair_dir / f"noise{ny:02d}_{nx:02d}.png"
        canvas.save(out)

    print(f"Saved {len(tokens)} images to {pair_dir}")


if __name__ == "__main__":
    main()