Skip to content
Snippets Groups Projects
Commit 89049300 authored by Brummans, Nick's avatar Brummans, Nick
Browse files

push

parent 1ad480ea
Branches
No related tags found
No related merge requests found
# ClearML demo # ClearML demo
## opdracht:
- Create Mnist dataset in clearml
- train mnist model and optimize accuracy
- Log metrics in experiment -> run in clearml
- Deploy model so pictures from mnist can be send to API and prediction comes back
- create pipeline that trains and deploys model on set timer (once a week)
## Getting started ## Setup ClearML:
To make it easy for you to get started with GitLab, here's a list of recommended next steps. - pip install clearml
- clearml-init
- Create workspace credentials
- Settings -> Workspace -> Create new credentials
- copy code in clearml-init prompt in your terminal
https://clear.ml/docs/latest/docs/getting_started/ds/ds_first_steps/
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! Server details:
-
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://git.wur.nl/mdt-research-it-solutions/clearml-demo.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://git.wur.nl/mdt-research-it-solutions/clearml-demo/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
File added
File added
from clearml import Task
from clearml.automation.controller import PipelineController
# Connecting ClearML with the current process
task = Task.init(project_name='pipeline', task_name='pipeline demo',
task_type=Task.TaskTypes.controller, reuse_last_task_id=False)
# Creating the pipeline
pipe = PipelineController(
name='pipeline test',
project='pipeline',
version='0.0.1',
add_pipeline_tags=False,
)
pipe.set_default_execution_queue('default')
# Adding the first stage to the pipeline, a clone of the base tasks will be created and used
pipe.add_step(name='stage_data', base_task_project='pipeline', base_task_name='pipeline step 1 dataset artifact')
# overriding the arguments of the the third stage(adding the second stage’s task_id) and adding it to the pipeline
pipe.add_step(name='stage_train', parents=['stage_data', ],
base_task_project='pipeline', base_task_name='pipeline step 2 train model',
parameter_override={'General/dataset_task_id': '${stage_data.id}'})
# Starting the pipeline
pipe.start()
# Wait until pipeline terminates
pipe.wait()
# cleanup everything
pipe.stop()
print('done')
mnist-test @ 12886248
Subproject commit 1288624836748d3ac17043c9175be2f71f7a2a22
model.py 0 → 100644
import torch.nn as nn
class CNNModel(nn.Module):
def __init__(self):
super(CNNModel, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(
in_channels=3,
out_channels=16,
kernel_size=5,
stride=1,
padding=2,
),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),
)
self.conv2 = nn.Sequential(
nn.Conv2d(16, 32, 5, 1, 2),
nn.ReLU(),
nn.MaxPool2d(2),
) # fully connected layer, output 10 classes
self.out = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x) # flatten the output of conv2 to (batch_size, 32 * 7 * 7)
x = x.view(x.size(0), -1)
output = self.out(x)
return output
from clearml import Task, StorageManager
task = Task.init(project_name="pipeline", task_name="pipeline step 1 dataset artifact")
# only create the task, it will be executed remotely later
task.execute_remotely(queue_name='default')
# add and upload local file containing the dataset
task.upload_artifact('training_dataset', artifact_object='mnist-test/data/mnist_png/training')
task.upload_artifact('testing_dataset', artifact_object='mnist-test/data/mnist_png/testing')
print('uploading artifacts in the background')
print('Done')
import pickle
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.utils.data import DataLoader
import torch
import argparse
import torch.nn as nn
import torch.optim as optim
import time
from tqdm.auto import tqdm
from model import CNNModel
from utils import save_model
from clearml import Task
from clearml import Logger
from clearml import InputModel
from clearml import StorageManager
# training
def train(model, trainloader, optimizer, criterion):
model.train()
print('Training')
train_running_loss = 0.0
train_running_correct = 0
counter = 0
for i, data in tqdm(enumerate(trainloader), total=len(trainloader)):
counter += 1
image, labels = data
image = image.to(device)
labels = labels.to(device)
optimizer.zero_grad()
# forward pass
outputs = model(image)
# calculate the loss
loss = criterion(outputs, labels)
train_running_loss += loss.item()
# calculate the accuracy
_, preds = torch.max(outputs.data, 1)
train_running_correct += (preds == labels).sum().item()
# backpropagation
loss.backward()
# update the optimizer parameters
optimizer.step()
# loss and accuracy for the complete epoch
epoch_loss = train_running_loss / counter
epoch_acc = 100. * (train_running_correct / len(trainloader.dataset))
return epoch_loss, epoch_acc
# validation
def validate(model, testloader, criterion):
model.eval()
print('Validation')
valid_running_loss = 0.0
valid_running_correct = 0
counter = 0
with torch.no_grad():
for i, data in tqdm(enumerate(testloader), total=len(testloader)):
counter += 1
image, labels = data
image = image.to(device)
labels = labels.to(device)
# forward pass
outputs = model(image)
# calculate the loss
loss = criterion(outputs, labels)
valid_running_loss += loss.item()
# calculate the accuracy
_, preds = torch.max(outputs.data, 1)
valid_running_correct += (preds == labels).sum().item()
# loss and accuracy for the complete epoch
epoch_loss = valid_running_loss / counter
epoch_acc = 100. * (valid_running_correct / len(testloader.dataset))
return epoch_loss, epoch_acc
task = Task.init(project_name="pipeline", task_name="pipeline step 2 train model")
# Use either dataset_task_id to point to a tasks artifact or
# use a direct url with dataset_url
# construct the argument parser
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=10, help='number of epochs to train our network for')
parser.add_argument('--train-batch-size', type=int, default=256, help='batch size for training set')
parser.add_argument('--validation-batch-size', type=int, default=256, help='batch size for validation set')
parser.add_argument('--train-num-workers', type=int, default=0, help='number of workers for training dataloader. Set to 0 if OOM')
parser.add_argument('--validation-num-workers', type=int, default=0, help='number of workers for validation dataloader. Set to 0 if OOM')
parser.add_argument('--dataset-task-id', type=str, default='', help='task artifact id')
parser.add_argument('--train-dataset-url', type=str, default='', help='train task artifact url')
parser.add_argument('--test-dataset-url', type=str, default='', help='test task artifact url')
parser.add_argument('--resize', type=int, default=28, help='set size for resizing')
parser.add_argument('--lr', type=float, default=1e-3, help='set learning rate for training')
args = parser.parse_args()
# only create the task, we will actually execute it later
task.execute_remotely(queue_name='default')
# get dataset from task's artifact
if args['dataset_task_id']:
dataset_upload_task = Task.get_task(task_id=args['dataset_task_id'])
# download the artifact
mnist_pickle_train = train_dataset_upload_task.artifacts['training_dataset'].get_local_copy()
mnist_pickle_test = test_dataset_upload_task.artifacts['testing_dataset'].get_local_copy()
# get the dataset from a direct url
elif args['dataset_url']:
# simulate local dataset
mnist_pickle_train = StorageManager.get_local_copy(remote_url=args['train_dataset_url'])
mnist_pickle_test = StorageManager.get_local_copy(remote_url=args['test_dataset_url'])
else:
raise ValueError("Missing dataset link")
# open the local copy of the dataset
mnist_train = pickle.load(open(mnist_pickle_train, 'rb'))
mnist_test = pickle.load(open(mnist_pickle_test, 'rb'))
# get logger
logger = Logger.current_logger()
# the training transforms
train_transform = transforms.Compose([
transforms.Resize(args.resize),
#transforms.RandomHorizontalFlip(p=0.5),
#transforms.RandomVerticalFlip(p=0.5),
#transforms.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5)),
#transforms.RandomRotation(degrees=(30, 70)),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5]
)
])
# the validation transforms
valid_transform = transforms.Compose([
transforms.Resize(args.resize),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5]
)
])
# training dataset
train_dataset = datasets.ImageFolder(
root=mnist_train,
transform=train_transform
)
# validation dataset
valid_dataset = datasets.ImageFolder(
root=mnist_test,
transform=valid_transform
)
# training data loaders
train_loader = DataLoader(
train_dataset, batch_size=args.train_batch_size, shuffle=True,
num_workers=args.train_num_workers, pin_memory=True
)
# validation data loaders
valid_loader = DataLoader(
valid_dataset, batch_size=args.validation_batch_size, shuffle=False,
num_workers=args.validation_num_workers, pin_memory=True
)
device = ('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Computation device: {device}\n")
model = CNNModel().to(device)
print(model)
# total parameters and trainable parameters
total_params = sum(p.numel() for p in model.parameters())
print(f"{total_params:,} total parameters.")
total_trainable_params = sum(
p.numel() for p in model.parameters() if p.requires_grad)
print(f"{total_trainable_params:,} training parameters.")
# optimizer
optimizer = optim.Adam(model.parameters(), lr=args.lr)
# loss function
criterion = nn.CrossEntropyLoss()
# lists to keep track of losses and accuracies
train_loss, valid_loss = [], []
train_acc, valid_acc = [], []
# start the training
for epoch in range(args.epochs):
print(f"[INFO]: Epoch {epoch+1} of {args.epochs}")
train_epoch_loss, train_epoch_acc = train(model, train_loader,
optimizer, criterion)
valid_epoch_loss, valid_epoch_acc = validate(model, valid_loader,
criterion)
train_loss.append(train_epoch_loss)
valid_loss.append(valid_epoch_loss)
train_acc.append(train_epoch_acc)
valid_acc.append(valid_epoch_acc)
print(f"Training loss: {train_epoch_loss:.3f}, training acc: {train_epoch_acc:.3f}")
logger.report_scalar(
"loss", "train", iteration=epoch, value=train_epoch_loss
)
logger.report_scalar(
"accuracy", "train", iteration=epoch, value=train_epoch_acc
)
print(f"Validation loss: {valid_epoch_loss:.3f}, validation acc: {valid_epoch_acc:.3f}")
logger.report_scalar(
"loss", "validation", iteration=epoch, value=valid_epoch_loss
)
logger.report_scalar(
"accuracy", "validation", iteration=epoch, value=valid_epoch_acc
)
print('-'*50)
time.sleep(5)
# save the trained model weights
save_model(args.epochs, model, optimizer, criterion)
input_model = InputModel.import_model(
# Name for model in ClearML
name='mnist model',
# Import the model using a URL
weights_url='outputs/model.pth',
framework='PyTorch'
)
# Connect the input model to the task
task.connect(input_model)
print('TRAINING COMPLETE')
utils.py 0 → 100644
import torch
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
def save_model(epochs, model, optimizer, criterion):
"""
Function to save the trained model to disk.
"""
torch.save({
'epoch': epochs,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': criterion,
}, 'outputs/model.pth')
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment