File size: 5,462 Bytes
813c1b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
"""Shared helpers for the FlowLensing evaluation scripts.

Normalization contract
----------------------
Images are stored as raw simulation output in physical brightness units. Every
evaluation applies the same two steps the model was trained with:

  1. minmax_to_unit  : stretch each image to [0, 1] using its own min and max
  2. Normalize(.5,.5): map [0, 1] -> [-1, 1]

Generated samples come out of the sampler on [-1, 1] and are returned on [0, 1]
by `sample_cfg`, which is the scale the regressor and classifier expect.

Step 1 is idempotent, so it is safe to leave on for data that was already
normalized offline.
"""
import numpy as np
import torch
import torch.nn as nn


def minmax_to_unit(img):
    """Stretch one image to [0, 1] using its own min and max."""
    lo, hi = img.min(), img.max()
    rng = hi - lo
    if rng <= 0:
        return torch.zeros_like(img)
    return (img - lo) / rng


def load_npy_image(path, normalize=True):
    """Load a .npy sample and return a (1, 64, 64) tensor on [0, 1]."""
    data = np.load(path, allow_pickle=True)
    if data.dtype == object or (data.ndim == 1 and data.shape[0] == 5):
        data = data[0]              # (image, theta_E, x, y, beta) packing
    img = np.asarray(data, dtype=np.float32).squeeze()
    t = torch.from_numpy(img).float().unsqueeze(0)
    return minmax_to_unit(t) if normalize else t


def to_imagenet_rgb(img01):
    """(B,1,H,W) on [0,1] -> (B,3,H,W) ImageNet-normalized, for the ResNet."""
    if img01.dim() == 3:
        img01 = img01.unsqueeze(0)
    x = img01.repeat(1, 3, 1, 1)
    mean = torch.tensor([0.485, 0.456, 0.406], device=x.device).view(1, 3, 1, 1)
    std = torch.tensor([0.229, 0.224, 0.225], device=x.device).view(1, 3, 1, 1)
    return (x - mean) / std


def pick_device(spec="auto"):
    if spec != "auto":
        return torch.device(spec)
    if torch.cuda.is_available():
        return torch.device("cuda")
    if torch.backends.mps.is_available():
        return torch.device("mps")
    return torch.device("cpu")


# --------------------------------------------------------------------------
# Model loading
# --------------------------------------------------------------------------

ARCH = dict(input_size=64, patch_size=2, in_channels=1, hidden_size=512,
            depth=6, num_heads=8, timestep_freq_scale=1000)


def load_flow_model(ckpt_path, kind, device):
    """kind='class' -> 3-class model (model.py); kind='param' -> 4-var model."""
    if kind == "class":
        from model import NanoDiT
        net = NanoDiT(num_classes=3, **ARCH)
    elif kind == "param":
        from model_regress import NanoDiT
        net = NanoDiT(cond_dim=4, **ARCH)
    else:
        raise ValueError(f"unknown kind: {kind}")
    sd = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    if isinstance(sd, dict) and "model_state_dict" in sd:
        sd = sd["model_state_dict"]
    sd = {k.replace("_orig_mod.", ""): v for k, v in sd.items()}
    net.load_state_dict(sd, strict=True)
    return net.to(device).eval()


def load_classifier(ckpt_path, arch, device, num_classes=3):
    """ResNet classifier: 3-channel ImageNet-normalized input, Linear head."""
    from torchvision.models import resnet18, resnet34
    net = {"resnet18": resnet18, "resnet34": resnet34}[arch](weights=None)
    net.fc = nn.Linear(net.fc.in_features, num_classes)
    ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    sd = ck.get("model_state_dict", ck) if isinstance(ck, dict) else ck
    sd = {k.replace("_orig_mod.", ""): v for k, v in sd.items()}
    net.load_state_dict(sd, strict=True)
    return net.to(device).eval()


def load_regressor(ckpt_path, device):
    from regression_model import ImageRegressor
    net = ImageRegressor(num_outputs=4)
    sd = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    sd = sd.get("model_state_dict", sd) if isinstance(sd, dict) else sd
    net.load_state_dict({k.replace("_orig_mod.", ""): v for k, v in sd.items()})
    return net.to(device).eval()


# --------------------------------------------------------------------------
# Sampling (Euler ODE + classifier-free guidance), matching the training code
# --------------------------------------------------------------------------

@torch.no_grad()
def sample_cfg(model, cond, ode_steps=100, cfg_scale=2.0, device=None,
               img_size=64, channels=1):
    """cond: LongTensor (B,) of class ids, or FloatTensor (B,4) of parameters.

    Returns (B, 1, H, W) on [0, 1].
    """
    device = device or next(model.parameters()).device
    n = cond.shape[0]
    z = torch.randn((n, channels, img_size, img_size), device=device)
    y = cond.to(device)

    using_cfg = cfg_scale >= 1.0
    if using_cfg:
        if y.dim() == 1:                       # class ids -> null token id 3
            y_null = torch.full_like(y, 3)
        else:                                  # parameter vectors -> zeros
            y_null = torch.zeros_like(y)
        y = torch.cat([y, y_null], 0)

    dt = 1.0 / ode_steps
    for i in range(ode_steps, 0, -1):
        z_in = torch.cat([z, z], 0) if using_cfg else z
        t = torch.full((z_in.shape[0],), i / ode_steps, device=device, dtype=z_in.dtype)
        v = model(z_in, t, y)
        if using_cfg:
            v_cond, v_uncond = v.chunk(2, dim=0)
            v = v_uncond + cfg_scale * (v_cond - v_uncond)
        z = z - dt * v

    return torch.clamp((z + 1) / 2.0, 0.0, 1.0)