Image-to-Image
Diffusers
Safetensors
SeismicImpInvCLDMPipeline
seismic-inversion
impedance-inversion
diffusion
ddpm
cldm
overthrust
synthetic-data
Instructions to use mally-2000/saii-cldm-synthetic with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use mally-2000/saii-cldm-synthetic with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline from diffusers.utils import load_image # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("mally-2000/saii-cldm-synthetic", dtype=torch.bfloat16, device_map="cuda") prompt = "Turn this cat into a dog" input_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png") image = pipe(image=input_image, prompt=prompt).images[0] - Notebooks
- Google Colab
- Kaggle
File size: 22,273 Bytes
3f19d1a d105891 3f19d1a d105891 3f19d1a d105891 | 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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
import numpy as np
import torch
from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, UNet2DModel, VQModel
from diffusers.utils import BaseOutput
@dataclass
class SeismicImpInvLDDPMPipelineOutput(BaseOutput):
impedance_samples: torch.Tensor | np.ndarray
impedance_latents: torch.Tensor | np.ndarray
impedance_dipin: torch.Tensor | np.ndarray
impedance_reconstructed: torch.Tensor | np.ndarray | None = None
record_features: torch.Tensor | np.ndarray | None = None
class SeismicImpInvLDDPMPipeline(DiffusionPipeline):
"""SAII-LDDPM impedance inversion pipeline."""
def __init__(
self,
vq_model: VQModel,
condition_encoder: torch.nn.Module,
unet: UNet2DModel,
scheduler: DDPMScheduler,
):
super().__init__()
self.register_modules(
vq_model=vq_model,
condition_encoder=condition_encoder,
unet=unet,
scheduler=scheduler,
)
def _encode_conditioning(
self, dipin: torch.Tensor, record: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
dipin_latents = self.vq_model.encode(dipin).latents
if hasattr(self.condition_encoder, "encode") and callable(
self.condition_encoder.encode
):
record_features = self.condition_encoder.encode(record)
else:
record_features = self.condition_encoder(record)
return (
dipin_latents.to(dtype=self.unet.dtype),
record_features.to(dtype=self.unet.dtype),
)
@staticmethod
def _extract_into_tensor(
arr: torch.Tensor, timesteps: torch.Tensor, broadcast_shape: torch.Size
) -> torch.Tensor:
values = arr.to(device=timesteps.device, dtype=torch.float32).gather(0, timesteps)
return values.reshape(timesteps.shape[0], *((1,) * (len(broadcast_shape) - 1)))
@staticmethod
def _build_legacy_ddpm_buffers(
scheduler: DDPMScheduler, device: torch.device
) -> dict[str, torch.Tensor]:
betas = scheduler.betas.to(device=device, dtype=torch.float32)
alphas = 1.0 - betas
alphas_cumprod = torch.cumprod(alphas, dim=0)
alphas_cumprod_prev = torch.cat(
[torch.ones(1, device=device), alphas_cumprod[:-1]], dim=0
)
posterior_variance = betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
posterior_log_variance_clipped = torch.log(
torch.clamp(posterior_variance, min=1e-20)
)
return {
"sqrt_recip_alphas_cumprod": torch.sqrt(1.0 / alphas_cumprod),
"sqrt_recipm1_alphas_cumprod": torch.sqrt(1.0 / alphas_cumprod - 1),
"posterior_mean_coef1": betas
* torch.sqrt(alphas_cumprod_prev)
/ (1.0 - alphas_cumprod),
"posterior_mean_coef2": (1.0 - alphas_cumprod_prev)
* torch.sqrt(alphas)
/ (1.0 - alphas_cumprod),
"posterior_log_variance_clipped": posterior_log_variance_clipped,
}
@staticmethod
def _randn_like_sample(
sample: torch.Tensor, generator: torch.Generator | list[torch.Generator] | None
) -> torch.Tensor:
if isinstance(generator, list):
if len(generator) != sample.shape[0]:
raise ValueError(
f"Expected {sample.shape[0]} generators, got {len(generator)}"
)
return torch.cat(
[
torch.randn(
sample[i : i + 1].shape,
generator=sample_generator,
device=sample.device,
dtype=sample.dtype,
)
for i, sample_generator in enumerate(generator)
],
dim=0,
)
return torch.randn(
sample.shape, generator=generator, device=sample.device, dtype=sample.dtype
)
def _ddpm_step(
self,
latents: torch.Tensor,
conditioning: torch.Tensor,
timestep: torch.Tensor,
generator: torch.Generator | list[torch.Generator] | None,
buffers: dict[str, torch.Tensor],
) -> torch.Tensor:
model_input = torch.cat([latents, conditioning], dim=1)
noise_pred = self.unet(model_input, timestep).sample
pred_x0 = (
self._extract_into_tensor(
buffers["sqrt_recip_alphas_cumprod"], timestep, latents.shape
)
* latents
- self._extract_into_tensor(
buffers["sqrt_recipm1_alphas_cumprod"], timestep, latents.shape
)
* noise_pred
)
pred_x0 = self.vq_model.quantize(pred_x0)[0]
model_mean = (
self._extract_into_tensor(
buffers["posterior_mean_coef1"], timestep, latents.shape
)
* pred_x0
+ self._extract_into_tensor(
buffers["posterior_mean_coef2"], timestep, latents.shape
)
* latents
)
noise = self._randn_like_sample(latents, generator)
nonzero_mask = (1 - (timestep == 0).float()).reshape(
latents.shape[0], *((1,) * (len(latents.shape) - 1))
)
return model_mean + nonzero_mask * (
0.5
* self._extract_into_tensor(
buffers["posterior_log_variance_clipped"], timestep, latents.shape
)
).exp() * noise
@torch.no_grad()
def __call__(
self,
dipin: torch.Tensor,
record: torch.Tensor,
image: torch.Tensor | None = None,
num_inference_steps: int = 1000,
seed: int | None = None,
seeds: list[int] | tuple[int, ...] | torch.Tensor | None = None,
generator: torch.Generator | None = None,
output_type: str = "tensor",
) -> SeismicImpInvLDDPMPipelineOutput:
device = self.unet.device
if seeds is not None:
if isinstance(seeds, torch.Tensor):
seeds = seeds.detach().cpu().tolist()
seeds = [int(value) for value in seeds]
if len(seeds) != dipin.shape[0]:
raise ValueError(f"Expected {dipin.shape[0]} seeds, got {len(seeds)}")
generator = [
torch.Generator(device=device).manual_seed(value) for value in seeds
]
elif seed is not None:
generator = torch.Generator(device=device).manual_seed(seed)
elif generator is None:
generator = torch.Generator(device=device)
dipin = dipin.to(device=device, dtype=self.vq_model.dtype)
record = record.to(device=device, dtype=self.unet.dtype)
impedance_dipin, record_features = self._encode_conditioning(dipin, record)
conditioning = torch.cat([impedance_dipin, record_features], dim=1)
impedance_latents = self._randn_like_sample(
torch.empty(
impedance_dipin.shape,
device=device,
dtype=self.unet.dtype,
),
generator,
)
buffers = self._build_legacy_ddpm_buffers(self.scheduler, device)
for t in reversed(range(num_inference_steps)):
timestep = torch.full(
(impedance_latents.shape[0],), t, device=device, dtype=torch.long
)
impedance_latents = self._ddpm_step(
impedance_latents, conditioning, timestep, generator, buffers
)
impedance_samples = self.vq_model.decode(
impedance_latents.to(dtype=self.vq_model.dtype)
).sample
impedance_reconstructed = None
if image is not None:
image = image.to(device=device, dtype=self.vq_model.dtype)
image_latents = self.vq_model.encode(image).latents
impedance_reconstructed = self.vq_model.decode(image_latents).sample
if output_type == "np":
impedance_samples = impedance_samples.detach().cpu().numpy()
impedance_latents = impedance_latents.detach().cpu().numpy()
impedance_dipin = impedance_dipin.detach().cpu().numpy()
record_features = record_features.detach().cpu().numpy()
if impedance_reconstructed is not None:
impedance_reconstructed = impedance_reconstructed.detach().cpu().numpy()
return SeismicImpInvLDDPMPipelineOutput(
impedance_samples=impedance_samples,
impedance_latents=impedance_latents,
impedance_dipin=impedance_dipin,
impedance_reconstructed=impedance_reconstructed,
record_features=record_features,
)
@torch.no_grad()
def encode_decode(
self, image: torch.Tensor, output_type: str = "tensor"
) -> torch.Tensor | np.ndarray:
image = image.to(device=self.vq_model.device, dtype=self.vq_model.dtype)
reconstruction = self.vq_model.decode(self.vq_model.encode(image).latents).sample
if output_type == "np":
return reconstruction.detach().cpu().numpy()
return reconstruction
class SeismicImpInvCLDMPipeline(SeismicImpInvLDDPMPipeline):
"""SAII-CLDM inference pipeline.
This reuses the same trained components as SAII-LDDPM and replaces only the
reverse sampling procedure with DDIM plus model-driven resampling.
"""
@staticmethod
def _get_operator_fn(operator: Any) -> Callable[[torch.Tensor], torch.Tensor]:
if callable(operator):
return operator
if hasattr(operator, "forward") and callable(operator.forward):
return operator.forward
raise TypeError("`operator` must be callable or expose a callable `forward` method.")
@staticmethod
def _build_ddim_scheduler(
scheduler: DDPMScheduler,
num_inference_steps: int,
device: torch.device,
) -> DDIMScheduler:
ddim_scheduler = DDIMScheduler.from_config(
scheduler.config,
clip_sample=False,
set_alpha_to_one=False,
steps_offset=1,
timestep_spacing="leading",
)
ddim_scheduler.set_timesteps(num_inference_steps, device=device)
return ddim_scheduler
@staticmethod
def _default_pixel_optimization_param() -> dict[str, float | int]:
return {
"eps": 1e-4,
"max_iters": 100,
"lr": 1e-5,
"y_coef": 1.0,
"x_coef": 0.0,
"tv_coef": 0.0,
"dh_coef": 1.0,
"dw_coef": 1.5,
}
@staticmethod
def _default_last_pixel_optimization_param() -> dict[str, float | int]:
return {
"eps": 1e-4,
"max_iters": 1,
"lr": 1e-4,
"y_coef": 1.0,
"x_coef": 0.1,
"tv_coef": 0.0,
"dh_coef": 1.0,
"dw_coef": 1.5,
}
@staticmethod
def _tv_loss(x: torch.Tensor, *, dh_coef: float, dw_coef: float) -> torch.Tensor:
dh = dh_coef * torch.abs(x[..., :, 1:] - x[..., :, :-1])
dw = dw_coef * torch.abs(x[..., 1:, :] - x[..., :-1, :])
return torch.mean(dh[..., :-1, :] + dw[..., :, :-1])
def _ddim_step(
self,
latents: torch.Tensor,
conditioning: torch.Tensor,
timestep: int,
scheduler: DDIMScheduler,
eta: float,
generator: torch.Generator | list[torch.Generator] | None,
quantize_denoised: bool,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]:
model_input = torch.cat(
[
scheduler.scale_model_input(latents, timestep),
conditioning.to(dtype=latents.dtype),
],
dim=1,
)
timestep_tensor = torch.full(
(latents.shape[0],), timestep, device=latents.device, dtype=torch.long
)
noise_pred = self.unet(model_input, timestep_tensor).sample
alpha_t = scheduler.alphas_cumprod[timestep].to(
device=latents.device, dtype=latents.dtype
)
prev_timestep = timestep - (
scheduler.config.num_train_timesteps // scheduler.num_inference_steps
)
if prev_timestep >= 0:
alpha_prev = scheduler.alphas_cumprod[prev_timestep].to(
device=latents.device, dtype=latents.dtype
)
else:
alpha_prev = scheduler.final_alpha_cumprod.to(
device=latents.device, dtype=latents.dtype
)
beta_t = 1.0 - alpha_t
pred_x0 = (latents - beta_t.sqrt() * noise_pred) / alpha_t.sqrt()
pseudo_x0 = (latents - beta_t * noise_pred) / alpha_t.sqrt()
if quantize_denoised:
pred_x0 = self.vq_model.quantize(pred_x0.to(dtype=self.vq_model.dtype))[0].to(
dtype=latents.dtype
)
noise_pred = (latents - alpha_t.sqrt() * pred_x0) / beta_t.sqrt()
variance = scheduler._get_variance(timestep, prev_timestep).to(
device=latents.device, dtype=latents.dtype
)
sigma_t = eta * variance.sqrt()
direction = torch.clamp(1.0 - alpha_prev - sigma_t**2, min=0.0).sqrt() * noise_pred
noise = torch.zeros_like(latents)
if eta > 0:
noise = sigma_t * self._randn_like_sample(latents, generator)
prev_sample = alpha_prev.sqrt() * pred_x0 + direction + noise
batch_shape = (latents.shape[0], 1, 1, 1)
return (
prev_sample,
pred_x0,
pseudo_x0,
{
"a_t": torch.full(
batch_shape,
float(alpha_t.item()),
device=latents.device,
dtype=latents.dtype,
),
"a_prev": torch.full(
batch_shape,
float(alpha_prev.item()),
device=latents.device,
dtype=latents.dtype,
),
},
)
def _optimize_pixels(
self,
x_prime: torch.Tensor,
measurement: torch.Tensor,
operator_fn: Callable[[torch.Tensor], torch.Tensor],
params: dict[str, Any],
) -> torch.Tensor:
merged = {**self._default_pixel_optimization_param(), **params}
if int(merged["max_iters"]) <= 0:
return x_prime.detach()
loss_fn = torch.nn.MSELoss(reduction="mean")
opt_var = x_prime.detach().clone().requires_grad_(True)
opt_init = x_prime.detach().clone()
optimizer = torch.optim.AdamW([opt_var], lr=float(merged["lr"]))
for _ in range(int(merged["max_iters"])):
optimizer.zero_grad(set_to_none=True)
measurement_loss = (
loss_fn(measurement, operator_fn(opt_var)) * float(merged["y_coef"])
+ loss_fn(opt_init, opt_var) * float(merged["x_coef"])
)
if float(merged["tv_coef"]) != 0.0:
measurement_loss = measurement_loss + float(merged["tv_coef"]) * self._tv_loss(
opt_var,
dh_coef=float(merged["dh_coef"]),
dw_coef=float(merged["dw_coef"]),
)
measurement_loss.backward()
optimizer.step()
if float(measurement_loss.detach().cpu().item()) < float(merged["eps"]):
break
return opt_var.detach()
def _stochastic_resample(
self,
pseudo_x0: torch.Tensor,
x_t: torch.Tensor,
a_t: torch.Tensor,
sigma: torch.Tensor,
generator: torch.Generator | list[torch.Generator] | None,
) -> torch.Tensor:
sigma = torch.clamp(sigma, min=1e-12)
one_minus_a_t = torch.clamp(1.0 - a_t, min=1e-12)
noise = self._randn_like_sample(pseudo_x0, generator)
return (
(sigma * a_t.sqrt() * pseudo_x0 + one_minus_a_t * x_t)
/ (sigma + one_minus_a_t)
+ noise * torch.sqrt(1.0 / (1.0 / sigma + 1.0 / one_minus_a_t))
)
def __call__(
self,
dipin: torch.Tensor,
record: torch.Tensor,
measurement: torch.Tensor | None = None,
operator: Any | None = None,
image: torch.Tensor | None = None,
num_inference_steps: int = 30,
seed: int | None = None,
seeds: list[int] | tuple[int, ...] | torch.Tensor | None = None,
generator: torch.Generator | None = None,
eta: float = 0.01,
interval: int = 6,
sigma_a: float = 20.0,
pixel_optimization_param: dict[str, Any] | None = None,
last_pixel_optimization_param: dict[str, Any] | None = None,
quantize_denoised: bool = False,
output_type: str = "tensor",
) -> SeismicImpInvLDDPMPipelineOutput:
if measurement is None:
measurement = record
if operator is None:
raise ValueError("SAII-CLDM requires a forward `operator`.")
if interval <= 0:
raise ValueError("`interval` must be a positive integer.")
device = self.unet.device
if seeds is not None:
if isinstance(seeds, torch.Tensor):
seeds = seeds.detach().cpu().tolist()
seeds = [int(value) for value in seeds]
if len(seeds) != dipin.shape[0]:
raise ValueError(f"Expected {dipin.shape[0]} seeds, got {len(seeds)}")
generator = [
torch.Generator(device=device).manual_seed(value) for value in seeds
]
elif seed is not None:
generator = torch.Generator(device=device).manual_seed(seed)
elif generator is None:
generator = torch.Generator(device=device)
with torch.no_grad():
dipin = dipin.to(device=device, dtype=self.vq_model.dtype)
record = record.to(device=device, dtype=self.unet.dtype)
measurement = measurement.to(device=device, dtype=self.unet.dtype)
impedance_dipin, record_features = self._encode_conditioning(dipin, record)
conditioning = torch.cat([impedance_dipin, record_features], dim=1)
impedance_latents = self._randn_like_sample(
torch.empty(
impedance_dipin.shape,
device=device,
dtype=self.unet.dtype,
),
generator,
)
operator_fn = self._get_operator_fn(operator)
pixel_params = pixel_optimization_param or {}
last_pixel_params = last_pixel_optimization_param or self._default_last_pixel_optimization_param()
schedule = self._build_ddim_scheduler(self.scheduler, num_inference_steps, device)
time_range = [int(timestep) for timestep in schedule.timesteps.tolist()]
resample_start_index = len(time_range) // 4
for step_idx, timestep in enumerate(time_range):
index = len(time_range) - step_idx - 1
with torch.no_grad():
next_latents, pred_x0, pseudo_x0, step_stats = self._ddim_step(
impedance_latents,
conditioning,
timestep,
schedule,
eta,
generator,
quantize_denoised,
)
if (index >= resample_start_index or index == 0) and (
index % interval == 0 or index == 0
):
x_t_reference = next_latents.detach().clone()
sigma = sigma_a * (1.0 - step_stats["a_prev"]) / (
1.0 - step_stats["a_t"]
)
sigma = sigma * (1.0 - step_stats["a_t"] / step_stats["a_prev"])
sigma = torch.clamp(sigma, min=1e-12)
with torch.no_grad():
pseudo_x0_pixel = self.vq_model.decode(
pseudo_x0.detach().to(dtype=self.vq_model.dtype)
).sample
optimized_pixels = self._optimize_pixels(
pseudo_x0_pixel,
measurement,
operator_fn,
last_pixel_params if index == 0 else pixel_params,
)
with torch.no_grad():
optimized_latents = self.vq_model.encode(
optimized_pixels.to(dtype=self.vq_model.dtype)
).latents.to(dtype=self.unet.dtype)
next_latents = self._stochastic_resample(
optimized_latents,
x_t_reference,
step_stats["a_prev"],
sigma.to(dtype=self.unet.dtype),
generator,
)
impedance_latents = next_latents.detach()
with torch.no_grad():
impedance_samples = self.vq_model.decode(
impedance_latents.to(dtype=self.vq_model.dtype)
).sample
impedance_reconstructed = None
if image is not None:
image = image.to(device=device, dtype=self.vq_model.dtype)
image_latents = self.vq_model.encode(image).latents
impedance_reconstructed = self.vq_model.decode(image_latents).sample
if output_type == "np":
impedance_samples = impedance_samples.detach().cpu().numpy()
impedance_latents = impedance_latents.detach().cpu().numpy()
impedance_dipin = impedance_dipin.detach().cpu().numpy()
record_features = record_features.detach().cpu().numpy()
if impedance_reconstructed is not None:
impedance_reconstructed = impedance_reconstructed.detach().cpu().numpy()
return SeismicImpInvLDDPMPipelineOutput(
impedance_samples=impedance_samples,
impedance_latents=impedance_latents,
impedance_dipin=impedance_dipin,
impedance_reconstructed=impedance_reconstructed,
record_features=record_features,
)
|