<jupyter_start><jupyter_text>Lab Environment for BYOA PipelineThis notebook instance will act as the lab environment for setting up and triggering changes to our pipeline.  This is being used to provide a consistent environment, gain some familiarity with Amazon SageMaker Notebook Instances, and to avoid any issues with debugging individual laptop configurations during the workshop. PLEASE review the [sample notebook](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/advanced_functionality/scikit_bring_your_own/scikit_bring_your_own.ipynb) for detailed documentation on the model being built---  Step 1:  View the Data  In the code cell below, we'll take a look at the training/test/validation datasets and then upload them to S3. Just as the sample notebook referenced above, For the purposes of this example, we're using some the classic [Iris Flower](https://en.wikipedia.org/wiki/Iris_flower_data_set) dataset, which we have included in the local notebook instance under the ./data folder.<jupyter_code>import pandas as pd
train_data = pd.read_csv('./data/1-train/train/iris.csv', sep=',')
pd.set_option('display.max_columns', 500)     # Make sure we can see all of the columns
pd.set_option('display.max_rows', 5)         # Keep the output on one page
print('\nTraining Data\n', train_data)

smoketest_data = pd.read_csv('./data/1-train/smoketest/iris.csv', sep=',')
pd.set_option('display.max_columns', 500)     # Make sure we can see all of the columns
pd.set_option('display.max_rows', 5)         # Keep the output on one page
print('\nSmoke Test Data\n', smoketest_data)

validation_data = pd.read_csv('./data/1-train/validation/iris.csv', sep=',')
pd.set_option('display.max_columns', 500)     # Make sure we can see all of the columns
pd.set_option('display.max_rows', 5)         # Keep the output on one page
print('\nValidation Data\n', validation_data)<jupyter_output>Training Data
         setosa  5.1  3.5  1.4  0.2
0       setosa  4.9  3.0  1.4  0.2
1       setosa  4.7  3.2  1.3  0.2
..         ...  ...  ...  ...  ...
147  virginica  6.2  3.4  5.4  2.3
148  virginica  5.9  3.0  5.1  1.8

[149 rows x 5 columns]

Smoke Test Data
        setosa  5.0  3.5  1.3  0.3
0  versicolor  5.5  2.6  4.4  1.2
1   virginica  5.8  2.7  5.1  1.9

Validation Data
         setosa  5.2  3.5  1.5  0.2
0       setosa  5.2  3.4  1.4  0.2
1       setosa  4.7  3.2  1.6  0.2
..         ...  ...  ...  ...  ...
42  versicolor  5.9  3.2  4.8  1.8
43  versicolor  6.1  2.8  4.0  1.3

[44 rows x 5 columns]<jupyter_text>--- Step 2:  Upload Data to S3 We will utilize this notebook to perform some of the setup that will be required to trigger the first execution of our pipeline.   In this second step in our Machine Learning pipeline, we are going to simulate what would typically be the last step in an Analytics pipeline of creating datasets. To accomplish this, we will actually be uploading data from our local notebook instance (data can be found under /data/1-train/*) to S3.  In a typical scenario, this would be done through your analytics pipeline.  We will use the S3 bucket that was created through the CloudFormation template we launched at the beginning of the lab. You can validate the S3 bucket exists by:  1. Going to the [S3 Service](https://s3.console.aws.amazon.com/s3/) inside the AWS Console  2. Find the name of the S3 data bucket created by the CloudFormation template: mlops-data-*yourintials*-*randomid*  In the code cell below, we'll take a look at the training/test/validation datasets and then upload them to S3.     UPDATE THE BUCKET NAME BELOW BEFORE EXECUTING THE CELL<jupyter_code>import os
import boto3
import re
import time

# UPDATE THE NAME OF THE BUCKET TO MATCH THE ONE WE CREATED THROUGH THE CLOUDFORMATION TEMPLATE
# Example: mlops-data-jdd-df4d4850
#bucket = 'mlops-data-<yourinitials>-<generated id>'
bucket = 'mlops-data-jdd-d4d740c0'


from sagemaker import get_execution_role

role = get_execution_role()
region = boto3.Session().region_name


trainfilename = 'train/train.csv'
smoketestfilename = 'smoketest/smoketest.csv'
validationfilename = 'validation/validation.csv'


s3 = boto3.resource('s3')

s3.meta.client.upload_file('./data/1-train/train/iris.csv', bucket, trainfilename)
s3.meta.client.upload_file('./data/1-train/smoketest/iris.csv', bucket, smoketestfilename)
s3.meta.client.upload_file('./data/1-train/validation/iris.csv', bucket, validationfilename)<jupyter_output><empty_output><jupyter_text>--- Step 3:  Commit Training Code To Trigger Pipeline BuildIn this step, we are going to trigger an execution of the pipeline by committing our training code to the CodeCommit repository that was setup as part of the CloudFormation stack.  The CodeCommit repository created was associated with this SageMaker Notebook Instance via a setting in the CloudFormation Stack using the [SageMaker Notebook Instance Git Association](https://docs.aws.amazon.com/sagemaker/latest/dg/nbi-git-repo.html) feature.The pipeline is currently setup to trigger on a commit to the master branch; however, this should be adjusted in a real-world scenario based on your branching strategy. The CodeCommit repository created can be viewed by:  1. Going to the [CodeCommit Service](https://console.aws.amazon.com/codesuite/codecommit/repositories) inside the AWS Console  2. Find the name of the repository created by the CloudFormation template: mlops-codecommit-byo-*yourinitials*  **UPDATE** Ensure you update the cell below where noted prior to executing<jupyter_code># View the CodeCommit repository -
# This Git integration was configured as part of the creation of the notebook instance in the CloudFormation stack.

# The following will return the CodeCommit repository that has been configured with this notebook and will be used 
# for the source control repository during this workshop. 

# Ensure remote repo is setup
!git remote -v

!git config --global user.name "<NAME>"
!git config --global user.email <EMAIL><jupyter_output>origin	https://git-codecommit.us-east-1.amazonaws.com/v1/repos/mlops-codecommit-byo-jdd (fetch)
origin	https://git-codecommit.us-east-1.amazonaws.com/v1/repos/mlops-codecommit-byo-jdd (push)<jupyter_text>Commit training code to the CodeCommit repository to trigger the execution of the CodePipeline<jupyter_code>!git pull
!git add ./model-code/*
!git commit -m "Initial add of model code to CodeCommit Repo"
!git push origin master<jupyter_output>Already up-to-date.
[master ebb3723] Initial add of model code to CodeCommit Repo
 2 files changed, 2 insertions(+), 9 deletions(-)
Counting objects: 6, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (6/6), 502 bytes | 502.00 KiB/s, done.
Total 6 (delta 4), reused 0 (delta 0)
To https://git-codecommit.us-east-1.amazonaws.com/v1/repos/mlops-codecommit-byo-jdd
   7594aae..ebb3723  master -> master<jupyter_text>---- Step 4:  Monitor CodePipeline ExecutionThe code above will trigger the execution of your CodePipeline. You can monitor progress of the pipeline execution in the [CodePipeline dashboard](https://console.aws.amazon.com/codesuite/codepipeline/pipelines).You can also validate that your code is now committed to the CodeCommit repository in the [CodeCommit dashboard](https://console.aws.amazon.com/codesuite/codecommit/repositories)As the pipeline is executing information is being logged to [Cloudwatch logs](https://console.aws.amazon.com/cloudwatch/logs).  Explore the logs for your Lambda functions (/aws/lambda/MLOps-BYO*) as well as output logs from SageMaker (/aws/sagemaker/*)Note: It will take awhile to execute all the way through the pipeline.  Please don't proceed to the next step until the last stage is shows **'succeeded'** ---  Step 5: Edit CodePipeline Triggers to add model retrainingIn the steps above, we demonstrated how you can trigger the pipeline when new code is committed to CodeCommit.  As you continue to modify your training/inference code, you essentially re-execute the cell above to commit new code and trigger another execution of the pipeline.  Although we are using a notebook instance for the purposes of the workshop, the commit to a source code repository above can happen in your local environment and/or IDEs of choice. In this step, we want to modify the pipeline to add the capability to not only trigger based off code changes but to also trigger a retraining cycle in the event of receiving new training data. If the file/object containing the training data is a single object that will be inclusive of all training data you want to use, you can trigger CodePipeline based on the object itself. However, if you are looking to training incrementally or if your analytics pipeline puts new data to your S3 bucket as deltas then you need to have a trigger mechanism included in your analytics pipeline that notifies CodePipeline it is time to retrain. To simplify the setup for this workshop, we are going to trigger based on a new training dataset that is inclusive of all the data we want to retrain with.    1. Go to your [CodePipeline Pipeline](https://console.aws.amazon.com/codesuite/codepipeline/pipelines)    2. Click on the link to your pipeline (i.e. MLOps-BYO-BuildPipeline*)      3. Click the **Edit** Button       4. Inside **Edit:Source** , click the **Edit stage** button --> then Click **Add Action**      5. Under Edit Action:          * **Action Name** : RetrainData              * **Action Provider** : Source - S3              * **Bucket** : *Enter the name of your S3 data bucket* Example: mlops-data-jdd-d4d740c0              * **S3 object key** : train/train.csv              * **Output Artifacts** : RetrainDataIn                 6. Validate your screen contains all information as shown below:                     7. Click **Done**      8. Click the orange **Save** button in the upper right hand corner to save your changes, confirm changes and hit **Save** again. Because we may not want rebuild the training/inference container image in the case where we only want to retrain the model, you could optionally create a separate retraining pipeline that excludes the rebuild of the image.  Depending on what you are using for orchestration across your pipeline, you can accomplish this through a single or multiple pipelines.  ---- Step 6: Trigger retraining based on new data Let's test our new CodePipeline trigger by adding new training data to our S3 data bucket.  The S3 data bucket is setup with versioning enabled.<jupyter_code>trainfilename = 'train/train.csv'

s3 = boto3.resource('s3')

s3.meta.client.upload_file('./data/1-train/train/iris-2.csv', bucket, trainfilename)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0808005237070981, 'fraction_numerical': 0.023753857663892267, 'mean_word_length': 3.9145220588235294, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 24, 'https://': 12, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '329909', 'license': 'Apache-2.0', 'n_tokens_mistral': 3171, 'n_tokens_neox': 3051, 'n_words': 1328, 'path': '2-Bring-Your-Own/03.MLOps-BYO-LabNotebook.ipynb', 'repo_name': 'chrisbarrantes/amazon-sagemaker-devops-with-ml', 'size': '10711'}