<jupyter_start><jupyter_text>Appendix 1 - Transfer Learning with MONK  Steps to take1. Create a network    - Creating base network    - Visualize layers    - Creating loss function module    - Creating optimizer module [Set learning rates here]    - Creating learning rate scheduler        2. Data prepraration    - Creating a data transformer    - Downloading and storing dataset    - Applying transformation    - Understanding dataset    - Loading the transformed dataset [Set batch size and number of parallel processors here]        3. Setting up data - plotters4. Training    - Set Epoch    - Train model        5. Testing    - Just after training    - After loading saved weights<jupyter_code>!git clone https://github.com/Tessellate-Imaging/monk_v1
#!pip install -r monk_v1/installation/requirements_cu9.txt    
#Select Installation file as per the system
import sys
sys.path.append("monk_v1/monk/")
from pytorch_prototype import prototype

# Step 1 - Create experiment
ptf = prototype(verbose=1);
ptf.Prototype("exp-1", "proj-1");
'''
original code - snippet

data_transforms = {
    'train': transforms.Compose([
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val': transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
}

data_dir = 'cat_dog/'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}
                  
                  


batch = 4
parallel_processors = 3

dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch,
                                             shuffle=True, num_workers=parallel_processors)
              for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes

'''
# Replicating same using Monk


ptf.Dataset_Params(dataset_path=["cat_dog/train", "cat_dog/val"],
                   input_size=224, 
                   batch_size=4, shuffle_data=True, num_processors=3);

# Transform
ptf.apply_random_horizontal_flip(train=True);
ptf.apply_normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], train=True, val=True, test=True);


ptf.Dataset();
'''
Original Code Snippet

model_ft = models.resnet18(pretrained=True) # Using pretrained models
num_ftrs = model_ft.fc.in_features # Adding a new layer to next final layer
model_ft.fc = nn.Linear(num_ftrs, 2)
model_ft.cuda()


'''
# Replicating same using Monk

ptf.Model_Params(model_name="resnet18", freeze_base_network=True, 
                 use_gpu=True, use_pretrained=True);
ptf.Model();
'''
Original Code Snippet

cross_entropy_loss = nn.CrossEntropyLoss()
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)

'''
# Replicating same using Monk
ptf.optimizer_sgd(0.001);
ptf.lr_fixed();
ptf.loss_softmax_crossentropy()
'''
Original Code Snippet

def train_model(model, criterion, optimizer, num_epochs=25):
    since = time.time()

    # A shallow copy constructs a new compound object and then (to the extent possible) inserts 
    #    references into it to the objects found in the original. 
    # A deep copy constructs a new compound object and then, recursively, inserts copies into it of 
    #    the objects found in the original.
    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch, num_epochs - 1))
        print('-' * 10)

        # Each epoch has a training and validation phase
        for phase in ['train', 'val']:
            if phase == 'train':
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for inputs, labels in dataloaders[phase]:
                inputs = inputs.cuda()
                labels = labels.cuda()

                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                # track history if only in train
                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.double() / dataset_sizes[phase]

            print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase, epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())

        print()

    time_elapsed = time.time() - since
    print('Training complete in {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))
    print('Best val Acc: {:4f}'.format(best_acc))

    torch.save(model.state_dict(), "cat_dog_model")
    
    # load best model weights
    model.load_state_dict(best_model_wts)
    return model

model_ft = train_model(model_ft, cross_entropy_loss, optimizer_ft,
                       num_epochs=5)

'''
# Replicating using Monk

ptf.Training_Params(num_epochs=4, display_progress=True, display_progress_realtime=True, 
        save_intermediate_models=True, intermediate_model_prefix="intermediate_model_", save_training_logs=True);
ptf.Train();<jupyter_output>Training params
    Num Epochs: 4

Display params
    Display progress:          True
    Display progress realtime: True
    Save Training logs:        True
    Save Intermediate models:  True
    Intermediate model prefix: intermediate_model_

Training Start
    Epoch 1/4
    ----------
StarcoderdataJupyterStructuredCleanDedup