<?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 Juri Sarbach on Medium]]></title>
        <description><![CDATA[Stories by Juri Sarbach on Medium]]></description>
        <link>https://medium.com/@juri.sarbach?source=rss-833154bbee14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PvwH4Bs6a0ZxOw7k8Hdztw.jpeg</url>
            <title>Stories by Juri Sarbach on Medium</title>
            <link>https://medium.com/@juri.sarbach?source=rss-833154bbee14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:18:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juri.sarbach/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[Cloud Monitoring, We Need to Chat]]></title>
            <link>https://levelup.gitconnected.com/cloud-monitoring-we-need-to-chat-54c45b346a21?source=rss-833154bbee14------2</link>
            <guid isPermaLink="false">https://medium.com/p/54c45b346a21</guid>
            <category><![CDATA[incident-management]]></category>
            <category><![CDATA[google-chat]]></category>
            <category><![CDATA[cloud-monitoring]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-operations]]></category>
            <dc:creator><![CDATA[Juri Sarbach]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 16:43:24 GMT</pubDate>
            <atom:updated>2022-01-20T16:43:24.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*52cqGE4qZtdNMmmC" /><figcaption>Photo by <a href="https://unsplash.com/@lunarts?utm_source=medium&amp;utm_medium=referral">Volodymyr Hryshchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://cloud.google.com/monitoring">Cloud Monitoring</a> is an essential tool for tracking application metrics and errors of workloads running on Google Cloud Platform. Besides its dashboarding capabilities, it lets you define alerting policies so that you’re automatically notified whenever an error is thrown or a metric is above its threshold.</p><p>Cloud Monitoring supports different <a href="https://cloud.google.com/monitoring/support/notification-options">notification channels</a> such as e-mail, SMS or Slack, but strangely not Google’s own chat app that is part of Google Workspace. I personally prefer getting the alerts in a team chat rather than per e-mail so that the team can coordinate the resolution of the incident more easily.</p><p>Luckily, we can build the missing integration with Google Chat ourselves in almost no time using <a href="https://cloud.google.com/functions">Cloud Functions</a> and <a href="https://cloud.google.com/pubsub">Pub/Sub</a>. Here’s the setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q0_JsytDj4PCUrSbh001Vw.png" /><figcaption>Alerts will be published to Pub/Sub and then forwarded to Google Chat via Cloud Functions</figcaption></figure><p>We start by configuring Google Chat and work backwards to the alerting policies in Cloud Monitoring.</p><p>First, we need to <a href="https://developers.google.com/chat/how-tos/webhooks#setting_up_an_incoming_webhook">create a webhook</a> in the Google Chat Space we want the alerts to be published.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*enDqI9FGp2BWD6-Zcu1jxQ.png" /><figcaption>Create a webhook, copy the URL</figcaption></figure><p>Next, we write the Cloud Function that forwards the monitoring alerts to the webhook URL that was generated in the previous step. The reason we can’t use this webhook directly as a notification channel in Cloud Monitoring but need a Cloud Function in between, is that Google Chat requires a different message payload structure than the one Cloud Monitoring produces. As described in the <a href="https://cloud.google.com/monitoring/support/notification-options#pubsub">documentation</a>, the alert message is a JSON of this form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*JlNbONvzrh7EFq3mz5qJUw.png" /><figcaption>Source: <a href="https://cloud.google.com/monitoring/support/notification-options#pubsub">https://cloud.google.com/monitoring/support/notification-options#pubsub</a></figcaption></figure><p>Google Chat, however, <a href="https://developers.google.com/chat/api/guides/message-formats/basic#basic_unformatted_messages">expects</a> the payload to look like this: {&quot;text&quot;: &quot;Here goes the message content&quot;}. Therefore, we define a message template for Google Chat with placeholders for the alert parameters of interest (e.g. incident[summary]) and have a Cloud Function replace the placeholders with the actual values from the alert and forward the resulting JSON to Google Chat.</p><p>Let’s use Python and the fancier <a href="https://developers.google.com/chat/api/guides/message-formats/cards">card message</a> format rather than the basic text format. It basically just takes three lines of code and the message template (the full code is also on <a href="https://github.com/jsarbach/cloud-monitoring-2-google-chat">Github</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/317b55c225c8256da1bb3475c33956c6/href">https://medium.com/media/317b55c225c8256da1bb3475c33956c6/href</a></iframe><p>Note that instead of defining the template in the form of a dictionary and looping over all its nested levels to replace the placeholders, we define the template as a JSON string, use format() to replace, and then parse it into a dictionary. Which is one single line of code instead of many:</p><pre>message = json.loads(MESSAGE_TEMPLATE.format(**alert))</pre><p>The double curly braces {{...}} in the template string are needed for <a href="https://docs.python.org/3/library/string.html#format-string-syntax">escaping</a> when applying format().</p><p>Time to deploy!</p><pre>gcloud functions deploy monitoring-alerts --entry-point monitoring_alerts --region europe-west6 --runtime python39 <br>--trigger-topic monitoring-alerts</pre><p>The Pub/Sub topic monitoring-alerts is automatically created for us. So, all that’s left to do is to set up a corresponding Pub/Sub notification channel and use it in our <a href="https://cloud.google.com/monitoring/alerts/using-alerting-ui">alerting policies</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*u7cL7ApWkpvCh561gJESAw.png" /><figcaption>Create a notification channel for the monitoring alerts…</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*kJ78D4GSU9Hy1q3k9D_FdA.png" /><figcaption>… and use it in the alerting policies</figcaption></figure><p>That’s it. Now enjoy your alert messages showing up in Google Chat (but don’t forget to follow up on them).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*Dp7hsPGO3HisiQ5y0xWRtA.png" /><figcaption>Oh hello, you pretty error</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54c45b346a21" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/cloud-monitoring-we-need-to-chat-54c45b346a21">Cloud Monitoring, We Need to Chat</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating ML Datasets with Ease using BigQuery and Dataflow]]></title>
            <link>https://medium.com/data-science/creating-ml-datasets-with-ease-using-bigquery-and-dataflow-121eef01f53a?source=rss-833154bbee14------2</link>
            <guid isPermaLink="false">https://medium.com/p/121eef01f53a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[apache-beam]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Juri Sarbach]]></dc:creator>
            <pubDate>Thu, 06 May 2021 14:50:09 GMT</pubDate>
            <atom:updated>2021-05-07T13:38:07.674Z</atom:updated>
            <content:encoded><![CDATA[<h4>Drop in-memory processing in favour of parallel execution and horizontal scaling</h4><p>TL; DR: If you’re working with large amounts of data, BigQuery and Dataflow on the Google Cloud Platform (GCP) can boost your efficiency and make your life easier when generating datasets for machine learning.</p><p>Recently I was approached by the startup <a href="https://reviewr.ai/">reviewr.ai</a> for a data engineering task that consisted of preparing data for machine learning (ML) and training an ML model. Unlike larger corporations that apparently can afford to let their data scientists spend days or weeks on such a task because they have to work with on-prem infrastructure or with a cloud provider that was chosen mainly because the company has been licensing its office suite for years, a startup wants to get things done quickly — speed matters. And unlike a lot of corporations, a startup is typically very flexible when it comes to choosing the infrastructure for a certain task. Therefore, we agreed that this should be done on GCP which in my opinion is still the best cloud platform for all things big data and ML. So instead of spending days, I did the whole data preparation in one morning and took the afternoon off while the ML model was being trained.</p><p>This article is not about the machine learning part of the task or the accuracy of the ML model. It’s about the data engineering and preprocessing that has to happen before the machine learning can even begin. As most data scientists would probably agree, that’s where usually the majority of time and effort is spent.</p><h4>An amazoning task</h4><p>I was asked to train a simple NLP classification model using the <a href="https://huggingface.co/datasets/amazon_us_reviews">amazon_us_reviews dataset from Hugging Face</a>. It contains almost 151 million customer reviews from the Amazon website, amounting to about 76 GB of data. Based on the product reviews users have written, the model should classify the reviews into certain categories. The class membership (label) can be derived from the data contained in the dataset. Since this problem is pretty standard and because we wanted quick results, I used <a href="https://cloud.google.com/natural-language/automl/docs">AutoML</a> on GCP.</p><p>To be able to use the data in AutoML, I had to somehow select at most 1 million suitable samples out of the 151 million and convert them into the <a href="https://cloud.google.com/natural-language/automl/docs/prepare#csv">required format</a>, i.e. one text file per sample containing the review text plus an index CSV file that contains the URIs and the classes of all the samples. Sounds daunting or time-consuming? It’s neither.</p><h4>BigQuery: all in</h4><p>Let’s start with getting a copy of the data. The files are stored on an AWS S3 bucket and are publicly accessible via HTTP request. <a href="https://cloud.google.com/storage">Google Cloud Storage</a> (GCS) is the right place to put them before we process them further. In particular, I’m going to ingest the data into <a href="https://cloud.google.com/bigquery">BigQuery</a> for reasons that will become apparent in a moment. There are several ways one can transfer the data to GCS — e.g. with a bash script that wgets or curls the files and gsutil cps them to GCS in a loop or with a small <a href="https://github.com/jsarbach/data-engineering/blob/main/dataset-creation-bigquery-dataflow/dataset_to_gcs.py">Python script</a>.</p><p>I run this in <a href="https://cloud.google.com/shell">Cloud Shell</a> rather than on my local machine because transferring the data over Google’s network takes considerably less time. Once all the files are in the GCS bucket, I simply <a href="https://cloud.google.com/bigquery/docs/loading-data-cloud-storage-csv">load the them into BigQuery</a> in one go using bq, still from Cloud Shell:</p><pre>bq load --source_format CSV --autodetect --field_delimiter tab <br>--skip_leading_rows 1 --quote &#39; &#39; [DATASET_NAME].amazon_us_reviews gs://[BUCKET_NAME]/datasets/amazon-us-reviews/raw/*.tsv.gz</pre><p>As you can tell by looking at the flags, I let BigQuery infer the <a href="https://cloud.google.com/bigquery/docs/schemas">schema</a> from the data and set the field delimiter to tab instead of comma and the quote character to none instead of double quotes (“tab delimited, with no quote and escape characters” as the dataset description states). BigQuery can natively handle gzipped files, so we don’t have to decompress the files first.</p><p>After a couple of minutes, the data are stored in BigQuery and ready for inspection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*ciq2QwUzN691vfcp08gbQQ.png" /></figure><p>On a side note: If you have an AWS account (and hence can create an <em>access key ID</em> and a <em>secret access key</em>), you can download the files without writing a single line of code using the <a href="https://cloud.google.com/storage-transfer-service">Storage Transfer Service</a> or even ingest the data directly into BigQuery with the <a href="https://cloud.google.com/bigquery-transfer/docs/s3-transfer">BigQuery Data Transfer Service</a>.</p><p>Next, let’s run a couple of queries to get a feeling for the data. For example, we could ask how many reviews there are per product group and star-rating and what’s the percentage of star-ratings within the product groups:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*gR14cEmO3cCeYtJQjLstPQ.png" /></figure><p>Or: Which product categories get the longest reviews on average?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*JXwYZwDcyF8p3GvDOTIB_Q.png" /><figcaption>The shortest is for Gift Cards by the way, which probably won’t come as a surprise.</figcaption></figure><p>As you can see, running these queries over 151 million rows only takes a couple of seconds. Hence, you can let your creativity go wild and dissect the data as quickly as you come up with questions. (However, keep in mind that you’re <a href="https://cloud.google.com/bigquery/pricing#analysis_pricing_models">billed</a> by the amount of data processed unless you go with the flat-price model.) If you want to plot the results, you can visualise them in <a href="https://cloud.google.com/bigquery/docs/visualize-data-studio">Data Studio</a> with a single click.</p><h4>SELECT training data FROM dataset</h4><p>However, we don’t just want to analyse the data. We also want to generate the training dataset for AutoML which means selecting 1 million samples from the total of 151 million and calculating the features. I don’t want to disclose exactly what <em>reviewr.ai</em> wanted me to work on, so let’s just assume we wanted to infer the rating (1–5 stars) from the review body. Ideally, we’d have 200,000 examples per class in this case.</p><p>First of all, we’ll exclude all reviews that don’t have a review body (i.e. WHERE review_body IS NOT NULL). Also, we have to exclude rows that have the same review_body because the classification in the ground truth may become ambiguous and AutoML won’t allow duplicates anyway. As it turns out, there are quite a few of them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*ezZH0ueo9MDk88Ec9-zlLg.png" /><figcaption>Awesome!</figcaption></figure><p>To narrow down the results further, we’ll focus on reviews a majority of users found helpful. Also, we’ll require that a review received at least x votes. Where to set the threshold, x? Let’s build a histogramme to get a feeling for how the number of votes per rating are distributed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*I_Je0HM-pJzAaTd2OwwmEg.png" /></figure><p>If we set the threshold somewhere between 10 and 20, we seem to still have enough samples for every class, so I’ll go with 15. This means we only include reviews that received at least 15 votes, a majority of which were deemed helpful. Of course, we could go even further and require that every product category should be equally represented. For the purpose of this article, we leave it here. So, here is the query that finally defines our dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31ebb3432d94cbb7b185c64b4c2ebb5b/href">https://medium.com/media/31ebb3432d94cbb7b185c64b4c2ebb5b/href</a></iframe><p>Running a quick SELECT class, COUNT(*) FROM ... GROUP BY class confirms that we have indeed 200,000 samples per class.</p><p>Once we’re happy with our query, we can run it and materialise the result as a table or save the query itself as a view. Loading the table will be faster than querying the view (which is basically the same as running the query itself). Nevertheless, I chose to create a view because we’re going to query it only once or a few times, so speed won’t matter really. The view has the advantage of documenting how the dataset was created and that you can easily modify and save it under a different name if you want to create a new dataset for another model iteration.</p><p>So, now that we came up with the definition of our training dataset by means of an SQL query — how do we get it into the format we need (one text file per example containing the review body plus a CSV file with the URIs and classes of all the examples)? Export the query result as a CSV file and write a Python script to process the file, line by line? That would take an eternity or two (the processing, not the writing of the script). Instead, let’s turn to yet another great tool that is specialised for this kind of workload: <a href="https://beam.apache.org/">Apache Beam</a> and <a href="https://cloud.google.com/dataflow">Dataflow</a> on GCP.</p><h4>Parallel execution for unparalleled speed</h4><p>To cite the <a href="https://beam.apache.org/get-started/beam-overview/">documentation</a>, “Apache Beam is an open source, unified model for defining both batch and streaming data-parallel processing pipelines”. Dataflow is a fully managed runner for Apache Beam on GCP. The usual workflow is like this: Write your pipeline (in Java or Python), test it locally with a few elements to verify it works, then deploy it to Dataflow to process the whole dataset at scale in the cloud.</p><p>Apache Beam has a bunch of I/O connectors (“sources” and “sinks”), among others one for BigQuery and one for GCS. This means we can read directly from our BigQuery query result and write the output to a GCS bucket. Conceptually, the pipeline we’re going to build looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*Nfv_3beE1w7gEaDhng0uHw.png" /></figure><p>The pipeline reads from one source (the BigQuery query result, containing the review_id, the review_body, and the class) and produces two outputs: The first branch creates the 1 million text files with the review_body, the second one creates 1 million strings containing the URI (gs://...) and the class, then concatenates them and writes the result to a single CSV file. The pipeline operates on a per-row basis. i.e each element is a row from our query result.</p><p>Here’s the full pipeline code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0023102690f2db838ce37b168efa53c9/href">https://medium.com/media/0023102690f2db838ce37b168efa53c9/href</a></iframe><p>The beauty of using Apache Beam is that because each row of the query result can be processed independently, we achieve massively parallel processing. As you can see below, Dataflow indeed scaled the number of workers up to a maximum of 527, processing about 2,200 rows per second:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7y74w9Vn-4STk0koZnze6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbsyVBCcr2XRx_F39XSHhg.png" /></figure><p>The infrastructure required for the job is fully managed. Dataflow spends a couple of minutes provisioning the infrastructure (compute engines) before it starts the actual pipeline execution. After the job has successfully completed (or failed), it spins down and deletes the VMs.</p><p>Thanks to parallel execution, the equivalent of 72 CPU hours of work has been completed in just about 18 minutes. One important note: The extent to which Dataflow scales your workload might be limited by quotas. In particular, the <em>Compute Engine API in-use IP addresses</em> quota that has a default of 8 per region in newly created GCP projects can limit the amount of compute instances provisioned for the job (because every worker instance needs an IP address). Therefore, make sure to request a quota increase in advance should you find the existing quota to be too low.</p><p>And here we have it: 1 million text files and one CSV, ready to be imported into AutoML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*VfbDMYNh4U7N3qs-9ypwOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*funhaV4DnP9Cvd0fbtABnw.png" /><figcaption>Proof of work</figcaption></figure><h4>Takeaways</h4><p>Now that the hassle of preparing this dataset has evaporated into the cloud, let’s draw some conclusions:</p><ul><li><strong>Horizontal instead of vertical scaling.</strong> A lot of data scientists I know are fixated with vertical scaling. It doesn’t fit into memory? Let’s get a larger instance with more RAM. However, just throwing more memory at the problem while sticking with in-memory processing gives away the benefits of parallelising workloads and hence getting done more in less time. For the data analysis in BigQuery I didn’t have to spend a second considering how much memory it would require — I just opened the BigQuery UI and started querying. And the workers for my Dataflow job were all <a href="https://cloud.google.com/compute/docs/machine-types">n1-standard-1</a> VMs with 1 vCPU and 3.75 GB of memory. The only instance that could face a memory bottleneck is the worker that collects and concatenates the 1 million rows before writing them to a text file. In this case, the resulting string used 123 MB, so not even close to hitting a limit. And if we did, we’d just create sharded files instead of one single file.</li><li><strong>Use the specialised data engineering tools on GCP.</strong> Why bother launching a Jupyter notebook and loading data into pandas every time you want to work with it when instead, you can just dump the data into BigQuery where it is persisted, allowing you to query it ad-hoc and in almost no time? You’re likely done with your data analysis in BigQuery by the time your Jupyter instance would have finished spinning up and you’ve managed to load all the data into a pandas DataFrame. You can still use Jupyter of course — it has its merits for data science tasks after all. But use it to query BigQuery and to write Apache Beam pipelines rather than to process the data in-memory. By the way: There are also a lot of ready-to-use <a href="https://cloud.google.com/dataflow/docs/guides/templates/provided-templates">Dataflow templates</a>, so you may not even have to write your own pipeline.</li><li><strong>Lean and reusable process.</strong> The workflow with BigQuery and Apache Beam is lean and flexible. Need another training set with different features? Just write the query needed, start the pipeline, and 20 minutes later, you’re already importing your new dataset into AutoML. What if we want to train our own model in TensorFlow with the same datasets? Modify the Apache Beam pipeline slightly to output TFRecord files and you’re set.</li><li><strong>Efficient use of infrastructure.</strong> Working with these tools is efficient not only in terms of time spent, but also with respect to infrastructure usage and hence costs. As both BigQuery and Dataflow are serverless, there is no under or over-utilised infrastructure and no fixed costs (besides storage costs of course which are negligible in most cases). Given the ephemeral nature of the workload and the limited financial commitment that is needed, you might want to consider using GCP for this kind of data engineering tasks even if it isn’t your default workhorse.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=121eef01f53a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/creating-ml-datasets-with-ease-using-bigquery-and-dataflow-121eef01f53a">Creating ML Datasets with Ease using BigQuery and Dataflow</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>
        <item>
            <title><![CDATA[How to Deploy your AutoML Model in a Cost-effective Way]]></title>
            <link>https://medium.com/@juri.sarbach/how-to-deploy-your-automl-model-in-a-cost-effective-way-5efdd377d4d2?source=rss-833154bbee14------2</link>
            <guid isPermaLink="false">https://medium.com/p/5efdd377d4d2</guid>
            <category><![CDATA[automl-vision]]></category>
            <category><![CDATA[google-cloud-build]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Juri Sarbach]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 08:47:33 GMT</pubDate>
            <atom:updated>2020-03-24T08:47:33.787Z</atom:updated>
            <content:encoded><![CDATA[<p><em>TL;DR: If your Google Cloud AutoML Vision deployment is underutilised, consider moving it to Cloud Run.</em></p><p>Google Cloud’s <a href="https://cloud.google.com/automl">AutoML</a> is a fine thing. If you have a standard AI problem like image classification, object detection or entity extraction, chances are that AutoML will solve it with very little effort from your side. Just import your own dataset and retrain a state of the art model with it. After a couple of hours of training, you can use your customised model right away and make predictions via an automatically deployed endpoint.</p><p>It’s a great shortcut if you need fast results without having to bother with all the data wrangling or with finding suitable neural network architectures first. As such, it very much feels like Data Science as a Service. With AutoML, Google has definitely commoditised AI, at least with respect to common computer vision or natural language processing problems.</p><p>Recently, I played around with it to build a coffee classifier web app. Take a picture of your cup of coffee and it will tell you whether it’s a cappuccino, an espresso or an americano (no flat white, sorry hipsters). Admittedly not the most useful application ever, but sufficient to show that you can indeed get a pretty accurate model for your specific use case, including an endpoint that serves your model for immediate use. It was supposed to be a fun application. But then, a glance at the Google Cloud billing report took the fun out of it quite a bit…</p><h3>AutoML, as in Auto Money Leak?</h3><p>The main disadvantage of deploying a model on <a href="https://cloud.google.com/vision/automl/docs">AutoML Vision</a> is that the infrastructure behind it doesn’t automatically scale to zero — unlike what we’re used to from serverless Google Cloud products. In fact, it doesn’t auto-scale at all. You have to decide how many nodes you want to provision and scale your deployment manually to cope with the request volume. In other words, you provision fixed capacity with at least 1 node running 24/7 — and with it the cost meter, regardless of usage. At the current pricing, my coffee classifier costs USD 30 per day and node or USD 900 per month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*VxqIdAzl_3_tROmghshkgg.gif" /></figure><p>That may be fine if you have an application with a substantial user base and a revenue model that pays your Google Cloud bill. But what if the application is used irregularly (like my coffee classifier) or if you just want to validate a new product with a few users? The <a href="https://cloud.google.com/vision/automl/pricing">documentation</a> laconically mentions that you should undeploy your model to save costs. But in case of an unpredictable usage pattern, this is certainly not practical.</p><h3>Cloud Run take over please</h3><p>Fortunately, we have all the tools at hand to mitigate this shortcoming. So let’s replace the AutoML deployment by a solution that auto-scales with the requests (down to zero if necessary) and thus strains your purse proportionally to the usage. Time for <a href="https://cloud.google.com/run">Cloud Run</a>!</p><p>Here’s what we are going to do:</p><ul><li>After training the model on AutoML Vision, export it instead of deploying it right away;</li><li>download the exported model and add it to a pre-built Docker container;</li><li>deploy the image on Cloud Run;</li><li>finally, send requests to the API from a web app on App Engine to get predictions.</li></ul><p>This may sound like quite a bit of work, but actually, it’s done in less than 10 minutes.</p><h3>Exporting the model</h3><p>In order to be able to export the model later, choose <em>Edge</em> instead of <em>Cloud hosted </em>when launching the training job<em>.</em> (You can still choose to deploy the model on AutoML later if you wish.) Also, select <em>Higher accuracy</em> as the goal because we will have enough resources on Cloud Run.</p><p>Once the model has finished training, click on the <em>Container</em> card in the <em>TEST &amp; USE</em> tab, select the destination on Cloud Storage (GCS) where to export the <a href="https://www.tensorflow.org/guide/saved_model#the_savedmodel_format_on_disk">SavedModel</a> and click on the <em>EXPORT</em> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aG__N6RwZB2km6KUy8YfDw.png" /></figure><p>Moments later, the SavedModel is stored on GCS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjUyZezb1WvD6_pAx_JXnw.png" /></figure><p>Next, let’s create a deployment that serves this model so that we can get predictions via HTTP request.</p><h3>Deploying to Cloud Run</h3><p>As in the <a href="https://cloud.google.com/vision/automl/docs/containers-gcs-tutorial">documentation</a>, we use the gcr.io/automl-vision-ondevice/gcloud-container-1.12.0:latest Docker image. In contrast to the documentation, though, we copy the SavedModel into the container instead of mounting a volume and deploy it to Cloud Run instead of running it locally. To automate all of this and to get an easily repeatable process, we use <a href="https://cloud.google.com/cloud-build">Cloud Build</a>. As a result, deploying a model or a new model version is accomplished with just one simple gcloud builds submit ... command.</p><h4>First things first: IAM</h4><p>Before we start, let’s get the <a href="https://cloud.google.com/run/docs/reference/iam/roles#additional-configuration">IAM permissions</a> right so that Cloud Build can deploy to Cloud Run. First, add the <em>Cloud Run Admin</em> role to the Cloud Build service account (project-number@cloudbuild.gserviceaccount.com). Then, select your Cloud Run runtime service account. By default, this is the <em>Compute Engine default service account.</em> I usually create a distinct Cloud Run runtime service account instead so that I can assign the least privileges needed. Whatever you prefer, add the Cloud Build service account as a member with the <em>Service Account User</em> role to your Cloud Run runtime service account. (On the service account page, select the Cloud Run runtime service account, show the info panel, and click on the add member button.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*oJ18GAgMhBEJL9maj_yf-Q.png" /></figure><h4>Build automation</h4><p>Next, we need a Dockerfile to build an image with our saved_model.pb copied into:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0873d0314d20ccad799741c1512f7737/href">https://medium.com/media/0873d0314d20ccad799741c1512f7737/href</a></iframe><p>The build itself process is defined in a cloudbuild.yaml file (replace the xxx@project-id.iam.gserviceaccount.com with your Cloud Run runtime service account):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68ae8396630f9be24619d32ae088c577/href">https://medium.com/media/68ae8396630f9be24619d32ae088c577/href</a></iframe><p>The cloudbuild.yaml above defines four build steps:</p><ol><li>Download the saved_model.pb from GCS to the subfolder</li><li>Build the Docker image using the Dockerfile in the subfolder</li><li>Push the Docker image to Container Registry</li><li>Deploy the image to Cloud Run</li></ol><p>When kicking off the build process, we need to set three mandatory substitutions:</p><ul><li>_MODEL_NAME: Arbitrary name for the ML model that will be used as Cloud Run service name; here <em>coffee-classifier.</em></li><li>_DOCKERFOLDER: Subfolder with the Dockerfile to use. In order to be flexible to use another version of the automl-vision-ondevice image or even different images in the future, create a subfolder for every image. Like this, you can simply use a different base image by changing the value of _DOCKERFOLDER when deploying without having to change our cloudbuild.yaml. In this example, it’s the <em>automl-vision-cpu-1.12.0</em> subfolder.</li><li>_GCS_MODEL_PATH: GCS path to the ML model export (saved_model.pb), including the gs:// prefix.</li></ul><p>All the other substitution variables are optional and have a default value defined in cloudbuild.yaml under substitutions.</p><h4>Run!</h4><p>With the cloudbuild.yaml and the Dockerfile in the subfolder, we’re ready to submit the build:</p><pre>gcloud builds submit --substitutions _MODEL_NAME=coffee-classifier,_DOCKERFOLDER=automl-vision-cpu-1.12.0,_GCS_MODEL_PATH=gs://my-automl-demos-vcm/model-export/icn/tf_saved_model-coffee_classifier_20200225020250–2020–02–25T20:44:26.192Z,_VERSION=20200225020250</pre><p>The optional _VERSION substitution is used to tag the Docker image with the model version so that we know which one we put inside. If omitted, it defaults to latest.</p><p>One or two minutes later, the Cloud Run service is deployed and ready to serve traffic from [CLOUD_RUN_SERVICE_URL]/v1/models/default:predict. If you deploy without authentication (by setting the --allow-unauthenticated flag instead of --no-allow-unauthenticated), you can already start using the endpoint, e.g. with curl -X POST ... from the command line or requests.post(...) in Python. However, since Cloud Run exposes a publicly accessible endpoint (URL), you probably do want to activate authentication so that only authorised requests are allowed. Hence, let’s spend another 10 minutes on this.</p><h3>Adding authentication</h3><p>Adding authentication to a Cloud Run service is as easy as setting the --no-allow-unauthenticated flag when deploying, as shown above. On the side of the calling service, in our case the web app on App Engine, a bit more work is required. We’re going to create a service account and assign it the <em>Cloud Run Invoker</em> role. We then use it in our calling service to create an ID token that we are going to add to the header of the HTTP request.</p><p>Create a service account called cloud-run-invoker with the respective role:</p><pre>PROJECT_ID=$(gcloud config get-value project)</pre><pre>gcloud iam service-accounts create cloud-run-invoker</pre><pre>gcloud projects add-iam-policy-binding ${PROJECT_ID} --member serviceAccount:cloud-run-invoker@${PROJECT_ID}.iam.gserviceaccount.com --role roles/run.invoker</pre><p>Since we will need the service account key to create the JWT in the web app and I don’t want to deal with handling key files, we’re going to store the key in <a href="https://cloud.google.com/secret-manager">Secret Manager</a> (currently in beta). We can use the command line to create the key and pipe it directly into a new secret called cloud-run-invoker-key without downloading it first:</p><pre>gcloud iam service-accounts keys create /dev/stdout --iam-account cloud-run-invoker@${PROJECT_ID}.iam.gserviceaccount.com | gcloud beta secrets create cloud-run-invoker-key --data-file - --replication-policy automatic</pre><p>With that, we’re all set to make authorised requests against our Cloud Run service from the web app.</p><h3>Using the endpoint</h3><p>The demo website I created is a simple Python/Flask web app. It lets you upload an image or take a picture of your coffee with the camera, then it sends it to the Cloud Run endpoint and displays the classification result.</p><p>The core functionality — the interaction with the Cloud Run deployment — is very simple: Create a payload containing the Base64 encoded image and POST it to the Cloud Run service URL. Note the headers argument used to pass the ID token:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3eb464c4f30af4b9d0373afcb05ee53/href">https://medium.com/media/a3eb464c4f30af4b9d0373afcb05ee53/href</a></iframe><p>The get_token() function creates the ID token using the service account key we stored in Secret Manager earlier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77a0e939ef6a46504a26b3309dbaedd3/href">https://medium.com/media/77a0e939ef6a46504a26b3309dbaedd3/href</a></iframe><p>We use the Python API client library to retrieve the key. Note: The App Engine service account will need the <em>Secret Manager Secret Accessor</em> role.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc314b6e69ecba7d68f7aa9f5b73b7a/href">https://medium.com/media/2dc314b6e69ecba7d68f7aa9f5b73b7a/href</a></iframe><p>That’s it! We successfully moved the model deployment from AutoML to Cloud Run and used the prediction endpoint from an App Engine context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*Ff-7VchlYac-9Nys6VajAA.png" /><figcaption>With all the latte art on it, clearly a cappuccino</figcaption></figure><h3>Performance considerations</h3><p>So, we now have a cheaper solution, but what about performance? Typically, scale-to-zero services suffer from cold start latency when they haven’t been used for some time. Also, there are no GPUs on Cloud Run, at least for now.</p><p>Having said that, I was surprised how fast it is. I didn’t measure and compare the latency of AutoML deployment vs. Cloud Run deployment, so I won’t make a quantitative statement here. Anecdotal evidence from my personal end user perspective suggests that cold starts do indeed cause latency when the service was idle for some time, whereas inference is very fast. If I had a prototype app or a use case where latency is not the main concern, I would be perfectly happy with this kind of performance.</p><p>As always, it’s a tradeoff between performance and costs. Here, we improved a lot on the cost side while sacrificing very little on the performance side. This choice is not set in stone, of course. If you decide to switch back to AutoML, you can just deploy your model there and reroute traffic. Your Cloud Run deployment will scale to zero and with it its costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*BKyoeZgDlgIKVN_zPRB-cA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5efdd377d4d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run, Gateway, Run! — Algorithmic Trading the Serverless Way]]></title>
            <link>https://levelup.gitconnected.com/run-gateway-run-algorithmic-trading-the-serverless-way-71634dc1a37?source=rss-833154bbee14------2</link>
            <guid isPermaLink="false">https://medium.com/p/71634dc1a37</guid>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[interactive-brokers]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Juri Sarbach]]></dc:creator>
            <pubDate>Sat, 08 Feb 2020 12:52:40 GMT</pubDate>
            <atom:updated>2020-02-10T12:53:31.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>Run, Gateway, Run! — Algorithmic Trading the Serverless Way</h3><p>In my <a href="https://medium.com/@juri.sarbach/building-my-own-cloud-based-robo-advisor-5588ec1b74d3">last article</a>, I presented my solution for an automated algorithmic trading infrastructure on the Google Cloud Platform (GCP). Initially, I had intended to deploy the application as small pieces of serverless Cloud Functions, triggered by Cloud Scheduler. I refrained from this preferred approach and instead chose to build a Kubernetes-based application because I had to run the Interactive Brokers (IB) gateway software on a compute instance or in a Docker container. Hence, the serverless way seemed to be doomed from the beginning.</p><h4>Run time!</h4><p>While working on the Kubernetes application though, I realised that this is actually not true. There is indeed a way to run containerised workloads serverlessly on Google Cloud. The offering is called <a href="https://cloud.google.com/run/">Cloud Run</a> and was released to general availability just recently (I refer to the <a href="https://cloud.google.com/run/choosing-a-platform#cloud-run-fully-managed">fully managed platform</a> in the remainder of this article). Cloud Run let’s you deploy stateless workloads that listen on an HTTP port. The service automatically exposes a unique endpoint (URL) you can use to invoke it by an HTTP request. And it scales automatically up and down, even to zero if there are no requests.</p><p>In this respect, it feels much like Cloud Functions. Just that you deploy whole Docker images instead of mere Python, Node.js or Go functions. This means that you can use any programming language or run any binary you like. Binaries such as the IB gateway. So, let’s re-architect the trading application to be serverless.</p><p>Since Cloud Run is working with containers, I could reuse a lot from my Kubernetes solution. Nevertheless, the ephemeral nature of Cloud Run workloads required some changes to the application logic as we shall see. The basic idea is to turn every microservice on Kubernetes into a serverless Cloud Run service. To trigger the investment strategy algorithms, I use <a href="https://cloud.google.com/scheduler/">Cloud Scheduler</a>. It’s GCP’s cron job as a service product and takes over that functionality from the CronJob objects in Kubernetes. Thus, that’s what the new application architecture looks like from a high-level perspective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*NIG-nS-DxA8WGsukahbG3A.png" /><figcaption>A simple plan</figcaption></figure><p>Let’s go through the setup step by step. I start with the core (the application itself) and then touch the configuration of Cloud Scheduler, authentication, secret management, and finally continuous deployment. I’m going to highlight just some parts of the code. If you’re interested in more detail, you can find the whole source code on <a href="https://github.com/jsarbach/ib-trading/tree/master/cloud-run">GitHub</a>.</p><h4>Paving the gateway</h4><p>The main change compared to the Kubernetes solution arises from the fact that there is no more gateway running all the time in the Cloud Run version. In the Kubernetes cluster, the gateway microservice is always up and available to other parts of the application such as the allocators or investment strategies. While the application architecture remains request-driven in Cloud Run, we now have to launch the gateway with every request. Hence, we undo the separation and instead bundle it with every service.</p><p>According to the <a href="https://cloud.google.com/run/docs/reference/container-contract#cpu-request">Cloud Run contract</a>, computation is limited to the duration of the request. Unlike with Kubernetes, where the gateway is started during pod creation using <a href="https://github.com/IbcAlpha/IBC">IBC</a>, we will start it this time with every request and stop it before returning the response. Like this, it is terminated properly before the container enters a suspended state.</p><p>As before in the Kubernetes version, I use gunicorn and Falcon for the webserver. It provides the entrypoint and handles the HTTP request, calls the actual application, and produces the response:</p><pre># <a href="https://github.com/jsarbach/ib-trading/blob/master/cloud-run/application/py/main.py">main.py</a></pre><pre>from datetime import datetime<br>import falcon<br>import json<br>import logging</pre><pre><br>class Main:</pre><pre>    <strong>def on_get</strong>(self, request, response, trading_mode):<br>        self._on_request(request, response, trading_mode)</pre><pre>    <strong>def on_post</strong>(self, request, response, trading_mode):<br>        body = json.load(request.stream)\<br>           if request.content_length else {}<br>        self._on_request(request, response, trading_mode, **body)</pre><pre>    @staticmethod<br>    def _on_request(_, response, trading_mode, **body):<br>        if trading_mode in [&#39;live&#39;, &#39;paper&#39;]:<br>            try:<br>                [start and connect to IB gateway...]</pre><pre>                [run application logic...]</pre><pre>                [disconnect from and terminate gateway...]<br>            except Exception as e:<br>                error_str = &#39;{}: {}&#39;.format(e.__class__.__name__, e)<br>                logging.error(error_str)<br>                retval = {&#39;error&#39;: error_str}<br>                response.status = falcon.HTTP_500<br>        else:<br>            logging.warning(&#39;Trading mode unset or invalid&#39;)<br>            retval = {}<br>            response.status = falcon.HTTP_200</pre><pre>        retval[&#39;utcTimestamp&#39;] = datetime.utcnow().isoformat()<br>        response.content_type = falcon.MEDIA_JSON<br>        <strong>response.body = json.dumps(retval)</strong></pre><pre><strong>api = falcon.API()<br>api.add_route(&#39;/{trading_mode}&#39;, Main())</strong></pre><p>Thus, one prerequisite is that we can control the gateway from within our application which in my case is written in Python. Luckily, <a href="https://github.com/erdewit/ib_insync">IB-insync</a> is again a great help: With its <a href="https://ib-insync.readthedocs.io/api.html#ibc">IBC class</a>, commanding IBC to start and terminate the gateway is just one function call each.</p><p>To simplify things even a bit more, I wrote a class that inherits from IB-insync’s IB class and adds the necessary IBC class functionality. In particular, I packed starting the gateway and connecting to it into one method. It attempts to connect to the gateway once a second until the connection succeeds or a timeout is reached. Starting the gateway usually takes about 20 to 25 seconds.</p><pre># <a href="https://github.com/jsarbach/ib-trading/blob/master/cloud-run/application/py/lib/ibgw.py">ibgw.py</a></pre><pre>from ib_insync import IB, IBC<br>import logging</pre><pre><br>class IBGW(IB):</pre><pre>    def __init__(self,<br>                 ibc_config,<br>                 ib_config={},<br>                 connection_timeout=60):<br>        self.ibc_config = ibc_config<br>        self.ib_config = {<br>            &#39;host&#39;: &#39;127.0.0.1&#39;,<br>            &#39;port&#39;: 4001,<br>            &#39;clientId&#39;: 1,<br>            **ib_config<br>        }<br>        self.connection_timeout = connection_timeout</pre><pre><strong>        self.ibc = IBC(**self.ibc_config)<br>        </strong>super().__init__()</pre><pre>    def start_and_connect(self):<br>        logging.info(&#39;Starting IBC...&#39;)<br>        <strong>self.ibc.start()<br>        </strong>wait = self.connection_timeout</pre><pre>        try:<br>            while not self.isConnected():  <br>                # retry until connection is established or timeout<br>                # is reached<br>                IB.sleep(1)<br>                wait -= 1<br>                logging.info(&#39;Connecting to IB gateway...&#39;)<br>                try:<br>                    <strong>self.connect(**self.ib_config)<br>                </strong>except ConnectionRefusedError:<br>                    if not wait:<br>                        logging.warning(&#39;Timeout reached&#39;)<br>                        raise TimeoutError(<br>                            &#39;Could not connect to IB gateway&#39;)<br>        except Exception as e:<br>            logging.error(e)<br>            raise e</pre><pre>    def stop_and_terminate(self, wait=0):<br>        [...]</pre><p>Having the webserver and the gateway ready, we are set to turn to the application itself.</p><h4>One image to rule them all</h4><p>The trading application has several components, running investment strategies being the most obvious one. But I also have supplementary services such as the <em>summary</em> one that shows open positions and an account summary or the <em>close-all</em> one, some sort of kill switch that closes all open positions. Both are triggered ac-hoc from my dashboard deployed on App Engine that was already part of the Kubernetes solution.</p><p>While these components all get their own Cloud Run service that can be triggered individually, the application Docker image itself is the same for all services. No matter whether I call the summary service or one of the strategy services, it is always that one application image that is started by Cloud Run. What is actually being executed at runtime is controlled by environment variables, in particular by the INTENT one. The INTENTs are the switches that define what route the request will take inside the container. The environment variables are going to be injected by Cloud Run services so that we indeed need only one <a href="https://github.com/jsarbach/ib-trading/blob/master/cloud-run/application/Dockerfile">Dockerfile</a> and one Docker image for all services.</p><p>Thanks to Python’s import_module() function, we can import dynamically what we need according to our INTENT. For instance, if the INTENT is set to “summary”, the module intents.summary is imported first and then, summary.main() is called.</p><pre># <a href="https://github.com/jsarbach/ib-trading/blob/master/cloud-run/application/py/main.py">main.py</a></pre><pre>import falcon<br>from importlib import import_module<br>import json<br>from os import environ</pre><pre><strong><br>INTENT = environ.get(&#39;INTENT&#39;)</strong></pre><pre>[...]</pre><pre><strong>intent = import_module(&#39;intents.&#39; + INTENT)</strong></pre><pre>[...]<br></pre><pre>class Main:</pre><pre>    [...]</pre><pre>    @staticmethod<br>    def _on_request(_, response, trading_mode, **body):<br>        [...]</pre><pre>        ib_gw.start_and_connect()<br>        retval = <strong>intent.main</strong>(ib_gw, trading_mode, **body)<strong><br>        </strong>response.status = falcon.HTTP_200</pre><pre>        [...]</pre><pre>        response.content_type = falcon.MEDIA_JSON<br>        response.body = json.dumps(retval)</pre><p>The main() function in summary.py now does the actual work and produces the response.</p><pre># <a href="https://github.com/jsarbach/ib-trading/blob/master/cloud-run/application/py/intents/summary.py">summary.py</a></pre><pre>def main(ib_gw, trading_mode):<br>    [get account summary information…]</pre><pre>    response = {…}</pre><pre>    return response</pre><p>Packing the whole trading application together with the gateway into one image is way more maintainable than creating images for every single intent.</p><h4>Ready to Runble</h4><p>Now that the image is ready to deploy, let’s create the Cloud Run services. First, select the application image and the <a href="https://cloud.google.com/run/docs/locations">GCP region</a>. Next, activate authentication, because you probably don’t want the whole world to access your services. Remember that Cloud Run services on the managed platform get a publicly accessible URL. With authentication required, only requests with a valid token in the Authorization header are accepted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*c9iNzX16JubiaS8-KuYQXg.png" /><figcaption>You shall not pass (unless authorised)</figcaption></figure><p>I choose the following non-default <em>revision</em> settings:</p><ul><li>Memory allocated: The IB gateway can be a bit greedy when it comes to memory usage, so I’m generous and give it 2 GB of memory to be on the safe side.</li><li>Maximum requests per container: Since the gateway doesn’t allow multiple concurrent sessions with the same user ID, I prevent concurrency by changing this value to 1.</li><li>Service account: Preset is the Compute Engine default service account which has the role of Project Editor. This is quite broad. Therefore, I created a designated service account for my Cloud Run services and gave it only the roles it really needs. It’s good practice and follows the principle of least privilege.</li><li>Maximum number of instances: I don’t want multiple instances for the same reason as above (no concurrency allowed), therefore, I again set it to 1.</li><li>Environment variables: Set the INTENT and whatever other variables your application needs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*hP3WL3tyJIm21NQahBUHpg.png" /><figcaption>No service without intent</figcaption></figure><p>Here are some examples of Cloud Run services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwORwajs5NCVYec-8r73NA.png" /></figure><h4>Set the clock</h4><p>If Cloud Run is the heart of the trading application, Cloud Scheduler is the pacemaker. It triggers the Cloud Run services that carry out the automated investing according to a predefined schedule, in my case once a day. The configuration is pretty straightforward: Define the frequency in cron job notation, select HTTP as target, and specify the request (Cloud Run service URL, GET/POST method, request body).</p><p>The only slightly advanced part is the authentication. Since we only allow authenticated requests to our Cloud Run services, we have to make sure Cloud Scheduler adds an acceptable ID token in the Authorization header when triggering the service. I created a new service account and assigned the <em>Cloud Run Invoker</em> role to it. This can now be used to authenticate everything that invokes my Cloud Run services, such as Cloud Scheduler or App Engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*fbkOvwwdz-xrB5s-2UEq8Q.png" /><figcaption>Service account creation in IAM</figcaption></figure><p>When creating the Scheduler job, select <em>Add OIDC token</em> as the Auth header and then enter the service account you just created as well as the audience (the Cloud Run service URL). Done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*kZWELG3LknRzTzc2tw0UmA.png" /><figcaption>Cloud Scheduler configuration with authentication</figcaption></figure><h4>My secret service</h4><p>One thing I particularly like in Kubernetes is the way you can <a href="https://kubernetes.io/docs/concepts/configuration/secret/">manage secrets</a>. Luckily, this has an equivalent service on the Google Cloud Platform: <a href="https://cloud.google.com/secret-manager">Secret Manager</a> (currently in Beta). It’s a store for sensitive data such as my IB credentials. I store both user ID and password in Secret Manager and retrieve the latest version of them at runtime just before starting the IB gateway:</p><pre># <a href="https://github.com/jsarbach/ib-trading/blob/master/cloud-run/application/py/main.py">main.py</a></pre><pre>from base64 import b64decode<br>from googleapiclient.discovery import build<br></pre><pre>SECRET_RESOURCE = &#39;projects/[PROJECT_ID]/secrets/ib-credentials_{}_{}/versions/latest&#39;<br></pre><pre><strong>def get_secret</strong>(trading_mode, name):<br>    [...]</pre><pre><strong>    response = secret_service.projects().secrets().versions()\<br>        .access(name=SECRET_RESOURCE.format(<br>            trading_mode, name)).execute()</strong></pre><pre>    [...]</pre><pre><strong>    return b64decode(response[&#39;payload&#39;][&#39;data&#39;]).decode()</strong></pre><pre><br># build Secret Manager service<br><strong>secret_service = build(&#39;secretmanager&#39;,<br>                       &#39;v1beta1&#39;,<br>                        cache_discovery=False)</strong></pre><pre>[...]</pre><pre>ib_credentials = {<br>    secret: <strong>get_secret(trading_mode, secret)</strong><br>    for secret in [&#39;userid&#39;, &#39;password&#39;]<br>}<br>config = {<br>    **ibc_config,<br>    &#39;tradingMode&#39;: trading_mode,<br>    **ib_credentials<br>}<br>logging.info({**config, &#39;password&#39;: &#39;xxx&#39;})</pre><pre>ib_gw = IBGW(config)</pre><p>Note that your Cloud Run service account needs the <em>Secret Manager Secret Accessor</em> role to be able to retrieve the credentials.</p><p>Using Secret Manager has the advantage that storage and management of the credentials are decoupled from the application itself. Instead of adding them to the container image, passwords are held in a centralised vault. This not only facilitates password rotation, but it also releases you from finding clever ways of how to safely store and add credentials to your containers. This is particularly useful when you automate the deployment.</p><h4>Build, deploy, repeat</h4><p>Deploying an update of the application requires building a new application image, pushing it to the container repository, and updating all Cloud Run services to use the new image. Luckily, this can be automated with <a href="https://cloud.google.com/cloud-build">Cloud Build</a> which makes the whole deployment process way more convenient and at the same time less error-prone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUA4FVRtMv5QpqPgnPGE5A.png" /><figcaption>Automated deployment pipeline with Cloud Build</figcaption></figure><p>To do so, add a <a href="https://github.com/jsarbach/ib-trading/blob/master/cloud-run/application/cloudbuild.yaml">cloudbuild.yaml</a> file with three build steps to your code repository: build the image, push the image to Container Registry, and update the Cloud Run services with the new image:</p><pre>images:<br>- &quot;eu.gcr.io/${PROJECT_ID}/cloud-run/application&quot;<br>steps:<br>- name: &quot;gcr.io/cloud-builders/docker&quot;<br>  args: [&quot;build&quot;, &quot;-t&quot;, &quot;eu.gcr.io/${PROJECT_ID}/cloud-run/application:${SHORT_SHA}&quot;, &quot;cloud-run/application/&quot;]<br>- name: &quot;gcr.io/cloud-builders/docker&quot;<br>  args: [&quot;push&quot;, &quot;eu.gcr.io/${PROJECT_ID}/cloud-run/application:${SHORT_SHA}&quot;]<br>- name: &quot;gcr.io/cloud-builders/gcloud-slim&quot;<br>  entrypoint: &quot;bash&quot;<br>  args:<br>  - &quot;-c&quot;<br>  - |<br>    services=(${_SERVICES})<br>    for service in &quot;${services[@]}&quot;<br>    do<br>      gcloud run deploy ${service}-dev --image eu.gcr.io/${PROJECT_ID}/cloud-run/application:${SHORT_SHA} --region ${_GCP_REGION} --platform managed<br>    done</pre><p>Tagging the image with the git commit hash (${SHORT_SHA}) has the advantage that you can always easily retrace what’s inside.</p><p>Next, create a build trigger that will execute the build steps defined in the yaml file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*bYcFxKZw937KvZ0YnH50kA.png" /><figcaption>Cloud Build trigger configuration</figcaption></figure><p>Note that I added two substitution variables, _GCP_REGION and _SERVICES. These will be replaced in the cloudbuild.yaml by their values when the build is performed. Like this, we don’t have to hard-code the GCP region or the names of the Cloud Run services.</p><p>See the <a href="https://cloud.google.com/run/docs/continuous-deployment-with-cloud-build">documentation</a> for more details on how to configure a continuous deployment pipeline, especially for the IAM setup. In particular, remember to grant your Cloud Build service account the <em>Cloud Run Admin</em> role and to add it as a member with the <em>Service Account User</em> role to the runtime service account.</p><p>Of course, you can create multiple build triggers to support different release stages. For example, you could create one associated with the dev branch that deploys the testing release and another one associated with the master branch that deploys to production.</p><p>My pipeline above deploys to the testing stage, hence the -dev suffix after the service name. Whenever I consider an image is stable enough to be used in production, I manually tag it with “stable” and run a <a href="https://github.com/jsarbach/ib-trading/blob/master/cloud-run/application/deploy-to-production.sh">bash script</a> that basically performs the last build step, i.e. a loop over all services to deploy a new revision of the production services with the application:stable image.</p><h4>Spoilt for choice</h4><p>That’s it! Here’s the complete architecture summarised:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RH7IzgxPxB5qG5kMwpIyoQ.png" /><figcaption>That’s the way I like it: completely serverless</figcaption></figure><p>Compared with the <a href="https://medium.com/@juri.sarbach/building-my-own-cloud-based-robo-advisor-5588ec1b74d3">Kubernetes</a> architecture, it looks somewhat the same but different. The key difference of course is the serverlessness of the application core. Most of the surroundings, however, remain the same. In particular, I use the same Firestore database to store settings and to log application activity, and it’s the same dashboard application running on App Engine, now making direct authenticated requests to Cloud Run instead of using Serverless VPC Access to connect to the Kubernetes cluster.</p><p>So, which one should you choose — the Kubernetes or the Cloud Run implementation? It depends on your requirements, really. Things to consider:</p><ul><li><strong>Trading frequency:</strong> The higher your trading frequency, the more it’s worth having the IB gateway continuously running. However, if your strategies trade only once or twice a day or even less, the Cloud Run way is probably sufficient.</li><li><strong>Concurrency:</strong> Do you run multiple strategies and allocators that need to access the gateway simultaneously? Then you have to choose the Kubernetes implementation. Since there can only be one open session per IB account, running multiple instances of the gateway in Cloud Run at the same time is not possible.</li><li><strong>Latency:</strong> As mentioned, it takes 20 to 25 seconds to start the gateway. If your trading strategy requires a real-time view on the market, this is certainly not acceptable. In this case, you’d go with the Kubernetes-based solution.</li><li><strong>Costs:</strong> If you’re cost sensitive, the <a href="https://cloud.google.com/run/pricing#cloudrun-pricing">Cloud Run</a> implementation is more appealing as the infrastructure scales down to zero when not used, costing you nothing.</li></ul><p>In my case, the Cloud Run implementation is clearly the way to go. I currently run two end-of-day strategies, i.e. I need the gateway 10 times a week for about a minute each time. Therefore, there is no point in having a cluster running 24/7. Latency is not an issue as I rely on closing prices anyway. Also, my GCP bill imploded by about three orders of magnitude, from about USD 70 per month to virtually nothing. Sorry Google. ;-)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*rUKBRvkeb2mgABnyoxPKgg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71634dc1a37" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/run-gateway-run-algorithmic-trading-the-serverless-way-71634dc1a37">Run, Gateway, Run! — Algorithmic Trading the Serverless Way</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building my own Cloud-based Robo-advisor]]></title>
            <link>https://medium.com/@juri.sarbach/building-my-own-cloud-based-robo-advisor-5588ec1b74d3?source=rss-833154bbee14------2</link>
            <guid isPermaLink="false">https://medium.com/p/5588ec1b74d3</guid>
            <category><![CDATA[algotrading]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[interactive-brokers]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Juri Sarbach]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 09:20:44 GMT</pubDate>
            <atom:updated>2020-01-06T09:20:44.498Z</atom:updated>
            <content:encoded><![CDATA[<p>A long, long time ago, I worked in quant asset management. It’s the business of rule-based investing or algorithmic trading where you base investment decisions on data and models rather than human judgement and fundamental assessment of markets or companies. Nowadays one would say it’s data-driven investing.</p><h4>Get rich or lie on the beach tryin’</h4><p>My actual job was to do data analytics and to design profitable strategies that would typically earn some risk premium and to combine several of them in a portfolio. As the decision making is purely algorithmic, the implementation can be fully automated.</p><p>When you do this all day long, you’re eventually attracted by the somewhat romantic idea of letting the money work for you, get wealthy easily by running an automated algorithmic trading strategy on your own account and live a glamorous life happily ever after. We often used the term “beach trader” as a symbol for it — you know, the trader that lies on the beach while the algorithm earns his living and eventually checks his P/L with the smartphone between two sips from a cocktail.</p><p>As a side note: As appealing as the idea may be, chances are that one won’t consistently beat the market (well, unless you’re <a href="https://en.wikipedia.org/wiki/Jim_Simons_(mathematician)">Jim Simons</a>). Instead, the risk premium you’re earning eventually turns out to be more risk than premium and the losses you take wipe out your profits. You then tell yourself “oh screw it, I didn’t want to lie on the beach all day long anyway!” Well, at least I did.</p><h4>Reviving an old idea</h4><p>Back then, algorithmic trading relied on local infrastructure. My broker of choice, Interactive Brokers (IB), came up early with APIs to their backend so that one could build trading strategies including automated trade execution through the API. I never wanted to have a server at home running 24/7 (too noisy and ugly) or touch one of the low-level programming languages supported by the API at the time (too cumbersome), so I never automated the whole process.</p><p>But now that there’s cloud computing and Python support, I thought I could give it another try. More for the sake of building a cloud architecture and creating my own robo-advisor that follows a disciplined investment approach rather than chasing big trading profits. Being a fan of serverless, I immediately started sketching an architecture on the Google Cloud Platform (GCP) in my head, with Cloud Scheduler triggering Cloud Functions that would calculate trading signals and place orders in the market and so on.</p><p>Unfortunately, IB’s API solution comes from a time when “the cloud” was just some fluffy thing in the sky. Unlike modern APIs such as GCP’s client libraries that talk directly to Google’s services, IB’s solution requires a piece of gateway software meant to run on premise, connecting the API client to IB’s API servers and handling the authentication, routing orders etc. The worst thing about it is that it’s not designed as headless software, i.e. the application requires some sort of display and you have to log in with your username and password through a UI. Ugh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*bOufF6ZJMsR1scL2Y756uQ.gif" /><figcaption>Source: <a href="https://giphy.com/gifs/statefarm-ad-7WsiIldMO7w3NQQa7t">GIPHY</a></figcaption></figure><p>Given this legacy, a completely serverless solution solely with Cloud Functions was off the table, because the gateway requires a compute instance running somewhere anyway. So, should I set up a Windows instance on GCP? Nah… this lacks the fun component and moreover, cloud computing can do more than just replicate what you would build on premise.</p><h4>Put components into containers…</h4><p>Since I had already envisioned some kind of microservices architecture with Cloud Functions, I found it quite straightforward to put the single parts into Docker containers and use Kubernetes to orchestrate them. Of course, I could also run the containers on a GCE instance, but I like it a bit more managed. The way you get things like pod lifecycle management, DNS, rolling updates, health checks etc. with Kubernetes makes operations quite a bit easier.</p><p>So, the first challenge was to containerise that IB gateway relic. Fortunately, I was not the first one to try this. “The internet” has come up with solutions how to run the gateway headlessly. Tools such as <a href="https://github.com/ib-controller/ib-controller">IBController</a> or (preferably) <a href="https://github.com/IbcAlpha/IBC">IBC</a> take care of starting the gateway, logging you in, handling dialogue windows etc. You just need to make sure you install and run a window manager like Xvfb. If you’re interested in the details, head over to <a href="https://github.com/jsarbach/ib-trading/tree/master/gke/ib-gateway/ibc">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*mzXmtqw6mfpI_v6qMHwiMA.png" /><figcaption>And there we have it: the IB gateway</figcaption></figure><p>Once you have your gateway up and running in a container, you can start making use of the IB API and writing your trading application. <a href="https://github.com/erdewit/ib_insync">IB-insync</a> is a really great, object oriented wrapper for IB’s Python API that makes the use of the API way easier (hats off to you, Ewald de Wit).</p><h4>… mesh them…</h4><p>Here’s what the application looks like — the main components are:</p><ul><li><strong>IB gateways</strong> are the connector to IB’s servers. It consists of a <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">Deployment</a> and a corresponding <a href="https://kubernetes.io/docs/concepts/services-networking/service/">Service</a>. There is one for the live account (with real money) and for the “paper” account (simulated trading). The deployments must not have more than one replica each as the gateway software only allows one session per user ID. Once deployed, any microservice within the cluster can connect to the gateway to get market and account data, place orders etc. With IB-insync and Kubernetes’ DNS, connecting to the gateway service is as easy as ib.connect(host=&#39;ib-gw-live&#39;, port=4003). The IB gateway software has a tendency to hang, cause a burst in memory usage, lose connection to IB’s servers or log you out. Therefore, it’s crucial to include a health check to have the gateway container restarted in case it’s not responding for whatever reason. I added a small web server container to the gateway pods that queries the current time from the gateway to see if it’s alive. It is sufficient to define a <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes">livenessProbe</a>.httpGet in the gateway container spec, and Kubernetes takes care of repeatedly performing the health check. See the full configuration and code on <a href="https://github.com/jsarbach/ib-trading/tree/master/gke/ib-gateway">GitHub</a>.</li><li><strong>Strategies</strong> are the microservices that calculate signals or weights of a particular investment strategy upon HTTP request. I used gunicorn and Falcon as web server framework because Flask and IB-insync don’t go well together. Every strategy has its own Deployment and Service, so a request.get(&#39;http://my-strategy:8080&#39;) would produce a response with a JSON object containing the signals of my-strategy, such as buy X and sell Y or invest 70% in X and 30% in Y. You can find an example of a (pseudo) strategy on <a href="https://github.com/jsarbach/ib-trading/tree/master/gke/strategy-api">GitHub</a>.</li><li><strong>Allocators</strong> are the orchestrators of the investment process. They make a request to the strategy services to obtain trading signals and convert them into orders like buy 12 shares of X and 345 shares of Y. Allocators are <a href="https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/">CronJob</a> objects, i.e. they are started according to a schedule, e.g. hourly during trading hours or daily after the market close or on the first day of the month. Check out <a href="https://github.com/jsarbach/ib-trading/tree/master/gke/allocator">GitHub</a> for an example of how an allocator runs the above pseudo strategy once a day.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Ri9aMsnBpHxzkWpIdkQFQ.png" /><figcaption>Algo-trader, at your (micro-)service</figcaption></figure><p>Let’s do a quick example, following the diagram above: Say I want to hold stocks that had a positive news flow or a strong performance the day before (no-one would want to do that, it’s just for the example’s sake).</p><ol><li>The allocator-1 CronJob is started every business day after the market close. It sends a request to the strategy-1 Service and one to the strategy-2 Service.</li><li>Both strategy Deployments will then independently fetch the necessary data from public sources for the news flow and from ib-gw-live for the stock returns…</li><li>… calculate the signals, and send them back to allocator-1 in the HTTP response.</li><li>allocator-1 then consolidates both strategy signals and requests account value, current holdings, market prices, and FX rates from the gateway to come up with buy and sell orders.</li><li>Finally, it places the orders in the market through the gateway.</li></ol><p>The illustration also shows a second allocator used to test a new investment idea with simulated trading.</p><h4>… and ship them to the cloud</h4><p>Let’s deploy the application on GCP. First, we need a small cluster on <a href="https://cloud.google.com/kubernetes-engine/">GKE</a>. By small I mean <a href="https://cloud.google.com/compute/docs/machine-types#sharedcore">g1-small</a>. You’ll typically need one node per gateway, so if you want to have both the live and the paper one deployed, create a cluster with two g1-small nodes. You can also set up a single-node n1-standard-1 cluster and place both gateways on the same node, however, with g1-small nodes you get smaller (i.e. cheaper) increments should you ever need to scale the cluster. Of course, the optimal cluster configuration ultimately depends on how many concurrent strategies you want to run or whether you use resource hungry machine learning models for example.</p><p>When you create a standard cluster, the nodes by default get external IP addresses and hence, the cluster is exposed to the internet even if you don’t define an Ingress. I found that I sleep better when my trading infrastructure is less exposed to the world. Therefore, I decided to create a <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/private-clusters">private cluster</a>, i.e. one with no external IP addresses and therefore no public endpoint. Instead, the nodes only have internal IP addresses and are reachable solely from within the VPC. This isolates the cluster from the public internet.</p><p>However, this also has two major consequences: First, you can’t kubectl the cluster from your local machine or Cloud Shell; and second, if your cluster nodes don’t have an external IP, the application can’t communicate with the outer world, in this case with IB’s servers or a public data source that your strategy may require. Hence, we need two more things: a bastion host and <a href="https://cloud.google.com/nat/docs/overview#NATwithGKE">Cloud NAT</a>. The bastion host allows us to kubectl from there in case we need to administer our cluster resources, given it is in the same network as the cluster and given the appropriate firewall rules. Cloud NAT enables the cluster to reach the internet while protecting it from unwarranted access.</p><p>Of course, I also used other GCP products and tools to garnish the architecture:</p><ul><li><a href="https://cloud.google.com/deployment-manager/">Deployment Manager</a> to create the VPC network and subnetwork, the firewall rules, network tags, Cloud NAT, bastion host, and finally the GKE cluster. You could argue that using Deployment Manager for such a small setup that doesn’t even need to be repeatable is a bit over engineered. But I really learned to appreciate it: Spinning up and tearing down everything with one command instead of having to create or delete single resources is quite handy. Also, it’s a great way to <a href="https://github.com/jsarbach/ib-trading/blob/master/gke/deployment-config.yaml">document your infrastructure and its configuration</a>.</li><li><a href="https://cloud.google.com/logging/">Logging</a> and <a href="https://cloud.google.com/monitoring/">Monitoring</a> to catch application errors, trigger notifications and monitor the cluster in general.</li><li><a href="https://cloud.google.com/firestore/">Firestore</a> as the database to store application settings (e.g. the cash quote) and parameters as well as to log application activity (e.g. strategy signals or orders). I used Firestore for this instead of deploying a database to the cluster because it doesn’t require additional cluster resources (nodes) and is easy to use.</li><li><a href="https://cloud.google.com/cloud-build/">Cloud Build</a> and <a href="https://cloud.google.com/container-registry/">Container Registry</a> to build and store the Docker images.</li><li><a href="https://cloud.google.com/source-repositories/">Source Repositories</a> for the source code.</li></ul><h4>Trust is good, control is better</h4><p>Alright, the application is up and running, but it’s somehow hidden away in its private cluster. It would be nice to see what it is doing, considering that I’ve given it power of attorney to invest my money. Of course, I can check the logs in Stackdriver and Firestore to get an idea of what’s going on. Also, I can always log into IB’s account management website. However, as IB allows only one session per user ID, I’d have to delete the gateway deployment for a moment or take the whole application offline. Not really practical.</p><p>So, let’s add a dashboard that shows account and portfolio summaries, trading activity etc. I also want to have some sort of kill switch that lets me close all open positions and stop trading activity in case something goes terribly wrong. I could easily deploy a web app to the cluster, but then it would have to be a public cluster rather than a private one.</p><p>Therefore, let’s use App Engine instead. We have the <a href="https://cloud.google.com/appengine/docs/the-appengine-environments">choice</a> between the flexible environment that has at least one instance running 24/7 and the standard environment that scales down to zero if there’s no traffic. Given that the dashboard app will have very little traffic because I’m the only user and I’ll only check it out every once in a while between two sips from a cocktail, the standard one is way cheaper. However, in contrast to the flexible environment, the standard one has no instances in your own VPC network, a prerequisite since the private cluster only allows VPC-internal traffic.</p><p>Enter <a href="https://cloud.google.com/vpc/docs/configure-serverless-vpc-access">Serverless VPC access</a> (currently in Beta). It allows you to create a connector your App Engine (standard environment) or Cloud Function can use to communicate with the resources in your VPC. It will cost you two f1-micro instances (may be subject to change though) which is still cheaper than the n1-standard-1 an App Engine flex instance would cost. If you choose to use Firebase and Cloud Functions instead of App Engine, using Serverless VPC access is also the way to go. By adding an internal LoadBalancer to the gateway service(s) in the cluster, we get an internal IP address the web app can use to talk to the gateway through the Serverless VPC access connector.</p><p>The last thing to do is to add an authentication layer, preventing the web app from being accessible by the whole world. The easiest way is to set up <a href="https://cloud.google.com/iap/">Identity-Aware Proxy</a> so I can simply use my Google account credentials to log into my web app.</p><p>To summarise, here’s the complete GCP architecture for the algo-trading solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iThVDvif-cXiujWRhjOpxw.png" /><figcaption>Trading cluster and companions on GCP</figcaption></figure><h4>Not quite a free lunch</h4><p>Finally, some cost considerations. Investing is about money, after all.</p><p>Running a cluster with two g1-small nodes 24/7 costs at least about USD 28 per month (including sustained use discounts). Depending on which GCP-region you chose to deploy your application, it can be higher, e.g. about USD 37 in case of Zurich region. The privateness feature makes the setup considerably more expensive as you also need Cloud NAT and Serverless VPC access which together cost around USD 40 in a cheap region (the pricing of Serverless VPC access may be subject to changes once the product is out of beta stage).</p><p>So, all in all, we’re talking roughly about costs of USD 70 per month. If you run a 1 million dollar portfolio, that’s about 8.4 basis points off your annual return, so pretty affordable. If instead it’s 10 grand, it would cost you 8.4 per cent annually, quite a hefty fee from your virtual investment manager. If you choose to curb security for lower costs and do without the private cluster option, the total price will come down to about 30 USD per month — still somewhat expensive compared to a lean, completely serverless solution that scales resources and costs down to zero when they’re not needed. I haven’t given up hope yet that one day, IB will come up with a more modern API solution that makes the gateway software obsolete…</p><h4>Epilogue</h4><p>Turns out that serverless and low-cost may be back in the game after all. There is a new hope… No, not this guy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ry1-WgTGlex5k7pFZWnMlw.gif" /><figcaption>Source: <a href="https://giphy.com/gifs/starwars-movie-star-wars-xTiIzSicOljxwmWuhq">GIPHY</a></figcaption></figure><p>More about an alternative implementation in another article soon, so stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5588ec1b74d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracing Python Cloud Functions]]></title>
            <link>https://faun.pub/tracing-python-cloud-functions-a17545586359?source=rss-833154bbee14------2</link>
            <guid isPermaLink="false">https://medium.com/p/a17545586359</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[latency]]></category>
            <dc:creator><![CDATA[Juri Sarbach]]></dc:creator>
            <pubDate>Thu, 29 Nov 2018 18:28:12 GMT</pubDate>
            <atom:updated>2019-07-17T16:03:29.702Z</atom:updated>
            <content:encoded><![CDATA[<p>Did you ever have the impression that after deploying a <a href="https://cloud.google.com/functions/">Cloud Function</a> to the cloud, your view of it was… well… clouded? Because it was hard to understand what caused its latency, now that it had ascended to no-ops heaven?</p><p>Among the application performance management (APM) products on the Google Cloud Platform, there is a nice tool called <a href="https://cloud.google.com/trace/">Stackdriver Trace</a> to analyse and dissect the latency of your applications. It’s very useful to find out what part of your function it may be worth spending time on optimising. To use it with Cloud Functions, all you have to do is to make sure traces are being captured and sent to Stackdriver Trace.</p><h4>Getting Started</h4><p>In the <a href="https://cloud.google.com/functions/docs/concepts/python-runtime">Python 3.7 runtime</a>, this is very easy. In fact, so easy that you probably want to implement it by default. My advice: Do not bother wrangling with the <a href="https://googleapis.github.io/google-cloud-python/latest/trace/index.html">Python API</a>; it’s a rather unpleasant experience from a usability and documentation point of view. Instead, use <a href="https://github.com/census-instrumentation/opencensus-python">OpenCensus</a> which will save you head-scratching and get you straight down to the nitty-gritty.</p><p>Start by adding the OpenCensus and Stackdriver Trace dependencies to your requirements.txt:</p><pre>google-cloud-trace==0.19.0<br>opencensus==0.1.8</pre><p>In your main.py, import the required OpenCensus modules and create a Stackdriver exporter instance:</p><pre>from opencensus.trace import tracer as tracer_module<br>from opencensus.trace.exporters import stackdriver_exporter<br>from opencensus.trace.exporters.transports.background_thread \<br>    import BackgroundThreadTransport</pre><pre># instantiate trace exporter<br>exporter = stackdriver_exporter.StackdriverExporter(<br>    project_id=PROJECT_ID, transport=BackgroundThreadTransport)</pre><p>Of course, introducing extra latency to the code execution by adding tracing would be silly. To avoid this, initialise the exporter with the transport=BackgroundThreadTransport argument so that it uses a background thread to send the data to Stackdriver.</p><h4>Define Traces and Spans</h4><p>Now, all that is left to do is to create a tracer instance and to define what you want to have traced. In case you’re wondering, the Cloud Function snippet I used here as an example queries data from BigQuery and calculates some key performance indicators (KPI) with pandas.</p><pre>def get_kpis(request):<br>    &quot;&quot;&quot;<br>    This is the entry point to my Cloud Function.<br>    I will complete the docstring later -- promised!<br>    &quot;&quot;&quot;</pre><pre>    # instantiate tracer<br>    tracer = tracer_module.Tracer(exporter=exporter)</pre><p>Make sure not to create the tracer instance in the global scope. Otherwise, every function call will be logged in the same single trace.</p><p>Next, use the tracer’s span method to define the spans, i.e. the operations within a trace that shall be observed. Probably the most convenient way to do this is to use with statements. Also, giving the span a meaningful name makes it easier to identify in Stackdriver Trace. In my example, the root span named get_kpis covers the whole function:</p><pre>    <strong>with tracer.span(name=&#39;get_kpis&#39;)</strong> as span_get_kpis:<br>        # parse HTTP request<br>        client_id, filters = parse_request(request.get_json())</pre><p>Everything within this with statement will now be traced as one span. To get a more granular view, let’s create nested spans by enclosing sub-operations in child spans.</p><pre>        # query data from database<br>        <strong>with span_get_kpis.span(name=&#39;query_data&#39;)</strong>:<br>            data = query_data(client_id, filters)</pre><pre>        # calculate KPIs<br>        <strong>with span_get_kpis.span(name=&#39;calc_kpis&#39;)</strong> as span_calc_kpis:<br>            # instantiate KPI object<br>            kpis = KPI(data)</pre><pre>            # define DataFrame index<br>            <strong>with span_calc_kpis.span(name=&#39;create_df_index&#39;)</strong>:<br>                kpis.create_df_index()</pre><pre>            # add I/O counts<br>            <strong>with span_calc_kpis.span(name=&#39;add_io_counts&#39;)</strong>:<br>                kpis.add_io_counts()</pre><pre>            # add smoothed I/O<br>            <strong>with span_calc_kpis.span(name=&#39;add_smoothed_io&#39;)</strong>:<br>                kpis.add_smoothed_io()</pre><pre>            .<br>            . [other KPI calculations omitted]<br>            .</pre><pre>        # create response body dict from DataFrame<br>        <strong>with span_get_kpis.span(name=&#39;df_to_dict&#39;)</strong>:<br>            body = kpis.to_dict()</pre><pre>    # return HTTP response<br>    return json.dumps(body), 200</pre><p>Voilà. Now call your function, locally or after deploying, and head over to your <a href="https://console.cloud.google.com/traces/traces">Cloud Console</a> to inspect the latency.</p><h4>Trace Visualisation and Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0EQu8Df9-nG6X6RS2kJwQ.png" /><figcaption>Stackdriver Trace dashboard in Cloud Console</figcaption></figure><p>Select one particular trace to break it down and see where the latency comes from. In the timeline, the spans appear hierarchically, exactly as you defined it in your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Dh0dk7O5bkg0AI0VaXFhQ.png" /><figcaption>I may want to look into those query_data and add_tpt operations again…</figcaption></figure><p>Analysing single traces is helpful to uncover the bottlenecks in your code. However, in terms of the overall latency, you get rather anecdotal evidence. To have a better statistical understanding of how your function performs overall, you can create analysis reports with nice distribution charts. This is particularly useful to assess the impact of changes to your code on latency. Analysis reports are available once you have at least 100 traces. If you want to fast-forward, you can call the <a href="https://artillery.io/">Artillery</a> to take your function under fire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TaBDq2YwTOW0OWnIPr0BA.png" /><figcaption>Comparing the latency distributions of two different deployments</figcaption></figure><h4>Automated Monitoring and Alerting</h4><p>Even after optimising the latency, it could still deteriorate every now and then. E.g., shirking dependencies such as a database or network connection could eventually slow down your function and require you to take action.</p><p>Of course, you don’t want to continuously keep an eye on the dashboard to observe how the latency evolves over time. And you don’t have to. Instead, you can set up an alerting policy in <a href="https://cloud.google.com/monitoring/">Stackdriver Monitoring</a> to have your latency monitored around the clock. Whenever it surpasses a level you defined, you’re notified automatically so that you can act early. Pretty neat, isn’t it?</p><p>So, grab a cup of coffee, lean back, rejoice, and look smart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Join our community Slack and read our weekly Faun topics ⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a17545586359" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/tracing-python-cloud-functions-a17545586359">Tracing Python Cloud Functions</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Serverless Dataset and AI Model Management Tool]]></title>
            <link>https://medium.com/@juri.sarbach/building-a-serverless-dataset-and-ai-model-management-tool-9658ef2b72b9?source=rss-833154bbee14------2</link>
            <guid isPermaLink="false">https://medium.com/p/9658ef2b72b9</guid>
            <category><![CDATA[cloud-datastore]]></category>
            <category><![CDATA[logo-detection]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Juri Sarbach]]></dc:creator>
            <pubDate>Sat, 10 Nov 2018 20:49:18 GMT</pubDate>
            <atom:updated>2018-11-10T20:49:18.075Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@juri.sarbach/building-a-serverless-end-to-end-solution-for-brand-detection-in-video-fa5a2cd64b4d">In my last article</a>, I illustrated how we built a completely serverless application for brand detection in videos on the Google Cloud Platform (GCP). This time, I outline how we added an admin tool that lets the operators of the app manage the brand detection engine itself. I would have loved to call it “Episode II: The Server Strikes Back”. But it doesn’t. This is as serverless as the main application.</p><h4>Motivation</h4><p>Which serverless GCP product didn’t we use so far? Ah right, <a href="https://cloud.google.com/datastore/">Cloud Datastore</a>! So let’s do something with Datastore, shall we?</p><p>Admittedly, the reasoning behind that admin tool was somewhat different: When iterating through the training of our brand detection model based on the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a>, we relied on a very hands-on approach. Which is in this case just a euphemism for a lot of manual work…</p><p>The Object Detection API gave us a nice and almost easy access to pre-trained neural networks and hence a jump-start to our own brand detection model. However, the training of the models still required a lot of manual effort: managing local conda environments, annotating images by drawing bounding boxes around logos, creating TFRecords data files on our local machines, editing Object Detection API config files, copying files to and from Cloud Storage, launching training and evaluation jobs on Cloud ML Engine, copying files back and forth again, exporting trained models, copying files back and forth again and again, and finally deploying models as a service on Cloud ML Engine.</p><p>All in all, a terrible mix of local and cloud-based data storage and code execution, and a lot of typing Cloud SDK commands such as gsutil -m cp ... and gcloud ml-engine jobs submit .... I even created a list of all the necessary commands and their correct order. At some point, I had written a couple of bash scripts to automate at least some of the steps, but still: unacceptably tedious.</p><p>The worst thing besides the lousy user experience was, however, the mess it created. If you’re not endowed with an accountant-esque discipline and hence do not embrace thorough bookkeeping (like me), you’ll find yourself quickly juggling a lot of different datasets and model checkpoints, losing track of which model was trained with which dataset, based on which checkpoint for what reason and producing what results. Even worse, as we were lacking a proper checkpoint management, we found ourselves overwriting older model checkpoints with newer ones. No reproducibility, no traceability. And certainly far away from best practice.</p><p>As a GCP evangelist (yeah, I hate that expression, too, but look: pun ahead!), in such situations, I often ask myself WWGD (what would Google do)? Well, I guess they would probably let machines do the annoying stuff and automate humdrum things away. And wrap everything into a proper app. So, what would it take to app-ify this whole process of handling data and models?</p><h4>The Requirements</h4><p>To be more precise, we wanted our admin tool to allow us to</p><ul><li>upload and annotate training data;</li><li>build TFRecords datasets;</li><li>launch training jobs on Cloud ML Engine;</li><li>deploy models to the Cloud ML Engine service;</li><li>keep track of the model checkpoint history and hierarchy;</li><li>have a cloud-only solution with a browser-based UI.</li></ul><p>Our main app already had an Angular frontend and a Python backend running on App Engine. Also, we had all the Python code necessary for the TensorFlow related tasks like the dataset generation. So it all came down to deploying our existing code in a reasonable way, adding a database solution, using the APIs to interact with Cloud ML Engine and other GCP components, and integrate the admin tool into the main app. That seemed pretty doable.</p><p>We decided to use Datastore as the database because it is ready to use a.k.a. serverless and perfectly suited since all we want to store is basically key-value pairs. Let’s have a quick look at the data model before we go more into the details of some of the components.</p><h4>The Data Model</h4><p>Datastore is very much at the centre of the tool. Every object we manage — brands, training images, label maps, datasets, models — is represented by an <a href="https://cloud.google.com/datastore/docs/concepts/overview#comparison_with_traditional_databases"><em>entity</em></a><em>,</em> organised in six <a href="https://cloud.google.com/datastore/docs/concepts/overview#comparison_with_traditional_databases"><em>kinds</em></a><em>:</em></p><ul><li><strong>Brands </strong>and <strong>Logos:</strong> First, we need a notion for the objects we want to detect. In our case, these are brands or, to be more precise, logos. Oftentimes, a brand has more than one logo, e.g. a word mark and a figurative mark or even <a href="https://www.google.ch/search?q=adidas+logo&amp;tbm=isch">multiple logos</a>. Therefore, we distinguish between logos (the things we actually train our models to detect) and brands (what our analytics are based on) and introduce a one-to-many parent-child relation in Datastore.</li><li><strong>Images:</strong> By design, neural networks are trained by showing them a lot of examples to learn from. In our case, each training example consists of an image file and an annotation defining the logos (IDs from our Logos kind) and their locations in the image (coordinates of the bounding boxes). Annotations are represented as an array of <em>embedded entities</em> (think of a JSON object). The image files themselves go to Cloud Storage.</li><li><strong>LabelMaps:</strong> Since classifier models work with numeric classes rather than labels (“Adidas”), we use label maps to — surprise, surprise — map labels to class ID integers. In our Datastore kind, a label map is represented as an entity containing an array of logo IDs. The array index plus 1 corresponds to the class ID. We can create label maps for every set of brands we want to train a separate model with, e.g. one for the sponsors of a football league and another one for alpine skiing.</li><li><strong>Datasets:</strong> To ingest the training images and corresponding annotations efficiently into a TensorFlow model, we want to bundle them in a single TFRecords dataset file. Of course, we only include images that contain logos relevant for a particular training run. We’ve defined such a set of relevant logos just before when creating a label map. By including the label map ID in the dataset entity, we keep track of which logos the corresponding TFRecords file contains.</li><li><strong>ModelCheckpoints:</strong> One advantage of using the TensorFlow Object Detection API is that you don’t have to build and train your object detection model from scratch. Instead, you start with a pre-trained model and fine-tune its weights with your data which saves training time. If later, you want to improve your model further e.g. because you have new data, you can now start from your last model run. Hence in our case, every model has an ancestor. We mirror this model hierarchy in Datastore using a one-to-many parent-child relation. Therefore, every ModelCheckpoints entity has a parent property along with a property for the dataset ID that was used for this particular model training run. The TensorFlow model checkpoint files themselves are stored in Cloud Storage, of course.</li></ul><p>Datastore connects the bits and pieces. The model checkpoint “knows” which dataset it was trained with; the dataset knows which label map it is based on; the label map knows which logos it contains. When a video is being analysed based on a particular model in the <a href="https://medium.com/@juri.sarbach/building-a-serverless-end-to-end-solution-for-brand-detection-in-video-fa5a2cd64b4d">main app</a>, it’s easy to reconstruct how the numeric class IDs returned by the model have to be mapped to logos and hence which brand names have to be written to BigQuery.</p><p>Here is how Datastore is connected to the rest of the admin tool architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuSWyRtL98_9fEBG0uKQ6g.png" /><figcaption>Admin tool building blocks</figcaption></figure><p>Let’s now have a closer look at some of the components. I skip the brand/logo and label map management components as they are quite trivial; it’s really just more or less creating Datastore entities.</p><h4>Image Upload and Annotation</h4><p>As mentioned in the requirements, the image management component is supposed to do more than just upload images to Cloud Storage and list them. It comes with fully fledged annotation functionality so we don’t have to use third party tools on our local machines anymore. Instead, we can select and display images after the upload and draw bounding boxes around a logo in the browser and define which logo it contains (by assigning a logo ID to it). It also allows us to modify or delete existing bounding boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlvLNxVVUFfEiDRze9Pf_A.png" /><figcaption>Image annotation tool (training image taken from a YouTube video)</figcaption></figure><p>Annotating images is still a heavily manual task of course, but at least it is now integrated into one single tool and process. Unlike before, it uses tool-wide consistent IDs for the logo classes. Also, images are queryable, e.g.: Which images have no annotations yet? How many examples with the Adidas logo do we have? As a nice side effect, we can easily add examples of the logos to our brand/logo management section by just querying the bounding box information from Datastore and cropping the images accordingly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8DTFbYr1A3145V034NEMw.png" /><figcaption>Brand and logo management with logo samples cropped from training images</figcaption></figure><p>So far, so good, but I reckon that a serverless solution somehow lacks coolness without <a href="https://cloud.google.com/functions/">Cloud Functions</a>. Luckily, we could mitigate this flaw: To ensure every image conforms to the requirements of the TensorFlow models (in particular, they need to have three colour channels), we extended the upload process with a Cloud Function that automatically converts every image to RGB if necessary. At the same time, it also extracts metadata like the dimensions.</p><p>After deploying this, we thought it might be fun to use Google’s <a href="https://cloud.google.com/vision/">Vision API</a> to add a bit of context to every image (usually sports scenes). Therefore, we wrote another Cloud Function that sends every image through the Vision API and adds the detected labels (e.g. “ice hockey” or “skiing” or… “galliformes” — er, what?) to the Datastore entity. We’re not sure yet how useful this feature really is, but since almost everything on GCP is just an API request away and writing a Cloud Function is super easy and fun, why bother. Let’s just try it out and see whether it proves to be useful or not. And so, images are now searchable for brands and context. Summarising, here’s how the whole image upload and processing pipeline looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTSJ1uImfRutiNkx_KuYeA.png" /><figcaption>Image upload and processing pipeline</figcaption></figure><h4>Dataset Generation</h4><p>Once the annotated images are ready together with the label maps that define sets of logos to train a model with, we can pack the training data into a TFRecords file. First, we query the information we need from Datastore: We start with the ID of the label map of interest, query its constituents (logo IDs) and then the images containing these logos together with the bounding box information. Second, we pull the required image files from Cloud Storage, pack everything into one TFRecords file, and ship it back to Cloud Storage. All with a single click on a button on the frontend and with the backend running recycled Python code from before when we still did all of this on our local machines.</p><h4>Model Training and Deployment</h4><p>Having the datasets at hand, we are now ready to perform the actual model training. As mentioned, our models have a hierarchy, forming a tree.</p><p>Every tree starts with a pre-trained architecture from the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md">Object Detection API model zoo</a> at its root. Uploading such a model creates a representation of the model in the form of a Datastore entity as well as a directory on Cloud Storage with the checkpoint files. From here, one can create a child model by forking it. Every fork creates another model entity and a copy of the checkpoint files in its own directory. To train it, click on the respective button, chose a dataset, set the training parameters, give it a description, and the training can start. The backend will write the necessary Object Detection API config files to Cloud Storage and then launch a training job on Cloud ML Engine (CMLE). Depending on the commissioned machinery, model architecture, and innovations introduced by the dataset, the job may run for a couple of hours. Therefore, the status of the job is queried periodically via the CMLE API to check whether it is still running or has completed.</p><p>Not happy yet with the accuracy of the model? Just fork again and continue with the training. Since every forked model starts with the weights of its parent, it can build upon what its ancestors have learned and, therefore, usually converges faster.</p><p>Once the model has reached satisfactory accuracy, one can deploy it so that it can be used in production. With a single click, the backend takes care of exporting the model to the right format and of triggering the deployment on CMLE. This actually creates a service on CMLE that can be used by the main application via simple API requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*sUCRxE7f9Z2LwnwU4OJ4dQ.png" /><figcaption>Model tree</figcaption></figure><h4>Conclusion</h4><p>In contrast to what we had before, most of the hassle has now disappeared behind a frontend with some buttons, input fields, and lists. Tedious manual work steps have been replaced by a couple of clicks which saves us time and nerves. The action is consequently taking place in the cloud and not partially on our laptops anymore. And we have gained structure and traceability. At the same time, its serverlessness makes it very operating cost-effective.</p><p>And the development costs? Well, the most time-consuming part was the frontend. Everything backend — designing the data model, modifying and deploying the existing code, and adding API requests to it — was a matter of a couple of days. We see it as yet another great example of how a serverless cloud infrastructure helps us develop solutions quickly and with little effort.</p><h4>Epilogue</h4><p>But, but… did we do all of this just for this one logo detection use case? Isn’t that a bit over-engineered? Well, yes and no. Of course, it felt great to take the hassle out of the whole data and model handling process. But we also hat two other things in mind.</p><p>First, we planned to introduce a completely new type of object detection model. One that takes a two-step approach, separating object localisation from classification. The first step would just learn to distinguish the logos from the background, basically placing bounding boxes around what seems to be a logo. For each of these, the second step would then calculate a feature representation and compare it to a set of known feature representations to classify it as one particular logo. This has the advantage that you can handle untrained logos way better because it allows ex-post classification in case the classifier step couldn’t find a match among the known logos.</p><p>Say you have a video featuring the <em>Rivella </em>logo which our model has never seen before (probably like you, unless you are Swiss). The localisation model would still recognise it as a logo because it has the abstract features of a logo. It just doesn’t know what logo, so it saves its feature representation and flags it as unclassified logo. The admin can then go through all video frames with unclassified logos and assign the right logo to the proposed bounding box. Not only for this frame but for also all past and future ones since different examples of the same logo should produce a very similar feature representation. See how this integrates nicely into the admin tool with its application-wide logo management and annotation feature?</p><p>Second, we see it as some sort of blueprint for future projects and products. This is by no means restricted to brands and logos or this kind of object detection models. With a few tweaks, it will be applicable in another context. Hence, we see it as a general tool for other use cases and well worth the exercise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9658ef2b72b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Serverless End-to-End Solution for Brand Detection in Video]]></title>
            <link>https://medium.com/@juri.sarbach/building-a-serverless-end-to-end-solution-for-brand-detection-in-video-fa5a2cd64b4d?source=rss-833154bbee14------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa5a2cd64b4d</guid>
            <category><![CDATA[logo-detection]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[dataflow]]></category>
            <dc:creator><![CDATA[Juri Sarbach]]></dc:creator>
            <pubDate>Sat, 06 Oct 2018 16:39:40 GMT</pubDate>
            <atom:updated>2018-10-06T16:39:40.577Z</atom:updated>
            <content:encoded><![CDATA[<p>Some time ago, we were asked by a client to help them on the technical implementation of a business venture. The idea was to detect brands and logos in TV sports broadcasts and videos in order to measure the brand exposure during e.g. a football match or a ski race. The project was abandoned by the client before the MVP was completed because of commercial reasons. We decided to finish the MVP nevertheless and put part of it <a href="https://argus.quantworks.ch/">online</a> because we reckoned it is fun. Here is how we built a full end-to-end solution on the Google Cloud Platform (GCP).</p><h4><strong>The Requirements</strong></h4><p>The client wanted the solution to:</p><ul><li>detect specific brands in video media (classification and localisation);</li><li>calculate brand exposure metrics (how often did a brand appear and how well was it visible on screen);</li><li>cover two use cases: 24/7 real-time analysis of TV broadcasts as well as on demand analysis after the sports event (overnight processing of recorded videos);</li><li>handle HD quality video with up to 25 fps and multiple simultaneous TV broadcasts.</li></ul><p>We had already developed a brand detection model in TensorFlow based on the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a> that worked reasonably well, at least for the purpose of a prototype. So, all that was left to do was to embed it into an end-to-end architecture that acquires video streams and files, preprocesses them, detects the brands in all the single frames, stores the results in a data warehouse, and calculates and visualises the metrics in a dashboard; everything in almost real time and irrespective of the number of the amount of data that we throw at it (e.g. take ten simultaneous TV broadcasts at 25 fps and you’re about to run brand detection on 250 HD images per second). Piece of cake, right? All it takes is a bunch of sysops people that set up, operate, scale up and down, and maintain the infrastructure needed. Oh, wait. We don’t have such people at Quantworks. We don’t even have an IT department. So…?</p><p>Of course, you’ll have guessed where this is going (it’s in the title of this article, after all). As a small startup with quite some data engineering capabilities but no sysops personnel, we’ve become used (more precisely: addicted) to the blessings of serverless on the GCP. Write your code, test it, deploy it to a service. Plug (the services together) and play. Bam! No capacity planning, no manual scaling of infrastructure, no configuration or maintenance of servers. (What are these “servers” anyway?)</p><h4><strong>The Building Blocks</strong></h4><p>So, let’s recap what had to be done: receive a video stream or a video file; split it into the single frames; run brand detection on each single frame using our TensorFlow model; dump the results into a data warehouse that allows online analytical processing (OLAP) on a large amount of data; visualise the metrics in a web based dashboard.</p><p>The architecture on GCP for the last three steps is pretty straightforward: deploy the TensorFlow model on <a href="https://cloud.google.com/ml-engine/">Cloud ML Engine</a>, allowing us to do inference through API requests; store the inference results in <a href="https://cloud.google.com/bigquery/">BigQuery</a> so that we can calculate the exposure metrics on the fly with SQL queries; and use <a href="https://cloud.google.com/appengine/">App Engine</a> to run the web frontend. As far as the ingestion is concerned, a different pipeline is needed for each of the two use cases: a Batch one and a strEAMing one — a case for <a href="https://beam.apache.org/">Apache BEAM</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIvcXZeVUOJFf9jWWNAAMQ.png" /><figcaption>High-level overview of the building blocks</figcaption></figure><p>So let’s dig deeper into the setup of the two pipelines.</p><h4><strong>The Streaming Pipeline</strong></h4><p>The streaming pipeline has to cope with a constant inflow of media streams from different TV stations. We use OpenCV to read the video streams and to split them into the single frames (usually 25 frames per second and stream). The frames are saved in a Cloud Storage bucket. We tested this successfully on a Compute Engine instance. However, if we were to put this into production, we would probably deploy it as a service on App Engine for, you know, serverlessness reasons.</p><p>Images arriving in the Cloud Storage bucket trigger a <a href="https://cloud.google.com/pubsub/">Cloud PubSub</a> notification. The rest of the pipeline is built with the Apache Beam Java framework, running in <a href="https://cloud.google.com/dataflow/">Dataflow</a> on the GCP. It is subscribed to the PubSub topic and hence notified about every image being saved in the bucket. It then loads the image and includes it in the API request to our model deployed on Cloud ML Engine. The response from Cloud ML Engine containing the classes and bounding boxes of the detected brands is then inserted into BigQuery.</p><p>Once deployed, the Dataflow pipeline runs forever, fed by the video frames dropped in the storage bucket, processing them in parallel, and scaling compute instances automatically according to the data volume. Add another TV broadcast? Just make sure the frames land in the bucket; the rest like provisioning more resources is taken care of by Dataflow.</p><p>Since we don’t need any sophisticated preprocessing on the images nor advanced Beam features like windowing or watermarks, we could also have implemented all of this with <a href="https://cloud.google.com/functions/">Cloud Functions</a>. However, we wanted to keep open the option of doing more sophisticated preprocessing later which is easier to accomplish in Java than in JavaScript (the Python runtime for Cloud Functions was not yet available at that time). Also, we could reuse most of the code for the batch pipeline.</p><h4><strong>The Batch Pipeline</strong></h4><p>The batch pipeline is triggered by the user uploading a video file over the frontend for analysis. After the video has been uploaded to a Cloud Storage bucket, a Dataflow batch job defined in a template is launched. It reads the video file, splits it into frames and the rest is the same as with the streaming pipeline (and by “the same” I mean exactly the same, as in: exactly the same code), i.e. call the Cloud ML Engine service and store the inference results in BigQuery. Since we thought it would be nice to give the user not only the metrics but also a glimpse behind the scenes of object detection, we decided to add one more step to the batch pipeline that draws the bounding boxes and labels of the detected brands onto the frames and assembles everything back to one video file.</p><p>A behaviour totally acceptable for the original use case (overnight processing of videos) but somewhat unsatisfactory for the demo we have put online is the long processing time of videos. Without going into too much detail, this is due to a pipeline property that limits the full parallelisation of the whole Dataflow pipeline. (For the Dataflow affine among you: we have to materialise the PCollection after a high fan-out ParDo step — one video file split into a lot of single frames — in order to prevent Dataflow’s fusion optimisation which in this case is, well, not really an optimisation; see the <a href="https://cloud.google.com/dataflow/service/dataflow-service-desc#fusion-optimization">Dataflow documentation</a> for more details.)</p><p>One could mitigate this using Cloud Functions instead of Dataflow, however, this would come at the cost of losing the notion of the bounded PCollection, i.e. of the fixed-size data set enabling the pipeline to know when it is done with processing all the frames (by contrast, Cloud Functions would execute the parallel steps autonomously and without a master process that keeps track of completeness). And the boundedness comes in handy if one wants to show the progress on the frontend or create the output video. We decided to add an additional preprocessing step that splits the video file into several parts before handing them over to Dataflow in order to allow for more parallel processing. This is accomplished with a Node.js Cloud Function and using FFMPEG. It mitigates the latency problem a little, but doesn’t eliminate it.</p><h4><strong>Conclusion</strong></h4><p>So, there you have it: A completely serverless solution on the GCP that scales automatically with the inflowing amount of data. All it took us to extend the TensorFlow brand detection model into a full end-to-end application is a GCP architect with a bit of coding skills and an Angular-savvy intern for the frontend. Piece of cake indeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqLC0Pu4vry5WFKesDxPRg.png" /><figcaption>Complete architecture</figcaption></figure><p>We’ve put the batch processing-only part <a href="https://argus.quantworks.ch/">online</a> as a sort of MVP. (It’s an MVP, okay? Expect bugs and a far from perfect UX.)</p><p>More to come! In another article, I’ll show you how we enhanced the solution with an administration site that facilitates the training and management of brand detection models and the management of data sets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa5a2cd64b4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>