dedelste commited on
Commit
1156de8
·
0 Parent(s):

first try

Browse files
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
ambient_diffusion.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ All-in-one utilities for Ambient Diffusion (random-inpainting variant).
3
+
4
+ Implements
5
+ ----------
6
+ sample_inpainting_mask - A (Eq. 3.1)
7
+ further_corrupt - ~A (Eq. 3.2)
8
+ make_ambient_batch - build (~A x_t , A) for training
9
+ ambient_loss - J_corr (Eq. 3.2)
10
+ AmbientDDPMPipeline - fixed-mask sampler (Eq. 3.3)
11
+ """
12
+
13
+ from __future__ import annotations
14
+ import torch
15
+ from torch import Tensor
16
+ from typing import Tuple, Optional
17
+ from diffusers.schedulers.scheduling_ddpm import DDPMScheduler
18
+ from diffusers import DDPMPipeline
19
+
20
+ # ------------------------------------------------------------------
21
+ # Corruptions
22
+ # ------------------------------------------------------------------
23
+
24
+ def sample_inpainting_mask(
25
+ shape: Tuple[int, int, int, int],
26
+ p: float = 0.9,
27
+ device: torch.device | str | None = None,
28
+ ) -> Tensor:
29
+ """Diagonal Bernoulli mask A: 1 = keep, 0 = erase."""
30
+ B, C, H, W = shape
31
+ return torch.bernoulli(torch.full((B, 1, H, W), p, device=device)).expand(-1, C, -1, -1)
32
+
33
+
34
+ def further_corrupt(A: Tensor, delta: float = 0.05) -> Tensor:
35
+ """Sample ~A = B A by turning surviving pixels off with prob delta."""
36
+ B_mat = torch.bernoulli(torch.full_like(A, 1.0 - delta))
37
+ return B_mat * A
38
+
39
+ # ------------------------------------------------------------------
40
+ # Training helpers
41
+ # ------------------------------------------------------------------
42
+
43
+ def make_ambient_batch(
44
+ clean: Tensor,
45
+ noise_scheduler: DDPMScheduler,
46
+ timesteps: Tensor,
47
+ p: float = 0.9,
48
+ delta: float = 0.05,
49
+ ) -> tuple[Tensor, Tensor]:
50
+ """
51
+ Returns:
52
+ y_t_tilde : ~A x_t (to feed the network)
53
+ A_mask : A (needed only for the loss)
54
+ """
55
+ B, C, H, W = clean.shape
56
+ device = clean.device
57
+
58
+ # 1. A x₀
59
+ A = sample_inpainting_mask((B, C, H, W), p=p, device=device)
60
+
61
+ # 2. add diffusion noise → x_t , then A x_t
62
+ noise = torch.randn_like(clean)
63
+
64
+ if timesteps.ndim == 0:
65
+ timesteps = torch.full((B,), timesteps, device=device, dtype=torch.long)
66
+ elif timesteps.shape[0] != B:
67
+ raise ValueError(f"Timesteps batch size {timesteps.shape[0]} does not match input batch size {B}")
68
+
69
+ x_t = noise_scheduler.add_noise(clean, noise, timesteps)
70
+
71
+ # 3. ~A x_t
72
+ A_tilde = further_corrupt(A, delta=delta)
73
+ mask_ch = A_tilde[:, :1] # (B,1,H,W)
74
+ net_input = torch.cat([A_tilde * x_t, mask_ch], dim=1)
75
+ return net_input, A
76
+
77
+ def ambient_loss(pred, clean, A_mask, snr_weights=None):
78
+ """
79
+ Masked L2 loss with optional SNR weights (Eq. 2 in the paper).
80
+ """
81
+ diff = A_mask * (pred - clean)
82
+ loss = 0.5 * diff.pow(2)
83
+ if snr_weights is not None:
84
+ loss = snr_weights * loss
85
+ return loss.mean()
86
+ # ------------------------------------------------------------------
87
+ # Sampler
88
+ # ------------------------------------------------------------------
89
+
90
+ class AmbientDDPMPipeline(DDPMPipeline):
91
+ """
92
+ Fixed-mask sampler (Eq. 3.3). Drop-in replacement for DDPMPipeline.
93
+ """
94
+
95
+ def __init__(self, *, unet, scheduler, p_mask: float = 0.9):
96
+ # 1) Let base class register the trainable modules
97
+ super().__init__(unet=unet, scheduler=scheduler)
98
+
99
+ # 2) Store hyper‑parameter in the *config* **and** as an attribute
100
+ self.register_to_config(p_mask=p_mask) # guarantees serialisation
101
+ self.p_mask = p_mask # convenient runtime access
102
+
103
+ @torch.no_grad()
104
+ def __call__(
105
+ self,
106
+ batch_size: int = 1,
107
+ generator: Optional[torch.Generator] = None,
108
+ num_inference_steps: int = 250,
109
+ class_labels: Optional[torch.Tensor] = None,
110
+ guidance_scale: float = 1.5,
111
+ output_type: str = "pt",
112
+ return_dict: bool = True,
113
+ ):
114
+ device = self.device
115
+ h = w = self.unet.config.sample_size
116
+
117
+ mask = sample_inpainting_mask(
118
+ (batch_size, 1, h, w), p=self.p_mask, device=device
119
+ )
120
+
121
+ x = torch.randn(
122
+ (batch_size, 1, h, w),
123
+ generator=generator,
124
+ device=device,
125
+ )
126
+
127
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
128
+
129
+
130
+ if class_labels is None:
131
+ cond_lbls = torch.zeros(
132
+ (batch_size,
133
+ getattr(self.unet.config, "multihot_dim", 1)),
134
+ dtype=torch.long if not hasattr(self.unet.config, "multihot_dim") else torch.float,
135
+ device=device,
136
+ )
137
+ else:
138
+ cond_lbls = class_labels.to(device)
139
+
140
+ uncond_lbls = torch.zeros_like(cond_lbls)
141
+
142
+ for t in self.scheduler.timesteps:
143
+
144
+ if guidance_scale == 1.0 or class_labels is None:
145
+ # single unconditional (or conditional) pass
146
+ net_inp = torch.cat([mask * x, mask[:, :1]], dim=1)
147
+ eps = self.unet(net_inp, t, class_labels=cond_lbls).sample
148
+ else:
149
+ # duplicate batch: cond | uncond
150
+ net_inp = torch.cat([mask * x, mask[:, :1]], dim=1) # (B,C+1,H,W)
151
+ inp = torch.cat([net_inp, net_inp], dim=0) # (2B,C+1,H,W)
152
+ lbls = torch.cat([cond_lbls, uncond_lbls], dim=0)
153
+ tids = t.expand(2 * batch_size)
154
+
155
+ eps_cond, eps_uncond = (
156
+ self.unet(inp, tids, class_labels=lbls).sample.chunk(2)
157
+ )
158
+ eps = eps_uncond + guidance_scale * (eps_cond - eps_uncond)
159
+
160
+ # ---------- Eq. 3.3 update (must be INSIDE the loop) ----------
161
+ x0_hat = eps
162
+ sigma = self.scheduler._get_variance(t).sqrt()
163
+ gamma = sigma ** 2 / (sigma ** 2 + 1)
164
+ x = gamma * x + (1 - gamma) * x0_hat
165
+ x = self.scheduler.step(eps, t, x).prev_sample
166
+
167
+ x = (x / 2 + 0.5).clamp(0, 1)
168
+ img = x.cpu().permute(0, 2, 3, 1).numpy()
169
+ if output_type == "pil":
170
+ img = self.numpy_to_pil(img)
171
+ return dict(images=img) if return_dict else (img,)
app.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Example: app.py for the Inference Endpoint
2
+ import os
3
+ import torch
4
+ from PIL import Image
5
+ import numpy as np
6
+ from diffusers import DDPMScheduler
7
+ import base64
8
+ from io import BytesIO
9
+
10
+ try:
11
+ from cfg_diffusion import CustomClassConditionedUnet
12
+ from conditional_ddpm_pipeline import ConditionalDDPMPipeline
13
+ from ambient_diffusion import AmbientDDPMPipeline
14
+ from constants import CHEXPERT_CLASSES as _CHEXPERT_CLASSES
15
+ except ImportError as e:
16
+ print(f"Error importing from src: {e}. Ensure 'src' directory is structured correctly in the repo.")
17
+ _CHEXPERT_CLASSES = [
18
+ "No Finding", "Enlarged Cardiomediastinum", "Cardiomegaly", "Lung Opacity",
19
+ "Lung Lesion", "Edema", "Consolidation", "Pneumonia", "Atelectasis",
20
+ "Pneumothorax", "Pleural Effusion", "Pleural Other", "Fracture", "Support Devices"
21
+ ]
22
+ raise e
23
+
24
+
25
+ class EndpointHandler:
26
+ def __init__(self, model_dir="."):
27
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
28
+ self.model_dir = model_dir
29
+ self.loaded_unets_cache = {} # Cache for {variant_name: unet_model}
30
+ self.loaded_schedulers_cache = {} # Cache for {variant_name: scheduler_instance}
31
+ print(f"Initializing EndpointHandler on device: {self.device}")
32
+
33
+ default_scheduler_path = os.path.join(self.model_dir, "scheduler")
34
+ if os.path.exists(os.path.join(default_scheduler_path, "scheduler_config.json")):
35
+ self.default_scheduler_config_path = default_scheduler_path
36
+ print(f"Found default scheduler config at {default_scheduler_path}")
37
+ else:
38
+ self.default_scheduler_config_path = None
39
+ print(f"Default scheduler config not found at {default_scheduler_path}. Will create default DDPMScheduler if needed.")
40
+
41
+ print("EndpointHandler initialized.")
42
+
43
+ def _check_unet_files_exist(self, unet_path: str) -> bool:
44
+ config_path = os.path.join(unet_path, "config.json")
45
+ weights_bin_path = os.path.join(unet_path, "diffusion_pytorch_model.bin")
46
+ weights_safetensors_path = os.path.join(unet_path, "diffusion_pytorch_model.safetensors")
47
+ return os.path.exists(config_path) and (os.path.exists(weights_bin_path) or os.path.exists(weights_safetensors_path))
48
+
49
+ def _get_or_load_unet(self, model_variant_name: str):
50
+ if model_variant_name in self.loaded_unets_cache:
51
+ print(f"Using cached UNet for variant: {model_variant_name}")
52
+ return self.loaded_unets_cache[model_variant_name]
53
+
54
+ unet_load_path_primary = os.path.join(self.model_dir, f"unet_{model_variant_name}")
55
+ unet_load_path_final = None
56
+
57
+ if self._check_unet_files_exist(unet_load_path_primary):
58
+ unet_load_path_final = unet_load_path_primary
59
+ elif model_variant_name == "conditional": # Fallback for "conditional" to try "unet_cfg"
60
+ unet_load_path_fallback = os.path.join(self.model_dir, "unet_cfg")
61
+ if self._check_unet_files_exist(unet_load_path_fallback):
62
+ unet_load_path_final = unet_load_path_fallback
63
+ else:
64
+ raise FileNotFoundError(f"UNet for variant '{model_variant_name}' not found at {unet_load_path_primary} or {unet_load_path_fallback}. Required: config.json and (diffusion_pytorch_model.bin or .safetensors)")
65
+ else:
66
+ raise FileNotFoundError(f"UNet for variant '{model_variant_name}' not found at {unet_load_path_primary}. Required: config.json and (diffusion_pytorch_model.bin or .safetensors)")
67
+
68
+ print(f"Loading UNet for variant '{model_variant_name}' from {unet_load_path_final}...")
69
+ unet = CustomClassConditionedUnet.from_pretrained(unet_load_path_final).to(self.device)
70
+ unet.eval()
71
+ self.loaded_unets_cache[model_variant_name] = unet
72
+ print(f"Loaded and cached UNet for {model_variant_name} with in_channels: {unet.config.in_channels}")
73
+ return unet
74
+
75
+ def _get_or_load_scheduler(self, model_variant_name: str, pipeline_type: str):
76
+ scheduler_key = f"scheduler_for_{pipeline_type}"
77
+
78
+ if scheduler_key in self.loaded_schedulers_cache:
79
+ print(f"Using cached scheduler configured for {pipeline_type}")
80
+ return self.loaded_schedulers_cache[scheduler_key]
81
+
82
+ if self.default_scheduler_config_path:
83
+ scheduler = DDPMScheduler.from_pretrained(self.default_scheduler_config_path)
84
+ print(f"Loaded base scheduler from {self.default_scheduler_config_path}")
85
+ else:
86
+ scheduler = DDPMScheduler(num_train_timesteps=1000, beta_schedule="linear")
87
+ print("Created new default DDPMScheduler instance.")
88
+
89
+ if pipeline_type == "ambient":
90
+ scheduler.config.prediction_type = "sample"
91
+ else:
92
+ scheduler.config.prediction_type = "epsilon"
93
+
94
+ print(f"Scheduler configured with prediction_type: '{scheduler.config.prediction_type}' for {pipeline_type} pipeline.")
95
+ self.loaded_schedulers_cache[scheduler_key] = scheduler
96
+ return scheduler
97
+
98
+ def __call__(self, data: dict) -> dict:
99
+ inputs = data.pop("inputs", data)
100
+ model_variant = inputs.get("model_variant", "conditional").lower()
101
+ pipeline_type = inputs.get("pipeline_type", model_variant).lower()
102
+ conditions_input = inputs.get("conditions", ["No Finding"])
103
+ guidance_scale = float(inputs.get("guidance_scale", 3.0))
104
+ seed = int(inputs.get("seed", 42))
105
+ num_inference_steps = int(inputs.get("num_inference_steps", 50))
106
+ p_mask = float(inputs.get("p_mask", 0.9))
107
+
108
+ print(f"Request: model_variant='{model_variant}', pipeline_type='{pipeline_type}', conditions='{conditions_input}', guidance={guidance_scale}, seed={seed}, steps={num_inference_steps}")
109
+
110
+ try:
111
+ unet_to_use = self._get_or_load_unet(model_variant)
112
+ scheduler_to_use = self._get_or_load_scheduler(model_variant, pipeline_type)
113
+ except FileNotFoundError as e:
114
+ print(f"Error loading model components: {e}")
115
+ return {"error": str(e)}
116
+ except Exception as e:
117
+ print(f"Unexpected error during model/scheduler loading: {e}")
118
+ return {"error": f"Unexpected error loading components: {str(e)}"}
119
+
120
+ unet_in_channels = unet_to_use.config.in_channels
121
+ active_pipeline = None
122
+
123
+ if pipeline_type == "conditional":
124
+ if unet_in_channels != 1:
125
+ error_msg = f"UNet incompatible: Requested conditional pipeline, but loaded UNet '{model_variant}' has {unet_in_channels} input channels (expected 1)."
126
+ print(error_msg)
127
+ return {"error": error_msg}
128
+ if scheduler_to_use.config.prediction_type != "epsilon":
129
+ print(f"Warning: Conditional pipeline expects 'epsilon' prediction, but scheduler is '{scheduler_to_use.config.prediction_type}'. Forcing to 'epsilon'.")
130
+ scheduler_to_use.config.prediction_type = "epsilon"
131
+ active_pipeline = ConditionalDDPMPipeline(unet=unet_to_use, scheduler=scheduler_to_use)
132
+ print(f"Using ConditionalDDPMPipeline with UNet '{model_variant}'.")
133
+
134
+ elif pipeline_type == "ambient":
135
+ if unet_in_channels != 2:
136
+ error_msg = f"UNet incompatible: Requested ambient pipeline, but loaded UNet '{model_variant}' has {unet_in_channels} input channels (expected 2 for image+mask)."
137
+ print(error_msg)
138
+ return {"error": error_msg}
139
+ if scheduler_to_use.config.prediction_type != "sample":
140
+ print(f"Warning: Ambient pipeline expects 'sample' prediction, but scheduler is '{scheduler_to_use.config.prediction_type}'. Forcing to 'sample'.")
141
+ scheduler_to_use.config.prediction_type = "sample"
142
+ active_pipeline = AmbientDDPMPipeline(unet=unet_to_use, scheduler=scheduler_to_use, p_mask=p_mask)
143
+ print(f"Using AmbientDDPMPipeline with UNet '{model_variant}' and p_mask: {p_mask}.")
144
+ else:
145
+ error_msg = f"Invalid pipeline_type: '{pipeline_type}'. Choose 'conditional' or 'ambient'."
146
+ print(error_msg)
147
+ return {"error": error_msg}
148
+
149
+ condition_vector = torch.zeros(len(_CHEXPERT_CLASSES), device=self.device)
150
+ for cond_name in conditions_input:
151
+ if cond_name in _CHEXPERT_CLASSES:
152
+ condition_index = _CHEXPERT_CLASSES.index(cond_name)
153
+ condition_vector[condition_index] = 1.0
154
+ class_labels = condition_vector.unsqueeze(0).float()
155
+
156
+ generator = torch.Generator(device=self.device).manual_seed(seed)
157
+
158
+ print(f"Starting inference with {pipeline_type} pipeline using UNet '{model_variant}'...")
159
+ with torch.no_grad():
160
+ result = active_pipeline(
161
+ batch_size=1, generator=generator, num_inference_steps=num_inference_steps,
162
+ output_type="np", class_labels=class_labels, guidance_scale=guidance_scale
163
+ )
164
+ image_np = result["images"][0]
165
+ print("Inference complete.")
166
+
167
+ if image_np.ndim == 3 and image_np.shape[2] == 1: # Ensure it's grayscale C=1
168
+ image_np = np.repeat(image_np, 3, axis=2) # Convert to C=3 for PNG
169
+ elif image_np.ndim == 2: # Grayscale H,W
170
+ image_np = np.stack((image_np,)*3, axis=-1) # Convert to H,W,3
171
+
172
+ image_np = (image_np * 255).round().astype("uint8")
173
+ pil_image = Image.fromarray(image_np)
174
+
175
+ buffered = BytesIO()
176
+ pil_image.save(buffered, format="PNG")
177
+ image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
178
+ print("Image processed and encoded to base64.")
179
+
180
+ return {"generated_image_base64": image_base64, "model_variant_used": model_variant, "pipeline_used": pipeline_type}
cfg_diffusion.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Classifier-Free Guidance implementation using the diffusers library.
3
+ """
4
+
5
+ import torch.nn as nn
6
+ from diffusers import UNet2DModel
7
+
8
+ class CustomClassConditionedUnet(UNet2DModel):
9
+ """UNet2DModel adapted for multi-hot classification vectors"""
10
+
11
+ def __init__(
12
+ self,
13
+ sample_size,
14
+ in_channels=1,
15
+ out_channels=1,
16
+ layers_per_block=2,
17
+ block_out_channels=(128, 128, 256, 256, 512, 512),
18
+ down_block_types=(
19
+ "DownBlock2D",
20
+ "DownBlock2D",
21
+ "DownBlock2D",
22
+ "DownBlock2D",
23
+ "AttnDownBlock2D",
24
+ "DownBlock2D",
25
+ ),
26
+ up_block_types=(
27
+ "UpBlock2D",
28
+ "AttnUpBlock2D",
29
+ "UpBlock2D",
30
+ "UpBlock2D",
31
+ "UpBlock2D",
32
+ "UpBlock2D",
33
+ ),
34
+ multihot_dim=14,
35
+ **kwargs,
36
+ ):
37
+ # Remove conflicting parameters if they exist
38
+ kwargs.pop("class_embed_type", None)
39
+ kwargs.pop("num_class_embeds", None)
40
+
41
+ # Initialize the base model without class conditioning
42
+ super().__init__(
43
+ sample_size=sample_size,
44
+ in_channels=in_channels,
45
+ out_channels=out_channels,
46
+ layers_per_block=layers_per_block,
47
+ block_out_channels=block_out_channels,
48
+ down_block_types=down_block_types,
49
+ up_block_types=up_block_types,
50
+ **kwargs,
51
+ )
52
+
53
+ # Compute the time embedding dimension
54
+ time_embed_dim = block_out_channels[0] * 4
55
+
56
+ # Replace the class embedding with a linear layer for multihot vectors
57
+ self.class_embedding = nn.Linear(multihot_dim, time_embed_dim)
58
+
59
+ # Save the multihot dimension
60
+ self.config.multihot_dim = multihot_dim
61
+
62
+ def forward(self, sample, timestep, class_labels=None, return_dict=True):
63
+ """
64
+ Forward pass that accepts multi-hot vectors for class_labels
65
+
66
+ Args:
67
+ sample: Image tensor [batch_size, channels, height, width]
68
+ timestep: Time steps [batch_size] or scalar
69
+ class_labels: Multi-hot vector [batch_size, multihot_dim]
70
+ return_dict: Whether to return a dictionary or just the sample
71
+
72
+ Returns:
73
+ Model prediction (noise or clean image depending on configuration)
74
+ """
75
+ return super().forward(sample, timestep, class_labels, return_dict)
conditional_ddpm_pipeline.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Create a conditional pipeline that matches the original closely
2
+ from diffusers import DDPMPipeline
3
+ import torch
4
+
5
+
6
+ class ConditionalDDPMPipeline(DDPMPipeline):
7
+ """DDPM Pipeline with class conditioning support"""
8
+
9
+ def __call__(
10
+ self,
11
+ batch_size=1,
12
+ generator=None,
13
+ num_inference_steps=1000,
14
+ output_type="pil",
15
+ class_labels=None,
16
+ guidance_scale=1.5,
17
+ return_dict=True,
18
+ ):
19
+ # Initialize with random noise (exactly like original)
20
+ image = torch.randn(
21
+ (
22
+ batch_size,
23
+ self.unet.config.in_channels,
24
+ self.unet.config.sample_size,
25
+ self.unet.config.sample_size,
26
+ ),
27
+ generator=generator,
28
+ device=self.device,
29
+ )
30
+
31
+ # Setup the scheduler (exactly like original)
32
+ self.scheduler.set_timesteps(num_inference_steps)
33
+
34
+ # Denoising process
35
+ for t in self.scheduler.timesteps:
36
+ # Only difference is we pass class_labels to the model
37
+ with torch.no_grad():
38
+ if guidance_scale > 1.0 and class_labels is not None:
39
+ # Conditional pass
40
+ cond_output = self.unet(
41
+ image, t, class_labels=class_labels
42
+ ).sample
43
+
44
+ # Unconditional pass
45
+ uncond_labels = torch.zeros_like(class_labels)
46
+ uncond_output = self.unet(
47
+ image, t, class_labels=uncond_labels
48
+ ).sample
49
+
50
+ # Combine with guidance scale
51
+ model_output = uncond_output + guidance_scale * (
52
+ cond_output - uncond_output
53
+ )
54
+ else:
55
+ # Standard pass with conditioning
56
+ model_output = self.unet(
57
+ image, t, class_labels=class_labels
58
+ ).sample
59
+
60
+ # Scheduler step (exactly like original)
61
+ image = self.scheduler.step(
62
+ model_output, t, image, generator=generator
63
+ ).prev_sample
64
+
65
+ # Final processing (exactly like original)
66
+ image = (image / 2 + 0.5).clamp(0, 1)
67
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
68
+
69
+ if output_type == "pil":
70
+ image = self.numpy_to_pil(image)
71
+
72
+ if not return_dict:
73
+ return (image,)
74
+
75
+ return dict(images=image)
constants.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Constants used throughout the project.
3
+ """
4
+
5
+ # CheXpert class labels
6
+ CHEXPERT_CLASSES = [
7
+ "No Finding",
8
+ "Enlarged Cardiomediastinum",
9
+ "Cardiomegaly",
10
+ "Lung Opacity",
11
+ "Lung Lesion",
12
+ "Edema",
13
+ "Consolidation",
14
+ "Pneumonia",
15
+ "Atelectasis",
16
+ "Pneumothorax",
17
+ "Pleural Effusion",
18
+ "Pleural Other",
19
+ "Fracture",
20
+ "Support Devices",
21
+ ]
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ diffusers==0.33.1
2
+ numpy==2.2.6
3
+ Pillow==11.2.1
4
+ torch==2.7.0+gpu
unet_ambient/config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "CustomClassConditionedUnet",
3
+ "_diffusers_version": "0.32.2",
4
+ "act_fn": "silu",
5
+ "add_attention": true,
6
+ "attention_head_dim": 8,
7
+ "attn_norm_num_groups": null,
8
+ "block_out_channels": [
9
+ 128,
10
+ 128,
11
+ 256,
12
+ 256,
13
+ 512,
14
+ 512
15
+ ],
16
+ "center_input_sample": false,
17
+ "class_embed_type": null,
18
+ "decay": 0.9999,
19
+ "down_block_types": [
20
+ "DownBlock2D",
21
+ "DownBlock2D",
22
+ "DownBlock2D",
23
+ "DownBlock2D",
24
+ "AttnDownBlock2D",
25
+ "DownBlock2D"
26
+ ],
27
+ "downsample_padding": 1,
28
+ "downsample_type": "conv",
29
+ "dropout": 0.0,
30
+ "flip_sin_to_cos": true,
31
+ "freq_shift": 0,
32
+ "in_channels": 2,
33
+ "inv_gamma": 1.0,
34
+ "layers_per_block": 2,
35
+ "mid_block_scale_factor": 1,
36
+ "min_decay": 0.0,
37
+ "norm_eps": 1e-05,
38
+ "norm_num_groups": 32,
39
+ "num_class_embeds": null,
40
+ "num_train_timesteps": null,
41
+ "optimization_step": 119500,
42
+ "out_channels": 1,
43
+ "power": 0.75,
44
+ "resnet_time_scale_shift": "default",
45
+ "sample_size": 128,
46
+ "time_embedding_dim": null,
47
+ "time_embedding_type": "positional",
48
+ "up_block_types": [
49
+ "UpBlock2D",
50
+ "AttnUpBlock2D",
51
+ "UpBlock2D",
52
+ "UpBlock2D",
53
+ "UpBlock2D",
54
+ "UpBlock2D"
55
+ ],
56
+ "update_after_step": 0,
57
+ "upsample_type": "conv",
58
+ "use_ema_warmup": true
59
+ }
unet_ambient/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e76dd35be900aa9a8cf0278888d9714c38c4699b1aa05bb353679b2d037d415
3
+ size 454758164
unet_conditional/config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "CustomClassConditionedUnet",
3
+ "_diffusers_version": "0.33.1",
4
+ "act_fn": "silu",
5
+ "add_attention": true,
6
+ "attention_head_dim": 8,
7
+ "attn_norm_num_groups": null,
8
+ "block_out_channels": [
9
+ 128,
10
+ 128,
11
+ 256,
12
+ 256,
13
+ 512,
14
+ 512
15
+ ],
16
+ "center_input_sample": false,
17
+ "class_embed_type": null,
18
+ "decay": 0.9999,
19
+ "down_block_types": [
20
+ "DownBlock2D",
21
+ "DownBlock2D",
22
+ "DownBlock2D",
23
+ "DownBlock2D",
24
+ "AttnDownBlock2D",
25
+ "DownBlock2D"
26
+ ],
27
+ "downsample_padding": 1,
28
+ "downsample_type": "conv",
29
+ "dropout": 0.0,
30
+ "flip_sin_to_cos": true,
31
+ "freq_shift": 0,
32
+ "in_channels": 1,
33
+ "inv_gamma": 1.0,
34
+ "layers_per_block": 2,
35
+ "mid_block_scale_factor": 1,
36
+ "mid_block_type": "UNetMidBlock2D",
37
+ "min_decay": 0.0,
38
+ "norm_eps": 1e-05,
39
+ "norm_num_groups": 32,
40
+ "num_class_embeds": null,
41
+ "num_train_timesteps": null,
42
+ "optimization_step": 145000,
43
+ "out_channels": 1,
44
+ "power": 0.75,
45
+ "resnet_time_scale_shift": "default",
46
+ "sample_size": 128,
47
+ "time_embedding_dim": null,
48
+ "time_embedding_type": "positional",
49
+ "up_block_types": [
50
+ "UpBlock2D",
51
+ "AttnUpBlock2D",
52
+ "UpBlock2D",
53
+ "UpBlock2D",
54
+ "UpBlock2D",
55
+ "UpBlock2D"
56
+ ],
57
+ "update_after_step": 0,
58
+ "upsample_type": "conv",
59
+ "use_ema_warmup": true
60
+ }
unet_conditional/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f44c8c99e878bcd234ce518eb531bc429fbc26d367b9a98a7f7e79958cb3cb88
3
+ size 454753556