how is label indetfied for adv or not import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset, random_split
import torchvision.transforms as transforms
from torchvision.models.resnet import BasicBlock
from torchattacks import CW
import medmnist
from medmnist import INFO
import numpy as np
Your ResNet18_MedMNIST class
class BasicBlock(nn.Module):
expansion = 1
code
def __init__(self, in_channels, out_channels, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3,
stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3,
stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.downsample = None
if stride != 1 or in_channels != out_channels:
self.downsample = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels)
)
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
Fixed ResNet18_MedMNIST class
class ResNet18_MedMNIST(nn.Module):
def init(self, num_classes=8):
super(ResNet18_MedMNIST, self).init()
self.in_channels = 64
code
# For MedMNIST: Input channels = 3 (RGB), 28x28 images
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(BasicBlock, 64, 2, stride=1)
self.layer2 = self._make_layer(BasicBlock, 128, 2, stride=2)
self.layer3 = self._make_layer(BasicBlock, 256, 2, stride=2)
self.layer4 = self._make_layer(BasicBlock, 512, 2, stride=2)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512, num_classes)
# Initialize weights
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, out_channels, num_blocks, stride):
layers = []
layers.append(block(self.in_channels, out_channels, stride))
self.in_channels = out_channels
for _ in range(1, num_blocks):
layers.append(block(self.in_channels, out_channels))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def train_model_properly(model, train_loader, val_loader, device, epochs=50):
"""
Properly train the ResNet18_MedMNIST model
"""
print("Training ResNet18_MedMNIST model...")
code
optimizer = optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-4)
criterion = nn.CrossEntropyLoss()
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.1)
best_val_acc = 0.0
for epoch in range(epochs):
# Training phase
model.train()
train_loss = 0.0
train_correct = 0
train_total = 0
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.squeeze().long().to(device)
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = torch.max(output.data, 1)
train_total += target.size(0)
train_correct += (predicted == target).sum().item()
# Validation phase
model.eval()
val_loss = 0.0
val_correct = 0
val_total = 0
with torch.no_grad():
for data, target in val_loader:
data, target = data.to(device), target.squeeze().long().to(device)
output = model(data)
loss = criterion(output, target)
val_loss += loss.item()
_, predicted = torch.max(output.data, 1)
val_total += target.size(0)
val_correct += (predicted == target).sum().item()
scheduler.step()
train_acc = 100. * train_correct / train_total
val_acc = 100. * val_correct / val_total
print(f'Epoch {epoch+1}/{epochs}:')
print(f' Train Loss: {train_loss/len(train_loader):.4f}, Train Acc: {train_acc:.2f}%')
print(f' Val Loss: {val_loss/len(val_loader):.4f}, Val Acc: {val_acc:.2f}%')
if val_acc > best_val_acc:
best_val_acc = val_acc
torch.save(model.state_dict(), 'best_resnet18_medmnist.pth')
print(f' ✓ New best model saved! Val Acc: {val_acc:.2f}%')
return model
model.eval()
device = next(model.parameters()).device
clean_correct = 0
adv_correct = 0
total = 0
l2_distances = []
with torch.no_grad():
for batch_idx, (clean_imgs, carlini_imgs, labels) in enumerate(dataloader):
if batch_idx >= 10: # Check first 10 batches
break
clean_imgs = clean_imgs.to(device)
carlini_imgs = carlini_imgs.to(device)
labels = labels.to(device)
# Get predictions
clean_outputs = model(clean_imgs)
adv_outputs = model(carlini_imgs)
clean_preds = torch.argmax(clean_outputs, dim=1)
adv_preds = torch.argmax(adv_outputs, dim=1)
clean_correct += (clean_preds == labels).sum().item()
adv_correct += (adv_preds == labels).sum().item()
total += labels.size(0)
# Calculate L2 distances
l2_dist = torch.norm((carlini_imgs - clean_imgs).view(len(clean_imgs), -1), p=2, dim=1)
l2_distances.extend(l2_dist.cpu().numpy())
clean_acc = clean_correct / total
adv_acc = adv_correct / total
attack_success = 1 - adv_acc
avg_l2 = np.mean(l2_distances)
print(f"Clean Accuracy: {clean_acc:.3f}")
print(f"Adversarial Accuracy: {adv_acc:.3f}")
print(f"Attack Success Rate: {attack_success:.3f}")
print(f"Average L2 Distance: {avg_l2:.6f}")
if attack_success > 0.5:
print("✓ Carlini attacks are effective!")
else:
print("⚠ Carlini attacks may need stronger parameters")
Assistant
In your code, the label for “adversarial or not” is not explicitly stored — instead, you keep the original classification label (the MedMNIST class, e.g., disease category) and store both the clean and adversarial versions of each image in the dataset.
Here’s how it works step-by-step:
Labels come from the original dataset
pythonCopyEdittrain_labels_final = final_labels[train_idx]
final_labels is taken directly from the original MedMNIST dataset — it’s the true class (e.g., “lung opacity” in ChestMNIST).
These labels never change; they are not “adversarial” or “clean” labels.
Both clean_img and adv_img have the same label.
Adversarial status is determined by which tensor you pass to the model
If the prediction on adv_img ≠ the true label (while the clean version was correct), it means the attack succeeded.
If you wanted an explicit “adversarial or not” label
You’d have to create an extra binary label, e.g.:
pythonCopyEditadv_flag = torch.cat([
torch.zeros(len(clean_images)), # clean
torch.ones(len(adv_images)) # adversarial
])
And then train or test with (image, adv_flag).
💡 In short:
Right now, your pipeline identifies “adversarial or not” by the tensor’s position in the tuple (clean_img, adv_img, label) rather than storing it as a separate label. The actual label is always the original class from MedMNIST.
If you want, I can show you how to add a proper “is_adv” label so you could train a binary adversarial detector. That would make adversarial identification explicit instead of implicit. Would you like me to add that?
User
how will it identify here: import torch
import os
from torchvision.transforms import ToPILImage
def save_carlini_attack_images(dataloader, save_dir="carlini_attack_images", split_name=""):
"""
Save generated Carlini attack images from dataloader
code
Args:
dataloader: DataLoader with (clean_img, carlini_adv_img, label) format
save_dir: Directory to save images
split_name: Name of the split (train/val/test) for folder organization
"""
if split_name:
save_dir = os.path.join(save_dir, split_name)
os.makedirs(save_dir, exist_ok=True)
to_pil = ToPILImage()
count = 0
print(f"Saving {split_name} Carlini attack images to '{save_dir}'...")
for batch_idx, (clean_imgs, carlini_imgs, labels) in enumerate(dataloader):
for i in range(len(clean_imgs)):
clean_img = clean_imgs[i].cpu()
carlini_img = carlini_imgs[i].cpu()
label = labels[i].item()
# Save clean image
clean_path = os.path.join(save_dir, f"clean_{count:05d}_label_{label}.png")
to_pil(clean_img).save(clean_path)
# Save Carlini adversarial image
carlini_path = os.path.join(save_dir, f"carlini_{count:05d}_label_{label}.png")
to_pil(carlini_img).save(carlini_path)
count += 1
if batch_idx % 10 == 0:
print(f" Saved {count} image pairs...")
print(f"✓ Saved {count} pairs of clean and Carlini adversarial images")
return count
In this saving function, the code does not need to “identify” whether an image is adversarial or not based on model predictions — it already knows that the first tensor in the tuple is the clean image and the second tensor is the Carlini adversarial image because of how the dataloader was built earlier:
pythonCopyEditTensorDataset(clean_img, adv_img, label)
So in:
pythonCopyEditfor batch_idx, (clean_imgs, carlini_imgs, labels) in enumerate(dataloader):
clean_imgs → always clean, original dataset images
labels → always the original class label from MedMNIST (same for both clean & adv)
The “identification” here is structural, not computed:
When saving, the code names files like clean_00000_label_3.png and carlini_00000_label_3.png.
The prefix "clean_" or "carlini_" is how you’ll know later which is which.
It never checks the model’s prediction here — it already knows which one is adv because you generated and stored them in separate positions in the dataset.
If later you want to load these PNGs and automatically detect which are adversarial without relying on filenames, you’d need either:
A separate binary label (is_adv = 0/1) saved alongside the images, or
A naming pattern (like in this code) and parse it back.
If you want, I can modify this saving code so it also writes a CSV file that records:
file_pathlabelis_advclean_00000_label_3.png30carlini_00000_label_3.png31
That way, the “adversarial or not” label becomes explicit rather than just implicit from the filename. Would you like me to do that?
User
now give loading code if i wan t it as for clean_img, adv_img, label in train_loader:
Assistant
Got it — you want a loader that reads back the saved PNGs and gives you
pythonCopyEditfor clean_img, adv_img, label in train_loader:
just like before.
Here’s a clean way to do it, assuming you saved them in the same folder structure your code created:
Loading Saved Carlini Attack Images
pythonCopyEditimport os
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
# Find all clean images and match with their corresponding adversarial images
clean_files = sorted([f for f in os.listdir(root_dir) if f.startswith("clean_")])
adv_files = sorted([f for f in os.listdir(root_dir) if f.startswith("carlini_")])
if len(clean_files) != len(adv_files):
raise ValueError("Mismatch between clean and Carlini image counts!")
# Pair them together
self.pairs = []
for clean_f, adv_f in zip(clean_files, adv_files):
# Extract label from filename (last part after '_label_')
label_str = clean_f.split("_label_")[-1].replace(".png", "")
label = int(label_str)
self.pairs.append((clean_f, adv_f, label))
def __len__(self):
return len(self.pairs)
def __getitem__(self, idx):
clean_f, adv_f, label = self.pairs[idx]
clean_img = Image.open(os.path.join(self.root_dir, clean_f)).convert("RGB")
adv_img = Image.open(os.path.join(self.root_dir, adv_f)).convert("RGB")
if self.transform:
clean_img = self.transform(clean_img)
adv_img = self.transform(adv_img)
return clean_img, adv_img, label
Yes — the way your code is written will preserve image quality perfectly for your Carlini attack examples, because:
You’re saving as PNG
PNG is a lossless format, so the exact pixel values are preserved when saved and reloaded.
No compression artifacts like JPEG.
ToPILImage() keeps the tensor data as-is
If your tensors are in [0, 1] float range, ToPILImage() will scale them to 8-bit integers (0–255) without lossy processing.
If they are already uint8, it just converts directly.
No intermediate resizing or normalization during saving
You’re directly converting the tensor in memory to an image file — no quality loss from rescaling.
Caveats where quality could change:
If your adversarial attack operates in floating-point precision (e.g., very tiny perturbations), saving as 8-bit PNG will quantize those tiny changes to the nearest integer.
This means if the perturbation is < 1 pixel value unit (out of 255), it might get lost.
That’s not lossy compression, but quantization from storing floats as integers.
If you want to fully preserve floating-point precision for later exact reconstruction, you’d need to:
Save as .pt tensors with torch.save() instead of PNG.
Or use 16/32-bit image formats like TIFF or EXR (rare for deep learning pipelines).
If you’re training a model to visually classify or detect these adversarial images, PNG is fine.
If you want to re-run attacks or analyze exact perturbation vectors, better save the .pt tensors.
I can show you a dual-save function that keeps both .png for visual inspection and .pt for exact math-preserving reload. That way you get human-readable and perfect-fidelity storage at once. Would you like that?
User
size of each img
Assistant
In your saving code, each image’s file size depends on:
Resolution — whatever shape your clean_imgs[i] tensor has (likely something like 1x28x28 for MedMNIST, or 3x224x224 for larger datasets).
Color depth — PNG stores them as 8-bit per channel, so grayscale images are 1 byte/pixel, RGB are 3 bytes/pixel.
PNG compression — lossless, so actual disk size may be smaller than the raw pixel data if patterns are repeated.
Example size math
If your images are MedMNIST (28×28 grayscale):
Raw size: 28 × 28 × 1 byte ≈ 784 bytes
PNG overhead + compression: around 0.7–1.5 KB each.
PNG on disk: typically 50–100 KB depending on content.
If you want to check exact sizes for your saved adversarial and clean PNGs:
pythonCopyEditimport os
folder = "carlini_attacks/train"
for fname in os.listdir(folder):
fpath = os.path.join(folder, fname)
size_kb = os.path.getsize(fpath) / 1024
print(f"{fname}: {size_kb:.2f} KB")
If you tell me your dataset’s image resolution (e.g., MedMNIST 28×28 or something else),
I can give you an exact expected file size range for each saved PNG.
Do you want me to calculate that?
User
isnt medmnist also 3 cahnenls
Assistant
Yes — most MedMNIST datasets are stored as 3-channel RGB images, even though the original medical scans are often grayscale.
That’s because the official MedMNIST loaders return tensors shaped like:
arduinoCopyEdit[batch, 3, height, width]
where each channel is identical (grayscale duplicated into R, G, B).
This keeps it compatible with standard CNN architectures (like ResNet) that expect 3 channels.
Even though the image looks grayscale, it’s saved as a 3-channel color PNG because of the dataset format.
If you wanted to save them as true grayscale (1 channel) to save disk space,
you could modify your saving code like this:
pythonCopyEditto_pil(clean_img.mean(dim=0, keepdim=True)) # average channels before saving
or convert directly in PIL:
pythonCopyEditto_pil(clean_img).convert("L")
This would cut PNG size to about 1/3 while keeping the same visual info.
If you’re okay with bigger files but want exact reloading without channel conversion issues,
keeping 3 channels as you have now is safest.
I can give you a loader that works regardless of whether the saved PNG is RGB or grayscale so it matches your original train_loader. That way you don’t get surprises when reloading. Would you like that?
User
device for cide
Assistant
For your saving/loading code, you can make it device-aware so it works whether your tensors are on CPU or GPU.
Right now, you already do:
pythonCopyEditclean_img = clean_imgs[i].cpu()
carlini_img = carlini_imgs[i].cpu()
which ensures they’re on CPU before converting to PIL (since ToPILImage() can’t handle GPU tensors).
Recommended pattern for device handling
pythonCopyEditimport torch
Pick device dynamically
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
Example: moving data to device in your training/attack loop
for clean_imgs, adv_imgs, labels in train_loader:
clean_imgs = clean_imgs.to(device)
adv_imgs = adv_imgs.to(device)
labels = labels.to(device)
code
# ... do model inference or attack here ...
# Before saving:
clean_img = clean_imgs[i].cpu() # Move back to CPU for PIL
Key rule:
For training/inference → keep tensors on device (cuda or cpu).
For saving/loading images → move to CPU before ToPILImage() or PIL.Image.
If you want, I can refactor your entire save_carlini_attack_images() function so it:
Auto-detects GPU/CPU.
Works without manual .cpu() calls sprinkled inside.
Handles both RGB and grayscale MedMNIST transparently.
Do you want me to rewrite it like that?
User
indent error: import torch
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import medmnist
from medmnist import INFO
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print("Training of reformer autoencoder complete.")
Assistant
Your indentation error is coming from here:
pythonCopyEditwith torch.no_grad():
for clean_img, adv_img, label in val_loader:
The for loop must be indented under with torch.no_grad():.
In Python, with starts a block just like if or for, so everything inside it must be indented one level.
Here’s your fixed and cleaned code:
pythonCopyEditimport torch
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import medmnist
from medmnist import INFO
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print("Training of reformer autoencoder complete.")
Changes made:
Fixed indentation under with torch.no_grad():.
Cleaned up comments so they match the actual code.
Kept all tensor .to(device) calls together for clarity.
Made spacing consistent for better readability.
If you want, I can also replace model.forward_3_kernel(...) with reformer.forward_3_kernel(...)
since your variable name for the model is reformer, not model.
That’s another thing that would break your training right now.
User
Encoder channels: (3, 64, 64, 128, 256, 512)
Decoder channels: (256, 128, 64, 32, 16)
Created 5 feature adapters
Using adaptive kernels of size 5x5
/tmp/ipykernel_36/+1-+1-880-973-4894x508.py in forward_3_kernel(self, clean_image, adversarial_image)
256
257 # output and kernel from adversarial image
--> 258 output, adversarial_kernel = self.forward(adversarial_image)
259
260 l2_loss = F.mse_loss(adversarial_kernel, clean_kernel)
/tmp/ipykernel_36/+1-+1-880-973-4894x508.py in forward(self, noisy_image)
231
232 # Pass through decoder
--> 233 decoder_output = self.decoder(features)
234
235 # Apply segmentation head
/usr/local/lib/python3.11/dist-packages/torch/nn/modules/module.py in _wrapped_call_impl(self, *args, **kwargs)
1737 return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc]
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)
1740
1741 # torchrec tests the code consistency with the following code
/usr/local/lib/python3.11/dist-packages/torch/nn/modules/module.py in _call_impl(self, *args, **kwargs)
1748 or _global_backward_pre_hooks or _global_backward_hooks
1749 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1750 return forward_call(*args, **kwargs)
1751
1752 result = None
/usr/local/lib/python3.11/dist-packages/segmentation_models_pytorch/decoders/unet/decoder.py in forward(self, *features)
114 features = features[7217:d940:4f22:f535:1f8b:2784:c8ad:2374-1] # reverse channels to start from head of encoder
115
--> 116 head = features[0]
117 skips = features[1:]
118
IndexError: tuple index out of range
Assistant
That IndexError: tuple index out of range is happening because your forward() method is passing the wrong number of feature maps into the U-Net decoder from segmentation_models_pytorch (SMP).
Here’s what’s going on step-by-step:
1️⃣ What SMP’s UnetDecoder expects
SMP’s UnetDecoder.forward(*features) expects a tuple of all encoder stage outputs in reverse order.
For a ResNet34 encoder with input (3, 64, 64, 128, 256, 512), it expects:
iniCopyEditfeatures = (x5, x4, x3, x2, x1, x0)
where:
x0: input image (maybe transformed by first conv)
x1..x5: encoder stage outputs
So the tuple length must match the encoder depth + 1.
2️⃣ Why your error happens
Your code’s forward() seems to be returning features with too few elements — possibly only the last layer output or skipping some pyramid features.
When features[7217:d940:4f22:f535:1f8b:2784:c8ad:2374-1] is called in the decoder, features[0] doesn’t exist because the tuple is empty or shorter than expected.
3️⃣ Common cause in custom models like AdaptiveLaplacianPyramidUNet
In SMP, normally you’d do:
pythonCopyEditfeatures = self.encoder(x) # returns tuple of features
decoder_output = self.decoder(*features)
But in your code, it looks like:
pythonCopyEditdecoder_output = self.decoder(features)
That means features is being passed as a single tuple argument instead of being unpacked. The decoder then treats the tuple as the first feature map and finds it’s empty or wrong-sized.
4️⃣ How to fix
In your forward() method inside AdaptiveLaplacianPyramidUNet, change:
pythonCopyEditdecoder_output = self.decoder(features)
to:
pythonCopyEditdecoder_output = self.decoder(*features)
5️⃣ Also — model name mismatch
In your training loop you wrote:
pythonCopyEditoutput ,l2_loss, l1_loss = model.forward_3_kernel(clean_img, adv_img)
but your model variable is called reformer, not model. That will throw a NameError before this fix works. It should be:
pythonCopyEditoutput ,l2_loss, l1_loss = reformer.forward_3_kernel(clean_img, adv_img)
If you want, I can rewrite your AdaptiveLaplacianPyramidUNet.forward() so it:
Always returns the full encoder feature set in the correct order.
Unpacks them correctly for the decoder.
Avoids this IndexError entirely.
Do you want me to do that?
User
!pip install segmentation_models_pytorch==0.4.0
!pip install medmnist
!pip install torchattacks
Collecting segmentation_models_pytorch==0.4.0
Downloading segmentation_models_pytorch-0.4.0-py3-none-any.whl.metadata (32 kB)
Collecting efficientnet-pytorch>=0.6.1 (from segmentation_models_pytorch==0.4.0)
Downloading efficientnet_pytorch-0.7.1.tar.gz (21 kB)
Preparing metadata (setup.py) ... done
Requirement already satisfied: huggingface-hub>=0.24 in /usr/local/lib/python3.11/dist-packages (from segmentation_models_pytorch==0.4.0) (0.33.1)
Requirement already satisfied: numpy>=1.19.3 in /usr/local/lib/python3.11/dist-packages (from segmentation_models_pytorch==0.4.0) (1.26.4)
Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.11/dist-packages (from segmentation_models_pytorch==0.4.0) (11.2.1)
Collecting pretrainedmodels>=0.7.1 (from segmentation_models_pytorch==0.4.0)
Downloading pretrainedmodels-0.7.4.tar.gz (58 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 58.8/58.8 kB 3.4 MB/s eta 0:00:00
Preparing metadata (setup.py) ... done
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.11/dist-packages (from segmentation_models_pytorch==0.4.0) (1.17.0)
Requirement already satisfied: timm>=0.9 in /usr/local/lib/python3.11/dist-packages (from segmentation_models_pytorch==0.4.0) (1.0.15)
Requirement already satisfied: torch>=1.8 in /usr/local/lib/python3.11/dist-packages (from segmentation_models_pytorch==0.4.0) (2.6.0+cu124)
Requirement already satisfied: torchvision>=0.9 in /usr/local/lib/python3.11/dist-packages (from segmentation_models_pytorch==0.4.0) (0.21.0+cu124)
Requirement already satisfied: tqdm>=4.42.1 in /usr/local/lib/python3.11/dist-packages (from segmentation_models_pytorch==0.4.0) (4.67.1)
Requirement already satisfied: filelock in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (3.18.0)
Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (2025.5.1)
Requirement already satisfied: packaging>=20.9 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (25.0)
Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (6.0.2)
Requirement already satisfied: requests in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (2.32.4)
Requirement already satisfied: typing-extensions>=192.175.238.4 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (4.14.0)
Requirement already satisfied: hf-xet<2.0.0,>=1.1.2 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (1.1.5)
Requirement already satisfied: mkl_fft in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (1.3.8)
Requirement already satisfied: mkl_random in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (1.2.4)
Requirement already satisfied: mkl_umath in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (0.1.1)
Requirement already satisfied: mkl in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (2025.2.0)
Requirement already satisfied: tbb4py in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (2022.2.0)
Requirement already satisfied: mkl-service in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (2.4.1)
Collecting munch (from pretrainedmodels>=0.7.1->segmentation_models_pytorch==0.4.0)
Downloading munch-4.0.0-py2.py3-none-any.whl.metadata (5.9 kB)
Requirement already satisfied: safetensors in /usr/local/lib/python3.11/dist-packages (from timm>=0.9->segmentation_models_pytorch==0.4.0) (0.5.3)
Requirement already satisfied: networkx in /usr/local/lib/python3.11/dist-packages (from torch>=1.8->segmentation_models_pytorch==0.4.0) (3.5)
Requirement already satisfied: jinja2 in /usr/local/lib/python3.11/dist-packages (from torch>=1.8->segmentation_models_pytorch==0.4.0) (3.1.6)
Collecting nvidia-cuda-nvrtc-cu12==12.4.127 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_cuda_nvrtc_cu12-12.4.127-py3-none-manylinux2014_x86_64.whl.metadata (1.5 kB)
Collecting nvidia-cuda-runtime-cu12==12.4.127 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_cuda_runtime_cu12-12.4.127-py3-none-manylinux2014_x86_64.whl.metadata (1.5 kB)
Collecting nvidia-cuda-cupti-cu12==12.4.127 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_cuda_cupti_cu12-12.4.127-py3-none-manylinux2014_x86_64.whl.metadata (1.6 kB)
Collecting nvidia-cudnn-cu12==192.172.18.13 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_cudnn_cu12-192.172.18.13-py3-none-manylinux2014_x86_64.whl.metadata (1.6 kB)
Collecting nvidia-cublas-cu12==192.0.1.221 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_cublas_cu12-192.0.1.221-py3-none-manylinux2014_x86_64.whl.metadata (1.5 kB)
Collecting nvidia-cufft-cu12==192.170.209.163 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_cufft_cu12-192.170.209.163-py3-none-manylinux2014_x86_64.whl.metadata (1.5 kB)
Collecting nvidia-curand-cu12==169.206.230.214 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_curand_cu12-169.206.230.214-py3-none-manylinux2014_x86_64.whl.metadata (1.5 kB)
Collecting nvidia-cusolver-cu12==192.31.216.183 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_cusolver_cu12-192.31.216.183-py3-none-manylinux2014_x86_64.whl.metadata (1.6 kB)
Collecting nvidia-cusparse-cu12==137.51.111.20 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_cusparse_cu12-137.51.111.20-py3-none-manylinux2014_x86_64.whl.metadata (1.6 kB)
Requirement already satisfied: nvidia-cusparselt-cu12==0.6.2 in /usr/local/lib/python3.11/dist-packages (from torch>=1.8->segmentation_models_pytorch==0.4.0) (0.6.2)
Requirement already satisfied: nvidia-nccl-cu12==2.21.5 in /usr/local/lib/python3.11/dist-packages (from torch>=1.8->segmentation_models_pytorch==0.4.0) (2.21.5)
Requirement already satisfied: nvidia-nvtx-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch>=1.8->segmentation_models_pytorch==0.4.0) (12.4.127)
Collecting nvidia-nvjitlink-cu12==12.4.127 (from torch>=1.8->segmentation_models_pytorch==0.4.0)
Downloading nvidia_nvjitlink_cu12-12.4.127-py3-none-manylinux2014_x86_64.whl.metadata (1.5 kB)
Requirement already satisfied: triton==3.2.0 in /usr/local/lib/python3.11/dist-packages (from torch>=1.8->segmentation_models_pytorch==0.4.0) (3.2.0)
Requirement already satisfied: sympy==1.13.1 in /usr/local/lib/python3.11/dist-packages (from torch>=1.8->segmentation_models_pytorch==0.4.0) (1.13.1)
Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from sympy==1.13.1->torch>=1.8->segmentation_models_pytorch==0.4.0) (1.3.0)
Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.11/dist-packages (from jinja2->torch>=1.8->segmentation_models_pytorch==0.4.0) (3.0.2)
Requirement already satisfied: intel-openmp<2026,>=2024 in /usr/local/lib/python3.11/dist-packages (from mkl->numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (2024.2.0)
Requirement already satisfied: tbb==2022.* in /usr/local/lib/python3.11/dist-packages (from mkl->numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (2022.2.0)
Requirement already satisfied: tcmlib==1.* in /usr/local/lib/python3.11/dist-packages (from tbb==2022. in /usr/local/lib/python3.11/dist-packages (from mkl->numpy->medmnist) (2022.2.0)
Requirement already satisfied: tcmlib==1.* in /usr/local/lib/python3.11/dist-packages (from tbb==2022.,>=5.3.0 in /usr/local/lib/python3.11/dist-packages (from torchvision>=0.8.2->torchattacks) (11.2.1)
Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.11/dist-packages (from jinja2->torch>=1.7.1->torchattacks) (3.0.2)
Requirement already satisfied: intel-openmp<2026,>=2024 in /usr/local/lib/python3.11/dist-packages (from mkl->numpy>=1.19.4->torchattacks) (2024.2.0)
Requirement already satisfied: tbb==2022.* in /usr/local/lib/python3.11/dist-packages (from mkl->numpy>=1.19.4->torchattacks) (2022.2.0)
Requirement already satisfied: tcmlib==1.* in /usr/local/lib/python3.11/dist-packages (from tbb==2022.*->mkl->numpy>=1.19.4->torchattacks) (1.4.0)
Requirement already satisfied: intel-cmplr-lib-rt in /usr/local/lib/python3.11/dist-packages (from mkl_umath->numpy>=1.19.4->torchattacks) (2024.2.0)
Requirement already satisfied: intel-cmplr-lib-ur==2024.2.0 in /usr/local/lib/python3.11/dist-packages (from intel-openmp<2026,>=2024->mkl->numpy>=1.19.4->torchattacks) (2024.2.0)
Downloading torchattacks-3.5.1-py3-none-any.whl (142 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 142.0/142.0 kB 5.8 MB/s eta 0:00:00
Downloading requests-2.25.1-py2.py3-none-any.whl (61 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.2/61.2 kB 3.9 MB/s eta 0:00:00
Downloading chardet-4.0.0-py2.py3-none-any.whl (178 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 178.7/178.7 kB 11.4 MB/s eta 0:00:00
Downloading idna-2.10-py2.py3-none-any.whl (58 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 58.8/58.8 kB 4.1 MB/s eta 0:00:00
Downloading urllib3-1.26.20-py2.py3-none-any.whl (144 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 144.2/144.2 kB 10.4 MB/s eta 0:00:00
Installing collected packages: urllib3, idna, chardet, requests, torchattacks
Attempting uninstall: urllib3
Found existing installation: urllib3 2.5.0
Uninstalling urllib3-2.5.0:
Successfully uninstalled urllib3-2.5.0
Attempting uninstall: idna
Found existing installation: idna 3.10
Uninstalling idna-3.10:
Successfully uninstalled idna-3.10
Attempting uninstall: chardet
Found existing installation: chardet 5.2.0
Uninstalling chardet-5.2.0:
Successfully uninstalled chardet-5.2.0
Attempting uninstall: requests
Found existing installation: requests 2.32.4
Uninstalling requests-2.32.4:
Successfully uninstalled requests-2.32.4
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
bigframes 2.8.0 requires google-cloud-bigquery-storage<3.0.0,>=2.30.0, which is not installed.
libpysal 4.9.2 requires requests>=2.27, but you have requests 2.25.1 which is incompatible.
datasets 3.6.0 requires fsspec[http]<=2025.3.0,>=2023.1.0, but you have fsspec 2025.5.1 which is incompatible.
datasets 3.6.0 requires requests>=2.32.2, but you have requests 2.25.1 which is incompatible.
jupyterlab-server 2.27.3 requires requests>=2.31, but you have requests 2.25.1 which is incompatible.
docker 7.1.0 requires requests>=2.26.0, but you have requests 2.25.1 which is incompatible.
google-colab 1.0.0 requires google-auth==2.38.0, but you have google-auth 2.40.3 which is incompatible.
google-colab 1.0.0 requires notebook==6.5.7, but you have notebook 6.5.4 which is incompatible.
google-colab 1.0.0 requires pandas==2.2.2, but you have pandas 2.2.3 which is incompatible.
google-colab 1.0.0 requires requests==2.32.3, but you have requests 2.25.1 which is incompatible.
google-colab 1.0.0 requires tornado==6.4.2, but you have tornado 6.5.1 which is incompatible.
pandas-gbq 0.29.1 requires google-api-core<3.0.0,>=2.10.2, but you have google-api-core 1.34.1 which is incompatible.
google-genai 1.21.1 requires requests<3.0.0,>=2.28.1, but you have requests 2.25.1 which is incompatible.
gcsfs 2025.3.2 requires fsspec==2025.3.2, but you have fsspec 2025.5.1 which is incompatible.
langchain-core 0.3.66 requires packaging<25,>=23.2, but you have packaging 25.0 which is incompatible.
google-cloud-storage 2.19.0 requires google-api-core<3.0.0dev,>=2.15.0, but you have google-api-core 1.34.1 which is incompatible.
yfinance 0.2.63 requires requests>=2.31, but you have requests 2.25.1 which is incompatible.
dataproc-spark-connect 0.7.5 requires google-api-core>=2.19, but you have google-api-core 1.34.1 which is incompatible.
sphinx 8.2.3 requires requests>=2.30.0, but you have requests 2.25.1 which is incompatible.
bigframes 2.8.0 requires google-cloud-bigquery[bqstorage,pandas]>=3.31.0, but you have google-cloud-bigquery 3.25.0 which is incompatible.
bigframes 2.8.0 requires requests>=2.27.1, but you have requests 2.25.1 which is incompatible.
bigframes 2.8.0 requires rich<14,>=12.4.4, but you have rich 14.0.0 which is incompatible.
tiktoken 0.9.0 requires requests>=2.26.0, but you have requests 2.25.1 which is incompatible.
jupyter-kernel-gateway 2.5.2 requires jupyter-client<8.0,>=5.2.0, but you have jupyter-client 8.6.3 which is incompatible.
tweepy 4.15.0 requires requests<3,>=2.27.0, but you have requests 2.25.1 which is incompatible.
Successfully installed chardet-4.0.0 idna-2.10 requests-2.25.1 torchattacks-3.5.1 urllib3-1.26.20
add Codeadd Markdown
from torchmetrics.image import PeakSignalNoiseRatio
import torch
add Codeadd Markdown
final_clean_images = torch.cat(all_clean_images)
final_carlini_images = torch.cat(all_carlini_images)
final_labels = torch.cat(all_clean_labels)
Assistant
Got it — then in your AdaptiveLaplacianPyramidUNet.forward() you just need to make sure you unpack the encoder outputs before sending them into the decoder.
Right now you likely have something like:
pythonCopyEditfeatures = self.encoder(noisy_image)
decoder_output = self.decoder(features) # ❌ passing tuple as a single tensor
That should be:
pythonCopyEditfeatures = self.encoder(noisy_image)
decoder_output = self.decoder(*features) # ✅ unpack tuple into separate args
This change alone should stop the
pgsqlCopyEditIndexError: tuple index out of range
because segmentation_models_pytorch’s UnetDecoder expects one argument per feature map (reversed internally), not a single tuple.
Since you’re using the pyramid structure, you just have to ensure that:
features returned by your encoder is a tuple of all stage outputs, e.g. (x0, x1, x2, x3, x4, x5).
The length matches your encoder depth + 1.
If the encoder currently only returns the final feature map, we’ll also need to change it to collect outputs at each stage.
Do you want me to show you the exact minimal forward() for AdaptiveLaplacianPyramidUNet so it’s fully SMP-compatible and works with your forward_3_kernel()?
Returns:
train_loader, val_loader, test_loader with (clean_img, carlini_adv_img, label) format
"""
if attack_config is None:
attack_config = {'c': 1e-2, 'kappa': 0, 'steps': 1000, 'lr': 0.01}
# Setup
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")
# Load MedMNIST dataset
print(f"\n1. Loading {data_flag} dataset...")
info = INFO[data_flag]
n_classes = len(info['label'])
DataClass = getattr(medmnist, info['python_class'])
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
# Load all available data
train_dataset = DataClass(split='train', transform=transform, download=True)
test_dataset = DataClass(split='test', transform=transform, download=True)
val_dataset = DataClass(split='val', transform=transform, download=True)
# Combine all splits to get maximum data
all_images = []
all_labels = []
print("Collecting all available samples...")
for dataset in [train_dataset, val_dataset, test_dataset]:
loader = DataLoader(dataset, batch_size=128, shuffle=False)
for images, labels in loader:
all_images.append(images)
all_labels.append(labels)
all_images = torch.cat(all_images)
all_labels = torch.cat(all_labels)
print(f"Total samples collected: {len(all_images)}")
# Create initial train/val split for model training (80/20)
total_samples = len(all_images)
train_size = int(0.8 * total_samples)
val_size = total_samples - train_size
torch.manual_seed(42) # For reproducible splits
indices = torch.randperm(total_samples)
train_indices = indices[:train_size]
val_indices = indices[train_size:]
train_images = all_images[train_indices]
train_labels = all_labels[train_indices]
val_images = all_images[val_indices]
val_labels = all_labels[val_indices]
# Create training dataloaders
train_dataset_temp = TensorDataset(train_images, train_labels)
val_dataset_temp = TensorDataset(val_images, val_labels)
train_loader_temp = DataLoader(train_dataset_temp, batch_size=64, shuffle=True)
val_loader_temp = DataLoader(val_dataset_temp, batch_size=64, shuffle=False)
print(f"Training split: {len(train_images)} samples")
print(f"Validation split: {len(val_images)} samples")
# 2. Train the model properly
print(f"\n2. Training ResNet18_MedMNIST model...")
model = ResNet18_MedMNIST(num_classes=n_classes).to(device)
model = train_model_properly(model, train_loader_temp, val_loader_temp, device, epochs=train_epochs)
# Load best model
model.load_state_dict(torch.load('best_resnet18_medmnist.pth'))
model.eval()
# 3. Generate Carlini attacks for ALL samples
print(f"\n3. Generating Carlini-Wagner attacks for all samples...")
batch_size = 32 # Process in smaller batches for memory efficiency
all_clean_images = []
all_carlini_images = []
all_clean_labels = []
# Process all samples in batches
for i in range(0, len(all_images), batch_size):
batch_images = all_images[i:i+batch_size]
batch_labels = all_labels[i:i+batch_size].squeeze().long()
# Generate Carlini attacks for this batch
carlini_batch = generate_real_carlini_attacks(
model, batch_images, batch_labels, **attack_config
)
all_clean_images.append(batch_images)
all_carlini_images.append(carlini_batch)
all_clean_labels.append(batch_labels)
if (i // batch_size + 1) % 10 == 0:
print(f" Processed {i+len(batch_images)}/{len(all_images)} samples")
# Concatenate all batches
final_clean_images = torch.cat(all_clean_images)
final_carlini_images = torch.cat(all_carlini_images)
final_labels = torch.cat(all_clean_labels)
print(f"✓ Generated {len(final_clean_images)} Carlini adversarial examples")
# 4. Create final train/val/test splits (70/15/15)
print(f"\n4. Creating final train/val/test splits...")
total_final = len(final_clean_images)
final_train_size = int(0.7 * total_final)
final_val_size = int(0.15 * total_final)
final_test_size = total_final - final_train_size - final_val_size
# Shuffle and split
torch.manual_seed(42)
final_indices = torch.randperm(total_final)
train_idx = final_indices[:final_train_size]
val_idx = final_indices[final_train_size:final_train_size + final_val_size]
test_idx = final_indices[final_train_size + final_val_size:]
# Create final datasets
train_clean = final_clean_images[train_idx]
train_carlini = final_carlini_images[train_idx]
train_labels_final = final_labels[train_idx]
val_clean = final_clean_images[val_idx]
val_carlini = final_carlini_images[val_idx]
val_labels_final = final_labels[val_idx]
test_clean = final_clean_images[test_idx]
test_carlini = final_carlini_images[test_idx]
test_labels_final = final_labels[test_idx]
# Create final dataloaders with (clean_img, adv_img, label) format
train_dataset_final = TensorDataset(train_clean, train_carlini, train_labels_final)
val_dataset_final = TensorDataset(val_clean, val_carlini, val_labels_final)
test_dataset_final = TensorDataset(test_clean, test_carlini, test_labels_final)
train_loader = DataLoader(train_dataset_final, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset_final, batch_size=32, shuffle=False)
test_loader = DataLoader(test_dataset_final, batch_size=32, shuffle=False)
print(f"✓ Final splits created:")
print(f" Train: {len(train_dataset_final)} samples ({len(train_dataset_final)/total_final:.1%})")
print(f" Val: {len(val_dataset_final)} samples ({len(val_dataset_final)/total_final:.1%})")
print(f" Test: {len(test_dataset_final)} samples ({len(test_dataset_final)/total_final:.1%})")
return train_loader, val_loader, test_loader
Now you can iterate like before:
for clean_img, adv_img, label in train_loader:
print(clean_img.shape, adv_img.shape, label)
break
How It Works
It looks for files starting with "clean_" and "carlini_" in the given directory.
It sorts them to keep matching pairs aligned.
It extracts the class label from the filename (because you stored label_X).
It returns them in (clean_img, adv_img, label) format exactly like your in-memory pipeline.
If your saving function keeps the same naming convention, this loader will always give you a dataset identical in structure to the one you had before saving.
If you want, I can make a unified loader that can load train/val/test from carlini_attacks/ in one go and give you all three dataloaders exactly like create_complete_carlini_pipeline() did. That way you can resume work without retraining or regenerating. Would you like me to do that next?
->mkl->numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (1.4.0)
Requirement already satisfied: intel-cmplr-lib-rt in /usr/local/lib/python3.11/dist-packages (from mkl_umath->numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (2024.2.0)
Requirement already satisfied: charset_normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests->huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (3.4.2)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests->huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (3.10)
Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests->huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (2.5.0)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests->huggingface-hub>=0.24->segmentation_models_pytorch==0.4.0) (2025.6.15)
Requirement already satisfied: intel-cmplr-lib-ur==2024.2.0 in /usr/local/lib/python3.11/dist-packages (from intel-openmp<2026,>=2024->mkl->numpy>=1.19.3->segmentation_models_pytorch==0.4.0) (2024.2.0)
Downloading segmentation_models_pytorch-0.4.0-py3-none-any.whl (121 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 121.3/121.3 kB 7.7 MB/s eta 0:00:00
Downloading nvidia_cublas_cu12-192.0.1.221-py3-none-manylinux2014_x86_64.whl (363.4 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 363.4/363.4 MB 4.7 MB/s eta 0:00:00:00:0100:01
Downloading nvidia_cuda_cupti_cu12-12.4.127-py3-none-manylinux2014_x86_64.whl (13.8 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 13.8/13.8 MB 102.5 MB/s eta 0:00:0000:010:01
Downloading nvidia_cuda_nvrtc_cu12-12.4.127-py3-none-manylinux2014_x86_64.whl (24.6 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 24.6/24.6 MB 78.4 MB/s eta 0:00:00:00:0100:01
Downloading nvidia_cuda_runtime_cu12-12.4.127-py3-none-manylinux2014_x86_64.whl (883 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 883.7/883.7 kB 45.7 MB/s eta 0:00:00
Downloading nvidia_cudnn_cu12-192.172.18.13-py3-none-manylinux2014_x86_64.whl (664.8 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 664.8/664.8 MB 2.5 MB/s eta 0:00:00:00:0100:01
Downloading nvidia_cufft_cu12-192.170.209.163-py3-none-manylinux2014_x86_64.whl (211.5 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 211.5/211.5 MB 4.9 MB/s eta 0:00:00:00:0100:01
Downloading nvidia_curand_cu12-169.206.230.214-py3-none-manylinux2014_x86_64.whl (56.3 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 56.3/56.3 MB 29.3 MB/s eta 0:00:00:00:0100:01
Downloading nvidia_cusolver_cu12-192.31.216.183-py3-none-manylinux2014_x86_64.whl (127.9 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 127.9/127.9 MB 13.4 MB/s eta 0:00:0000:0100:01
Downloading nvidia_cusparse_cu12-137.51.111.20-py3-none-manylinux2014_x86_64.whl (207.5 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 207.5/207.5 MB 2.2 MB/s eta 0:00:00:00:0100:01
Downloading nvidia_nvjitlink_cu12-12.4.127-py3-none-manylinux2014_x86_64.whl (21.1 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 21.1/21.1 MB 88.2 MB/s eta 0:00:00:00:0100:01
Downloading munch-4.0.0-py2.py3-none-any.whl (9.9 kB)
Building wheels for collected packages: efficientnet-pytorch, pretrainedmodels
Building wheel for efficientnet-pytorch (setup.py) ... done
Created wheel for efficientnet-pytorch: filename=efficientnet_pytorch-0.7.1-py3-none-any.whl size=16426 sha256=XXX
Stored in directory: /root/.cache/pip/wheels/8b/6f/9b/XXX
Building wheel for pretrainedmodels (setup.py) ... done
Created wheel for pretrainedmodels: filename=pretrainedmodels-0.7.4-py3-none-any.whl size=60945 sha256=XXX
Stored in directory: /root/.cache/pip/wheels/5f/5b/96/XXX
Successfully built efficientnet-pytorch pretrainedmodels
Installing collected packages: nvidia-nvjitlink-cu12, nvidia-curand-cu12, nvidia-cufft-cu12, nvidia-cuda-runtime-cu12, nvidia-cuda-nvrtc-cu12, nvidia-cuda-cupti-cu12, nvidia-cublas-cu12, munch, nvidia-cusparse-cu12, nvidia-cudnn-cu12, nvidia-cusolver-cu12, efficientnet-pytorch, pretrainedmodels, segmentation_models_pytorch
Attempting uninstall: nvidia-nvjitlink-cu12
Found existing installation: nvidia-nvjitlink-cu12 12.5.82
Uninstalling nvidia-nvjitlink-cu12-12.5.82:
Successfully uninstalled nvidia-nvjitlink-cu12-12.5.82
Attempting uninstall: nvidia-curand-cu12
Found existing installation: nvidia-curand-cu12 192.52.96.45
Uninstalling nvidia-curand-cu12-192.52.96.45:
Successfully uninstalled nvidia-curand-cu12-192.52.96.45
Attempting uninstall: nvidia-cufft-cu12
Found existing installation: nvidia-cufft-cu12 192.175.55.194
Uninstalling nvidia-cufft-cu12-192.175.55.194:
Successfully uninstalled nvidia-cufft-cu12-192.175.55.194
Attempting uninstall: nvidia-cuda-runtime-cu12
Found existing installation: nvidia-cuda-runtime-cu12 12.5.82
Uninstalling nvidia-cuda-runtime-cu12-12.5.82:
Successfully uninstalled nvidia-cuda-runtime-cu12-12.5.82
Attempting uninstall: nvidia-cuda-nvrtc-cu12
Found existing installation: nvidia-cuda-nvrtc-cu12 12.5.82
Uninstalling nvidia-cuda-nvrtc-cu12-12.5.82:
Successfully uninstalled nvidia-cuda-nvrtc-cu12-12.5.82
Attempting uninstall: nvidia-cuda-cupti-cu12
Found existing installation: nvidia-cuda-cupti-cu12 12.5.82
Uninstalling nvidia-cuda-cupti-cu12-12.5.82:
Successfully uninstalled nvidia-cuda-cupti-cu12-12.5.82
Attempting uninstall: nvidia-cublas-cu12
Found existing installation: nvidia-cublas-cu12 203.0.117.129
Uninstalling nvidia-cublas-cu12-203.0.117.129:
Successfully uninstalled nvidia-cublas-cu12-203.0.117.129
Attempting uninstall: nvidia-cusparse-cu12
Found existing installation: nvidia-cusparse-cu12 100.184.117.135
Uninstalling nvidia-cusparse-cu12-100.184.117.135:
Successfully uninstalled nvidia-cusparse-cu12-100.184.117.135
Attempting uninstall: nvidia-cudnn-cu12
Found existing installation: nvidia-cudnn-cu12 198.48.205.170
Uninstalling nvidia-cudnn-cu12-198.48.205.170:
Successfully uninstalled nvidia-cudnn-cu12-198.48.205.170
Attempting uninstall: nvidia-cusolver-cu12
Found existing installation: nvidia-cusolver-cu12 101.181.76.185
Uninstalling nvidia-cusolver-cu12-101.181.76.185:
Successfully uninstalled nvidia-cusolver-cu12-101.181.76.185
Successfully installed efficientnet-pytorch-0.7.1 munch-4.0.0 nvidia-cublas-cu12-192.0.1.221 nvidia-cuda-cupti-cu12-12.4.127 nvidia-cuda-nvrtc-cu12-12.4.127 nvidia-cuda-runtime-cu12-12.4.127 nvidia-cudnn-cu12-192.172.18.13 nvidia-cufft-cu12-192.170.209.163 nvidia-curand-cu12-169.206.230.214 nvidia-cusolver-cu12-192.31.216.183 nvidia-cusparse-cu12-137.51.111.20 nvidia-nvjitlink-cu12-12.4.127 pretrainedmodels-0.7.4 segmentation_models_pytorch-0.4.0
Collecting medmnist
Downloading medmnist-3.0.2-py3-none-any.whl.metadata (14 kB)
Requirement already satisfied: numpy in /usr/local/lib/python3.11/dist-packages (from medmnist) (1.26.4)
Requirement already satisfied: pandas in /usr/local/lib/python3.11/dist-packages (from medmnist) (2.2.3)
Requirement already satisfied: scikit-learn in /usr/local/lib/python3.11/dist-packages (from medmnist) (1.2.2)
Requirement already satisfied: scikit-image in /usr/local/lib/python3.11/dist-packages (from medmnist) (0.25.2)
Requirement already satisfied: tqdm in /usr/local/lib/python3.11/dist-packages (from medmnist) (4.67.1)
Requirement already satisfied: Pillow in /usr/local/lib/python3.11/dist-packages (from medmnist) (11.2.1)
Collecting fire (from medmnist)
Downloading fire-0.7.0.tar.gz (87 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 87.2/87.2 kB 4.2 MB/s eta 0:00:00
Preparing metadata (setup.py) ... done
Requirement already satisfied: torch in /usr/local/lib/python3.11/dist-packages (from medmnist) (2.6.0+cu124)
Requirement already satisfied: torchvision in /usr/local/lib/python3.11/dist-packages (from medmnist) (0.21.0+cu124)
Requirement already satisfied: termcolor in /usr/local/lib/python3.11/dist-packages (from fire->medmnist) (3.1.0)
Requirement already satisfied: mkl_fft in /usr/local/lib/python3.11/dist-packages (from numpy->medmnist) (1.3.8)
Requirement already satisfied: mkl_random in /usr/local/lib/python3.11/dist-packages (from numpy->medmnist) (1.2.4)
Requirement already satisfied: mkl_umath in /usr/local/lib/python3.11/dist-packages (from numpy->medmnist) (0.1.1)
Requirement already satisfied: mkl in /usr/local/lib/python3.11/dist-packages (from numpy->medmnist) (2025.2.0)
Requirement already satisfied: tbb4py in /usr/local/lib/python3.11/dist-packages (from numpy->medmnist) (2022.2.0)
Requirement already satisfied: mkl-service in /usr/local/lib/python3.11/dist-packages (from numpy->medmnist) (2.4.1)
Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas->medmnist) (2.9.0.post0)
Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas->medmnist) (2025.2)
Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas->medmnist) (2025.2)
Requirement already satisfied: scipy>=1.11.4 in /usr/local/lib/python3.11/dist-packages (from scikit-image->medmnist) (1.15.3)
Requirement already satisfied: networkx>=3.0 in /usr/local/lib/python3.11/dist-packages (from scikit-image->medmnist) (3.5)
Requirement already satisfied: imageio!=2.35.0,>=2.33 in /usr/local/lib/python3.11/dist-packages (from scikit-image->medmnist) (2.37.0)
Requirement already satisfied: tifffile>=2022.8.12 in /usr/local/lib/python3.11/dist-packages (from scikit-image->medmnist) (2025.6.11)
Requirement already satisfied: packaging>=21 in /usr/local/lib/python3.11/dist-packages (from scikit-image->medmnist) (25.0)
Requirement already satisfied: lazy-loader>=0.4 in /usr/local/lib/python3.11/dist-packages (from scikit-image->medmnist) (0.4)
Requirement already satisfied: joblib>=1.1.1 in /usr/local/lib/python3.11/dist-packages (from scikit-learn->medmnist) (1.5.1)
Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.11/dist-packages (from scikit-learn->medmnist) (3.6.0)
Requirement already satisfied: filelock in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (3.18.0)
Requirement already satisfied: typing-extensions>=4.10.0 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (4.14.0)
Requirement already satisfied: jinja2 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (3.1.6)
Requirement already satisfied: fsspec in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (2025.5.1)
Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (12.4.127)
Requirement already satisfied: nvidia-cuda-runtime-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (12.4.127)
Requirement already satisfied: nvidia-cuda-cupti-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (12.4.127)
Requirement already satisfied: nvidia-cudnn-cu12==192.172.18.13 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (192.172.18.13)
Requirement already satisfied: nvidia-cublas-cu12==192.0.1.221 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (192.0.1.221)
Requirement already satisfied: nvidia-cufft-cu12==192.170.209.163 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (192.170.209.163)
Requirement already satisfied: nvidia-curand-cu12==169.206.230.214 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (169.206.230.214)
Requirement already satisfied: nvidia-cusolver-cu12==192.31.216.183 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (192.31.216.183)
Requirement already satisfied: nvidia-cusparse-cu12==137.51.111.20 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (137.51.111.20)
Requirement already satisfied: nvidia-cusparselt-cu12==0.6.2 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (0.6.2)
Requirement already satisfied: nvidia-nccl-cu12==2.21.5 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (2.21.5)
Requirement already satisfied: nvidia-nvtx-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (12.4.127)
Requirement already satisfied: nvidia-nvjitlink-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (12.4.127)
Requirement already satisfied: triton==3.2.0 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (3.2.0)
Requirement already satisfied: sympy==1.13.1 in /usr/local/lib/python3.11/dist-packages (from torch->medmnist) (1.13.1)
Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from sympy==1.13.1->torch->medmnist) (1.3.0)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil>=2.8.2->pandas->medmnist) (1.17.0)
Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.11/dist-packages (from jinja2->torch->medmnist) (3.0.2)
Requirement already satisfied: intel-openmp<2026,>=2024 in /usr/local/lib/python3.11/dist-packages (from mkl->numpy->medmnist) (2024.2.0)
Requirement already satisfied: tbb==2022.
->mkl->numpy->medmnist) (1.4.0)
Requirement already satisfied: intel-cmplr-lib-rt in /usr/local/lib/python3.11/dist-packages (from mkl_umath->numpy->medmnist) (2024.2.0)
Requirement already satisfied: intel-cmplr-lib-ur==2024.2.0 in /usr/local/lib/python3.11/dist-packages (from intel-openmp<2026,>=2024->mkl->numpy->medmnist) (2024.2.0)
Downloading medmnist-3.0.2-py3-none-any.whl (25 kB)
Building wheels for collected packages: fire
Building wheel for fire (setup.py) ... done
Created wheel for fire: filename=fire-0.7.0-py3-none-any.whl size=114249 sha256=XXX
Stored in directory: /root/.cache/pip/wheels/46/54/24/XXX
Successfully built fire
Installing collected packages: fire, medmnist
Successfully installed fire-0.7.0 medmnist-3.0.2
Collecting torchattacks
Downloading torchattacks-3.5.1-py3-none-any.whl.metadata (927 bytes)
Requirement already satisfied: torch>=1.7.1 in /usr/local/lib/python3.11/dist-packages (from torchattacks) (2.6.0+cu124)
Requirement already satisfied: torchvision>=0.8.2 in /usr/local/lib/python3.11/dist-packages (from torchattacks) (0.21.0+cu124)
Requirement already satisfied: scipy>=0.14.0 in /usr/local/lib/python3.11/dist-packages (from torchattacks) (1.15.3)
Requirement already satisfied: tqdm>=4.56.1 in /usr/local/lib/python3.11/dist-packages (from torchattacks) (4.67.1)
Collecting requests~=2.25.1 (from torchattacks)
Downloading requests-2.25.1-py2.py3-none-any.whl.metadata (4.2 kB)
Requirement already satisfied: numpy>=1.19.4 in /usr/local/lib/python3.11/dist-packages (from torchattacks) (1.26.4)
Requirement already satisfied: mkl_fft in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.4->torchattacks) (1.3.8)
Requirement already satisfied: mkl_random in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.4->torchattacks) (1.2.4)
Requirement already satisfied: mkl_umath in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.4->torchattacks) (0.1.1)
Requirement already satisfied: mkl in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.4->torchattacks) (2025.2.0)
Requirement already satisfied: tbb4py in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.4->torchattacks) (2022.2.0)
Requirement already satisfied: mkl-service in /usr/local/lib/python3.11/dist-packages (from numpy>=1.19.4->torchattacks) (2.4.1)
Collecting chardet<5,>=3.0.2 (from requests~=2.25.1->torchattacks)
Downloading chardet-4.0.0-py2.py3-none-any.whl.metadata (3.5 kB)
Collecting idna<3,>=2.5 (from requests~=2.25.1->torchattacks)
Downloading idna-2.10-py2.py3-none-any.whl.metadata (9.1 kB)
Collecting urllib3<1.27,>=1.21.1 (from requests~=2.25.1->torchattacks)
Downloading urllib3-1.26.20-py2.py3-none-any.whl.metadata (50 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 50.1/50.1 kB 2.1 MB/s eta 0:00:00
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests~=2.25.1->torchattacks) (2025.6.15)
Requirement already satisfied: filelock in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (3.18.0)
Requirement already satisfied: typing-extensions>=4.10.0 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (4.14.0)
Requirement already satisfied: networkx in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (3.5)
Requirement already satisfied: jinja2 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (3.1.6)
Requirement already satisfied: fsspec in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (2025.5.1)
Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (12.4.127)
Requirement already satisfied: nvidia-cuda-runtime-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (12.4.127)
Requirement already satisfied: nvidia-cuda-cupti-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (12.4.127)
Requirement already satisfied: nvidia-cudnn-cu12==192.172.18.13 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (192.172.18.13)
Requirement already satisfied: nvidia-cublas-cu12==192.0.1.221 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (192.0.1.221)
Requirement already satisfied: nvidia-cufft-cu12==192.170.209.163 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (192.170.209.163)
Requirement already satisfied: nvidia-curand-cu12==169.206.230.214 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (169.206.230.214)
Requirement already satisfied: nvidia-cusolver-cu12==192.31.216.183 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (192.31.216.183)
Requirement already satisfied: nvidia-cusparse-cu12==137.51.111.20 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (137.51.111.20)
Requirement already satisfied: nvidia-cusparselt-cu12==0.6.2 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (0.6.2)
Requirement already satisfied: nvidia-nccl-cu12==2.21.5 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (2.21.5)
Requirement already satisfied: nvidia-nvtx-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (12.4.127)
Requirement already satisfied: nvidia-nvjitlink-cu12==12.4.127 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (12.4.127)
Requirement already satisfied: triton==3.2.0 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (3.2.0)
Requirement already satisfied: sympy==1.13.1 in /usr/local/lib/python3.11/dist-packages (from torch>=1.7.1->torchattacks) (1.13.1)
Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from sympy==1.13.1->torch>=1.7.1->torchattacks) (1.3.0)
Requirement already satisfied: pillow!=8.3.
Saving all generated Carlini attacks...
add Codeadd Markdown
import os
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
# Find all clean images and match with their corresponding adversarial images
clean_files = sorted([f for f in os.listdir(root_dir) if f.startswith("clean_")])
adv_files = sorted([f for f in os.listdir(root_dir) if f.startswith("carlini_")])
if len(clean_files) != len(adv_files):
raise ValueError("Mismatch between clean and Carlini image counts!")
# Pair them together
self.pairs = []
for clean_f, adv_f in zip(clean_files, adv_files):
# Extract label from filename (last part after '_label_')
label_str = clean_f.split("_label_")[-1].replace(".png", "")
label = int(label_str)
self.pairs.append((clean_f, adv_f, label))
def __len__(self):
return len(self.pairs)
def __getitem__(self, idx):
clean_f, adv_f, label = self.pairs[idx]
clean_img = Image.open(os.path.join(self.root_dir, clean_f)).convert("RGB")
adv_img = Image.open(os.path.join(self.root_dir, adv_f)).convert("RGB")
if self.transform:
clean_img = self.transform(clean_img)
adv_img = self.transform(adv_img)
return clean_img, adv_img, label
# Segmentation head
self.segmentation_head = nn.Conv2d(
decoder_channels[-1],
3,
kernel_size=3,
padding=1
)
# Feature adapters
self.feature_adapters = nn.ModuleList()
for target_channels in encoder_channels[1:]:
adapter = PyramidToEncoderAdapter(3, target_channels)
self.feature_adapters.append(adapter)
print(f"Created {len(self.feature_adapters)} feature adapters")
print(f"Using adaptive kernels of size {kernel_size}x{kernel_size}")
# def forward(self, noisy_image):
# """
# Forward pass with adaptive kernel prediction
# """
# # Get adaptive pyramid decomposition
# pyramid, adaptive_kernel = self.pyramid_encoder(noisy_image)
# # Convert pyramid to encoder-like features
# features = [noisy_image]
# for i, pyramid_level in enumerate(pyramid):
# if i < len(self.feature_adapters):
# adapted_features = self.feature_adapters[i](pyramid_level)
# features.append(adapted_features)
# # Pass through decoder
# decoder_output = self.decoder(features)
# # Apply segmentation head
# denoised_features = self.segmentation_head(decoder_output)
# # Ensure output matches input size
# if denoised_features.shape[2:] != noisy_image.shape[2:]:
# denoised_features = F.interpolate(
# denoised_features,
# size=noisy_image.shape[2:],
# mode='bilinear',
# align_corners=False
# )
# # Residual connection
# output = noisy_image + denoised_features
# return output, adaptive_kernel
def forward(self, clean_image, adversarial_image):
# kernel from clean image
pyramid_levels, clean_kernel = self.pyramid_encoder(clean_image)
# output and kernel from adversarial image
output, adversarial_kernel = self.forward(adversarial_image)
l2_loss = F.mse_loss(adversarial_kernel, clean_kernel)
l1_loss = F.mse_loss(output, clean_image)
return output, l2_loss, l1_loss
add Codeadd Markdown
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
psnr_metric = PeakSignalNoiseRatio(data_range=1.0).to(device)
add Codeadd Markdown
arrow_upwardarrow_downwarddelete
import torch
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import medmnist
from medmnist import INFO
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')