# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/AIWintermuteAI/aXeleRate/blob/master/resources/aXeleRate_test_segnet.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + [markdown] id="hS9yMrWe02WQ" colab_type="text"
# ## Segmentation model Training and Inference
#
# In this notebook we will use axelerate Keras-based framework for AI on the edge to quickly setup model training and then after training session is completed convert it to .tflite and .kmodel formats.
#
# First, let's take care of some administrative details. 
#
# 1) Before we do anything, make sure you have choosen GPU as Runtime type (in Runtime - > Change Runtime type).
#
# 2) We need to mount Google Drive for saving our model checkpoints and final converted model(s). Press on Mount Google Drive button in Files tab on your left. 
#
# In the next cell we clone axelerate Github repository and import it. 
#
# **It is possible to use pip install or python setup.py install, but in that case you will need to restart the enironment.** Since I'm trying to make the process as streamlined as possibile I'm using sys.path.append for import.

# + id="y07yAbYbjV2s" colab_type="code" colab={}
# %tensorflow_version 1.x
# !git clone https://github.com/AIWintermuteAI/aXeleRate.git
import sys
sys.path.append('/content/aXeleRate')
from axelerate import setup_training,setup_inference

# + [markdown] id="5TBRMPZ83dRL" colab_type="text"
# At this step you typically need to get the dataset. You can use !wget command to download it from somewhere on the Internet or !cp to copy from My Drive as in this example
# ```
# # # !cp -r /content/drive/'My Drive'/pascal_20_segmentation.zip .
# # # !unzip --qq pascal_20_segmentation.zip
# ```
# For this notebook small test dataset is already in axelerate/sample_datasets folder, so no need to download anything.
#
# For semantic segmentation the dataset consists of RGB images and segmentation masks. 
# A few things to keep in mind:
#
# - The filenames of the annotation images should be same as the filenames of the RGB images.
#
# - The dimensions of the annotation image for the corresponding RGB image should be same.
#
# - For each pixel in the RGB image, the class label of that pixel in the annotation image would be the value of the annotation image pixel.
#
# Let's visualize our semantic segmentation test dataset and see what that means in practice.
#

# + id="_tpsgkGj7d79" colab_type="code" colab={}
# %matplotlib inline
from axelerate.networks.segnet.data_utils.visualize_dataset import visualize_segmentation_dataset

visualize_segmentation_dataset('aXeleRate/sample_datasets/segmentation/imgs_validation', 'aXeleRate/sample_datasets/segmentation/anns_validation', n_classes=20)

# + [markdown] id="S1oqdtbr7VLB" colab_type="text"
# Next step is defining a config dictionary. Most lines are self-explanatory.
#
# Type is model frontend - Classifier, Detector or Segnet
#
# Architecture is model backend (feature extractor) 
#
# - Full Yolo
# - Tiny Yolo
# - MobileNet1_0
# - MobileNet7_5 
# - MobileNet5_0 
# - MobileNet2_5 
# - SqueezeNet
# - VGG16
# - ResNet50
#

# + id="Jw4q6_MsegD2" colab_type="code" colab={}
config = {
            "model" : {
                "type":                 "SegNet",
                "architecture":         "MobileNet7_5",
                "input_size":           224,
                "n_classes" : 		20
            },
            "weights" : {
            "full":   				"",
            "backend":   		    "imagenet"
        },
            "train" : {
                "actual_epoch":         5,
                "train_image_folder":   "aXeleRate/sample_datasets/segmentation/imgs",
                "train_annot_folder":   "aXeleRate/sample_datasets/segmentation/anns",
                "train_times":          4,
                "valid_image_folder":   "aXeleRate/sample_datasets/segmentation/imgs_validation",
                "valid_annot_folder":   "aXeleRate/sample_datasets/segmentation/anns_validation",
                "valid_times":          4,
                "valid_metric":         "val_loss",
                "batch_size":           8,
                "learning_rate":        1e-4,
                "saved_folder":   		"segment",
                "first_trainable_layer": "",
                "ignore_zero_class":    False,
                "augumentation":				True
            },
            "converter" : {
                "type":   				["k210","tflite"]
            }
        }

# + [markdown] id="kobC_7gd5mEu" colab_type="text"
# Let's check what GPU we have been assigned in this Colab session, if any.

# + id="rESho_T70BWq" colab_type="code" colab={}
from tensorflow.python.client import device_lib
device_lib.list_local_devices()

# + [markdown] id="cWyKjw-b5_yp" colab_type="text"
# Finally we start the training by passing config dictionary we have defined earlier to setup_training function. The function will start the training with Checkpoint, Reduce Learning Rate on Plateu and Early Stopping callbacks. After the training has stopped, it will convert the best model into the format you have specified in config and save it to the project folder.

# + id="deYD3cwukHsj" colab_type="code" colab={}
model_path = setup_training(config_dict=config)

# + [markdown] id="ypTe3GZI619O" colab_type="text"
# After training it is good to check the actual perfomance of your model by doing inference on your validation dataset and visualizing results. This is exactly what next block does. Obviously since our model has only trained on a few images the reults are far from stellar, but if you have a good dataset, you'll have better results.

# + id="jE7pTYmZN7Pi" colab_type="code" colab={}
from keras import backend as K 
K.clear_session()
setup_inference(config, model_path)

# + [markdown] id="5YuVe2VD11cd" colab_type="text"
# Good luck and happy training! Have a look at these articles, that would allow you to get the most of Google Colab or connect to local runtime if there are no GPUs available;
#
# https://medium.com/@oribarel/getting-the-most-out-of-your-google-colab-2b0585f82403
#
# https://research.google.com/colaboratory/local-runtimes.html

StarcoderdataJupyterScriptsDedupFiltered