<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Stefan Natu on Medium]]></title>
        <description><![CDATA[Stories by Stefan Natu on Medium]]></description>
        <link>https://medium.com/@stefannatu?source=rss-5b52acb0f7e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_YYAufiYjikgfg7s</url>
            <title>Stories by Stefan Natu on Medium</title>
            <link>https://medium.com/@stefannatu?source=rss-5b52acb0f7e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:56:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stefannatu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simple MLOps with Amazon SageMaker, Lambda and AWS Step Functions Data Science SDK]]></title>
            <link>https://medium.com/data-science/simple-mlops-with-amazon-sagemaker-lambda-and-aws-step-functions-data-science-sdk-e8052825a56c?source=rss-5b52acb0f7e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8052825a56c</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Stefan Natu]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 20:24:19 GMT</pubDate>
            <atom:updated>2020-03-30T14:37:15.279Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build your own ML CI/CD pipeline using serverless components on AWS.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIQiHq7XwrJGN9tKlY734Q.png" /></figure><p>By <a href="https://medium.com/u/5b52acb0f7e6">Stefan Natu,</a> <a href="https://medium.com/u/ed7018b898fc">Shreyas Subramanian,</a> and <a href="https://www.linkedin.com/in/liqingwei/">Qingwei Li</a></p><h3>Introduction</h3><p>As the machine learning space matures, there is an increasing need for simple ways to automate and deploy ML pipelines into production. With the explosion of data science platforms, companies and teams are often using diverse machine learning platforms for data exploration, Extract-Transform-Load (ETL) jobs, model training and deployment. In this blog, we describe how users can bring their own algorithm code to build a training and inference image using Docker, train and host their model using Amazon SageMaker and AWS StepFunctions. We use Mask R-CNN, a highly popular instance segmentation model used for numerous computer vision use cases as such as [1]. Readers who wish to get hands-on with the contents of this blog can refer to our <a href="https://github.com/aws-samples/aws-stepfunctions-byoc-mlops-using-data-science-sdk">Github</a> [2].</p><h3>AWS Services Used</h3><p><strong>AWS CodeBuild:</strong> AWS CodeBuild is a fully managed continuous integration (CI) service that allows users to compile and package code into deployable artifacts. Here we will use CodeBuild to package our custom Mask R-CNN container into a Docker image, which we upload into Amazon Elastic Container Registry (ECR)<br> <br> <strong>AWS Lambda:</strong> AWS Lambda is a service that lets you run code without provisioning servers. Here we will use AWS Lambda to deploy a CodeBuild job.<br> <br> <strong>AWS StepFunctions:</strong> AWS StepFuntions is an orchestration tool that allows users to build pipelines and coordinate microservices into a workflow. AWS StepFunctions can then trigger that workflow in an event driven manner without having the user manage any underlying servers or compute.<br> <br> <strong>Amazon SageMaker: </strong>Amazon SageMaker is a fully managed machine learning platform for building, training and deploying machine learning models. Here we use Amazon SageMaker to author training and model deployment jobs, as well as SageMaker Jupyter notebooks to author a StepFunctions workflow.</p><h3>Create a Mask R-CNN container</h3><p>Because we run the same image in training or hosting, Amazon SageMaker runs your container with the argument train or serve. When Amazon SageMaker runs training, your train script is run just like a regular Python program. Hosting has a very different model than training because hosting is responding to inference requests that come in via HTTP. In this example, we use our recommended Python serving stack to provide robust and scalable serving of inference requests:</p><h4>The container</h4><p>In the `container` directory are all the components you need to package the sample algorithm for Amazon SageMager.</p><pre>├── Dockerfile<br>    ├── build_and_push.sh<br>    └── mask_r_cnn<br>        ├── nginx.conf<br>        ├── predictor.py<br>        ├── serve<br>        ├── wsgi.py<br>        ├── transforms.py<br>        ├── utils.py<br>        ├── coco_eval.py<br>        ├── coco_utils.py<br>        ├── engine.py<br>        └── helper.py</pre><p>Let&#39;s discuss each of these in turn:</p><ul><li><strong>Dockerfile</strong> describes how to build your Docker container image. More details below.</li><li><strong>build_and_push.sh</strong> is a script that uses the Dockerfile to build your container images and then pushes it to ECR. We&#39;ll invoke the commands directly later in this notebook, but you can just copy and run the script for your own algorithms.</li><li><strong>mask_r_cnn</strong> is the directory which contains the files that will be installed in the container.</li></ul><p>In this simple application, we only install five files in the container. The files that we&#39;ll put in the container are:</p><ul><li><strong>nginx.conf</strong> is the configuration file for the nginx front-end. Generally, you should be able to take this file as-is.</li><li><strong>predictor.py</strong> is the program that actually implements the Flask web server and the decision tree predictions for this app.</li><li><strong>serve</strong> is the program started when the container is started for hosting. It simply launches the gunicorn server which runs multiple instances of the Flask app defined in predictor.py. You should be able to take this file as-is.</li><li><strong>train</strong> is the program that is invoked when the container is run for training.</li><li><strong>wsgi.py</strong> is a small wrapper used to invoke the Flask app. You should be able to take this file as-is.</li></ul><p>We have customized train.py and predictor.py for fine tuning Mask R-CNN during training, and for loading tuned model, deserializing request data, making prediction, and sending back the serialized results.</p><h4>The Dockerfile</h4><p>The Dockerfile describes the image that we want to build. We will start from a standard Ubuntu installation and run the normal tools to install the things needed such as python, torch, torchvision, and Pillow. Finally, we add the code that implements our specific algorithm to the container and set up the right environment to run under. The Dockerfile looks like below,</p><pre>FROM ubuntu:16.04</pre><pre>MAINTAINER Amazon AI &lt;sage-learner@amazon.com&gt;<br></pre><pre>RUN apt-get -y update &amp;&amp; apt-get install -y --no-install-recommends \<br>         wget \<br>         gcc\<br>         g++\<br>         python3 \<br>         python3-dev\<br>         nginx \<br>         ca-certificates \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br></pre><pre>RUN wget <a href="https://bootstrap.pypa.io/get-pip.py">https://bootstrap.pypa.io/get-pip.py</a> &amp;&amp; python3 get-pip.py &amp;&amp; \<br>    pip install cython numpy==1.16.2 scipy==1.2.1 pandas flask gevent gunicorn &amp;&amp; \<br>        (cd /usr/local/lib/python3.5/dist-packages/scipy/.libs; rm *; ln ../../numpy/.libs/* .) &amp;&amp; \<br>        rm -rf /root/.cache<br>RUN pip install  torch torchvision fastai thinc  Pillow</pre><pre>ENV PYTHONUNBUFFERED=TRUE<br>ENV PYTHONDONTWRITEBYTECODE=TRUE<br>ENV PATH=&quot;/opt/program:${PATH}&quot;</pre><pre># Set up the program in the image<br>COPY mask_r_cnn /opt/program<br>WORKDIR /opt/program</pre><h3>Build your image using AWS Lambda and CodeBuild</h3><h4>SageMaker containers project</h4><p>For building SageMaker-ready containers, such as the one discussed above for Mask R-CNN, we use the open source “SageMaker Containers” project which can be found here <a href="https://github.com/aws/sagemaker-containers">https://github.com/aws/sagemaker-containers</a>. SageMaker Containers gives you tools to create SageMaker-compatible Docker containers, and has additional tools for letting you create Frameworks (SageMaker-compatible Docker containers that can run arbitrary Python or shell scripts). Currently, this library is used by the following containers: <a href="https://github.com/aws/sagemaker-tensorflow-container/tree/script-mode">TensorFlow Script Mode</a>, <a href="https://github.com/aws/sagemaker-mxnet-container">MXNet</a>, <a href="https://github.com/aws/sagemaker-pytorch-container">PyTorch</a>, <a href="https://github.com/aws/sagemaker-chainer-container">Chainer</a>, and <a href="https://github.com/aws/sagemaker-scikit-learn-container">Scikit-learn</a>. To create a Sagemaker compatible container, we require the following components:</p><ol><li>train.py file with your training code, and</li><li>Dockerfile, such as the one above</li></ol><p>The training script must be located under the folder /opt/ml/code and its relative path is defined in the environment variable SAGEMAKER_PROGRAM. The following scripts are supported:</p><ul><li>Python scripts: uses the Python interpreter for any script with .py suffix</li><li>Shell scripts: uses the Shell interpreter to execute any other script</li></ul><p>When training starts, the interpreter executes the entry point, from the example above:</p><pre>python train.py</pre><p>For more information on hyper-parameters and environment variables, please refer to <a href="https://github.com/aws/sagemaker-containers#id10">https://github.com/aws/sagemaker-containers#id10</a>.</p><h4>Automating container builds using Lambda and CodeBuild</h4><p>We will use a Cloud formation template to automate the container build of our Mask R-CNN. The template sets up the following architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*Ekly4AVv1SVwHVTvWsJpTg.png" /></figure><p>The Lambda function contains the train.py file and Dockerfile that can be edited inline. Once triggered (manually, or through a step functions approach as shown in the next section), the Lambda function:</p><ol><li>Creates an ECR repository ,if it doesn’t already exist, to store the container images once built</li><li>Uploads the train.py and Dockerfile to an S3 bucket</li><li>Creates a Codebuild project and uses the above files with a buildspec.yml to start the process to build a container push the image to ECR.</li></ol><p>The Lambda function also contains useful environment variables that can be reconfigured for new builds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AOAipJ4jWoBwbO6jHS0Lw.png" /></figure><h3>Train and Deploy your container using AWS Step Functions Data Science SDK</h3><p>Once the Lambda function is set up, we are now ready to build out Automation pipeline to train and deploy the model to an endpoint. For this, we will use AWS Step Functions, which is an orchestration tool which lets users author state machines as JSON objects and execute them without provisioning or managing any servers. Step Functions also now provides a Data Science Python SDK for authoring machine learning pipelines using python in a familiar Jupyter notebook environment. We refer the reader to the Step Functions Github repository to get started [3].<br> <br> Here we simply demonstrate the key components of the pipeline that are described in detail in our Github [2]. To author the code, we will use Amazon SageMaker, AWS fully managed machine learning platform. <br> <br> As with all AWS Services, we first need to provide the appropriate service the IAM permissions to call other AWS Services. For this we first need to allow Amazon SageMaker to call Step Functions APIs, and AWS Step Functions to call SageMaker for model training, and endpoint creation and deployment. Detailed instructions on how to set up proper IAM credentials are described in [3].<br> <br> Once this is set up, we will first create a Lambda state to run the Lambda function that takes the code and deploys it as a container to host in ECR.</p><pre>lambda_state = LambdaStep(<br>    state_id=&quot;Calls CodeBuild to Build Container&quot;,<br>    parameters={  <br>        &quot;FunctionName&quot;: &quot;Docker_Lambda&quot;, #replace with the name of the Lambda function you created<br>        &quot;Payload&quot;: {  <br>           &quot;input&quot;: &quot;HelloWorld&quot;<br>        }<br>    }<br>)</pre><pre>lambda_state.add_retry(Retry(<br>    error_equals=[&quot;States.TaskFailed&quot;],<br>    interval_seconds=15,<br>    max_attempts=2,<br>    backoff_rate=4.0<br>))</pre><pre>lambda_state.add_catch(Catch(<br>    error_equals=[&quot;States.TaskFailed&quot;],<br>    next_step=Fail(&quot;LambdaTaskFailed&quot;)<br>))</pre><p>Retry and Catch steps here are added for error handling. You can modify these with your custom error handling steps, but this lets Step Functions know to end the workflow if the Lambda function fails to deploy the container.<br> <br> The next steps are to chain together the training job and the model creation from the trained artifacts. Fortunately, Step Functions Data Science SDK provides the logic and APIs to chain these steps together, with any custom branching logic that could be required.</p><pre>train_step = TrainingStep(&#39;Train Step&#39;,<br>estimator=maskrcnn,<br>data=os.path.dirname(data_location),<br>job_name=execution_input[&#39;JobName&#39;])</pre><pre>model_step = ModelStep(&#39;Save model&#39;,<br>model=train_step.get_expected_model(),<br>model_name=execution_input[&#39;ModelName&#39;])</pre><pre>endpoint_config_step = EndpointConfigStep(<br>    &quot;Create Endpoint Config&quot;,<br>    endpoint_config_name=execution_input[&#39;ModelName&#39;],<br>    model_name=execution_input[&#39;ModelName&#39;],<br>    initial_instance_count=1,<br>    instance_type=&#39;ml.m5.large&#39;<br>)</pre><pre>endpoint_step = EndpointStep(&quot;Create Endpoint&quot;,<br>endpoint_name=execution_input[&#39;EndpointName&#39;],<br>endpoint_config_name=execution_input[&#39;ModelName&#39;])</pre><p>Here we use our <strong>mask-rcnn</strong> estimator which is a general SageMaker Estimator object that lets us specify the type of instance we want to train our model on, identify any network or security settings if needed and model hyperparameters, as well as the output paths to the models. The input to the estimator is the container image that is created by our Lambda function above.</p><pre>maskrcnn = sagemaker.estimator.Estimator(image,<br>                       role, 1, &#39;ml.p2.xlarge&#39;, #feel free to modify with your own. A cost estimate is provided in Readme.<br>                       output_path=&quot;s3://{}/{}/output&quot;.format(sess.default_bucket(), key),<br>                       sagemaker_session=sess)</pre><pre>maskrcnn.set_hyperparameters(num_epochs = 1,<br>                              num_classes = 2)</pre><p>By using the Chain utility, we can chain all the above steps together to occur sequentially. We can then choose to output the entire workflow as a JSON, that can be used in a much larger Cloud Formation template for example, which also includes information on the provisioning of instances, setting up of network security etc., or run on its own. By creating the workflow and rendering the graph, a state machine will be created in Amazon Step Functions console.</p><pre>workflow_definition = Chain([<br>    lambda_state,<br>    train_step,<br>    model_step,<br>    endpoint_config_step,<br>    endpoint_step<br>])</pre><pre># Next, we define the workflow<br>workflow = Workflow(<br>    name=&quot;MyWorkflow-BYOC-MaskRCNN-{}&quot;.format(uuid.uuid1().hex),<br>    definition=workflow_definition,<br>    role=workflow_execution_role<br>)</pre><pre>workflow.render_graph()</pre><p>This renders the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIQiHq7XwrJGN9tKlY734Q.png" /></figure><p>This completes our Step Function workflow. We can now execute this workflow directly in Amazon SageMaker <br> and check the progress using the workflow.execute and workflow.render_progress() APIs or from the Step Functions console directly. Executions will be logged in CloudWatch and can be used to send alerts and notifications in a downstream system to users.<br> <br> With AWS Step Functions Data Science SDK, data scientists and engineers can seamlessly deploy custom containers, train ML models and deploy them into production. For integrating other AWS big data tools such as EMR and AWS Glue into Step Functions workflows, we refer the reader to [4, 5].</p><h3>References</h3><p>[1] He, K., Gkioxari, G., Dollar, P., and Girshick, R., Mask R-CNN, <a href="https://arxiv.org/abs/1703.06870">https://arxiv.org/abs/1703.06870.</a><br> [2] <a href="https://github.com/aws-samples/aws-stepfunctions-byoc-mlops-using-data-science-sdk">https://github.com/aws-samples/aws-stepfunctions-byoc-mlops-using-data-science-sdk</a><br> [3] <a href="https://github.com/awslabs/amazon-sagemaker-examples/tree/master/step-functions-data-science-sdk">https://github.com/awslabs/amazon-sagemaker-examples/tree/master/step-functions-data-science-sdk</a><br> [4]<a href="https://medium.com/@elesin.olalekan/automating-machine-learning-workflows-with-aws-glue-sagemaker-and-aws-step-functions-data-science-b4ed59e4d7f9">https://medium.com/@elesin.olalekan/automating-machine-learning-workflows-with-aws-glue-sagemaker-and-aws-step-functions-data-science-b4ed59e4d7f9</a><br> [5]<a href="https://aws.amazon.com/blogs/aws/new-using-step-functions-to-orchestrate-amazon-emr-workloads/">https://aws.amazon.com/blogs/aws/new-using-step-functions-to-orchestrate-amazon-emr-workloads/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8052825a56c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/simple-mlops-with-amazon-sagemaker-lambda-and-aws-step-functions-data-science-sdk-e8052825a56c">Simple MLOps with Amazon SageMaker, Lambda and AWS Step Functions Data Science SDK</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>