Witllm/unsuper/minist.py

214 lines
7.9 KiB
Python
Raw Normal View History

2024-08-18 17:42:00 +08:00
import os
import sys
2024-07-31 22:04:01 +08:00
import torch
import torch.nn as nn
import torch.nn.functional as F # Add this line
import torchvision
import torchvision.transforms as transforms
2024-08-18 17:42:00 +08:00
sys.path.append("..")
from tools import show
seed = 4321
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
2024-07-31 22:04:01 +08:00
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
2024-08-29 16:47:06 +08:00
# device = torch.device("mps")
2024-07-31 22:04:01 +08:00
2024-08-18 17:42:00 +08:00
num_epochs = 1
2024-09-02 18:06:47 +08:00
batch_size = 64
2024-07-31 22:04:01 +08:00
2024-08-18 00:46:36 +08:00
transform = transforms.Compose([transforms.ToTensor()])
2024-07-31 22:04:01 +08:00
2024-08-18 00:46:36 +08:00
train_dataset = torchvision.datasets.MNIST(root="./data", train=True, download=True, transform=transform)
test_dataset = torchvision.datasets.MNIST(root="./data", train=False, download=True, transform=transform)
2024-07-31 22:04:01 +08:00
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
2024-10-22 13:54:26 +08:00
self.conv1 = nn.Conv2d(1, 8, 3, 1, 0)
2024-07-31 22:04:01 +08:00
self.pool = nn.MaxPool2d(2, 2)
2024-09-02 17:52:33 +08:00
self.conv2 = nn.Conv2d(8, 1, 5, 1, 0)
self.fc1 = nn.Linear(1 * 4 * 4, 10)
2024-07-31 22:04:01 +08:00
def forward(self, x):
x = self.forward_unsuper(x)
x = self.pool(x)
2024-09-08 15:22:12 +08:00
x = self.pool(self.conv2(x))
2024-09-02 17:52:33 +08:00
x = x.view(x.shape[0], -1)
2024-09-08 15:22:12 +08:00
x = self.fc1(x)
return x
2024-10-22 13:54:26 +08:00
def normal_conv1_weight(self):
weight = self.conv1.weight.reshape(self.conv1.weight.shape[0], -1)
weight = weight.permute(1, 0)
mean = torch.mean(weight, dim=0)
weight = weight - mean
sum = torch.sum(torch.abs(weight), dim=0)
weight = weight / sum
weight = weight.permute(1, 0)
weight = weight.reshape(self.conv1.weight.shape)
2024-10-22 13:54:26 +08:00
return weight
def forward_unsuper(self, x):
x = torch.conv2d(x, self.normal_conv1_weight(), stride=1)
2024-07-31 22:04:01 +08:00
return x
2024-09-08 15:22:12 +08:00
def printFector(self, x, label, dir=""):
show.DumpTensorToImage(x.view(-1, x.shape[2], x.shape[3]), dir + "/input_image.png", Contrast=[0, 1.0])
2024-08-29 16:47:06 +08:00
# show.DumpTensorToLog(x, "input_image.log")
2024-10-22 13:54:26 +08:00
w = self.normal_conv1_weight()
x = torch.conv2d(x, w)
show.DumpTensorToImage(w.view(-1, w.shape[2], w.shape[3]), dir + "/conv1_weight.png")
2024-08-29 16:47:06 +08:00
# show.DumpTensorToLog(w, "conv1_weight.log")
2024-10-22 13:54:26 +08:00
show.DumpTensorToImage(x.view(-1, x.shape[2], x.shape[3]), dir + "/conv1_output.png")
2024-08-29 16:47:06 +08:00
# show.DumpTensorToLog(x, "conv1_output.png")
2024-08-18 17:42:00 +08:00
2024-09-22 15:18:08 +08:00
x = self.pool(x)
2024-08-18 17:42:00 +08:00
x = self.conv2(x)
w = self.conv2.weight
2024-10-22 13:54:26 +08:00
show.DumpTensorToImage(w.view(-1, w.shape[2], w.shape[3]).cpu(), dir + "/conv2_weight.png")
show.DumpTensorToImage(x.view(-1, x.shape[2], x.shape[3]).cpu(), dir + "/conv2_output.png")
2024-09-22 15:18:08 +08:00
x = self.pool(x)
2024-10-22 13:54:26 +08:00
show.DumpTensorToImage(x.view(-1, x.shape[2], x.shape[3]).cpu(), dir + "/pool_output.png")
2024-09-02 17:52:33 +08:00
pool_shape = x.shape
x = x.view(x.shape[0], -1)
2024-08-18 17:42:00 +08:00
x = self.fc1(x)
2024-09-02 17:52:33 +08:00
show.DumpTensorToImage(
2024-09-08 15:22:12 +08:00
self.fc1.weight.view(-1, pool_shape[2], pool_shape[3]), dir + "/fc_weight.png", Contrast=[-1.0, 1.0]
2024-09-02 17:52:33 +08:00
)
2024-09-08 15:22:12 +08:00
show.DumpTensorToImage(x.view(-1).cpu(), dir + "/fc_output.png")
2024-08-18 17:42:00 +08:00
criterion = nn.CrossEntropyLoss()
loss = criterion(x, label)
loss.backward()
2024-09-08 15:22:12 +08:00
if self.conv1.weight.requires_grad:
w = self.conv1.weight.grad
show.DumpTensorToImage(w.view(-1, w.shape[2], w.shape[3]).cpu(), dir + "/conv1_weight_grad.png")
if self.conv2.weight.requires_grad:
w = self.conv2.weight.grad
show.DumpTensorToImage(w.view(-1, w.shape[2], w.shape[3]), dir + "/conv2_weight_grad.png")
if self.fc1.weight.requires_grad:
show.DumpTensorToImage(
self.fc1.weight.grad.view(-1, pool_shape[2], pool_shape[3]), dir + "/fc_weight_grad.png"
)
2024-08-18 17:42:00 +08:00
2024-07-31 22:04:01 +08:00
model = ConvNet().to(device)
2024-09-08 15:22:12 +08:00
model.train()
# Train the model unsuper
2024-10-22 13:54:26 +08:00
epochs = 1
2024-09-08 15:22:12 +08:00
n_total_steps = len(train_loader)
for epoch in range(epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.to(device)
2024-10-22 13:54:26 +08:00
# # images = images[:,:,12:15,12:15]
# kernel_size = 3
# mean_filter = torch.ones((1, 1, kernel_size, kernel_size), device=device) / (kernel_size * kernel_size)
# images = F.conv2d(images, mean_filter, padding=1)
# images = F.conv2d(images, mean_filter, padding=1)
# images = F.conv2d(images, mean_filter, padding=1)
# # images = F.conv2d(images, mean_filter, padding=1)
# # images = F.conv2d(images, mean_filter, padding=1)
# images = torch.rand(3, 3).to(device=device)
# # images[1, 1] = images[1, 1] * 2
# # images[0, 0] = images[1, 1] * 2
# # images[2, 2] = images[1, 1] * 2
# images = images.view(1, 1, 3, 3)
2024-09-08 15:22:12 +08:00
outputs = model.forward_unsuper(images)
2024-09-22 15:18:08 +08:00
outputs = outputs.permute(0, 2, 3, 1) # 64 8 24 24 -> 64 24 24 8
2024-10-05 16:17:41 +08:00
sample = outputs.reshape(-1, outputs.shape[3]) # -> 36864 8
2024-10-07 16:39:29 +08:00
abs = torch.abs(sample).detach()
2024-10-05 16:17:41 +08:00
max, max_index = torch.max(abs, dim=1)
2024-10-07 16:39:29 +08:00
mean = torch.mean(abs, dim=1)
mean = torch.expand_copy(mean.reshape(-1, 1), sample.shape)
max = torch.expand_copy(max.reshape(-1, 1), sample.shape)
all = range(0, sample.shape[0])
ratio_max = abs / mean
ratio_nor = (max - abs) / max
ratio_nor[all, max_index] = ratio_max[all, max_index].clone()
ratio_nor = torch.where(torch.isnan(ratio_nor), 1.0, ratio_nor)
label = sample * ratio_nor
loss = F.l1_loss(sample, label)
2024-09-21 17:44:57 +08:00
model.conv1.weight.grad = None
2024-09-08 15:22:12 +08:00
loss.backward()
2024-09-22 15:18:08 +08:00
2024-10-22 13:54:26 +08:00
model.conv1.weight.data = model.conv1.weight.data - model.conv1.weight.grad * 100
2024-09-22 15:18:08 +08:00
2024-09-08 15:22:12 +08:00
if (i + 1) % 100 == 0:
2024-09-16 17:27:37 +08:00
print(f"Epoch [{epoch+1}/{epochs}], Step [{i+1}/{n_total_steps}], Loss: {loss.item():.8f}")
2024-08-18 00:46:36 +08:00
2024-10-22 13:54:26 +08:00
show.DumpTensorToImage(images.view(-1, images.shape[2], images.shape[3]), "input_image.png", Contrast=[0, 1.0])
g = model.conv1.weight.grad
show.DumpTensorToImage(g.view(-1, g.shape[2], g.shape[3]).cpu(), "conv1_weight_grad.png")
2024-10-05 16:17:41 +08:00
w = model.conv1.weight.data
2024-10-22 13:54:26 +08:00
show.DumpTensorToImage(w.view(-1, w.shape[2], w.shape[3]), "conv1_weight_update.png")
2024-10-05 16:17:41 +08:00
2024-10-07 16:39:29 +08:00
# loader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False)
# images, labels = next(iter(loader))
# images = images.to(device)
2024-07-31 22:04:01 +08:00
# Train the model
2024-09-08 15:22:12 +08:00
model.conv1.weight.requires_grad = False
model.conv2.weight.requires_grad = True
model.fc1.weight.requires_grad = True
criterion = nn.CrossEntropyLoss()
2024-09-16 17:27:37 +08:00
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=0.2)
2024-07-31 22:04:01 +08:00
n_total_steps = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
2024-07-31 22:04:01 +08:00
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
2024-08-29 16:47:06 +08:00
if (i + 1) % 100 == 0:
2024-07-31 22:04:01 +08:00
print(f"Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{n_total_steps}], Loss: {loss.item():.4f}")
2024-10-07 16:39:29 +08:00
print("Finished Training")
2024-07-31 22:04:01 +08:00
2024-09-08 15:22:12 +08:00
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False)
test_loader = iter(test_loader)
images, labels = next(test_loader)
images = images.to(device)
labels = labels.to(device)
model.printFector(images, labels, "dump1")
images, labels = next(test_loader)
images = images.to(device)
labels = labels.to(device)
model.printFector(images, labels, "dump2")
2024-07-31 22:04:01 +08:00
# Test the model
with torch.no_grad():
n_correct = 0
n_samples = 0
for images, labels in test_loader:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
# max returns (value ,index)
_, predicted = torch.max(outputs.data, 1)
n_samples += labels.size(0)
n_correct += (predicted == labels).sum().item()
acc = 100.0 * n_correct / n_samples
print(f"Accuracy of the network on the 10000 test images: {acc} %")