File size: 10,579 Bytes
0b4562b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2025 Apple Inc. All Rights Reserved.
#
"""
Inference utilities for STARFlow.
"""

import torch
import datetime
from typing import List
from torchmetrics.image.fid import FrechetInceptionDistance, _compute_fid
from torchmetrics.image.inception import InceptionScore
from torchmetrics.multimodal.clip_score import CLIPScore
from torchmetrics.utilities.data import dim_zero_cat

# Import Distributed from training module
from .training import Distributed


# ==== Metrics ====

class FID(FrechetInceptionDistance):
    def __init__(self, feature=2048, reset_real_features=True, normalize=False, input_img_size=..., **kwargs):
        super().__init__(feature, reset_real_features, normalize, input_img_size, **kwargs)
        self.reset_real_features = reset_real_features

    def add_state(self, name, default, *args, **kwargs):
        self.register_buffer(name, default)

    def manual_compute(self, dist):
        # manually gather the features
        self.fake_features_num_samples = dist.reduce(self.fake_features_num_samples)
        self.fake_features_sum = dist.reduce(self.fake_features_sum)
        self.fake_features_cov_sum = dist.reduce(self.fake_features_cov_sum)

        if self.reset_real_features:
            self.real_features_num_samples = dist.reduce(self.real_features_num_samples)
            self.real_features_sum = dist.reduce(self.real_features_sum)
            self.real_features_cov_sum = dist.reduce(self.real_features_cov_sum)

        print(f'Gathered {self.fake_features_num_samples} samples for FID computation')

        # compute FID
        mean_real = (self.real_features_sum / self.real_features_num_samples).unsqueeze(0)
        mean_fake = (self.fake_features_sum / self.fake_features_num_samples).unsqueeze(0)
        cov_real_num = self.real_features_cov_sum - self.real_features_num_samples * mean_real.t().mm(mean_real)
        cov_real = cov_real_num / (self.real_features_num_samples - 1)
        cov_fake_num = self.fake_features_cov_sum - self.fake_features_num_samples * mean_fake.t().mm(mean_fake)
        cov_fake = cov_fake_num / (self.fake_features_num_samples - 1)

        if dist.rank == 0:
            fid_score = _compute_fid(mean_real.squeeze(0), cov_real, mean_fake.squeeze(0), cov_fake).to(
                dtype=self.orig_dtype, device=self.real_features_sum.device)
            print(f'FID: {fid_score.item()} DONE')
        else:
            fid_score = torch.tensor(0.0, dtype=self.orig_dtype, device=self.real_features_sum.device)
        dist.barrier()

        # reset the state
        self.fake_features_num_samples *= 0
        self.fake_features_sum *= 0
        self.fake_features_cov_sum *= 0

        if self.reset_real_features:
            self.real_features_num_samples *= 0
            self.real_features_sum *= 0
            self.real_features_cov_sum *= 0

        return fid_score


class IS(InceptionScore):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def manual_compute(self, dist):
        # manually gather the features
        self.features = dim_zero_cat(self.features)
        features = dist.gather_concat(self.features)
        print(f'Gathered {features.shape[0]} samples for IS computation')

        if dist.rank == 0:
            idx = torch.randperm(features.shape[0])
            features = features[idx]

            # calculate probs and logits
            prob = features.softmax(dim=1)
            log_prob = features.log_softmax(dim=1)

            # split into groups
            prob = prob.chunk(self.splits, dim=0)
            log_prob = log_prob.chunk(self.splits, dim=0)

            # calculate score per split
            mean_prob = [p.mean(dim=0, keepdim=True) for p in prob]
            kl_ = [p * (log_p - m_p.log()) for p, log_p, m_p in zip(prob, log_prob, mean_prob)]
            kl_ = [k.sum(dim=1).mean().exp() for k in kl_]
            kl = torch.stack(kl_)

            mean = kl.mean()
            std = kl.std()

        else:
            mean = torch.tensor(0.0, device=self.features.device)
            std = torch.tensor(0.0, device=self.features.device)

        dist.barrier()

        return mean, std


class CLIP(CLIPScore):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def manual_compute(self, dist):
        # manually gather the features
        self.n_samples = dist.reduce(self.n_samples)
        self.score = dist.reduce(self.score)

        print(f'Gathered {self.n_samples} samples for CLIP computation')

        # compute CLIP
        clip_score = torch.max(self.score / self.n_samples, torch.zeros_like(self.score))
        print(f'CLIP: {clip_score.item()} DONE')
        # reset the state
        self.n_samples *= 0
        self.score *= 0
        return clip_score


class Metrics:
    def __init__(self):
        self.metrics: dict[str, list[float]] = {}

    def update(self, metrics: dict[str, torch.Tensor | float]):
        for k, v in metrics.items():
            if isinstance(v, torch.Tensor):
                v = v.item()
            if k in self.metrics:
                self.metrics[k].append(v)
            else:
                self.metrics[k] = [v]

    def compute(self, dist: Distributed | None) -> dict[str, float]:
        out: dict[str, float] = {}
        for k, v in self.metrics.items():
            v = sum(v) / len(v)
            if dist is not None:
                v = dist.gather_concat(torch.tensor(v, device='cuda').view(1)).mean().item()
            out[k] = v
        return out

    @staticmethod
    def print(metrics: dict[str, float], epoch: int):
        print(f'Epoch {epoch}  Time {datetime.datetime.now()}')
        print('\n'.join((f'\t{k:40s}: {v: .4g}' for k, v in sorted(metrics.items()))))


# ==== Denoising Functions (from starflow_utils.py) ====

def apply_denoising(model, x_chunk: torch.Tensor, y_batch,
                    text_encoder, tokenizer, args,
                    text_encoder_kwargs: dict, sigma_curr: float, sigma_next: float = 0) -> torch.Tensor:
    """Apply denoising to a chunk of data."""
    from .common import encode_text  # Import here to avoid circular imports

    noise_std_const = 0.3  # a constant used for noise levels.

    # Handle both encoded tensors and raw captions
    if isinstance(y_batch, torch.Tensor):
        y_ = y_batch
    elif y_batch is not None:
        y_ = encode_text(text_encoder, tokenizer, y_batch, args.txt_size,
                        text_encoder.device, **text_encoder_kwargs)
    else:
        y_ = None

    if getattr(args, 'disable_learnable_denoiser', False) or not hasattr(model, 'learnable_self_denoiser'):
        return self_denoise(
            model, x_chunk, y_,
            noise_std=sigma_curr,
            steps=1,
            disable_learnable_denoiser=getattr(args, 'disable_learnable_denoiser', False)
        )
    else:
        # Learnable denoiser
        if sigma_curr is not None and isinstance(y_batch, (list, type(None))):
            text_encoder_kwargs['noise_std'] = sigma_curr
        denoiser_output = model(x_chunk, y_, denoiser=True)
        return x_chunk - denoiser_output * noise_std_const * (sigma_curr - sigma_next) / sigma_curr


def self_denoise(model, samples, y, noise_std=0.1, lr=1, steps=1, disable_learnable_denoiser=False):
    """Self-denoising function - same as in train.py"""
    if steps == 0:
        return samples

    outputs = []
    x = samples.clone()
    lr = noise_std ** 2 * lr
    with torch.enable_grad():
        x.requires_grad = True
        model.train()
        z, _, _, logdets = model(x, y)
        loss = model.get_loss(z, logdets)['loss'] * 65536
        grad = float(samples.numel()) / 65536 * torch.autograd.grad(loss, [x])[0]
        outputs += [(x - grad * lr).detach()]
    x = torch.cat(outputs, -1)
    return x


def process_denoising(samples: torch.Tensor, y: List[str], args,
                      model, text_encoder, tokenizer, text_encoder_kwargs: dict,
                      noise_std: float) -> torch.Tensor:
    """Process samples through denoising if enabled."""
    if not (args.finetuned_vae == 'none' and
            getattr(args, 'vae_adapter', None) is None and
            getattr(args, 'return_sequence', 0) == 0):
        # Denoising not enabled or not applicable
        return samples

    torch.cuda.empty_cache()
    assert isinstance(samples, torch.Tensor)
    samples = samples.cpu()

    # Use smaller batch size for training to avoid memory issues
    b = samples.size(0)
    db = min(getattr(args, 'denoising_batch_size', 1), b)
    denoised_samples = []
    is_video = samples.dim() == 5

    for j in range(b // db):
        x_all = torch.clone(samples[j * db : (j + 1) * db]).detach().cuda()
        y_batch = y[j * db : (j + 1) * db] if y is not None else None

        if is_video:
            # Chunk-wise denoising for videos
            s_idx, overlap = 0, 0
            steps = x_all.size(1) if getattr(args, 'local_attn_window', None) is None else args.local_attn_window

            while s_idx < x_all.size(1):
                x_chunk = x_all[:, s_idx : s_idx + steps].detach().clone()
                x_denoised = apply_denoising(
                    model, x_chunk, y_batch, text_encoder, tokenizer,
                    args, text_encoder_kwargs, noise_std
                )
                x_all[:, s_idx + overlap: s_idx + steps] = x_denoised[:, overlap:]
                overlap = steps - 1 if getattr(args, 'denoiser_window', None) is None else args.denoiser_window
                s_idx += steps - overlap
        else:
            # Process entire batch for images
            x_all = apply_denoising(
                model, x_all, y_batch, text_encoder, tokenizer,
                args, text_encoder_kwargs, noise_std
            )

        torch.cuda.empty_cache()
        denoised_samples.append(x_all.detach().cpu())

    return torch.cat(denoised_samples, dim=0).cuda()


def simple_denoising(model, samples: torch.Tensor, y_encoded,
                     text_encoder, tokenizer, args, noise_std: float) -> torch.Tensor:
    """Simplified denoising for training - reuses apply_denoising without chunking."""
    if args.finetuned_vae != 'none' and args.finetuned_vae is not None:
        return samples

    # Reuse apply_denoising - it now handles both encoded tensors and raw captions
    text_encoder_kwargs = {}
    return apply_denoising(
        model, samples, y_encoded, text_encoder, tokenizer,
        args, text_encoder_kwargs, noise_std, sigma_next=0
    )