<?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 Ilnur Garifullin on Medium]]></title>
        <description><![CDATA[Stories by Ilnur Garifullin on Medium]]></description>
        <link>https://medium.com/@tidylobster?source=rss-7222e7db9e2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*38nxX7YhQSfAh4C52D9kBQ.jpeg</url>
            <title>Stories by Ilnur Garifullin on Medium</title>
            <link>https://medium.com/@tidylobster?source=rss-7222e7db9e2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:26:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tidylobster/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[Kubeflow Times Machine Learning — Reproducibility Step by Step]]></title>
            <link>https://medium.com/hydrosphere-io/train-and-deliver-machine-learning-models-to-production-with-a-single-button-push-a6f89dcb1bfb?source=rss-7222e7db9e2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6f89dcb1bfb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[kubeflow]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ilnur Garifullin]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 15:33:39 GMT</pubDate>
            <atom:updated>2019-07-11T09:32:27.629Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubeflow Times Machine Learning — Reproducibility Step by Step</h3><p>Very often a workflow of training machine learning models and delivering them to production environment contains loads of manual work. These could be various steps depending on the type of model you are using, company’s workflow you are working within and requirements from the deployed model. Industry has already developed tools for a continuous software delivery/integration, but they cannot be directly applied for machine learning models, which designates the problem. In this article we will show a way to create a pipeline that connects machine learning workflow steps (like collecting &amp; preparing data, model training, model deployment and so on) into a single reproducible run, which you can execute with a single command.</p><p>But before we actually start implementing such pipeline we should get on the same page about the general machine learning workflow. Let’s quickly recap the flow and its main aspects:</p><ol><li>Research in the subject area;<br>Suppose we’ve already have a task we need to solve. We need to make a research in the subject area, define requirements for the solution, define data sources, define tools that we are going to use and methods we are going to apply.</li><li>Data preparation;<br>We start with collecting the data, transforming it into a desirable form and version it.</li><li>Model training;<br>We build a model and train it using the prepared data. We experiment using different architectures, run training several times while tuning hyper-parameters and evaluating model’s performance.</li><li>Cataloguing;<br>Once the model has been trained we export it into a self-sufficient format. This means that model’s artifact can be independently used on other infrastructures without passing its source code and all dependencies along. We handle versioning of the model as well as extraction of the inputs and outputs of the model to use for deployment.</li><li>Model deployment;<br>After the model has been exported we deploy it on the prepared infrastructure and provision HTTP/gRPC endpoints to it.</li><li>Integration Testing;<br>We perform integration testing to ensure the model runs properly on the prepared environment.</li><li>Production Inferencing;<br>We start inferencing on our model while collecting all requests and predictions during model’s lifetime. We provide different deployment variants, such as A/B or Canary deployments for different model versions.</li><li>Performance Monitoring;<br>During inference time we automatically monitor how model behaves in the production environment; how data, flowing through the model, changes over a time, including insights to concept drifts, domain changes and anomaly detection.</li><li>Model Maintenance;<br>This stage is dedicated to the model’s long-term live. We interpret model’s predictions and explain why a model behaves in a way it does. We use that knowledge to improve the model by retraining it further on the production traffic, so to increase its performance.</li></ol><p>We will go over each of these steps throughout the article.</p><h3>Tools</h3><p>A short introduction to the tools we’re going to use:</p><ul><li><a href="https://www.kubeflow.org/docs/about/kubeflow/"><strong>Kubeflow</strong></a> is a machine learning toolkit for Kubernetes. It began as just a simpler way to run TensorFlow jobs on Kubernetes, but has since expanded to be a multi-architecture/multi-cloud framework for running and automating machine learning pipelines.</li><li><a href="https://hydrosphere.io/serving-docs/"><strong>Hydrosphere.io</strong></a><strong> </strong>is an open source model management platform for deploying, serving and monitoring machine learning models and ad-hoc algorithms.</li></ul><p>To make a great picture of the future pipeline, let’s see how different tools within Kubeflow toolset and Hydrosphere.io platform map onto workflow steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qYqYtWaUO5djE7fB2qJDQ.png" /></figure><p>The primary focus of Kubeflow ecosystem is to train machine learning models built in different frameworks in a distributed manner by leveraging the underlying Kubernetes cluster. This gives Kubeflow a noticeable advantage over manual set-ups of such training infrastructure. Model deployment is another part that Kubeflow manages to cover with niche (regarding frameworks) and over deployment tools. On top of that there’s a new service, called <a href="https://www.kubeflow.org/docs/components/pipelines/">Kubeflow Pipelines</a> which main goal is to connect different workflow steps into a single processing run.</p><p>Hydrosphere.io comprehends after-training part of the workflow. Its primary goals are model management, model delivery to production in simple and robust fashion, as well as monitoring models during inference time and gaining insights from predictions (for further model’s quality improvement).</p><h3>Prerequisites</h3><p>This tutorial presumes that you have an access to a Kubernetes cluster. If you don’t you can create your own single node cluster locally with <a href="https://kubernetes.io/docs/setup/minikube/">Minikube</a>. You will additionally need:</p><p>Locally:</p><ul><li><a href="https://docs.docker.com/">Docker</a></li><li><a href="https://helm.sh/">Helm</a></li><li><a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/#install-kubectl">Kubectl</a></li><li><a href="https://ksonnet.io/get-started/">Ksonnet</a></li><li><a href="https://github.com/kubeflow/pipelines/tree/master/sdk">Kubeflow Pipelines SDK</a></li></ul><p>On the Kubernetes Cluster:</p><ul><li><a href="https://www.kubeflow.org/docs/started/getting-started/#kubeflow-quick-start">Kubeflow</a></li><li><a href="https://hydrosphere.io/serving-docs/installation.html#kubernetes">Hydrosphere.io</a></li></ul><p>By default Kubeflow will be installed in the kubeflow namespace. In this tutorial I assume that Hydrosphere.io is installed in the same namespace as Kubeflow.</p><h4>PersistentVolumeClaims</h4><p>We will additionally need to provide a persistent storage for workflow pods to retain intermediate files and supply them between stages.</p><pre>$ kubectl apply -f - &lt;&lt;EOF <br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: data<br>spec:<br>  accessModes:<br>    - ReadWriteMany<br>  resources:<br>    requests:<br>      storage: 20Gi<br>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: models<br>spec:<br>  accessModes:<br>    - ReadWriteMany<br>  resources:<br>    requests:<br>      storage: 20Gi<br>EOF</pre><h4>Kubeflow Pipelines Manifest</h4><p>The whole workflow will be running on top of Kubeflow Pipelines. Pipelines are built upon <a href="https://github.com/argoproj/argo">Argo Workflows</a> — a container-native workflow engine. To execute such workflow you have to create a Kubernetes blueprint and then apply it on the cluster to start the job. To ease the process of creating such .yaml definitions Kubeflow released a <a href="https://github.com/kubeflow/pipelines/tree/master/sdk">Python SDK</a> library, which allows you to define your workflows as functions and then compile them to DSL.</p><p>First of all we will define a frame of that function. Create a root repository for this tutorial and define pipeline.py script in it.</p><pre>$ mkdir mnist  # create a root directory for this tutorial<br>$ touch pipeline.py</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88eb562acd513885ab8ed6d687b5a792/href">https://medium.com/media/88eb562acd513885ab8ed6d687b5a792/href</a></iframe><p>We’ve already created PVCs in our cluster, so we can supply pipeline definition with references to them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb4dc357ddf2c1d72c65369df839fda1/href">https://medium.com/media/cb4dc357ddf2c1d72c65369df839fda1/href</a></iframe><p>Throughout the article I will provide short code snippets to this pipeline.py file, which will only contain differences from previous versions. The full code is available <a href="https://github.com/Hydrospheredata/hydro-serving-kubeflow-demo/blob/master/examples/mnist/pipeline.py">here</a>.</p><p>To mention a few changes here — Kubeflow provides us with is the ability to customise the workflow from Pipelines UI. To do that you just have to supply parameters to the function like we do with data_directory and models_directory variables. There are some limitations using those parameters, but they would essentially disappear in the upcoming SDK versions. For now you can use these parameters in your function like so: a data_directory variable will be mapped to a {{workflow.parameters.data-directory}} string, when compiled into DSL, which we use while declaring volumes.</p><p>Let’s start with the actual machine learning model.</p><h3>Step 1. Research in the Subject Area</h3><p>In order to stay focused on the automation part I’ve chosen a well known digit recognition problem.</p><p>Objectives:</p><ul><li>Given an image of the hand-written digit classify what digit it is.</li></ul><p>Requirements:</p><ul><li>The deployed model should be able to predict on batches of images;</li></ul><p>Methods:</p><ul><li>A fully-connected neural network (for implementation simplicity).</li></ul><p>Tools:</p><ul><li>Language — Python (contains various deep learning frameworks);</li><li>Framework — Tensorflow (has a great model exportation mechanism; has a pre-made classification architectures).</li></ul><p>Data Sources:</p><ul><li>MNIST (50000 train &amp; 10000 test grayscale 28x28 images of handwritten digits).</li></ul><h3>Step 2. Data Preparation</h3><p>Real world scenario often forces you to obtain training data from the company’s data storage. The case might consist of the following:</p><ol><li>Gain access to the data warehouse;</li><li>Analyse the schema and write a query for selection;</li><li>Transform selected data into a desired form and store it for training.</li></ol><p>With the chosen problem we don’t have such a reach possibility. We will use an original publicly available MNIST dataset. Let’s create the first executable that will download the data and store it in our PersistentVolumeClaim (PVC).</p><pre>$ mkdir 01-download; cd 01-download<br>$ touch download.py</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ce979c4a961e8163a7e2f0f8d558619/href">https://medium.com/media/8ce979c4a961e8163a7e2f0f8d558619/href</a></iframe><p>This downloads all 4 files, unpacks them, converts into numpy arrays and stores those arrays under base_dir directory. The directory in this case will be a PVC, mounted to the pod under path specified by MNIST_DATA_DIR environment variable (we specify that variable below).</p><p>To be able to execute this file on the cluster as part of the workflow we need to pack it into Docker container. Create a Dockerfile for that.</p><pre>$ cat &gt; Dockerfile &lt;&lt; EOF<br>FROM python:3.6-slim<br>RUN pip install numpy==1.14.3 Pillow==5.2.0<br>ADD ./download.py /src/<br>WORKDIR /src/<br>ENTRYPOINT [ &quot;python&quot;, &quot;download.py&quot; ]<br>EOF</pre><p>We use python:3.6-slim as our base image, while additionally installing some python dependencies.</p><p>Once container definition has been created, we can build a Docker image from it and push it to the public Docker registry. As a <em>username</em> you can use your own <a href="https://hub.docker.com/">Docker Hub</a> account or use any available for you Docker Registry.</p><pre>$ cd ..<br>$ docker build -t {username}/mnist-pipeline-download 01-download<br>$ docker push {username}/mnist-pipeline-download</pre><p>Lastly let’s update pipeline definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aceda846a51bbcd0368e503634fedc84/href">https://medium.com/media/aceda846a51bbcd0368e503634fedc84/href</a></iframe><p>Here we define a new environment variable (1) to be attached to our container, define a container operation (2) to be executed on the cluster and finally attach (3) required resources.</p><h3>Step 3. Model Training</h3><p>After our data is ready we can switch to model building and training. Typically at this stage you build a model, train it, evaluate, tune hyper-parameters and repeat that loop until model has a desired performance. So, let’s first create a directory for the executable.</p><pre>$ mkdir 02-train; cd 02-train<br>$ touch train.py</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bf84283cdbae66a6fd792e3b8267964/href">https://medium.com/media/2bf84283cdbae66a6fd792e3b8267964/href</a></iframe><p>The model is quite simple, we just use a pre-made fully-connected neural network classifier (tf.estimator.DNNClassifier). We specify, that the model consists of 2 hidden layers with 256 and 64 units respectively. learning_rate, num_steps and batch_size are parameters, configured by environment variables. num_steps is responsible for how long the model is going to be trained.</p><p>After model training finishes, we immediately store it in the models PVC in the tf.saved_model format, specifying inputs of the model. Outputs will be automatically inferred.</p><p>Let’s create a Docker image from that executable.</p><pre>$ cat &gt; Dockerfile &lt;&lt; EOF<br>FROM tensorflow/tensorflow:1.9.0-py3 <br>ADD ./train.py /src/<br>WORKDIR /src/<br>ENTRYPOINT [ &quot;python&quot;, &quot;train.py&quot; ]<br>EOF </pre><pre>$ cd ..<br>$ docker build -t {username}/mnist-pipeline-train 02-train<br>$ docker push {username}/mnist-pipeline-train</pre><p>Update pipeline definition with training model container definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c2d006045c91dbc42621ec4389df328/href">https://medium.com/media/9c2d006045c91dbc42621ec4389df328/href</a></iframe><p>Similarly to the previous step we additionally define new environment variables (1) and define a container operation (2). We additionally specify, that this operation must be executed after the previous operation download completes. Otherwise they will start in parallel. At the bottom we define how much resources this container needs on the cluster (5). This instructs Kubeflow to start this container only when the required conditions are met.</p><h3>Step 4. Model Cataloguing</h3><p>Model Cataloguing is a term I would like to use to comprehend the following:</p><ul><li>Metadata extraction:<br>— Graph definition and weights;<br>— Inputs and outputs definitions;<br>— Training data version / statistics;<br>— Other dependencies (look_up vocabularies, etc);</li><li>Model artifact versioning;</li><li>Storing model in Repository;</li></ul><p>This describes the model in great detail. We can use such information for model deployment since we know inputs and outputs of the model and can build an appropriate infrastructure. We can identify data that was used for training for the current model. Later on we can experiment with the different architectures and varying data versions to see if we can reach better performance. This also allows us to analyze how newer architecture works with previous data versions, hence compare the performance. We version models to compare their performance via A/B or Canary deployments (we will talk about this in the next sections).</p><p>We have already done half of this in the previous step when we exported the model to tf.saved_model format. Other steps require actions though. If we will do this manually we would need to create a repository where all of our models will be stored and versioned. Along with that we would also need to handle metadata that wasn&#39;t provisioned with the model.</p><pre>$ mkdir 03-upload; cd 03-upload<br>$ touch execute.sh</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc406b8708cee0de8ed92faba4f6c09/href">https://medium.com/media/8fc406b8708cee0de8ed92faba4f6c09/href</a></iframe><p>At this stage we build a model artifact (retrieve all metadata needed for later inference and pack it along with the model binaries) and store the built artifact in a repository. The artifact is a Docker image with a frozen model inside it whereas the repository is a configured Docker registry (could be external). Along with that we supplement the model with the training data statistics, used for this model.</p><p><em>In case you are wondering why would we need to store a built model’s version in a file inside the pod (ii) → we can instruct Kubeflow to retrieve the contents of that file and use them in the subsequent pipeline steps (we will need it).</em></p><p>Let’s create a Docker image from that executable.</p><pre>$ cat &gt; Dockerfile &lt;&lt; EOF<br>FROM python:3.6-slim<br>RUN apt update &amp;&amp; apt install -y jq<br>RUN pip install hs==0.1.5<br>ADD ./execute.sh /src/<br>WORKDIR /src/<br>ENTRYPOINT [ &quot;bash&quot;, &quot;execute.sh&quot; ]<br>EOF </pre><pre>$ cd ..<br>$ docker build -t {username}/mnist-pipeline-upload 03-upload<br>$ docker push {username}/mnist-pipeline-upload</pre><p>Update pipeline definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/638dd4f39f5d03057294dd9274544013/href">https://medium.com/media/638dd4f39f5d03057294dd9274544013/href</a></iframe><p>One minor difference from code snippets — we tell Kubeflow to store the contents of /model_version.txt under model_version key in the internal key-value repository (line 26). We will use this in a subsequent step.</p><h3>Step 5. Model Deployment</h3><p>The next step is the actual model deployment. At this step we have a built model artifact stored in our repository which is not yet exposed to the world. A typical way of exposing model outside of the cluster consists of creating a runtime for the model and deploying it to the cluster (REST API web server, which will inference on the model and return predictions). There are niche solutions like Tensorflow Serving, TensorRT, but they are focused on the specific frameworks. There are no way to use them for models built on different frameworks such as scikit-learn or MXNet.</p><p>Along with implementing a runtime there will come up a necessity of implementing service meshing between model versions to create Canary deployments (when you deploy, for example, three model versions and let the traffic flow through them in different proportions, like 30/30/40, exposing outside only one endpoint). You might want to connect your models in chain, where some models retrieve features and others infer on that features.</p><p>Implementing such runtimes, configuring an underlying infrastructure, managing model interactions is not a trivial job. Using Hydrosphere.io you only have to create an application.</p><p>An <strong>application</strong> here is a microservice with an exposed API endpoint to interact with your model. It allows you to use your most recent deployed production models via HTTP-requests, gRPC API calls or configure it as a part of Kafka streams. It uses predefined runtimes to run your model artifacts and helps you to configure a multi-staged execution from model to model. Within an application you can design a setup with canary or A/B model deployments.</p><pre>$ mkdir 04-deploy; cd 04-deploy<br>$ touch execute.sh</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef0bf282d0427b1133dcc926a11aef5b/href">https://medium.com/media/ef0bf282d0427b1133dcc926a11aef5b/href</a></iframe><p>Let’s quickly analyze the manifest and its main parts:</p><ol><li>We define what resource this manifest describes;</li><li>We define an application name;</li><li>By defining a singular flag we state that this application is single-staged and contains just a single model version;</li><li>Here we define what model will be deployed and its version;</li><li>And finally we specify a runtime for the model.</li></ol><p>That’s basically it. After the last command the model will be deployed within an application and exposed to the world.</p><p>Let’s create a Docker image from that step.</p><pre>$ cat &gt; Dockerfile &lt;&lt; EOF<br>FROM python:3.6-slim<br>RUN pip install hs==0.1.5<br>ADD ./execute.sh /src/<br>WORKDIR /src/<br>ENTRYPOINT [ &quot;bash&quot;, &quot;execute.sh&quot; ]<br>EOF </pre><pre>$ cd ..<br>$ docker build -t {username}/mnist-pipeline-deploy 04-deploy<br>$ docker push {username}/mnist-pipeline-deploy</pre><p>Update pipeline definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23869fb3f3aeaec8d3432d2c7683f016/href">https://medium.com/media/23869fb3f3aeaec8d3432d2c7683f016/href</a></iframe><p>The minor difference here is located at line 19. We use output value from the previous upload container (model_vesion key) and pass it as an argument to the entrypoint of the deploy container operation.</p><h3>Step 6. Model Integration Testing</h3><p>This step aims to test the model when it’s deployed into production-like infrastructure. It helps us to eliminate configuration bugs, deployment and integration issues. It’s important to write test suites that comprehend the following data:</p><ul><li>A golden data set;</li><li>Edge cases;</li><li>Recent traffic.</li></ul><p>Let’s create a client application which will invoke the deployed model and estimate accuracy.</p><pre>$ mkdir 05-test; cd 05-test<br>$ touch test.py</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aca44476893c5c65849e009be0aa9dfa/href">https://medium.com/media/aca44476893c5c65849e009be0aa9dfa/href</a></iframe><p>generate_data function reads some amount of the testing data saved in our PVC. Then we use HTTP endpoint to reach our model, get predictions and store them in a list. At last we assert that accuracy of our model is above acceptable level. acceptable_accuracy reflects a corresponding environment variable.</p><p>Let’s create a Docker image from that step.</p><pre>$ cat &gt; Dockerfile &lt;&lt; EOF<br>FROM python:3.6-slim<br>RUN pip install scikit-learn==0.20.0 requests==2.21.0 numpy==1.14.3<br>ADD ./test.py /src/<br>WORKDIR /src/<br>ENTRYPOINT [ &quot;python&quot;, &quot;test.py&quot; ]<br>EOF </pre><pre>$ cd ..<br>$ docker build -t {username}/mnist-pipeline-test 05-test<br>$ docker push {username}/mnist-pipeline-test</pre><p>Update pipeline definition. Everything is similar to the whole pipeline definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/350eb3e83b56d64a726740f6989f1a5c/href">https://medium.com/media/350eb3e83b56d64a726740f6989f1a5c/href</a></iframe><h4>Run Workflow</h4><p>This was the last step we can implement within Kubeflow pipelines but the overall machine learning workflow does not end here. There’re a few important steps left but we will deal with them later.</p><p>We can compile the pipeline definition now.</p><pre>$ python pipeline.py</pre><p>This will produce a pipeline.tar.gz file. Let’s execute this pipeline on our cluster.</p><pre>$ kubectl port-forward deployment ambassador 8085:80</pre><p>This will allow you to reach Kubeflow UI from your local machine. Open <a href="http://localhost/pipeline/">http://localhost/pipeline/</a>.</p><p>Upload pipeline.tar.gz file using <em>Upload pipeline</em> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xOznhcrv-hJFazSZ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r0ITDc8cAw7VGurg" /></figure><p>Create a run (you would also have to create an experiment to which this run will be attached). During run creation you can specify parameters we’ve defined earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sFo124lus8cOU4M3" /></figure><p>And finally start a run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wy6yHKdHlk1xcbCc" /></figure><h3>7. Production Inferencing</h3><p>At this stage we have our model up and running in the production environment. We start collecting all requests and predictions during model’s lifetime. As model evolves (different architectures/more data were used) we might want to create different deployment configurations, like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSYCeiJ9UTjAVrgqgpLnGQ.png" /></figure><p>Throughout the life of the model we need to make sure that it scales appropriately according to the production needs. We want to increase the number of model replicas, when the incoming traffic hits certain limits (for example, by analyzing <strong>Latency</strong> degradation), and to decrease them respectively when the traffic goes down.</p><h3>8. Model Performance Monitoring</h3><p>During inference time we automatically monitor how model behaves in the production environment as well as how data, flowing through the model, changes. This helps us to gain insights about our vision of the production flow.</p><p>There’re a few graphics available for use out of the box — <strong>Requests Count</strong> and <strong>Latency</strong>. Their names are self-explanatory, the first one just counts how many request a model receives over a time, the second one watches how long each request took to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UaJ51-KEImV8-mnFi-HIeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5pHBN78Rq2N-CxiM8ipuA.png" /></figure><p>Other metrics use more sophisticated methods. One possible metric is <strong>Autoencoder. </strong>With it you can capture a “concept” of your data and monitor its reconstruction error. Let’s send some traffic to the deployed model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKToDh9lgXyaKEy9xOnKXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEu7PKJpwwCItsWdkRydRw.png" /></figure><p>On the left-hand side the plot shows how the production data was reconstructed when normal MNIST images were sent to the model. The reconstruction score merely reached 0.1 point. For this graphic we’ve also defined a threshold to be 0.15 score which means whenever a reconstruction score goes above the red line, the notification will be formed.</p><p>On the right hand side you can see how plot burst up to 60.000 points of the reconstruction score once the data was changed to letters (notMNIST dataset). Once monitoring identified that, it changed the state of the model to be “unhealthy”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Y2XVCtozG_LoFDAsg86Dg.png" /></figure><p>There’re also other evaluation metrics, but they would require you to provide labels for your requests. For this model we can count <strong>accuracy</strong> on the production stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kC32uF2tDshChP2qqkqXNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVgBfaddBZbt7l2A1gwLsQ.png" /></figure><p>The first version of the model (blue line) was less efficient judging by the diagrams above. It was subject to errors on image batches, thus showed downgrades of accuracy down to 0.85 percent on a batch. The second version (green line) looks better, as there are wider gaps between accuracy dropdowns (meaning, that all images in intermediate batches were classified perfectly == 1), as well as a higher accuracy score.</p><h3>9. Model Maintenance</h3><h4>Root Cause Analysis</h4><p>We are moving to the last stage where we are touching a model maintenance topic. Recall the example with a huge concept drift:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-4R_np930irdzonlshHlg.png" /></figure><p>It’s not so hard to understand what happened to our model if we just look to the requests. We can improve our model so it will be able to classify letters as well, but there are other cases: what if a concept drift doesn’t occur but the accuracy of the model stays low?</p><p>Machine learning models are often black-boxes for us and thus cannot be directly interpreted. But there are algorithms that help us to understand why a particular prediction was made. One of such methods called <a href="https://github.com/eclique/RISE">RISE</a>.</p><p>Briefly speaking, this algorithm treats our model as a black box. It generates a bunch of masks, hiding out different portions of pixels from the original image, and watches how model’s predictions change. Based on those observations the algorithm generates an importance map, showing what regions of the image play significant role for a particular class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDXp_aABcTgWAOvtvYaQQA.png" /></figure><p>In the plot above you can see importance regions for sample images (rows) with the respect to each class (columns). Ground truth image/class correlations are presented on the major diagonal.</p><p>Our current model is correct most of the time (green boxes), but it did confuse an image of a five and wrongly classified it as a three. Let’s investigate why this happened. If we take a look at the importance region of pixels for image of three and its respective class (row 4, column 4), we can see that the classifier watches on the top half of the digit and probably takes into account curly forms that a digit three has. Likewise an image of a five (row 6, column 4) has similar curly shapes, but the importance map is more shifted to the right. An importance map for the class five (row 6, column 6) shows, that for classifying a digit five the model watches on the empty left region.</p><p>Using this knowledge we can supply our training dataset with more related cases, or change model’s architecture.</p><h4>Subsampling</h4><p>At the time we’re touching inference mode we have no more training and testing datasets. We trained our model on as much data as possible, and deploy the model to production. But since then we would continuously receive more data for which, for sure, labels won’ be immediately available, but we would eventually obtain them sooner or later too.</p><p>The next logical step would be retraining the model on the newer data to capture more cases and enhance model’s performance. Returning to our pipeline — you can configure Kubeflow to train new models periodically and upload them to production.</p><p>When you send a request to the model deployed on Hydrosphere.io platform, along with the model’s predictions you will receive additional system information, like the trace_id for your request. You can store that trace_id and model’s predictions in your data storage and later on match these requests to the ground truth labels. We can use that data to fine tune existing model or train a new one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d04814a32fc5596545c348c010747dc9/href">https://medium.com/media/d04814a32fc5596545c348c010747dc9/href</a></iframe><p>Here we download [requests, responses] from Hydrosphere.io, look up for ground truth labels from MNISTTable and then prepare a new training dataset. The subsample line binary_data=reqstore.APIHandler.subsample(addr, name) would not download the whole inference history of our model, but it will instead download a representative subsample with the distribution of the production data. This way we can train a new model on the most relevant cases.</p><p>Using this script we can build a new container, replace the first step in the above pipeline and create a recurring run to repeatedly train and deploy new models every month with the most relevant training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFdiUxjQRjDu3bfyN6MdBA.png" /></figure><h3>Conclusion</h3><p>Configuring ML pipelines, once done properly, will save a lot of time and efforts in machine learning engineers’ daily routines. In this tutorial we’ve created an infrastructure an ML team can productively use every day multiple times in dispense with dedicated DevOps or software engineers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6f89dcb1bfb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydrosphere-io/train-and-deliver-machine-learning-models-to-production-with-a-single-button-push-a6f89dcb1bfb">Kubeflow Times Machine Learning — Reproducibility Step by Step</a> was originally published in <a href="https://medium.com/hydrosphere-io">hydrosphere.io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On the delivery of AI to Business]]></title>
            <link>https://medium.com/hydrosphere-io/on-the-delivery-of-ai-to-business-b7a9fee44d90?source=rss-7222e7db9e2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7a9fee44d90</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ilnur Garifullin]]></dc:creator>
            <pubDate>Fri, 08 Feb 2019 15:40:23 GMT</pubDate>
            <atom:updated>2019-02-08T15:40:23.797Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Before I start I have to mention that I don’t have any prior experience of working at the head of the security department. The example is made up for the sake of clarity and explainability of the important concepts on the delivery of AI products to the production environment. In this article I’ll try to cover some aspects that lie between an out-of-oven model and a production environment that handles millions of requests per second.</em></p><p><strong>January 15</strong></p><p>Suppose you’re a head of the security department in a bank. It’s the beginning of the working week. You enter your office and see a report on your table summing up the past year. You revise all the contents, everything seems good — overall amount of transactions almost doubled since the last year. But then you open the “Fraud” section where everything starts to go gross. Fraud transactions now are making up around 7.2% from all of the transactions. They gained 3.4% during the past year and are expected to grow further based on the exponential curve exploding from the previous years. This can no longer last, you have to do something with it.</p><p>You convene a meeting with the conjunction with analytical department and the agenda has only one discussing point — “Fraud”. You open with a quick greeting and immediately switch to the main issue that bothers you. After a small but definitive speech you wrap up with the short question — “What can we do?”. Some guy from the analytical department, Steve, mentions that he’s familiar with the machine learning techniques and can investigate data to see what could be done.</p><p>“It will take some time but I will show some results at the end of the week”, he says.</p><p>Likely for us you have a little odd habit — you’re eager for visualisations and like to draw everything down. You open your notebook and draw the first block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*VMhhOdTI0Q0jUDv0" /></figure><p><strong>January 17</strong></p><p>A couple days later Steve knoсks at your door with the good news — he can create a model that will learn to distinguish clean and fraudulent transactions, but he needs time for model building and evaluation. You discuss this with the head of the analytical department and you both decide to create a new department that will be charged for everything related to machine learning and artificial intelligence (since you don’t have one). Steve is appointed as a head of the department.</p><p>In the meantime you conform changes to the server side. Now a service responsible for conducting transactions has to execute an intermediate request with transaction data to a new service which will approve or decline it.</p><p>You open your notebook and add two more blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cILq2lYTa9S8NOHw" /></figure><p><strong>January 23</strong></p><p>In the next Monday you visit Steve to see what’s going on. He says he had already made a few models and all of them have an acceptable level of performance. These are great news, you can already infer on the historical data. And the development team has done their job too, the underlying infrastructure is ready.</p><p>“Steve, you have to expose an HTTP interface to your model”, you start a conversation.</p><p>Steve gently notices that he’s not a DevOps engineer and doesn’t have enough experience of configuring server applications.</p><p>“But”, he says, “I’ve created a few pet servers back in the university. I’ll check what I can do”.</p><p>“Good. I’ll send you someone from the development team to help you out”, you reply.</p><p>It seems legit for you to complete the diagram with the last block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z8BsE7PAD57v6pCv" /></figure><p><strong>January 24</strong></p><p>In the next day you hear altercations from the Steve’s department. Roger — a leader of the development team — is horrified from the Flask server Steve has created.</p><p>“It works but what happens when there will be be 10 requests per second? 100? 1000? It will crush and you wouldn’t even know about it”, you hear while opening the door. “Moreover, how are you going to manage your model? Will you update the model via VCS or by SSH connection each time you develop a new model version? What if a model will weight more than 5MB? 100MB? 500MB?”</p><p>Steve gets a little frustrated with all of these questions. You decide to intervene.</p><p>“Sorry for interrupting you guys, but we also have a minor change of plans. We cannot let all of the production traffic flow through the model on the first run. We need to make sure that the model performs well in the long term. At least we have to evaluate it on the first month of blocked and accepted transactions to see how well it does in the real environment. I think 5 percent will be a good starting point.”</p><p>Clearly Roger had a more cheerful expression when you’ve entered the room.</p><p>“Emm, that’s easy to say, not so easy to do,” he breaks the quiet. “An ugly trivial solution would be to put all logic of performing model inference into API server. This means Steve would have to hardcode this into the model.”</p><p>You notice Steve’s skin suddenly turned pale.</p><p>“The bad news is, this is not scalable, which is definitely a requirement for us,” continues Roger. “Moreover, what if we would want to run a second model in parallel? We should also collect the metadata for each request to be able to identify which requests went through which model”.</p><p>Steve exhales and the skin starts looking normal, although Roger goes even more upset.</p><p>“I would have to think about this. Surely this would require service meshing and overall models’ orchestration on a higher level. I’ll come up with updates next week”, Roger almost leaves the room but accidentally notices Steve’s happy face. “Don’t be so shiny, darling. If you’ll see some new article published recently that achieves better results which would force you to, for example, change the model significantly along with the web server — know, you cannot throw away your current endpoints without notifying me. There would be model export and runtime preparation for sure. I’ll talk to you after the lunch.”</p><p>“Seems like this is going to be the hell of the month”, says Steve.</p><p>“And when will we serve the model?”, you ask unobtrusively.</p><p>“Probably after runtime preparation the model will be deployed, then we can start obtaining predictions.”</p><p>Bitterly sighing you open your notebook and make a few corrections. Changes accumulate rapidly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OcyF1FRC_TilpMq5" /></figure><p><strong>February 5</strong></p><p>The next week swept past you painfully long. You’ve talked to Steve but all he got were some instructions on the model export from Roger. Steve said he shared a few versions of the model with Roger, but didn’t have any news since then. On the sync-ups Roger constantly replied he needed more time.</p><p>“The manager is still under development.”</p><p>“What is that?”, asked you once.</p><p>“That’d be a service that will manage all the models along with handling all intermediate actions”, replied Roger.</p><p>“Like what?”</p><p>“Like extracting models’ metadata and building Docker images on our own instead of forcing Steve to do that. This will increase fault tolerance and give us more flexibility for managing different models.”</p><p>Hmm, looks like you can associate blocks in the diagram with different teams. Although Roger’s work is not over yet, Steve’s workflow is already well-formed. He has done his major work and future tasks very likely will be related to the defined blocks. You open your notebook and distinguish the first four blocks labelling them as data science work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7DJ0Q06iFohPIIYv" /></figure><p><strong>February 15</strong></p><p>Today is exactly one month since you’ve started the project. You have already lost all of your patience and intended to “politely” elaborate on the fact that this can not be put on the long run when suddenly Roger enters your office with updates.</p><p>“It’s over!”, you hear a joyful Roger’s speech. “We’ve created a machine learning environment in our cloud. Steve has already uploaded a few model versions. Now we’re splitting the traffic into 95/5 proportions from which 95 percent go through the model which accepts all requests by default, the other 5 percent go through the Steve’s model for real predictions. This even can be used for A/B testing. All requests will be aggregated and stored within the environment. After we’ll obtain ground truth labels, we can check how well model performed throughout the month. We will test this setup for a while.”</p><p>“That’s fantastic, Roger!”, of course you’ve already forgotten your intents to crucify him. “But while you were working I’ve come up with a few ideas regarding model serving. I think, we should somehow monitor models during inference time. Detecting unusual behaviour or something else would be very helpful.”</p><p>Roger twisted for a moment.</p><p>“Hmm, It’s hard to come up with the solution immediately. Since this is an inference time, we should probably discuss this with Steve, maybe he has some thoughts on this problem”.</p><p>Sounds fair enough. Anyway, you open your notebook and add a few changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5L755wHWewkmU3T5" /></figure><p>Your assistant bursts into the room.</p><p>“We’ve got an overly increased number of transaction denials! Customers flooded technical support asking why their transactions were denied. What the hell happened?!”</p><p>You quickly glance at Roger but judging by the question mark represented by his face it’s very unlikely it’s his fault.</p><p>“Roger, any ideas?”</p><p>“None.”</p><p>“I think, we should see Steve. Come along”, you say while heading to Steve’s department.</p><p>You find Steve making himself a coffee.</p><p>“Hi, Steve, how is it going?”, both of you ask simultaneously.</p><p>“Great, I’ve uploaded a new model version half an hour ago. Probably it’s already running”, he replies.</p><p>“Yeah, we’ve noticed. And you know who else have noticed? About 10 000 customers tearing guys from technical support complaining about transaction denials!”</p><p>Steve evaporated almost immediately. You found him drilling his laptop mumbling something on the mixed language of curse words and technical jargon.</p><p>“What is it, Steve?”, ask you approaching.</p><p>“Seems like I’ve accidentally uploaded a wrong model version.”</p><p>“No good.”</p><p>Silence reigns the room for a while.</p><p>“A shameful mistake but can happen to anyone”, utter you finally. “Roger, can we execute integration tests before model release?”</p><p>“Yeah, I’ll handle that. Steve, you will have to upload test data and a baseline performance percentage that a newer model version have to achieve to be released”, replies Roger.</p><p>“What’s with the model?”</p><p>“Redeployed, everything should be good now”, replies Steve.</p><p>“Good”, you release your assistant with a few instructions. A light sense of relief fills the room. Not for long though, you recall your intents on model monitoring.</p><p>“Steve, can we do something about models’ monitoring? It’d be nice if we could track the changes in the production inference/data and see how model behaves to possibly avoid such situations.”</p><p>Unlike Roger, Steve is very optimistic about the idea.</p><p>“Oh, that sounds great! We can monitor distributions of the production data, model predictions and also some system metrics. Monitoring concept drifts would be also a good practice, I think. Ah! Anomaly detection! We should also push notifications when something goes wrong! I’ll help out Roger with implementing that.”</p><p>“Ah, come on! I’ve finished setting up the environment 2 hours ago”, Roger sullenly leaves the room.</p><p>Kindly smiling you advise Steve to leave Roger alone for a while and research a bit on the monitoring topic. Opening the notebook you add a few corrections along with a few blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TFhVdIpOBLp53DWI" /></figure><p>“It’s always good to have a second opinion”, pops up in your mind.</p><p>“Steve, do you have any comments?”, you show him your notes.</p><p>“What is that? Interesting!”, he’s very enthusiastic about your drawings. “Yeah, I see. It’s hard to label the rest blocks as DevOps-ish. I’m contributing here and there too. But! You can mix colours and everyone will be satisfied, I think.”</p><p>“Sound legit. Do you have a blue marker?”</p><p>“Yeah, sure!”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CGuRtREhDEbXLe2l" /></figure><p>“Looks great! We should also add here …”, starts Steve but you interrupt him with a quick gesture. “We’ve got enough here to start building our Machine Learning. For sure there are plenty of nice augmentations to be added but first thighs first. Now, let’s go and get things done!”</p><p><em>Thank you for reading the story. We could dive deeper to place, for instance, model sustenance procedures into the loop, but not this time as I believe the given workflow provides a rich soil for ML Workflow augmentations.</em></p><p><em>The story shows how a machine learning workflow could shape and evolve within a single company. The industry had developed a vision how machine learning projects have to be proceeded but the instrumental part leaves much to be desired and automated.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7a9fee44d90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydrosphere-io/on-the-delivery-of-ai-to-business-b7a9fee44d90">On the delivery of AI to Business</a> was originally published in <a href="https://medium.com/hydrosphere-io">hydrosphere.io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving Machine Learning Model in Production — Step-by-Step Guide-2]]></title>
            <link>https://medium.com/hydrosphere-io/serving-machine-learning-model-in-production-step-by-step-guide-2-5cbe9d18ec7?source=rss-7222e7db9e2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cbe9d18ec7</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mls]]></category>
            <dc:creator><![CDATA[Ilnur Garifullin]]></dc:creator>
            <pubDate>Fri, 05 Oct 2018 11:59:00 GMT</pubDate>
            <atom:updated>2018-10-11T08:32:29.515Z</atom:updated>
            <content:encoded><![CDATA[<h3>Serving Machine Learning Model in Production — Step-by-Step Guide-2</h3><p>In the <a href="https://medium.com/hydrosphere-io/serving-machine-learning-model-in-production-step-by-step-guide-bbad145c0d40">previous</a> article we’ve deployed and served a s<em>eq2seq</em> model, that was able to inference on a raw incoming strings and generate some answers. The main issue with that model was that it wasn’t able to recognize words with attached periods, commas, and words that are not in the lower letter case. In those situations model would’ve replaced these words with &lt;UNK&gt; tokens.</p><p>In this article we will address this problem by adding a pre-processing stage, which will properly tokenize incoming sentences and pass it further to the original model. All the code presented in this article is available on <a href="https://github.com/tidylobster/conversation-tensorflow">GitHub</a>.</p><h3>Prerequisites</h3><p>All the same steps, defined in the <a href="https://medium.com/hydrosphere-io/serving-machine-learning-model-in-production-step-by-step-guide-bbad145c0d40">previous</a> article.</p><h3>Tokenizer</h3><p>Defined issue can be resolved by attaching to the application an additional stage that will properly tokenize incoming strings and pass them further. This can be done in any language, but we will stick with Python and a <em>nltk</em> library. Inside conversation-tensorflow directory, let’s create another folder called tokenizer, which would hold our Python model.</p><pre>$ mkdir tokenizer<br>$ cd tokenizer</pre><p>The Python model should contain a processing script, a model’s contract and Python dependencies, if needed.</p><h4>Model</h4><p>Let’s start with actual processing script. It would handle the manipulations with the incoming string. First, create a src folder and place there a func_main.py file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/738dfda6b75d37a407b5676e18fe6c80/href">https://medium.com/media/738dfda6b75d37a407b5676e18fe6c80/href</a></iframe><p>Regarding the [1] point — for word tokenization <em>nltk</em> library uses its own language-specific vocabularies, so, for the very first time, when the <em>nltk</em> library have been just installed, you would need to execute the following lines inside Python shell:</p><pre>&gt;&gt;&gt; import nltk<br>&gt;&gt;&gt; nltk.download(&quot;punkt&quot;)</pre><p>This command will create a folder in the home directory and put all the vocabularies there. But because ML Lambda’s models’ infrastructure does not have an access to outside of the container, this approach cannot be applied. This constraint is made due to security reasons. To overcome this, we can download these vocabularies ourselves and pack it with the model. The reason for [1] is just to modify the list of searching paths, so that we could find packed vocabularies inside the model’s container. By default ML Lambda places all model’s files inside /model/files directory.</p><p>Next, we just tokenize our sentences [2] and create an output tensor [3].</p><h4>Model Dependencies</h4><p>As we mentioned above, we would need to additionally provide nltk_data folder. To do that install <em>nltk</em> library locally (pip install nltk), inside Python shell execute nltk.download(‘punkt’), and then copy nltk_data folder from your home directory to the model’s folder.</p><p>We also need to define requirements.txt for the model, if it uses any third-party packages that are not present in the Python Standard Library. In our case those are <em>nltk</em> and <em>numpy</em>.</p><pre>nltk==3.3<br>numpy==1.15.0</pre><h4>Model’s Contract</h4><p>Finally, let’s provide model’s contract. It is aimed to describe what would be the inputs and the outputs of the model. In our case it’s simply an incoming [x] and outcoming [input_data] strings. Create a serving.yaml file and place there the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25bf937b5d7c3ccb06d158a8eaa2ef70/href">https://medium.com/media/25bf937b5d7c3ccb06d158a8eaa2ef70/href</a></iframe><p>That’s it, the model is ready for serving. The final files structure should look like this:</p><pre>tokenizer<br>├── nltk_data<br>│   └── ...<br>├── requirements.txt<br>├── serving.yaml<br>└── src<br>    └── func_main.py</pre><h3>Model Serving</h3><p>We assume that you already have a running instance of ML Lambda, defined <em>hs cluster</em> and an uploaded <em>seq2seq</em> model. If you don’t, please refer to the <a href="https://medium.com/hydrosphere-io/serving-machine-learning-model-in-production-step-by-step-guide-bbad145c0d40">previous</a> article and prepare the environment.</p><p>Now let’s upload the model to the ML Lambda</p><pre>$ hs upload</pre><p>This command will upload all the model’s data to ML Lambda. Internally, a new Docker image will be created and stored in the Docker registry under specific version. This leads to a proper versioning, so you don’t have to worry about model’s versioning at all.</p><p>Next, let’s update existing <em>seq2seq</em> application. Go to the <em>Applications</em> page, select <em>seq2seq</em> application and click the <em>Edit</em> button. Add the new stage with <em>tokenizer</em> model before the original TensorFlow model and update the whole application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LVLLTV9kOA9MoGsN" /></figure><p><em>Note:</em> be cautious when you’re adding a new model to the pipeline. Make sure you doing this with the <em>Add New Stage</em> button at the UI bottom, not by selecting additional model in the existing stage.</p><p>Let’s test if everything works fine. We will do that via REST API.</p><pre>$ curl -X POST --header &#39;Content-Type: application/json&#39; --header &#39;Accept: application/json&#39; -d &#39;{&quot;x&quot;: [[&quot;Hello, there!&quot;]]}&#39; &quot;localhost/gateway/applications/seq2seq/seq2seq&quot;</pre><p>This yields the desired result.</p><pre>{&quot;output&quot;:&quot;right&quot;}</pre><p>For more information about applications’ interfaces refer to <a href="https://hydrosphere.io/serving-docs/applications.html#invoking-applications">documentation</a>.</p><h3>Conclusion</h3><p>In this article we’ve updated a <a href="https://medium.com/hydrosphere-io/serving-machine-learning-model-in-production-step-by-step-guide-bbad145c0d40">previously</a> defined application by upgrading it to a pipeline with the pre-processing model and the <em>seq2seq</em> model itself. Pre-processing model properly tokenizes incoming sentences, which resolves the issue with &lt;UNK&gt; tokens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cbe9d18ec7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydrosphere-io/serving-machine-learning-model-in-production-step-by-step-guide-2-5cbe9d18ec7">Serving Machine Learning Model in Production — Step-by-Step Guide-2</a> was originally published in <a href="https://medium.com/hydrosphere-io">hydrosphere.io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving Machine Learning Model in Production — Step-by-Step Guide]]></title>
            <link>https://medium.com/hydrosphere-io/serving-machine-learning-model-in-production-step-by-step-guide-bbad145c0d40?source=rss-7222e7db9e2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbad145c0d40</guid>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Ilnur Garifullin]]></dc:creator>
            <pubDate>Mon, 10 Sep 2018 15:07:25 GMT</pubDate>
            <atom:updated>2020-06-23T09:19:40.094Z</atom:updated>
            <content:encoded><![CDATA[<p>General purpose machine learning encoder-decoder systems allow us to use them in many areas such as Machine Translation, Text Summarization, Conversational Modeling, Image Captioning and more. Models created for different fields might require different preparational steps in order to deploy them into production environment. In this article we will deploy and serve a pre-trained Sequence-to-Sequence (Seq2Seq) model with an <a href="https://medium.com/heuritech/attention-mechanism-5aba9a2d4727">attention mechanism</a>, developed as a conversation modelling system.</p><h3>Prerequisites</h3><p>For the model we will use a TensorFlow implementation, taken from <a href="https://github.com/DongjunLee/conversation-tensorflow">conversation-tensorflow</a> repository. As a serving system we will use <a href="https://hydrosphere.io/ml-lambda/">ML Lambda</a> open source environment.</p><ul><li>Install <a href="https://docs.docker.com/install/">Docker</a></li><li>Install <a href="https://www.python.org/downloads/">Python3.6</a></li><li>Install Python dependencies:</li></ul><pre>$ pip install hs==0.1.3 tensorflow==1.9.0 nltk==3.3 hb-config==0.5.1 tqdm==4.24.0</pre><ul><li>Clone Seq2Seq model:</li></ul><pre>$ git clone <a href="https://github.com/DongjunLee/conversation-tensorflow">https://github.com/DongjunLee/conversation-tensorflow</a></pre><ul><li>Train the model on a small sample data:</li></ul><pre>$ python conversation-tensorflow/main.py --config check-tiny --mode train</pre><ul><li>Clone ML Lambda:</li></ul><pre>$ git clone <a href="https://github.com/Hydrospheredata/hydro-serving">https://github.com/Hydrospheredata/hydro-serving</a></pre><ul><li>Set up local server:</li></ul><pre>$ cd hydro-serving<br>$ docker-compose up -d</pre><ul><li>Create a hs cluster, that will work with the local server:</li></ul><pre>$ hs cluster add --name local --server <a href="http://localhost/">http://localhost</a><em><br></em>$ hs cluster use local</pre><p>Those steps will set up the whole environment for you. To check if ML Lambda is running, go to <a href="http://localhost/">http://localhost/</a> in your browser.</p><h3>Basics</h3><p>Typical pipeline of the conversation application consists of taking a string, encoding it to a vector of integers, passing the vector through the model, receiving other vector as an inference result and transforming it back to the string. This transformation is performed by means of manually built vocabulary (as in our case), which consists of [integer, string] pairs. Serving such a pipeline can be performed in two ways:</p><ol><li>Creating a monolithic model by slightly modifying the original model, i.e. including string transformations to input/output tensors of the model.</li><li>Creating a multi-staged model which will consist of the processing stages, and our inferencing model.</li></ol><p>In this article we will continue with the <em>monolithic</em> model for the sake of explanation of the deployment simplicity.</p><p>All the code presented in this article is available on <a href="https://github.com/tidylobster/conversation-tensorflow">GitHub</a>.</p><h3>Preparing and Serving Seq2Seq</h3><p>The chosen model is built upon tf.estimator. This is a high-level TensorFlow API that simplifies machine learning programming. We will need to modify the estimator a little since it wasn’t prepared for the serving. To do that we have to define a contract (export_outputs) for exporting model to a servable (tf.saved_model) format. Also, since we decided to create a monolithic model, we would need to put string-to-vector transformations inside the model.</p><h4>Model Preparation</h4><p>Let’s create an export.py file, that will export our model into a SavedModel.</p><pre>$ cd ../conversation-tensorflow<br>$ touch export.py</pre><p>For starters, let’s define a function, that will encode our vocabulary into a tf.contrib.lookup table. The vocabulary is placed in the conversation-tensorflow/data/tiny_processed_data/vocab file. The function would produce required tables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad4f6827d5b534e2ff340ed6ae8313a4/href">https://medium.com/media/ad4f6827d5b534e2ff340ed6ae8313a4/href</a></iframe><p><em>There’s an option for creating the </em>index_table<em> from file without the need to manually upload vocabulary and transform it to tensor. Since our vocabulary is relatively small, we’ve decided to store it as a part of the graph; you may want to consider </em><a href="https://www.tensorflow.org/api_docs/python/tf/contrib/lookup/index_table_from_file">tf.contrib.lookup.index_table_from_file</a><em>.</em></p><p>Seq2Seq model is presented by the class Conversation, defined in model.py file. It would be a good practice to not change the original class and only manipulate an extended class from it. In the extended class we will override model_fn and _init_placeholder functions and add two supplement functions _preprocess_input and _postprocess_output. Let’s define the structure of our class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd2817454bfc41fd5099dbd5d9192e88/href">https://medium.com/media/dd2817454bfc41fd5099dbd5d9192e88/href</a></iframe><p>model_fn will stay mostly the same, we just add tables and padding to the class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44c1199d37c13d30e99b34bcef8aad57/href">https://medium.com/media/44c1199d37c13d30e99b34bcef8aad57/href</a></iframe><p>Additional parameter export_outputs specifies the output type of our model for the export [1] and self._postprocess_output wraps the output tensor self.predictions [2].</p><p>Next, let’s modify incoming tensors in our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69b23e4b989dcbdeda1bdc7edad0e9f7/href">https://medium.com/media/69b23e4b989dcbdeda1bdc7edad0e9f7/href</a></iframe><p>This function will take incoming tensor of shape (None, 1) and type tf.string, and convert it to a tensor of shape (1, 60) and type tf.int64.</p><p>And we need to change outcoming tensor back to the original shape.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf336808b0f63eae8251203ae296ec3/href">https://medium.com/media/edf336808b0f63eae8251203ae296ec3/href</a></iframe><p>And as a final step, lets modify _init_placeholder function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c83393a5f9d3f447b0a1a4954e82fe4e/href">https://medium.com/media/c83393a5f9d3f447b0a1a4954e82fe4e/href</a></iframe><p>Saving model is performed in a following way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dfc278b6d6e5e9c739b0f8aa2ec7d67/href">https://medium.com/media/3dfc278b6d6e5e9c739b0f8aa2ec7d67/href</a></iframe><p>Note, that the crucial points here for us are: creating an estimator [3], preparing a serving_input_reciever_fn [4] and exporting the model [5]. The first two steps are only necessary for defining internal model parameters.</p><h4>Model Serving</h4><p>Now that our model is ready, we can export it to a tf.saved_model and upload it to ML Lambda.</p><pre>$ python export.py --config check_tiny</pre><p>This command will create a my_model/${TIMESTAMP} folder inside current directory with the exported model.</p><pre>$ cd my_model/${TIMESTAMP}<br>$ hs upload --name seq2seq</pre><p>This will upload our exported model to ML Lambda. Now, let’s create an application to infer the model. Open <a href="http://localhost/">http://localhost/</a>, you’ll see a seq2seq model uploaded in the Model’s section. Open Applications page, click Add New button and fill up the following fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfwKNdWG1UwepVMx43pUWQ.png" /></figure><p>As a model select the uploaded seq2seq model, as a runtime select serving-runtime-tensorflow runtime and create an application.</p><p>That’s it, you’ve just served a sequence-to-sequence model that you can use via different interfaces such as REST or RPC API.</p><p>To test, that everything works fine, click Test button, and send it some sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8uApSY_aXWXb8FyQQjOLg.png" /></figure><p>Calling the application via REST or RPC interfaces is described in a <a href="https://hydrosphere.io/serving-docs/invoke-applications.html">documentation</a>. As an example, we can invoke created application via gRPC.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4abe2a3f5e97003e608019e38593be0/href">https://medium.com/media/e4abe2a3f5e97003e608019e38593be0/href</a></iframe><p>Result:</p><pre>outputs {<br>  key: &quot;output&quot;<br>  value {<br>    dtype: DT_STRING<br>    tensor_shape {<br>      unknown_rank: true<br>    }<br>    string_val: &quot;sweet&quot;<br>    string_val: &quot;&lt;\\s&gt;&quot;<br>  }<br>}</pre><h3>Conclusion</h3><p>In this article we discussed how a single TensorFlow model can be served in a production environment. As an example we chose conversation-tensorflow model, written on a high-level tf.estimator API. The main issue with this model, is that it cannot properly tokenize the input sentences, since TensorFlow is not built for this task. In the next article we will show the issue resolution with the preprocessing script and serving the preprocessing and the model in a consequent pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbad145c0d40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydrosphere-io/serving-machine-learning-model-in-production-step-by-step-guide-bbad145c0d40">Serving Machine Learning Model in Production — Step-by-Step Guide</a> was originally published in <a href="https://medium.com/hydrosphere-io">hydrosphere.io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>