CristianLazoQuispe commited on
Commit
0a9cf85
·
1 Parent(s): 38c018e

mnist diff vs flow matching

Browse files
Files changed (7) hide show
  1. .gitignore +182 -0
  2. app.py +172 -0
  3. requirements.txt +4 -0
  4. src/__init__.py +1 -0
  5. src/dataset.py +23 -0
  6. src/model.py +86 -0
  7. src/utils.py +14 -0
.gitignore ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ models/
2
+ *.jpg
3
+ *.png
4
+ *.pth
5
+ data/MNIST/
6
+ flagged/
7
+ demo/flagged/
8
+
9
+ # Byte-compiled / optimized / DLL files
10
+ __pycache__/
11
+ *.py[cod]
12
+ *$py.class
13
+
14
+ # C extensions
15
+ *.so
16
+
17
+ # Distribution / packaging
18
+ .Python
19
+ build/
20
+ develop-eggs/
21
+ dist/
22
+ downloads/
23
+ eggs/
24
+ .eggs/
25
+ lib/
26
+ lib64/
27
+ parts/
28
+ sdist/
29
+ var/
30
+ wheels/
31
+ share/python-wheels/
32
+ *.egg-info/
33
+ .installed.cfg
34
+ *.egg
35
+ MANIFEST
36
+
37
+ # PyInstaller
38
+ # Usually these files are written by a python script from a template
39
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
40
+ *.manifest
41
+ *.spec
42
+
43
+ # Installer logs
44
+ pip-log.txt
45
+ pip-delete-this-directory.txt
46
+
47
+ # Unit test / coverage reports
48
+ htmlcov/
49
+ .tox/
50
+ .nox/
51
+ .coverage
52
+ .coverage.*
53
+ .cache
54
+ nosetests.xml
55
+ coverage.xml
56
+ *.cover
57
+ *.py,cover
58
+ .hypothesis/
59
+ .pytest_cache/
60
+ cover/
61
+
62
+ # Translations
63
+ *.mo
64
+ *.pot
65
+
66
+ # Django stuff:
67
+ *.log
68
+ local_settings.py
69
+ db.sqlite3
70
+ db.sqlite3-journal
71
+
72
+ # Flask stuff:
73
+ instance/
74
+ .webassets-cache
75
+
76
+ # Scrapy stuff:
77
+ .scrapy
78
+
79
+ # Sphinx documentation
80
+ docs/_build/
81
+
82
+ # PyBuilder
83
+ .pybuilder/
84
+ target/
85
+
86
+ # Jupyter Notebook
87
+ .ipynb_checkpoints
88
+
89
+ # IPython
90
+ profile_default/
91
+ ipython_config.py
92
+
93
+ # pyenv
94
+ # For a library or package, you might want to ignore these files since the code is
95
+ # intended to run in multiple environments; otherwise, check them in:
96
+ # .python-version
97
+
98
+ # pipenv
99
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
100
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
101
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
102
+ # install all needed dependencies.
103
+ #Pipfile.lock
104
+
105
+ # UV
106
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
107
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
108
+ # commonly ignored for libraries.
109
+ #uv.lock
110
+
111
+ # poetry
112
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
113
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
114
+ # commonly ignored for libraries.
115
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
116
+ #poetry.lock
117
+
118
+ # pdm
119
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
120
+ #pdm.lock
121
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
122
+ # in version control.
123
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
124
+ .pdm.toml
125
+ .pdm-python
126
+ .pdm-build/
127
+
128
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
129
+ __pypackages__/
130
+
131
+ # Celery stuff
132
+ celerybeat-schedule
133
+ celerybeat.pid
134
+
135
+ # SageMath parsed files
136
+ *.sage.py
137
+
138
+ # Environments
139
+ .env
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Ruff stuff:
179
+ .ruff_cache/
180
+
181
+ # PyPI configuration file
182
+ .pypirc
app.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import sys
4
+ import torch
5
+ import numpy as np
6
+ import gradio as gr
7
+ import matplotlib.pyplot as plt
8
+ from src.model import ConditionalUNet
9
+ from huggingface_hub import hf_hub_download
10
+
11
+ device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
12
+ img_shape = (1, 28, 28)
13
+
14
+
15
+ def resize(image,size=(200,200)):
16
+ stretch_near = cv2.resize(image, size, interpolation = cv2.INTER_LINEAR)
17
+ return stretch_near
18
+
19
+
20
+ model_diff = ConditionalUNet().to(device)
21
+ model_path = hf_hub_download(repo_id="CristianLazoQuispe/MNIST_Diff_Flow_matching", filename="outputs/diffusion/diffusion_model.pth",
22
+ cache_dir="models")
23
+ print("Diff Downloaded!")
24
+ model_diff.load_state_dict(torch.load(model_path, map_location=device))
25
+ model_diff.eval()
26
+
27
+
28
+ model_flow = ConditionalUNet().to(device)
29
+ model_path = hf_hub_download(repo_id="CristianLazoQuispe/MNIST_Diff_Flow_matching", filename="outputs/flow_matching/flow_model.pth",
30
+ cache_dir="models")
31
+ print("Flow Downloaded!")
32
+ model_flow.load_state_dict(torch.load(model_path, map_location=device))
33
+ model_flow.eval()
34
+
35
+ @torch.no_grad()
36
+ def generate_diffusion_intermediates(label):
37
+ timesteps = 500
38
+ img_shape = (1, 28, 28)
39
+ betas = torch.linspace(1e-4, 0.02, timesteps)
40
+ alphas = 1.0 - betas
41
+ alphas_cumprod = torch.cumprod(alphas, dim=0).to(device)
42
+
43
+ x = torch.randn(1, *img_shape).to(device)
44
+ y = torch.tensor([label], dtype=torch.long, device=device)
45
+ noise_magnitudes = []
46
+ intermediates = [resize(((x + 1) / 2.0)[0][0].clamp(0, 1).cpu().numpy())]
47
+
48
+ for t in reversed(range(timesteps)):
49
+ t_tensor = torch.full((x.size(0),), t, device=device, dtype=torch.float)
50
+ noise_pred = model_diff(x, t_tensor, y)
51
+ x = (1 / alphas[t].sqrt()) * (x - noise_pred * betas[t] / (1 - alphas_cumprod[t]).sqrt() )
52
+ if t > 0:
53
+ noise = torch.randn(1, *img_shape).to(device)
54
+ v = (1 - alphas_cumprod[t - 1]) / (1 - alphas_cumprod[t]) * betas[t]
55
+ x += v.sqrt() * noise
56
+
57
+ x = x.clamp(-1, 1)
58
+ if t in [400, 300, 200, 100,0]:
59
+ #print("t:",t)
60
+ img_np = ((x + 1) / 2)[0, 0].cpu().numpy()
61
+ intermediates.append(resize(img_np))
62
+
63
+ if t in [499, 399, 299, 199,99,0]:
64
+ # Compute velocity magnitude and convert to numpy for visualization
65
+ v_mag = noise_pred[0, 0].abs().clamp(0, 3).cpu().numpy() # Clamp to max value for better contrast
66
+ v_mag = (v_mag - v_mag.min()) / (v_mag.max() - v_mag.min() + 1e-5)
67
+ vel_colored = plt.get_cmap("coolwarm")(v_mag)[:, :, :3] # (H,W,3)
68
+ vel_colored = (vel_colored * 255).astype(np.uint8)
69
+ noise_magnitudes.append(resize(vel_colored, (100, 100)))
70
+
71
+ return intermediates+noise_magnitudes
72
+
73
+
74
+ def generate_localized_noise(shape, radius=5):
75
+ """Genera una imagen con ruido solo en un círculo en el centro."""
76
+ B, C, H, W = shape
77
+ assert C == 1, "Solo imágenes en escala de grises."
78
+
79
+ # Crear máscara circular
80
+ yy, xx = torch.meshgrid(torch.arange(H), torch.arange(W), indexing='ij')
81
+ center_y, center_x = H // 2, W // 2
82
+ mask = ((yy - center_y)**2 + (xx - center_x)**2) >= radius**2
83
+ mask = mask.float().unsqueeze(0).unsqueeze(0) # (1, 1, H, W)
84
+
85
+ # Aplicar máscara a ruido
86
+ noise = torch.randn(B, C, H, W)
87
+ localized_noise = noise * mask + -1*(1-mask) # solo hay ruido dentro del círculo
88
+ return localized_noise
89
+
90
+
91
+ @torch.no_grad()
92
+ def generate_flow_intermediates(label):
93
+ x = torch.randn(1, *img_shape).to(device)
94
+ #x = generate_localized_noise((1, 1, 28, 28), radius=12).to(device)
95
+ y = torch.full((1,), label, dtype=torch.long, device=device)
96
+ steps = 500
97
+ dt = 1.0 / steps
98
+
99
+ images = [(x + 1) / 2.0] # initial noise
100
+ vel_magnitudes = []
101
+ for i in range(steps):
102
+
103
+ t = torch.full((1,), i * dt, device=device)
104
+ v = model_flow(x, t, y)
105
+ x = x + v * dt
106
+
107
+ if i in [100,200,300,400,499]:
108
+ images.append((x + 1) / 2.0)
109
+ # Compute velocity magnitude and convert to numpy for visualization
110
+ if i in [0,100,200,300,400,499]:
111
+ v_mag = dt*v[0, 0].abs().clamp(0, 3).cpu().numpy() # Clamp to max value for better contrast
112
+ v_mag = (v_mag - v_mag.min()) / (v_mag.max() - v_mag.min() + 1e-5)
113
+ vel_colored = plt.get_cmap("coolwarm")(v_mag)[:, :, :3] # (H,W,3)
114
+ vel_colored = (vel_colored * 255).astype(np.uint8)
115
+ vel_magnitudes.append(resize(vel_colored, (100, 100)))
116
+
117
+ return [resize(images[0][0][0].clamp(0, 1).cpu().numpy())]+[resize(img[0][0].clamp(0, 1).cpu().numpy()) for img in images[-5:]]+vel_magnitudes
118
+
119
+ with gr.Blocks() as demo:
120
+ gr.Markdown("# Conditional MNIST Generation: Diffusion vs Flow Matching")
121
+
122
+ with gr.Tab("Diffusion"):
123
+ label_d = gr.Slider(0, 9, step=1, label="Digit Label")
124
+ btn_d = gr.Button("Generate")
125
+ with gr.Row():
126
+ outs_d = [
127
+ gr.Image(label="Noise"),
128
+ gr.Image(label="Diffusion t=400"),
129
+ gr.Image(label="Diffusion t=300"),
130
+ gr.Image(label="Diffusion t=200"),
131
+ gr.Image(label="Diffusion t=100"),
132
+ gr.Image(label="Diffusion t=0"),
133
+ ]
134
+ with gr.Row():
135
+ #400, 300, 200, 100,0
136
+ flow_noise_imgs = [
137
+ gr.Image(label="Noise pred t=500"),
138
+ gr.Image(label="Noise pred t=400"),
139
+ gr.Image(label="Noise pred t=300"),
140
+ gr.Image(label="Noise pred t=200"),
141
+ gr.Image(label="Noise pred t=100"),
142
+ gr.Image(label="Noise pred t=0")
143
+ ]
144
+ btn_d.click(fn=generate_diffusion_intermediates, inputs=label_d, outputs=outs_d+flow_noise_imgs)
145
+
146
+ with gr.Tab("Flow Matching"):
147
+ label_f = gr.Slider(0, 9, step=1, label="Digit Label")
148
+ btn_f = gr.Button("Generate")
149
+ with gr.Row():
150
+ outs_f = [
151
+ gr.Image(label="Noise"),
152
+ gr.Image(label="Flow step=100"),
153
+ gr.Image(label="Flow step=200"),
154
+ gr.Image(label="Flow step=300"),
155
+ gr.Image(label="Flow step=400"),
156
+ gr.Image(label="Flow step=499"),
157
+ ]
158
+ with gr.Row():
159
+ #100,200,300,400,499
160
+ flow_vel_imgs = [
161
+ gr.Image(label="Velocity step=0"),
162
+ gr.Image(label="Velocity step=100"),
163
+ gr.Image(label="Velocity step=200"),
164
+ gr.Image(label="Velocity step=300"),
165
+ gr.Image(label="Velocity step=400"),
166
+ gr.Image(label="Velocity step=499")
167
+ ]
168
+
169
+ btn_f.click(fn=generate_flow_intermediates, inputs=label_f, outputs=outs_f+flow_vel_imgs)
170
+
171
+ #demo.launch()
172
+ demo.launch(share=False, server_port=9070)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio==4.44.1
2
+ torch==2.0.0
3
+ opencv-python==4.6.0.66
4
+ numpy==1.26.4
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from . import *
src/dataset.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torchvision import datasets, transforms, utils
6
+ from torch.utils.data import DataLoader
7
+ from tqdm import tqdm
8
+
9
+
10
+
11
+ def get_data(batch_size):
12
+ # --- Dataset ---
13
+ transform = transforms.Compose([
14
+ transforms.ToTensor(),
15
+ transforms.Lambda(lambda x: x * 2 - 1)
16
+ ])
17
+ full_dataset = datasets.MNIST(root='data', train=True, download=True, transform=transform)
18
+ train_size = int(0.9 * len(full_dataset))
19
+ val_size = len(full_dataset) - train_size
20
+ train_dataset, val_dataset = torch.utils.data.random_split(full_dataset, [train_size, val_size])
21
+ train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
22
+ val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
23
+ return train_loader, val_loader
src/model.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # conditional_mnist_diffusion_flow.py
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torchvision import datasets, transforms, utils
6
+ from torch.utils.data import DataLoader
7
+ from tqdm import tqdm
8
+ import os
9
+ import sys
10
+ import numpy as np
11
+ import matplotlib.pyplot as plt
12
+
13
+
14
+ # --- Utilidades ---
15
+ def timestep_embedding(timesteps, dim):
16
+ half = dim // 2
17
+ freqs = torch.exp(-torch.arange(half, dtype=torch.float32) * torch.log(torch.tensor(10000.0)) / half)
18
+ args = timesteps[:, None].float() * freqs[None]
19
+ emb = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
20
+ if dim % 2:
21
+ emb = torch.cat([emb, torch.zeros_like(emb[:, :1])], dim=-1)
22
+ return emb
23
+
24
+
25
+ # --- Bloque residual con condición ---
26
+ class ResidualBlock(nn.Module):
27
+ def __init__(self, in_channels, out_channels, emb_channels):
28
+ super().__init__()
29
+ self.norm1 = nn.GroupNorm(1, in_channels)
30
+ self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)
31
+ self.emb_proj = nn.Linear(emb_channels, out_channels)
32
+ self.norm2 = nn.GroupNorm(1, out_channels)
33
+ self.dropout = nn.Dropout(0.1)
34
+ self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)
35
+ self.skip = nn.Conv2d(in_channels, out_channels, 1) if in_channels != out_channels else nn.Identity()
36
+
37
+ def forward(self, x, emb):
38
+ h = F.silu(self.norm1(x))
39
+ h = self.conv1(h)
40
+ h += self.emb_proj(F.silu(emb))[:, :, None, None]
41
+ h = F.silu(self.norm2(h))
42
+ h = self.dropout(h)
43
+ h = self.conv2(h)
44
+ return h + self.skip(x)
45
+
46
+
47
+ # --- UNet condicional ---
48
+ class ConditionalUNet(nn.Module):
49
+ def __init__(self, num_classes=10, base_channels=64):
50
+ super().__init__()
51
+ self.time_mlp = nn.Sequential(
52
+ nn.Linear(1, base_channels),
53
+ nn.SiLU(),
54
+ nn.Linear(base_channels, base_channels),
55
+ )
56
+ self.label_emb = nn.Embedding(num_classes, base_channels)
57
+
58
+ self.enc1 = ResidualBlock(1, base_channels, base_channels)
59
+ self.enc2 = ResidualBlock(base_channels, base_channels * 2, base_channels)
60
+ self.down = nn.Conv2d(base_channels * 2, base_channels * 2, 4, stride=2, padding=1)
61
+
62
+ self.mid = ResidualBlock(base_channels * 2, base_channels * 2, base_channels)
63
+
64
+ self.up = nn.ConvTranspose2d(base_channels * 2, base_channels * 2, 4, stride=2, padding=1)
65
+ self.dec2 = ResidualBlock(base_channels * 4, base_channels, base_channels)
66
+ self.dec1 = ResidualBlock(base_channels * 2, base_channels, base_channels)
67
+
68
+ self.out_norm = nn.GroupNorm(8, base_channels)
69
+ self.out_conv = nn.Conv2d(base_channels, 1, 3, padding=1)
70
+
71
+ def forward(self, x, t, y):
72
+ emb_t = self.time_mlp(t.view(-1, 1))
73
+ emb_y = self.label_emb(y)
74
+ emb = emb_t + emb_y
75
+
76
+ x1 = self.enc1(x, emb)
77
+ x2 = self.enc2(x1, emb)
78
+ x3 = self.down(x2)
79
+ m = self.mid(x3, emb)
80
+ u = self.up(m)
81
+
82
+ d2 = self.dec2(torch.cat([u, x2], dim=1), emb)
83
+ d1 = self.dec1(torch.cat([d2, x1], dim=1), emb)
84
+
85
+ out = self.out_conv(F.silu(self.out_norm(d1)))
86
+ return out
src/utils.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import random
4
+ import numpy as np
5
+
6
+
7
+ def set_seed(seed):
8
+ random.seed(seed)
9
+ np.random.seed(seed)
10
+ os.environ["PYTHONHASHSEED"] = str(seed)
11
+ torch.manual_seed(seed)
12
+ torch.cuda.manual_seed(seed)
13
+ torch.cuda.manual_seed_all(seed)
14
+ torch.backends.cudnn.deterministic = True