File size: 9,290 Bytes
c865888
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import numpy as np
import random
import pandas as pd
import math
from tqdm import tqdm
import time

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader

import Stage3_source.preprocess as prep
import Stage3_source.cond_diff_transformer_layer as mod
import Stage3_source.transformer_training_helper as train_helper



# generate missing pixels with one shot
@torch.no_grad()
def cond_autocomplete_real_samples(
        model: nn.Module,
        args: any,
        realization: torch.Tensor,
        y_c: torch.Tensor,
        idx: torch.Tensor
    ) -> (
            any,
            torch.Tensor,
            torch.Tensor,
            torch.Tensor,
            torch.Tensor
    ):

        model.eval()
        bs, channel, seq_length = realization.size()
        # get a batch of random sampling paths
        sampled_random_path = train_helper.sample_random_path(bs, seq_length, device=args.device)
        # create a mask that masks the locations where we've already sampled
        random_path_mask = train_helper.create_mask_at_random_path_index(sampled_random_path, idx, bs, seq_length)
        # tokenize realizations 
        real_tokens, bs, seq_length= train_helper.create_token_labels(args, realization)
        #real_tokens = realization.clone().squeeze(1)

        # mask realizations 
        real_token_masked =  train_helper.mask_realizations(real_tokens, random_path_mask)
        # conditional probability
        conditional_prob, probs = train_helper.cond_predict_conditional_prob(model, real_token_masked, y_c, idx, args)
        # evaluate the value of the log probability for the given realization:
        log_prob = train_helper.log_prob_of_realization(args, conditional_prob, real_tokens)
        
        return (
                conditional_prob,
                probs.cpu(),
                real_token_masked.cpu(),
                real_tokens.cpu(),
                log_prob.cpu(),
                sampled_random_path.cpu(),
                random_path_mask.cpu()
        )


# get the label for the corresponding sequence in the dataloader
def extract_samples_with_labels(
        dataloader: DataLoader,
        target_labels: int,
        total_num: int,
        pad_included: bool=False
    ) -> dict:

    extracted_sampled = {
            'sample': [],
            'label': []
    }

    for data, labels in dataloader:
        for i, label in enumerate(labels):

            if label.item() == target_labels:

                if pad_included:
                    pass
                else:
                    data[i] += 1 # account for the absorbing state (i.e. make room)

                extracted_sampled['sample'].append(data[i]) # account for abosrbed state
                extracted_sampled['label'].append(label)
                if len(extracted_sampled['label']) == total_num:
                    return extracted_sampled

    return extracted_sampled


# mask a given percentage of the sample
def corrupt_samples(
        args: any,
        realization: torch.Tensor,
        perc: float
    ) -> torch.Tensor:

    bs, channels, seq_length = realization.size()

    # number of samples to corrupt (i.e. idx)
    idx = (args.diffusion_steps * torch.Tensor([perc])).to(int).to(args.device)
    # get a batch of random sampling paths
    sampled_random_path = train_helper.sample_random_path(bs, seq_length, device=args.device)
    # we create a mask that masks the locations where we've already sampled
    random_path_mask = train_helper.create_mask_at_random_path_index(sampled_random_path, idx, bs, seq_length)
    # tokenize realizations 
    real_tokens, bs, seq_length= train_helper.create_token_labels(args, realization)
    # mask realizations 
    real_token_masked = train_helper.mask_realizations(real_tokens, random_path_mask)

    return (
            real_token_masked,
            sampled_random_path,
            idx
    )

# inpaint missing regions by predicting the next position
@torch.no_grad()
def predict_next_index(
        model: nn.Module,
        args: any,
        mask_realization: torch.Tensor,
        y_c: torch.Tensor,
        idx: torch.Tensor
    ) -> (
            any,
            torch.Tensor,
            torch.Tensor,
            torch.Tensor,
            torch.Tensor,
            torch.Tensor
    ):

        model.eval()
        bs, channel, seq_length = mask_realization.size()

        # conditional prob
        conditional_prob, probs = train_helper.cond_predict_conditional_prob(model, mask_realization.squeeze(1), y_c, idx, args)
        
        return (
                conditional_prob,
                probs.cpu(),
        )




def generate_denoised_sampled(
        args: any,
        model: nn.Module,
        extract_digit_samples: torch.Tensor,
        extract_time: torch.Tensor,
        extract_digit_label: torch.Tensor,
        sampling_path: torch.Tensor
    ) -> (
            list,
            list
    ):

        mask_realization_list, time_idx_list = [], []

        # prepare data
        temp_y_c = extract_digit_label.to(args.device)
        temp_mask_realization = extract_digit_samples.unsqueeze(1).long().to(args.device)
        temp_idx = torch.Tensor([extract_time]).to(args.device).squeeze(0)
        temp_sampling_path = sampling_path.to(args.device)
        
        for ii in tqdm(range(int(temp_idx.item()), args.diffusion_steps)):
            
            # where we need to sample next
            current_location = temp_sampling_path == temp_idx
            print(current_location.shape)

            # make position prediction
            conditional_prob, prob  = predict_next_index(
                    model=model,
                    args=args,
                    mask_realization=temp_mask_realization,
                    y_c=temp_y_c,
                    idx=temp_idx
            )

            # get the label for the next token position
            next_temp_realization = torch.argmax(
                    conditional_prob.sample(), dim=-1
            )

            temp_mask_realization[0, current_location] = next_temp_realization[current_location]
            mask_realization_list.append(temp_mask_realization.cpu().numpy())
            time_idx_list.append(temp_idx.cpu().numpy())
            temp_idx+=1


        return (
                mask_realization_list,
                time_idx_list
        )


def batch_generate_denoised_sampled(
        args: any,
        model: nn.Module,
        extract_digit_samples: torch.Tensor,
        extract_time: torch.Tensor,
        extract_digit_label: torch.Tensor,
        sampling_path: torch.Tensor
    ) -> (list, list):

    # Ensure batch dimension consistency across input tensors
    assert extract_digit_samples.size(0) == extract_digit_label.size(0) == sampling_path.size(0) == extract_time.size(0), "Mismatched batch dimensions"

    batch_size = extract_digit_samples.size(0)
    mask_realization_list, time_idx_list = [], []
    print('batch_size:', batch_size)

    # Prepare data
    temp_y_c = extract_digit_label.to(args.device)
    temp_mask_realization = extract_digit_samples.unsqueeze(1).long().to(args.device)
    temp_idx = extract_time.unsqueeze(-1).to(args.device)  # Adding an extra dimension for batch processing
    temp_sampling_path = sampling_path.to(args.device)
    print(f"Starting temp_idx: {temp_idx[0].item()}")
    
    start_time_index = temp_idx[0].item() # assume all temp_idx is the same values
    max_diffusion_step = args.diffusion_steps # max number of timesteps 
    

    for ii in tqdm(range(start_time_index, max_diffusion_step), initial=start_time_index, total=max_diffusion_step):
       
        # Check if any temp_idx has reached or exceeded diffusion_steps
        if torch.any(temp_idx >= args.diffusion_steps):
            break

        # Broadcast ii to match the batch size
        current_ii = torch.full((batch_size,), ii, dtype=torch.long, device=args.device)

        # Make position prediction
        conditional_prob, prob = predict_next_index(
                model=model,
                args=args,
                mask_realization=temp_mask_realization,
                y_c=temp_y_c,
                idx=temp_idx
        )
    

        # Get the label for the next token position
        next_temp_realization = torch.argmax(conditional_prob.sample(), dim=-1)

        # Update temp_mask_realization for each item in the batch
        current_location = temp_sampling_path == temp_idx  # Adding an extra dimension for comparison
        current_location = torch.argmax(current_location.detach().cpu()*1, dim=-1)
        temp_mask_realization[:, 0, current_location] = next_temp_realization[:,current_location]
        
        # Append results for each item in the batch
        mask_realization_list.append(temp_mask_realization.cpu().numpy())
        time_idx_list.append(temp_idx.cpu().numpy())

        # Increment temp_idx for the next iteration
        temp_idx += 1

    return mask_realization_list, time_idx_list



# convert sequence with numerical variables into character letters
def convert_num_to_chars(
        tokenizer: any,
        num_seq: list
    ) -> list:

    char_seq = [tokenizer[num] for num in num_seq]
    return "".join(char_seq)