Ubuntu
commited on
Commit
·
83a3d89
1
Parent(s):
17745c9
Modular code and removed misclassified images collection
Browse files- main.py +8 -2
- tmppl87qjev/_remote_module_non_scriptable.py +0 -81
- train_test.py +6 -1
- utils.py +4 -2
main.py
CHANGED
|
@@ -5,11 +5,15 @@ from resnet_model import ResNet50
|
|
| 5 |
from data_utils import get_train_transform, get_test_transform, get_data_loaders
|
| 6 |
from train_test import train, test
|
| 7 |
from utils import save_checkpoint, load_checkpoint, plot_training_curves, plot_misclassified_samples
|
|
|
|
| 8 |
|
| 9 |
def main():
|
| 10 |
# Initialize model, loss function, and optimizer
|
| 11 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 12 |
-
model = ResNet50()
|
|
|
|
|
|
|
|
|
|
| 13 |
criterion = nn.CrossEntropyLoss()
|
| 14 |
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)
|
| 15 |
|
|
@@ -56,7 +60,9 @@ def main():
|
|
| 56 |
plot_training_curves(epochs, train_acc1, test_acc1, train_acc5, test_acc5, train_losses, test_losses, learning_rates)
|
| 57 |
|
| 58 |
# Plot misclassified samples
|
|
|
|
| 59 |
plot_misclassified_samples(misclassified_images, misclassified_labels, misclassified_preds, classes=['class1', 'class2', ...]) # Replace with actual class names
|
|
|
|
| 60 |
|
| 61 |
if __name__ == '__main__':
|
| 62 |
-
main()
|
|
|
|
| 5 |
from data_utils import get_train_transform, get_test_transform, get_data_loaders
|
| 6 |
from train_test import train, test
|
| 7 |
from utils import save_checkpoint, load_checkpoint, plot_training_curves, plot_misclassified_samples
|
| 8 |
+
from torchsummary import summary
|
| 9 |
|
| 10 |
def main():
|
| 11 |
# Initialize model, loss function, and optimizer
|
| 12 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 13 |
+
model = ResNet50()
|
| 14 |
+
model = torch.nn.DataParallel(model)
|
| 15 |
+
model = model.to(device)
|
| 16 |
+
summary(model, input_size=(3, 224, 224))
|
| 17 |
criterion = nn.CrossEntropyLoss()
|
| 18 |
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)
|
| 19 |
|
|
|
|
| 60 |
plot_training_curves(epochs, train_acc1, test_acc1, train_acc5, test_acc5, train_losses, test_losses, learning_rates)
|
| 61 |
|
| 62 |
# Plot misclassified samples
|
| 63 |
+
'''
|
| 64 |
plot_misclassified_samples(misclassified_images, misclassified_labels, misclassified_preds, classes=['class1', 'class2', ...]) # Replace with actual class names
|
| 65 |
+
'''
|
| 66 |
|
| 67 |
if __name__ == '__main__':
|
| 68 |
+
main()
|
tmppl87qjev/_remote_module_non_scriptable.py
DELETED
|
@@ -1,81 +0,0 @@
|
|
| 1 |
-
from typing import *
|
| 2 |
-
|
| 3 |
-
import torch
|
| 4 |
-
import torch.distributed.rpc as rpc
|
| 5 |
-
from torch import Tensor
|
| 6 |
-
from torch._jit_internal import Future
|
| 7 |
-
from torch.distributed.rpc import RRef
|
| 8 |
-
from typing import Tuple # pyre-ignore: unused import
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
module_interface_cls = None
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
def forward_async(self, *args, **kwargs):
|
| 15 |
-
args = (self.module_rref, self.device, self.is_device_map_set, *args)
|
| 16 |
-
kwargs = {**kwargs}
|
| 17 |
-
return rpc.rpc_async(
|
| 18 |
-
self.module_rref.owner(),
|
| 19 |
-
_remote_forward,
|
| 20 |
-
args,
|
| 21 |
-
kwargs,
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def forward(self, *args, **kwargs):
|
| 26 |
-
args = (self.module_rref, self.device, self.is_device_map_set, *args)
|
| 27 |
-
kwargs = {**kwargs}
|
| 28 |
-
ret_fut = rpc.rpc_async(
|
| 29 |
-
self.module_rref.owner(),
|
| 30 |
-
_remote_forward,
|
| 31 |
-
args,
|
| 32 |
-
kwargs,
|
| 33 |
-
)
|
| 34 |
-
return ret_fut.wait()
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
_generated_methods = [
|
| 38 |
-
forward_async,
|
| 39 |
-
forward,
|
| 40 |
-
]
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def _remote_forward(
|
| 46 |
-
module_rref: RRef[module_interface_cls], device: str, is_device_map_set: bool, *args, **kwargs):
|
| 47 |
-
module = module_rref.local_value()
|
| 48 |
-
device = torch.device(device)
|
| 49 |
-
|
| 50 |
-
if device.type != "cuda":
|
| 51 |
-
return module.forward(*args, **kwargs)
|
| 52 |
-
|
| 53 |
-
# If the module is on a cuda device,
|
| 54 |
-
# move any CPU tensor in args or kwargs to the same cuda device.
|
| 55 |
-
# Since torch script does not support generator expression,
|
| 56 |
-
# have to use concatenation instead of
|
| 57 |
-
# ``tuple(i.to(device) if isinstance(i, Tensor) else i for i in *args)``.
|
| 58 |
-
args = (*args,)
|
| 59 |
-
out_args: Tuple[()] = ()
|
| 60 |
-
for arg in args:
|
| 61 |
-
arg = (arg.to(device),) if isinstance(arg, Tensor) else (arg,)
|
| 62 |
-
out_args = out_args + arg
|
| 63 |
-
|
| 64 |
-
kwargs = {**kwargs}
|
| 65 |
-
for k, v in kwargs.items():
|
| 66 |
-
if isinstance(v, Tensor):
|
| 67 |
-
kwargs[k] = kwargs[k].to(device)
|
| 68 |
-
|
| 69 |
-
if is_device_map_set:
|
| 70 |
-
return module.forward(*out_args, **kwargs)
|
| 71 |
-
|
| 72 |
-
# If the device map is empty, then only CPU tensors are allowed to send over wire,
|
| 73 |
-
# so have to move any GPU tensor to CPU in the output.
|
| 74 |
-
# Since torch script does not support generator expression,
|
| 75 |
-
# have to use concatenation instead of
|
| 76 |
-
# ``tuple(i.cpu() if isinstance(i, Tensor) else i for i in module.forward(*out_args, **kwargs))``.
|
| 77 |
-
ret: Tuple[()] = ()
|
| 78 |
-
for i in module.forward(*out_args, **kwargs):
|
| 79 |
-
i = (i.cpu(),) if isinstance(i, Tensor) else (i,)
|
| 80 |
-
ret = ret + i
|
| 81 |
-
return ret
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
train_test.py
CHANGED
|
@@ -31,6 +31,9 @@ def train(model, device, train_loader, optimizer, criterion, epoch, accumulation
|
|
| 31 |
|
| 32 |
pbar.set_description(desc=f'Epoch {epoch} | Loss: {running_loss / (batch_idx + 1):.4f} | Top-1 Acc: {100. * correct1 / total:.2f} | Top-5 Acc: {100. * correct5 / total:.2f}')
|
| 33 |
|
|
|
|
|
|
|
|
|
|
| 34 |
return 100. * correct1 / total, 100. * correct5 / total, running_loss / len(train_loader)
|
| 35 |
|
| 36 |
def test(model, device, test_loader, criterion):
|
|
@@ -56,13 +59,15 @@ def test(model, device, test_loader, criterion):
|
|
| 56 |
correct5 += predicted.eq(targets.view(-1, 1).expand_as(predicted)).sum().item()
|
| 57 |
|
| 58 |
# Collect misclassified samples
|
|
|
|
| 59 |
for i in range(inputs.size(0)):
|
| 60 |
if targets[i] not in predicted[i, :1]:
|
| 61 |
misclassified_images.append(inputs[i].cpu())
|
| 62 |
misclassified_labels.append(targets[i].cpu())
|
| 63 |
misclassified_preds.append(predicted[i, :1].cpu())
|
|
|
|
| 64 |
|
| 65 |
test_accuracy1 = 100. * correct1 / total
|
| 66 |
test_accuracy5 = 100. * correct5 / total
|
| 67 |
print(f'Test Loss: {test_loss/len(test_loader):.4f}, Top-1 Accuracy: {test_accuracy1:.2f}, Top-5 Accuracy: {test_accuracy5:.2f}')
|
| 68 |
-
return test_accuracy1, test_accuracy5, test_loss / len(test_loader), misclassified_images, misclassified_labels, misclassified_preds
|
|
|
|
| 31 |
|
| 32 |
pbar.set_description(desc=f'Epoch {epoch} | Loss: {running_loss / (batch_idx + 1):.4f} | Top-1 Acc: {100. * correct1 / total:.2f} | Top-5 Acc: {100. * correct5 / total:.2f}')
|
| 33 |
|
| 34 |
+
if (batch_idx + 1) % 50 == 0:
|
| 35 |
+
torch.cuda.empty_cache()
|
| 36 |
+
|
| 37 |
return 100. * correct1 / total, 100. * correct5 / total, running_loss / len(train_loader)
|
| 38 |
|
| 39 |
def test(model, device, test_loader, criterion):
|
|
|
|
| 59 |
correct5 += predicted.eq(targets.view(-1, 1).expand_as(predicted)).sum().item()
|
| 60 |
|
| 61 |
# Collect misclassified samples
|
| 62 |
+
'''
|
| 63 |
for i in range(inputs.size(0)):
|
| 64 |
if targets[i] not in predicted[i, :1]:
|
| 65 |
misclassified_images.append(inputs[i].cpu())
|
| 66 |
misclassified_labels.append(targets[i].cpu())
|
| 67 |
misclassified_preds.append(predicted[i, :1].cpu())
|
| 68 |
+
'''
|
| 69 |
|
| 70 |
test_accuracy1 = 100. * correct1 / total
|
| 71 |
test_accuracy5 = 100. * correct5 / total
|
| 72 |
print(f'Test Loss: {test_loss/len(test_loader):.4f}, Top-1 Accuracy: {test_accuracy1:.2f}, Top-5 Accuracy: {test_accuracy5:.2f}')
|
| 73 |
+
return test_accuracy1, test_accuracy5, test_loss / len(test_loader), misclassified_images, misclassified_labels, misclassified_preds
|
utils.py
CHANGED
|
@@ -9,13 +9,15 @@ def save_checkpoint(model, optimizer, epoch, loss, path):
|
|
| 9 |
'optimizer_state_dict': optimizer.state_dict(),
|
| 10 |
'loss': loss,
|
| 11 |
}, path)
|
|
|
|
| 12 |
|
| 13 |
def load_checkpoint(model, optimizer, path):
|
| 14 |
-
checkpoint = torch.load(path)
|
| 15 |
model.load_state_dict(checkpoint['model_state_dict'])
|
| 16 |
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
|
| 17 |
epoch = checkpoint['epoch']
|
| 18 |
loss = checkpoint['loss']
|
|
|
|
| 19 |
return model, optimizer, epoch, loss
|
| 20 |
|
| 21 |
def plot_training_curves(epochs, train_acc1, test_acc1, train_acc5, test_acc5, train_losses, test_losses, learning_rates):
|
|
@@ -62,4 +64,4 @@ def plot_misclassified_samples(misclassified_images, misclassified_labels, miscl
|
|
| 62 |
plt.imshow(misclassified_grid.permute(1, 2, 0))
|
| 63 |
plt.title("Misclassified Samples")
|
| 64 |
plt.axis('off')
|
| 65 |
-
plt.show()
|
|
|
|
| 9 |
'optimizer_state_dict': optimizer.state_dict(),
|
| 10 |
'loss': loss,
|
| 11 |
}, path)
|
| 12 |
+
print(f"Checkpoint saved at epoch {epoch}")
|
| 13 |
|
| 14 |
def load_checkpoint(model, optimizer, path):
|
| 15 |
+
checkpoint = torch.load(path, weights_only=True)
|
| 16 |
model.load_state_dict(checkpoint['model_state_dict'])
|
| 17 |
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
|
| 18 |
epoch = checkpoint['epoch']
|
| 19 |
loss = checkpoint['loss']
|
| 20 |
+
print(f"Checkpoint loaded, resuming from epoch {epoch}")
|
| 21 |
return model, optimizer, epoch, loss
|
| 22 |
|
| 23 |
def plot_training_curves(epochs, train_acc1, test_acc1, train_acc5, test_acc5, train_losses, test_losses, learning_rates):
|
|
|
|
| 64 |
plt.imshow(misclassified_grid.permute(1, 2, 0))
|
| 65 |
plt.title("Misclassified Samples")
|
| 66 |
plt.axis('off')
|
| 67 |
+
plt.show()
|