<?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[T-Mobile Tech - Medium]]></title>
        <description><![CDATA[turning telecoms on its head  (and looking way cool while doing it) - Medium]]></description>
        <link>https://medium.com/tmobile-tech?source=rss----e283d0ff239a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>T-Mobile Tech - Medium</title>
            <link>https://medium.com/tmobile-tech?source=rss----e283d0ff239a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:20:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/tmobile-tech" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[KAFKA UPGRADE — A HASSLE FREE JOURNEY]]></title>
            <link>https://medium.com/tmobile-tech/kafka-upgrade-a-hassle-free-journey-5c3bdbfc63db?source=rss----e283d0ff239a---4</link>
            <guid isPermaLink="false">https://medium.com/p/5c3bdbfc63db</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[amazon-msk]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Anirudha Karandikar]]></dc:creator>
            <pubDate>Thu, 21 Oct 2021 16:07:42 GMT</pubDate>
            <atom:updated>2021-10-21T16:07:41.135Z</atom:updated>
            <content:encoded><![CDATA[<h3>KAFKA UPGRADE — A HASSLE-FREE JOURNEY</h3><p>Our goal for this article is to share the experience of our Kafka upgrade with others in the data ingestion world. We hope our journey from a ‘couple generations behind’ <strong>self-managed</strong> infrastructure to a <strong>managed service</strong> that reduced the cognitive load on our operations team, while <strong>increasing security</strong> and <strong>unlocking newer features</strong>, will help you on your journey as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hu09yMvmqBJ0xJM2wIRM4Q.jpeg" /></figure><h3>A Brief introduction of D3</h3><p><strong>D3 is a Data ingestion service</strong> that is used by multiple upstream systems for posting diagnostic, analytic and telemetry type of data. The data is consumed from D3’s data lake by data owners and users to materialize business use cases, helping customers and improving D3’s services. D3 is a relatively high throughput and low latency system. We process about 3 billion events a day, about 500GB of compressed data.</p><p>As with many clickstream/data ingestion services, <strong>D3 has Kafka at the core of its system.</strong></p><h3>Backstory on our Kafka upgrade</h3><p>When D3 was built originally, a few years ago, it was one of the forerunners in a completely cloud based infrastructure and used the latest stable Kafka for that time. As with any well implemented Kafka based solution, our system was still running great, but it was time to <strong>get current </strong>and <strong>solve a few accumulated tech debt pain points</strong>. Our key drivers for this Kafka upgrade were:</p><p>· <strong>Stability</strong> — be the latest stable version of Kafka.</p><p>· <strong>Security</strong> — use the opportunity to do a security review and implement the latest guidelines.</p><p>· <strong>Operational Ease</strong> — Convert from a self-managed to a managed service solution.</p><p>· <strong>Unlocking the Latest Kafka Capability</strong> — To be able to support more use cases and more partners by using some of the latest features like Kafka streams and connect.</p><p>This is what set the course for the D3 Kafka Upgrade.</p><h3>Searching for a Solution Path</h3><p>We used the opportunity to learn from the experiences of other major Kafka users at T-Mobile and considered self-managed vs. managed, Amazon service, or Confluent service. <strong>We preferred Managed Service due to the benefits of not having to set up and maintain Kafka infra, ease of future upgrades, out of the box capabilities, and professional service support.</strong></p><p>After reviewing costs and enterprise agreements, we finalized the Amazon MSK for our Kafka upgrade Managed Service solution. Then the real work began.</p><h3>Overall Kafka Upgrade Implementation Approach</h3><p>With the goal of moving from an older version of Kafka (circa <strong>v0.10.0.1</strong>) i.e. deployed on our cloud infrastructure to Amazon MSK <strong>v2.5.1</strong> without impacting existing data ingestion, we adopted the approach outlined in the diagram below:</p><p>· Setting up a parallel Amazon MSK cluster on our AWS account with VPC connected to ours via ENI.</p><p>· Upgrade Kafka client libraries ( v2.5.1) on producers and consumers.</p><p>· Implement 2-way SSL for all connections to MSK.</p><p>· Set up parallel producers and consumers for testing in lower environment.</p><p>· Set up parallel consumers for managing production cutover with no data loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7eJXnZA0KRFC9bDNMlCeg.png" /></figure><h3>Implementation Summary</h3><p>Besides the obvious changes of updating the client library to be compatible with the target Kafka version, we covered following aspects:</p><p><strong>Security</strong></p><p>We covered security at three different levels:</p><p>· <strong>Network</strong> : Rules that allow connections from security groups corresponding to known producers and consumers.</p><p>· <strong>Encryption in transit</strong>: 2- way SSL for all connections to MSK with server chain in <strong>ACM-PCA</strong> (Amazon Certificate Manager -Private Certificate Authority) and client certs in a location accessible to our ci/cd pipeline.</p><p>· <strong>Encryption at rest</strong>: Ensured data at rest is encrypted with custom encryption key stored in KMS.</p><p>Below is a view into the adjusted ci-cd pipeline to handle client keys for 2-way SSL</p><p><em>Updated pipeline — Consumers</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yjl_nSC7_n0yP7pfENwJfg.png" /></figure><p><em>Updated pipeline — Producers</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbE2A73qX01iSNVCTWSfGw.png" /></figure><h3>Amazon MSK provisioning with Terraform</h3><p>With the goal of automating, creating, and updating the MSK cluster, we decided to use Terraform, primarily due to Terraform being generic and cloud provider agnostic.</p><p>Here is a view into our pipeline for automation:</p><p>(PS: It took about <strong><em>40</em></strong> minutes for our prod MSK cluster to come up with this automation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yjeyh45aEAg0-WPbL9d9lg.png" /></figure><h3>Monitoring &amp; System Telemetry</h3><p>Although Amazon MSK does come with a basic monitoring setup, it was not enough for our needs because we required more details. Instead, we decided to use an inhouse monitoring set up to export the metrics, feeding into the existing Prometheus to have multiple Grafana charts covering data movement and the Kafka system.</p><p>Example — <em>Kafka producer requests, topic wise</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHCn2GcXtcuVnxkXfsMbEw.png" /></figure><p>We built charts/alerts for</p><p>· Bytes In Per Sec</p><p>· Bytes Out Per Sec</p><p>· Bytes Rejected Per Sec</p><p>· Partition Counts per Broker</p><p>· Under Replicated Partitions per Broker</p><p>Example — <em>System health metric ( CPU)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eZQPpy-sccCROYU7yf-LA.png" /></figure><p>We built charts for other key metrics such as</p><p>· Available Filesystem Bytes per Broker</p><p>· Network Request Rate per Broker</p><p>· Error Rate per Broker</p><p>· Zookeeper Request Latency</p><h3>Testing covering Application and Performance</h3><p>To ensure there was no loss of functionality and that our partners were continuing to get current or better performance levels, we covered a range of tests.</p><p>· <strong>Functional Tests</strong>: We covered all data ingestion source/scenario combinations into Postman runner and externalized the environment configurations. The runners were executed after build/fix cycles with verifications to confirm that the intended payloads reached the target data lake.</p><p>· <strong>Performance Tests</strong>: We executed performance tests like 2x, 3x etc. using the Gatling load test tool triggered via Gitlab. Tests include combination of soak and load with consideration for 2-way SSL connections.</p><p>Our observations</p><p>· <strong>Horizontal scaling observation</strong>: (<em>increasing/decreasing the count of MSK brokers</em>) The process to create new brokers took longer (about 20–30 min). We observed that new topics got distributed across MSK cluster, however older topics prior to horizontal scaling had to be adjusted manually. We used the Reassign partition tool to redistribute existing topic partitions over new broker nodes</p><p>· <strong>Vertical scaling observations</strong>: (<em>moving to bigger instance type with same count of broker nodes</em>) In this case, brokers are updated in sequence. The incoming rate decreases slightly for a short period while the brokers are being updated. The replication rate shows significant dips during broker updates. While under heavy load JMX response times from the brokers can go as high as <strong>15s</strong>. After the updates were done, we noticed that the message ingestion rate increased and CPU Utilization decreased.</p><p>· <strong>Vertical downscaling</strong>: (<em>going to smaller instance type with same count of broker nodes</em>) While this should not be a common scenario for well forecasted throughput increases in production, it is a thing. And the general recommendation is to consider downscaling only when the CPU load is less than 30%. Based on the current instance types that Amazon offers, it appears the CPU factor changes by the factor 2. For example, if the current CPU is 60% and we downscale to the next smaller instance type for MSK, CPU could be in the range of 110–120 %.</p><p>· <strong>EBS storage volume scaling</strong>: This can be scaled independently of the brokers. There is also an out of the box auto scaling feature to auto-expand your broker storage at a specified storage utilization target. PS: storage size cannot be decreased</p><p>· <strong>Plaintext vs 2</strong>-<strong>way TLS</strong>: We observed that the ingestion rate dropped by 20–30% using 2-way SSL and CPU increased by about 15–20% with no significant change in message lag. So, it’s good to keep this in consideration when sizing MSK cluster.</p><p>And that led us into MSK sizing. Hang in there; we are getting closer to the Kafka upgrade in production 😊</p><h3>MSK Production cluster sizing</h3><p>Amazon provides a <a href="https://amazonmsk.s3.amazonaws.com/MSK_Sizing_Pricing.xlsx">Sizing Tool</a> which can be used to estimate size based on traffic (IO). We used this tool to calculate preliminary numbers. The final numbers were established based on the legacy Kafka setup, anticipated throughputs in near future, and our performance test outcomes.</p><h3>Detailed cutover planning and execution</h3><p>One of the important phases is to establish a clear cutover plan in production. Possibly test the plan at lower scale in a non-production environment. Our main goal was not to lose any data being ingested and not to impact our partners and data users. So, we ended up setting up parallel consumers for MSK (besides existing consumers from legacy Kafka) and during cutover moved producers to point to MSK. Our production cutover went smoothly, and we were very happy with the results.</p><h3>Few good takeaways, things to consider:</h3><h4>Partitioning for high throughput topics</h4><p>After the migration, we noticed consumer lag grew on certain topics as we got more data for those topics. So, we increased the partitions on the top 10–15 traffic heavy topics and within about an hour the consumer lag dropped to within a few seconds.</p><p>So, the backstory on this: Topic partition is the unit of parallelism in Kafka. Writes to different partitions can be done in parallel on the producer and broker side. However, on the consumer side, Kafka always gives one partition’s data to one consumer thread. So, the degree of parallelism within a consumer group is kind of bound by partitions being consumed. Our observation is that more partitions in Kafka cluster lead to higher throughput. There is no right number per se, it depends on the throughput of topic and the number of consumers in the setup.</p><h4>Key Configurations we looked at -</h4><p>While most of the Amazon MSK defaults serve well, we explored a few useful configurations and adjusted to our needs:</p><p>· <strong>default.replication.factor</strong>:</p><p>· <strong>log.retention.hours:</strong></p><p>· <strong>unclean.leader.election.enable: </strong><em>This is an important setting</em>: If availability is more important than avoiding data loss, ensure that this property is set to true. If preventing data loss is more important than availability, set this property to false. This setting operates as follows:</p><p>o If set to true (enabled), an out-of-sync replica will be elected as leader when there is no live in-sync replica (ISR). This preserves the availability of the partition, but there is a chance of data loss</p><p>o If set to false and there are no live in-sync replicas, Kafka returns an error and the partition will be unavailable</p><p>· <strong>offsets.topic.replication.factor: </strong>Typically set higher to ensure availability</p><p>· <strong>offsets.retention.minutes: </strong>Allows to move the offset back to the beginning if it isn’t changed within a set period of time. This is particularly useful in case all consumers go down. Not a common situation but good to consider</p><p>· <strong>replica.lag.time.max.ms: </strong>Determines the time period that an in-sync replica can fully catch up with the leader. This property is particularly useful if there is a spike in traffic and large batches of messages are written on the leader, unless the replica consistently remains behind the leader for replica.lag.time.max.ms, it will not shuffle in and out of the ISR. This in turn helps in improving the resiliency of the system.</p><h3>Our Kafka upgrade journey completed</h3><p>We have been running on Amazon MSK for Kafka for over a month now and our partners are happy. Actually, they didn’t even realize this upgrade happened. And they would have never found out if not for our partner, the D3 team, who notified them.</p><p>We hope you enjoyed reading about our Kafka upgrade journey from a couple generations behind self-managed infrastructure to a managed service that reduced our cognitive load on our operations team, while increasing security and unlocking newer features.</p><p>Keep in mind that not all data ingestion systems are built the same. So what we did as part of our journey may not fully apply to all situations. Some measures could be excessive for relatively simpler needs while some features should be more fully explored.</p><p>Good luck with whatever brought you here to this topic. Happy to get better and learn about your experience. So please consider sharing your feedback and comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c3bdbfc63db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tmobile-tech/kafka-upgrade-a-hassle-free-journey-5c3bdbfc63db">KAFKA UPGRADE — A HASSLE FREE JOURNEY</a> was originally published in <a href="https://medium.com/tmobile-tech">T-Mobile Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Humans in the Loop: Using AI to Get Big Tasks Done Fast]]></title>
            <link>https://medium.com/tmobile-tech/humans-in-the-loop-using-ai-to-get-big-tasks-done-fast-ea334418d3e9?source=rss----e283d0ff239a---4</link>
            <guid isPermaLink="false">https://medium.com/p/ea334418d3e9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[customer-service]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[industry]]></category>
            <dc:creator><![CDATA[Peter Baldridge]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 17:21:39 GMT</pubDate>
            <atom:updated>2020-08-05T17:44:06.345Z</atom:updated>
            <content:encoded><![CDATA[<p>Peter Baldridge, Data Scientist at AI@T-Mobile</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3Lsbgo6hZqo6UlmM37p7A.png" /></figure><p><strong>Picture This:</strong></p><p>You and your team just spent two weeks collecting survey data. You now have thousands of responses including a bunch of free-form text answers. You look in your inbox and see an email marked “important.” It turns out executive management would like to see a report on the survey in three days. 😨</p><p>So what do you do?</p><p><strong>Scenario A)</strong></p><p>You hire a fleet of consultants to clean, label, and organize your free text responses. The process costs tens of thousands of dollars, but you get your results back in two days instead of three. Plus, they throw in an extremely polished PowerPoint deck.</p><p><strong>Scenario B)</strong></p><p>You call a data scientist. 😎</p><p><strong>The Opportunity:</strong></p><p>Every year, T-Mobile conducts an enterprise fraud risk assessment. Part of the assessment is to send a survey to several thousand employees. The survey contains multiple choice questions as well as free text questions. Processing multiple choice questions is easy but processing the free text responses is not. Each comment must be hand-labelled according to its risk category before a summary can be generated.</p><p>You could label these comments one-by-one, but that approach would be very time-consuming (not to mention boring). Or you could figure out a way to do it faster…🏃‍♀️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*OQqY3wj6MmMzKXl-c56i_g.jpeg" /></figure><p><strong>The Approach:</strong></p><p>In principal, we want to bucket similar survey responses so that our fraud managers can label them in one fell swoop.</p><p>To do this, we need to create a similarity score for each pair of survey responses. If we do it the right way, phrases such as, “T-Mobile is great,” and “T-Mobile is awesome” will be considered similar.</p><p><strong>TF-IDF and Cosine Similarity:</strong></p><p>TF-IDF, which stands for term frequency — inverse document frequency is way to vectorize documents by highlighting unique keywords (<em>iPhone, Galaxy, Pixel</em>) while downplaying common words (<em>the, of, from</em>). It’s a way of bringing the most important information to the surface, almost like sifting for gold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmqArA3zCGNYSZ6h1STsYQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZzJO_Q1IGeKlyd4mMaV9A.png" /></figure><p>Next, we calculate similarity scores for each pair of phrases by looking at the angles between different vectors. The key idea is that similar phrases will also be closer in space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*C6Tsk7cao38ST6gC0_y-Iw.jpeg" /></figure><p><strong>Hierarchical Clustering (with Maximum Linkage):</strong></p><p>Finally, we bucket our responses. We use hierarchical clustering for this step, and more importantly we used <em>complete linkage</em> to ensure that there is some minimum degree of similarity between each pair of responses within each cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*DlYjaVk2_5B6H6qkk6QDCQ.png" /></figure><p><strong>The Results:</strong></p><p>By bucketing our survey responses, we were able to fit 2,649 survey responses into 110 buckets. <em>That’s an improvement of more than 95 percent! </em>😲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*i07U7LuYWNEBAxlt_RIAJw.png" /></figure><p><strong>What the Risk Management Team Found:</strong></p><p>The Risk Management team was able to make the labelling process even more efficient. They did it with a couple of ingenious tricks.</p><p><strong>Clustering ²:</strong></p><p>In many cases there were several clusters related to the same category. Sorting in different ways as well as adding some rudimentary Excel formulas for certain keywords allowed the team to label several clusters at once. They were also able to easily identify exceptions.</p><p>To put it another way: they clustered the clusters.</p><p>🤯</p><p><em>We know what you’re thinking</em></p><p><strong>Information-Rich vs. Information-Poor Responses:</strong></p><p>The audit team found that there were a lot of survey responses but not a lot of <em>meaningful</em> responses. During previous years, responses had to be manually tagged one-by-one (often with errors). The Fraud Management team found an ingenious way to separate information-rich responses from information-poor responses. Here’s a quote from Jonathan Arras, T-Mobile’s Director of Fraud Strategy about how he tackled the issue:</p><p><em>“I ran through a sample of about 50 records and personally evaluated what I believed the significance of each comment to be. Then I calculated the number of characters in each cell and without looking at my manual results drew some significance cuts based on word count. The results of each approach were almost identical and while it may seem crude to say “number of words = significance” it really did prove out and automating the rest of the counting/labeling took just seconds after that.”</em></p><p>In effect, he created a classifier for identifying information-richness of a response based on response length alone.</p><p><strong>TL;DR</strong></p><p>The Fraud Management team could have simply taken our results and called it a day. But instead they applied their own understanding of both the domain and analytics to make the process even faster.</p><p><em>Data scientists: I think the lesson here is that there’s really no substitute for proper domain knowledge. Data science can only take a problem so far. But when you combine analytical techniques with proper domain knowledge: that’s when you unlock a solution’s full potential!</em></p><p><strong>Other Interesting Findings:</strong></p><p><strong>ELMo and Bert:</strong></p><p>We love using new tools as much as the next team! We tried using ELMo or BERT as opposed to TF-IDF, but neither embedding structure worked as well as our TF-IDF embeddings.</p><p>We suspect that this is because we were using pre-trained ELMo and BERT embeddings. Had these embeddings been trained on a T-Mobile vocabulary, they may have done much better. It just goes to show how powerful the classical tools are, especially in a pinch.</p><p><strong>Fat-Tailed Distribution:</strong></p><p>Interestingly, bucket sizes followed a fat-tailed distribution. This is a common phenomenon in <a href="https://en.wikipedia.org/wiki/Pareto_distribution">nature</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*n4lg4ywzX6eSp047ONUA8Q.png" /></figure><p><strong>Citations:</strong></p><p><a href="https://en.wikipedia.org/wiki/Gold_panning#/media/File:Gold_panning_at_Bonanza_Creek.JPG">https://en.wikipedia.org/wiki/Gold_panning#/media/File:Gold_panning_at_Bonanza_Creek.JP</a>G</p><p><a href="https://stackoverflow.com/questions/40716459/choice-between-an-adjusted-cosine-similarity-vs-regular-cosine-similarity">https://stackoverflow.com/questions/40716459/choice-between-an-adjusted-cosine-similarity-vs-regular-cosine-similarity</a></p><p><a href="https://commons.wikimedia.org/wiki/File:Swiss_complete.png">https://commons.wikimedia.org/wiki/File:Swiss_complete.png</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea334418d3e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tmobile-tech/humans-in-the-loop-using-ai-to-get-big-tasks-done-fast-ea334418d3e9">Humans in the Loop: Using AI to Get Big Tasks Done Fast</a> was originally published in <a href="https://medium.com/tmobile-tech">T-Mobile Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FinOps at SMPD]]></title>
            <link>https://medium.com/tmobile-tech/finops-at-smpd-db7c9646bac5?source=rss----e283d0ff239a---4</link>
            <guid isPermaLink="false">https://medium.com/p/db7c9646bac5</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[t-mobile-tech]]></category>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Olivier D'hose]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 20:48:16 GMT</pubDate>
            <atom:updated>2020-07-06T23:57:24.871Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cloud resources are free… until they are not.</h3><figure><img alt="Banner" src="https://cdn-images-1.medium.com/max/468/1*tQKAVLVi9c1O5vxK5FoV2Q.png" /><figcaption>FinOps — Joel Marchand</figcaption></figure><p>Cloud computing is amazing. Resources of all sizes and shapes can be provisioned with a few commands. But at the risk of using a tired trope, with great power comes great responsibility, or at least great cost. My team saved Cloud costs by 40% while doubling our infrastructure by adopting FinOps principles articulated around four tenets. In this blog, I will introduce our process.</p><h3>Some Background:</h3><p>The Social and Messaging Product Development (SMPD) team lives within T-Mobile’s contact center organization. Our mission is to develop tools and experiences empowering customers to have the best and most effective interactions with T-Mobile over asynchronous communication modes (such as messaging or social networks). We build tools and a platform used by Customer Care experts to accelerate and optimize every contact with our customers.</p><p>Our application landscape is organized around an increasing number of microservices, running in containers orchestrated by Kubernetes and augmented by a collection of Amazon Web Services products for data persistence, streams management, encryption, etc.</p><p>Within SMPD, my team is focusing on creating and maintaining the platform, tools and guardrails allowing the product teams to innovate, disrupt and optimize business flows with increasing speed and quality. This team is known as the Engineering Efficiency team or E2. As the custodian of the infrastructure and platform, the E2 team took on the responsibility to introduce FinOps principles as part of the quality markers for each SMPD product. So even as our portfolio of products and services continues to grow and change, the E2 team is focusing on maximizing resource utilization by identifying and reducing waste while remaining on the leading edge of technology innovation.</p><p>These principles were put to the test during a recent project to achieve multi-region resilience. More on that later…</p><h3>To bootstrap our FinOps responsibilities, we organized four focus areas:</h3><p>1. Increase cost awareness across the whole organization (and make it fun!)</p><p>2. Provide automated guardrails for resources creation and management.</p><p>3. Reduce waste by adopting ephemeral environments principles.</p><p>4. Create cost modelling tools at design time.</p><h3>1. Making cost awareness fun</h3><p>The first step in our FinOps journey is to make the actual cost of services available to all. True to the spirit of the DevOps model, the operational responsibilities for a product lies fully with the team that creates the product. As such, it is important to make the cost of running a product completely transparent. The T-Mobile Cloud Center of Excellence (CCOE) provides each team using cloud resources a detailed report on the cost of running every aspect of our applications. From the CPUs and memory to network connection cost, the information is available in nearly real time. This invaluable tool is too often only available to comptrollers and management. We decided to provide that information to everybody inside the team. Awareness is the greatest tool to ensure the rightsizing of resources. This has become a part of our operational review of our applications. Every month, the E2 team reviews the numbers provided by the CCoE and presents them to the different product teams with suggestions on potential optimization opportunities.</p><p>To increase the participation of the product teams, we have also taken a page out of the gamification playbook. We regularly create contests between teams to achieve some widespread goals for the platform. For example, we needed the team to right-size the provisioning of the Kubernetes pods resources. Our goal was for each container to use 60% of assigned memory as a baseline for provisioning. Creating a leaderboard showing how each team’s portfolio met that goal increased awareness while tickling their competitive streak. It is a simple but very effective solution to ensure the teams’ participation.</p><figure><img alt="Resources utilization dashboard." src="https://cdn-images-1.medium.com/max/468/1*xwyxELdunAYRTanaYtojbw.png" /><figcaption>Gamified Resources Utilization Dashboard</figcaption></figure><h3>2. Guardrails for resource creation and management</h3><p>In SMPD, we strongly believe in bringing the decision-making process as close to the individual as possible. However, there are some requirements that are larger than the team. Security standards are a good example. To achieve adherence to organizational standards, the E2 team is designing automated guardrails that implement the patterns necessary for compliance without additional burdens on developers. Our CI/CD pipeline is a constantly evolving product designed to implement standards when they are needed. For example, the pipeline enforces naming conventions and tagging requirements on resources. And when automation is not possible, documentation starting with the “why” of a pattern is available for constant reference. We have affectionately named our documentation system E2Pedia. If the code does not meet our documented standards, the pipeline fails the build and prevents the deployment.</p><h3>3. Ephemeral environments</h3><p>With the resource creation and management guardrails in place, we move a step closer to ephemeral environments. One of the promises of the Cloud is the ability to create and destroy resources as needed. The ability to create, let’s say a Redis cluster, with a few mouse clicks is truly a game changer when it comes to designing disruptive products. Destroying that Redis cluster when done however seems to not generate the same level of glee. It is also not in the Cloud providers’ business model to encourage us to clean up after ourselves. My parents would be proud. Our team is moving towards a completely ephemeral provisioning model. Every Cloud resource required is created upon requests by the CI/CD pipeline and destroyed either on schedule or with the click of a button. This ensures that resources are only created for as long as they are needed. This seems like an obvious habit to implement but it does require us to declare all the infrastructure needed by an application with the application itself. Adopting the principles of “Infrastructure as Code” and empowering every developer to declare what resources is needed is a critical step in managing our cloud resources efficiently.</p><h3>4. Cost modeling tool at design time</h3><p>The next step in our FinOps initiative is to provide a cost modelling tool at design time. While we do not advocate for cost to be the sole or even a major design consideration, providing knowledge of the impact of those decisions helps shape better design decisions. The tool models the cost of the infrastructure required to run the service through a short survey. For example, a new application might require 4 new microservices deployed over 35 Kubernetes pods. Each pod is provisioned with 500 minutes of CPU time and 256 MiB of memory. The application also uses a couple DynamoDB tables and Kafka for streaming. Based on the information collected, we provide a strawman of the costs associated with running the application. The results can be saved for side by side comparison with different configurations. This information can also be compared with the results of some more rigorous performance testing to validate the design assumptions. This tool is still a work in progress. The feedback we gather from the different teams will make it more accurate over time. Data driven decisions make for better decisions.</p><h3>Walking the talk:</h3><p>One of our team’s initiatives for 2020 is to improve the resilience of our applications by distributing our services across multiple cloud regions and follow an active/active traffic distribution pattern. This meant duplicating our infrastructure and supporting cloud services. To validate our FinOps principles, we set a goal to be fully geo-redundant without increasing our cloud budget for the year. Six months into the year, the current forecast has us achieving that goal!</p><h3>Conclusions:</h3><p>Managing the costs associated with an application portfolio is rarely a pre-occupation of a traditional development team. We believe however that bringing the attention of the whole team on the financial aspects of software development empowers us to make better, more conscious decisions about the design, management and maintenance of our products. FinOps is a process complementary to any good DevOps team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db7c9646bac5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tmobile-tech/finops-at-smpd-db7c9646bac5">FinOps at SMPD</a> was originally published in <a href="https://medium.com/tmobile-tech">T-Mobile Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retraining is the Only Constant, or, The [Machine] Learning is Never Done]]></title>
            <link>https://medium.com/tmobile-tech/retraining-is-the-only-constant-or-the-machine-learning-is-never-done-28e386cf763d?source=rss----e283d0ff239a---4</link>
            <guid isPermaLink="false">https://medium.com/p/28e386cf763d</guid>
            <category><![CDATA[dataops]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mark Eric Hanson]]></dc:creator>
            <pubDate>Wed, 13 May 2020 16:51:15 GMT</pubDate>
            <atom:updated>2020-05-13T16:51:15.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwxqD0cslcZ_MpVC_6XSwg.jpeg" /><figcaption><a href="https://www.flickr.com/photos/59318060@N04/9049769218">“Staircase”</a> by <a href="https://www.flickr.com/photos/cokedragon/">Colin Tsoi</a> is licensed under <a href="https://creativecommons.org/licenses/by-nd/2.0/?ref=ccsearch">CC BY-ND 2.0</a></figcaption></figure><p>In <a href="https://opensource.t-mobile.com/blog/posts/r-tensorflow-api/">previous posts</a>, <a href="https://medium.com/@skyetetra">Jacqueline</a> and <a href="https://medium.com/@heathernolis">Heather</a> from <a href="https://opensource.t-mobile.com/blog/posts/r-tensorflow-api/#who-we-are">my team</a> described how we were able to go from exploratory analysis and modeling in R to production inference services <a href="https://medium.com/tmobile-tech/using-docker-to-deploy-an-r-plumber-api-863ccf91516d">in R using docker containers</a>. Net — less rework and less opportunity for error than our other alternatives and shorter cycle times to boot! Data Scientists and DevOps are both happy and that’s a huge win.</p><p>We’re applying ML at scale to support on-going mission critical activities. So what’s missing from what we’ve described so far? End users and change over time.</p><p>Our business changes, our customers change, and our end users’ needs change. The predictions of our production-deployed R services (and the functionality based on those predictions) have to change right along with them or the products we provide will quickly be discarded. This first became critical for us with a model we had to retrain at least daily. As we have described our patterns so far, the models themselves are built into the container (as rds files, h5 files, or other R-friendly mechanisms), requiring redeployment for a model change. This is somewhere between inefficient and untenable for a model that changes daily.</p><h3>First, a word from our lawyers!</h3><p>The code in this blog may need to be modified for your own environment. We will make our best effort to update but we make no guarantees on that. It goes without saying, but you are responsible for respecting the data you use and ensuring best practices for cybersecurity. In general, before using in production, please have your internal IT department (if they exist) review your code and your data. They know your environment better than we do, and we are not in a position to provide general support. In legalese, “Use is AS IS and without warranty.” Your IT department (if they exist) should be aware of the open source licenses for some of these tools. Note that different departments have different policies about open source.</p><h3>Motivation</h3><p>First a little context to provide the motivation. One of our products for our Customer Care organization automatically surfaces internal wiki articles (among other information and resources) based on the content of a conversation, the state of the customer, and the usage history of other agents in similar conversations. We use a variety of ML models operating in real-time with the conversation to select what content to present.</p><p>One of those models uses conversation text and other data to predict which internal wiki articles will be useful to an agent at any point in a conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxcJs56pbYWIjY7kXlM1iw.jpeg" /><figcaption>A customer care conversation and tool view with recommended articles on the lower right</figcaption></figure><p>As this is a wiki, both the content and usage change over time. Just as important — net-new content is introduced before applicable cases arise (for example content about new products, services, and offers). New content, changed content, and changes in usage patterns can each give rise to situations where today’s useful content predictions will be irrelevant (or at least sub-optimal) tomorrow.</p><p>If this were a simple database query, we’d change the data in the database and move on. It is not, however; it is a model trained on a combination of article text, customer conversations, and agent usage information. Some form of recurring retraining is required. In the case of the wiki model, we aligned to the potential publication of net-new information. That is generally a daily process so a daily retraining is where we started.</p><h3>Automated Retraining and Production Deployment</h3><p>Ideally, we want to train the model off line then deploy it such that the running R services can pick up the new models on the fly. That is exactly what we’ve done.</p><p>There are more than a few concerns that might arise. These include:</p><ul><li>In what form do we store the models?</li><li>Where do we store the model info that is both cost efficient and readily accessible to our R services?</li><li>How do the R services know a new model is available?</li><li>How do consumers of the model output know what version of the model a given result was based on?</li><li>How do we automate the retraining in a robust and reliable way?</li><li>What is the impact on performance of reading the new model on the fly?</li></ul><h3>The form of the models</h3><p>Keeping with our preference for simple approaches (<a href="https://quoteinvestigator.com/2016/07/17/solution/">or at least as simple as the problem allows</a>), we kept the form of the model unchanged. That is, if the Data Science team built an R service that relies on model data stored as rds files, we used rds files. If it relies on h5 files, we use h5 files.</p><h3>Where to keep the models?</h3><p>Many of our services run on AWS. As such at least two options leap to mind with which the team is familiar: DynamoDB and S3. We went with s3 for cost and simplicity. DynamoDB is a key part of our ecosystem, but nothing about our use case here called for more than simple storage.</p><h3>How do the running services know there is a new model?</h3><p>Again, keeping it simple we have the R services reload the then-current model info from S3 when servicing an REST call if it has been longer than a configured interval since the last model load. Currently, the models are reloaded on receipt of the first REST call at least 3600 seconds after the model was last loaded.</p><h3>How do model consumers know the version of the model used for any given result?</h3><p>Ok, so perhaps it wasn’t just simple storage we needed. S3 allows us to turn on object versioning. <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/AddingObjectstoVersioningEnabledBuckets.html">With versioning enabled, S3 assigns a unique version id to our model when we store it</a>. When we <a href="https://www.rdocumentation.org/packages/aws.s3/versions/0.3.12.1/topics/s3saveRDS">retrieve</a> the model, <a href="https://github.com/cloudyr/aws.s3/blob/master/man/head_object.Rd">we also retrieve the version (the x-amz-version-id property)</a>. The R services include that value as metadata along with the inference result itself.</p><pre>library(aws.s3)<br> <br> ...<br> <br>     model_info &lt;- s3readRDS( <br>       object = paste(<br>         config$model_key,<br>         &#39;model_info.rds&#39;,<br>         sep = &#39;/&#39;<br>       ),<br>       bucket = config$bucket_name<br>     )<br>     <br>     response &lt;- head_object( <br>       bucket = config$bucket_name, <br>       object = paste(<br>         config$model_key,<br>         &#39;model_info.rds&#39;,<br>         sep = &#39;/&#39;<br>       )<br>     )<br>     <br>     version &lt;- attr(response, &quot;x-amz-version-id&quot;)<br>     version_timestamp &lt;- attr(response,&quot;last-modified&quot;)</pre><h3>How do we automate the retraining in a robust and reliable way?</h3><p>In our environment, the periodic retraining of these models is not optional. It cannot rely on an engineer invoking a command or a cron job on a single EC2 instance. Enter the <a href="https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/">Kubernetes CronJob</a>!</p><p>We use K8s CronJobs to run the model retraining and allow K8s to handle providing a robust implementation periodic invocation.</p><h3>What is the impact on performance of reading the new model on the fly?</h3><p>Finally, you might say “That’s all great, but can you do it and still meet your latency requirements for model inference REST calls”? Good question!</p><p>One model we have externalized this way has a regular performance that looks something like this across peak traffic periods (excluding model reloads). Note I’ve taken these metric snapshots during the COVID19 crisis and core operating hours for the systems involved are 11:00 to 02:00 UTC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5DuX2tBdgxznmyDV7s5Pg.png" /></figure><p>95% of all queries returning in under 250 milliseconds is well within acceptable range for the service in question. That would be true of the p99 as well except for that spike near 11:30. More on that spike in a moment.</p><p>On to the impact of dynamically loading new model data!</p><p>First, of course, we try not to reload models during core operating hours. Our K8s CronJob lets us reload at 08:00 UTC the services are least used (and when almost all of our team has packed it in for the day). What does the performance look like then?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgvAbRUKJvkfgAJOV2UQXg.png" /></figure><p>While core operating hours are limited, there are still queries being serviced even when we do our reloading, so there is some data to look at. A few things to note here.</p><ul><li>The y-axis is logarithmic (base 2) to show detail.</li><li>p75 stays within normal bounds (less than 250ms).</li><li>p95 stays mostly but not entirely below the 350 ms mark as well.</li><li>p99 does show spikes over the course of a few hours. Let’s look at that a bit more.</li></ul><p>To be sure, sustained response times greater than half a second would be a problem (never mind 4 seconds!). However, these aren’t sustained. 75% of cases stay within the normal bounds. Even the 95% line stays close for most of the period. It is worth noting that traffic levels are quite low, as well, so a single slow response constitutes a greater fraction of total traffic than it would at peak. At 08:10, there are about 20 calls per minute versus the 2000 calls per minute during core hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcUyBoKLEzpovh82G-okvQ.png" /></figure><p>What drives those spikes in response time? Reloading the model, of course.</p><p>Why do the spikes go from approximately 08:00 up to that spike at 11:30 we noticed earlier? Reloading happens when 2 conditions are met. First, it has been at least an hour since the model was last loaded. Second, the service instance in question receives a REST call to process. In the worst case, an instance loads the previous model moments before it is replaced and then it waits the longest possible time to be load-shared a REST call to handle. As traffic is between 1% and 25% of peak until 11:30, that can be quite a wait.</p><h3>Where do we go from here?</h3><p>Even if this were a perfect solution (it isn’t), the world changes and it would not remain perfect long. So what are some of the backlogged items for us in this area?</p><ol><li>We would like to have a better model versioning solution that ties in with our requirements management, source control, and artifact repository systems. The s3 object version number works, but the lack of metadata and isolation from the rest of our environment poses a real challenge. To name just one — tracking down training data for a given model version means working backwards through logs and reconstituting the source data as it was at the time. That isn’t always possible. This is one of several reasons we’re looking at MLflow, Kubeflow, and others. More on that another time.</li><li>For the wiki content model mentioned in this article, a daily retrain is good enough (so far). In other cases, we would benefit from greater flexibility. Some problems have more volatile behavior potentially requiring retraining more frequently. Some training is more expensive than others, as well, so increasing the frequency of periodic retraining is too costly. We’re working on triggering retraining based on metrics we collect and automated A/B testing of model versions in addition to the periodic approach described above.</li></ol><h3>Wrapping Up</h3><p>With the successful production operationalization of inference services in R, we faced the need to update the underlying models with minimal disturbance to production. In particular, our recommendations of internal wiki content depend on timely incorporation of usage information as well as incremental and net-new content. To address this, we externalized the models themselves to S3 and changed the inferences services to periodically reload. We then put the training and model publication processes into reliable Kubernetes CronJobs and pushed “go!”. There are performance impacts when model reloads take place, but they are short lived and can be timed to coincide with low-usage periods for the services in question.</p><h3>Enough about us…</h3><p>Have you faced similar situations? How have you solved them? I would love to hear about it! Let us know in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28e386cf763d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tmobile-tech/retraining-is-the-only-constant-or-the-machine-learning-is-never-done-28e386cf763d">Retraining is the Only Constant, or, The [Machine] Learning is Never Done</a> was originally published in <a href="https://medium.com/tmobile-tech">T-Mobile Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Small data, big value]]></title>
            <link>https://medium.com/tmobile-tech/small-data-big-value-f783ceca4fdb?source=rss----e283d0ff239a---4</link>
            <guid isPermaLink="false">https://medium.com/p/f783ceca4fdb</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[customer-experience]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Jacqueline Nolis]]></dc:creator>
            <pubDate>Mon, 18 Nov 2019 19:41:01 GMT</pubDate>
            <atom:updated>2019-12-03T18:37:34.074Z</atom:updated>
            <content:encoded><![CDATA[<h4>How simple and quick machine learning projects can beat out massive technology investments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftOvmkYxrze-x57_2weuSQ.png" /></figure><p><strong>(Hate reading? Head straight to the </strong><a href="https://secure.message.t-mobile.com/v1/shiny/is-customer/app/"><strong>demo</strong></a><strong> and test the model yourself!)</strong></p><p><em>This post was coauthored with Joel Werdell, a Principal Product Manager at T-Mobile.</em></p><p>Machine learning journalism focuses solely on massive endeavors: giant datasets being loaded into intensive computing machines and months of work to produce results. When the only stories told are ones of massive budgets and GPU clusters that use a town’s worth of power, it creates a belief that for machine learning to be effective it needs to be a Grand Investment That Will Change the Business. But this is ridiculous! Just like you don’t need to be a bonafide tech company to create software, you don’t need to undergo a massive machine learning transformation to meaningfully drive your business using AI. Models can be created and used in small ways that provide simple victories for companies, immediately lowering risks and costs.</p><p><em>This blog post is the story of one such project at T-Mobile.</em></p><p>At T-Mobile, many people prefer to connect to us through text-channels such as text messages, Twitter, and messaging through the T-Mobile app. The people who message us may be T-Mobile customers interested in topics like how to upgrade a phone or pay a bill. They also may not yet be a customer and want to switch to T-Mobile, so they are looking to have a conversation about joining.</p><p>As we looked for ways to improve the messaging experience, we noticed that lots of conversations had an initial message from the person with a question in it like: “how much to switch 4 lines to T-Mobile?” or “how do I get Netflix on my account?” Our messaging software would respond to customers by asking: “are you a customer?” This was absolutely absurd, since the text of the customer’s question usually answered ours — for instance someone asking about changing their plan is clearly a customer. It seemed like a problem a computer should be able to solve, so we set out to do it. The AI @ T-Mobile team immediately dived in to make this better.</p><p>Thankfully, we had a great set of training data for a machine learning model. We had plenty of historic logs from conversations where people messaged T-Mobile, then immediately selected from our UI if they were a customer or not. Each person’s first message would be the input data to the model, and the selection they made would be what our model was trying to predict. Since we had historic logs of conversations and people’s customer selections (with customer data removed), we were in great shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5aWfH9t1_EZPJC92CJ7oQ.png" /><figcaption>An example of a message a person sent to T-Mobile and the picker the person selected their choice from.</figcaption></figure><p>Since the data was a set of strings (the messages) for the input and a yes or no variable (if they selected customer) for the output, the data was not large in size per data point. Further, the amount of data points we ultimately needed for the model was in the tens of thousands range, not the millions range. All together, this meant that we could make a machine learning model without having to worry much about big data.</p><p>We decided to train a neural network model on this data. Neural networks are especially well suited for text input since they can easily parse the sequence of words in the text. By using a neural network approach we could trust that the model would be able to find the important parts of the message and we didn’t have to spend time engineering features like we would with a different type of model. Neural networks are built on layers of nodes, where each layer provides a different function for the overall model. Out network had three key layers:</p><ol><li><strong>An embedding layer.</strong> This layer places the words in a small-dimensional space so that similar words in the message are treated similarly by the model (like “payment” and “payments”)</li><li><strong>A convolution layer.</strong> This layer creates features out of sets of five words in a row. By doing so it looks for important phrases in the message (like “pay my bill”)</li><li><strong>A dense layer.</strong> This layer reduces the network down to a single number which is used as the probability for the person being a customer.</li></ol><p>We used R to train the model with the Keras and TensorFlow packages for training the neural network. Since our model was only three simple layers we were able to be quickly train and test it. We left a test set of messages out of the training data to validate the model worked well enough for our messaging channels.</p><p>We then deployed our R neural network as an API in a Docker container. By using Docker containers with the T-Mobile standard engineering pipeline our model was soon put into production and helping people get routed faster. For an introduction to R in production check out our <a href="https://medium.com/tmobile-tech/r-can-api-c184951a24a3">blog posts</a>, <a href="https://github.com/tmobile/r-tensorflow-api">GitHub repo</a>, and <a href="https://resources.rstudio.com/rstudio-conf-2019/push-straight-to-prod-api-development-with-r-and-tensorflow-at-tmobile">RStudio::conf() video</a>.</p><p>With our tool in place we were able to reduce the number of people who saw the automated “are you a customer” selector by half. This was a great business success, removing a point of friction from the customer experience and getting customers to the experts who can help them faster. At T-Mobile we have the core belief that the customer should come first, and this machine learning model allowed us to drive towards that.</p><p>What’s more interesting than the technical approach we took was the things we <em>didn’t</em> need to successfully launch this product:</p><ul><li><strong>Big data platforms like spark.</strong> Because out data was reasonably sized, we were able to train our models locally rather than having complex platforms.</li><li><strong>Setting up virtual machines with GPUs for training.</strong> The simplicity of the problem meant that training on CPUs was fast enough to be practice, no graphics cards necessary.</li><li><strong>Any feature engineering on the data.</strong> Since the input data was just text, there wasn’t anything to engineer. We fed it into the neural network and saw immediate results.</li><li><strong>Cross-validation and other training techniques.</strong> Doing the traditional method of leaving a small percentage of data out of our model when training to use in testing had almost no impact on performance and got us to market more quickly.</li><li><strong>Fancy retraining methods.</strong> when we looked at the data we found almost no change to it over time. Because of this we didn’t have to worry about auto-retraining or complex deploying strategies.</li></ul><p>By doing without the complexities that most people discuss when they talk about machine learning, we were able to quickly get to market and easily maintain our work. As others look for use-cases for machine learning at other companies, consider what you can do if you limit yourself to simple projects.</p><p>Thanks for reading, and <a href="https://secure.message.t-mobile.com/v1/shiny/is-customer/app/">check out our live demo</a> of the “are you a customer” model to try it out for yourself.</p><figure><a href="https://secure.message.t-mobile.com/v1/shiny/is-customer/app/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMie6UjceYxwih3nHisMCQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f783ceca4fdb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tmobile-tech/small-data-big-value-f783ceca4fdb">Small data, big value</a> was originally published in <a href="https://medium.com/tmobile-tech">T-Mobile Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[loadtest: an R Package for Load Testing]]></title>
            <link>https://medium.com/tmobile-tech/loadtest-an-r-package-for-load-testing-23efeeb370a5?source=rss----e283d0ff239a---4</link>
            <guid isPermaLink="false">https://medium.com/p/23efeeb370a5</guid>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[load-testing]]></category>
            <dc:creator><![CDATA[Heather Nolis]]></dc:creator>
            <pubDate>Tue, 03 Sep 2019 17:37:34 GMT</pubDate>
            <atom:updated>2019-09-03T17:40:31.863Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>By: </strong><a href="https://medium.com/@skyetetra"><strong>Jacqueline Nolis</strong></a><strong> and </strong><a href="https://medium.com/@heathernolis"><strong>Heather Nolis</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*odKrJ8x6jpP0b9zVJIXJlw.png" /><figcaption>I’m R but stronger</figcaption></figure><p>APIs are great! Engineers love ‘em! They’re everywhere! By using packages like plumber in R, data scientists create their own APIs, allowing their models and code to be run by other people (<a href="https://medium.com/tmobile-tech/r-can-api-c184951a24a3">see here for an intro in R</a>). Lovely! But when you release an API, you’re giving people access to your own computing resources. If the code for your API is on a server, too many requests can cause it to fail.</p><p>Failure is really bad. Yes, it hurts to have something you’ve made fall over spectacularly but in software the outcomes have long-term consequences. Releasing new software is–secretly, <em>under the hood</em>–an exercise in building trust with your end users. A single piece of wonky software can sour the relationship with your users forever. Most of us have felt the effects of this ourselves. Quitting a video game because of a bad expansion, switching cloud providers because of buggy implementations, tweeting threads and threads because a UI update ruffles your sensibilities.</p><p>If you develop stuff that doesn’t work, people will remember.</p><p>Take this epic failure. If you were between 18–29 years old back on June 6, 2016, you probably personally remember this catastrophe–the launch of Pokémon GO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*SlGdULNp_tA-WpCjjWaC6A.png" /><figcaption>the cost of fame: a service being totally devastated by its pure virality <em>(source: </em><a href="https://cloud.google.com/blog/products/gcp/bringing-pokemon-go-to-life-on-google-cloud"><em>Google Cloud®</em></a><em>)</em></figcaption></figure><p>Niantic, the company that created the game, had 50 times the traffic that they expected in development. For days after launch, the app was unusable. Sure Pokémon GO was a viral phenomenon, but lots of people stopped using the app immediately after downloading it because of these performance issues–including a coauthor of this very article!</p><p>One quick, easy, cheap way to do avoid these catastophes is to simply apply load yourself before launching your code. Sometimes the best you can do is get your dev buds in a room, hand them a postman collection, and drown in the sound of mouse clicks as everyone wails manually at top speed, desperately hoping they can generate a useful amount of test traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*nlKzqBQl1AVNDxynBIA_7A.png" /><figcaption><em>the authors and their friends load testing before loadtest </em><a href="http://fb-links.weebly.com/blog/10-classic-aircraft-from-world-war-2-saviors-in-the-skies"><em>(source)</em></a></figcaption></figure><p>Mature software development workflow includes <em>performance testing</em> when a system’s performance is tested before it’s launched. One type of performance testing is <em>load testing</em>, simulating many users hitting your tool at once, which is done to see how the system behaves in real-world type conditions (or even worse ones). This can be multiple simultaneous users and lots of users in succession. By ensuring that the systems will work under extremely high loads, load testing gives stakeholders confidence in your software and helps identify bottlenecks in overall systems. Even in cases of total failure, if you’ve done good load testing in advance then you’re sitting pretty. Unlike companies who didn’t load test, you know what your system looks like when it is failing. You can detect failures more quickly and know what to do to fix them. By using computer programs to simulate the traffic rather than having developers repeatedly use the tool in unison, you lower the chance of hand injuries.</p><p>As APIs become more accessible to the data science community, so should engineering best practices around those APIs. However, most load testing tools are crafted for engineers or testing specialists–so we fixed that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*DELfvQYAbPkyLUWv43AVeA.png" /><figcaption>hex stickers make it real</figcaption></figure><p>Our new R package, <a href="https://github.com/tmobile/loadtest"><strong>loadtest</strong></a>, is a tool for easily running load tests without ever having to leave R, all with a single line of code. With loadtest, load testing is so easy you can trivially do it before a service is deployed in production to test it will work, or it can be used as a method of better understanding API behavior. The package includes several plots to quickly understand the test results, and a standard report to package the output as an html document. And since loadtest is a set of R functions, you can even add it as a step in a build process. The loadtest package uses JMeter on the backend, which is a standard industry tool for load testing, so the results are high-fidelity.</p><blockquote>The loadtest package has already solved production issues with R APIs. On the <em>AI @ T-Mobile</em> team, one of our APIs would be occasionally unresponsive. Using the loadtest package, we were able to simulate the production environment that produced the problem. We learned that 1 in 10 requests would take over a minute. With this information, we discovered that the unresponsive API was not due to our R code but an external HTTP request that sometimes would time out.</blockquote><p>As a demonstration we’ve created a website, <a href="http://teststuff.biz/">teststuff.biz</a>, which hosts an API version of the <a href="https://deepmoji.mit.edu/">MIT DeepMoji project</a>. DeepMoji is a neural network that takes text and returns emoji relevant to the test. We’ve hosted it on a tiny Amazon Web Services® EC2 instance, and we want to know how well it works under a load!</p><p>The way the API works is that we send a POST request with a JSON body containing text to turn into emoji, like:</p><pre>library(dplyr)<br>library(httr)</pre><pre># make the request<br>response &lt;- POST(“http://deepmoji.teststuff.biz&quot;,<br>  body = list(sentences = list(“I love this band”)),<br>  encode=”json”)</pre><pre># format the json into a table, then look at the 3 three emoji for that sentence<br>content(response)$emoji[[1]] %&gt;%<br>  bind_rows() %&gt;%<br>  arrange(desc(prob)) %&gt;%<br>  top_n(5, prob)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*7NlN6ZCi0lVuFGD7J1TW3w.png" /><figcaption>the 5 most probable emoji for the text “I love this band”</figcaption></figure><p>How fun! But how does this system do under load? Will it work when hundreds of people all want hundreds of sentences converted to emoji at once? That’s when load test comes in! Let’s run a test of having 10 concurrent users each make a request to convert sentences to emoji 25 times. That task can be done with a single function call, using almost the exact same parameters as the httr:POST request.</p><p>After <a href="https://github.com/tmobile/loadtest#installation">installing Java and JMeter</a> we install and load the loadtest library:</p><pre>remotes::install_github(“tmobile/loadtest”)<br>library(loadtest)</pre><p>Then we run a load test with one command:</p><pre>results &lt;- loadtest(url = “http://deepmoji.teststuff.biz&quot;,<br>  method = “POST”,<br>  body = list(sentences = list(“I love this band”)),<br>  threads = 8,<br>  loops = 32)</pre><p>As output get a table with a row for each of the 250 requests made. The table has lots of attributes for each request, but importantly we get the time each request was made and the time it took before the full response was received.</p><pre>results %&gt;%<br>  select(request_id, start_time, elapsed) %&gt;%<br>  head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*bNkLmSn1FEfKM8-vpYaI6g.png" /><figcaption>A table of loadtest results showing the time to get a response per request id</figcaption></figure><p>The elapsed time column gives us the precious data we need on how how quickly our API will respond.</p><p>We can use the loadtest package to plot the results too. Here is a plot showing the results over the course of the test:</p><pre>plot_elapsed_times(results)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*lM5YwNWqkxf-whzUU9xt8A.png" /><figcaption>A a plot returned from loadtest depicting relationships between when a request was sent and how long it took for the service to respond</figcaption></figure><p>This chart shows that for the 250 requests, the requests either took around 200–250ms, or 1000–1250ms which is an unusual bifurcation. Something in the API is causes the requests to either be super fast or super slow.</p><p>We can also look at the data as a measure of how quickly the API can handle responses. In this next plot from loadtest we can see a histogram of the number of requests per second the API handled:</p><pre>plot_requests_per_second(results)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*57JhueYUByf1rnrylM_TwA.png" /><figcaption>A visualization returned from loadtest showing the number of requests completed by the API per second</figcaption></figure><p>The API was able to handle 12–18 requests per second during the course of the test. If we expect to only get a few requests per second, say 1–4, then this API should work fine. If we expect to get 30 requests per second then our API would be too slow. In that case we’d want to add more containers or virtual machines running the API or find a way to make the API run more quickly.</p><p>There are more graphs you can make and you can make them all at once as a nice html report with loadtest as well. Using the loadtest_report command you can easily create a report right that can be shared around the office.</p><pre>loadtest_report(results)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*3H8qz0MUXcHJsriwiWe5UA.png" /><figcaption>A default report generated from loadtest</figcaption></figure><p>If you do any sort of API development, we encourage you to try this package out and see how your APIs fare! If you find features that are missing we’d love to hear from you in the <a href="https://github.com/tmobile/loadtest/issues">GitHub Issues</a>. Beyond running one-off load tests, you can also integrate it into your build pipeline so that after an API is deployed in testing an loadtest report is automatically generated. By making load tests as automatic as unit tests, your code is much more likely to handle the rigors of production. Happy testing!</p><p><em>Legal notes: this tool is released as open source for public use. It is released “as-is” and theoretically may have inconsistencies in reporting and stability. T-Mobile has no responsibility for the outcomes of the output of this tool–use at your own discretion. Loadtest is open-sourced under the terms of the Apache 2.0 license and is released AS IS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND pursuant to Section 7 of the Apache 2.0 license.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23efeeb370a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tmobile-tech/loadtest-an-r-package-for-load-testing-23efeeb370a5">loadtest: an R Package for Load Testing</a> was originally published in <a href="https://medium.com/tmobile-tech">T-Mobile Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enterprise Web Services with Neural Networks Using R and TensorFlow]]></title>
            <link>https://medium.com/tmobile-tech/enterprise-web-services-with-neural-networks-using-r-and-tensorflow-a09c1b100c11?source=rss----e283d0ff239a---4</link>
            <guid isPermaLink="false">https://medium.com/p/a09c1b100c11</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[t-mobile]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Heather Nolis]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 20:16:26 GMT</pubDate>
            <atom:updated>2019-04-01T20:16:26.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImtljHTUsgscWmyEauz2Xg.png" /><figcaption>love that whale</figcaption></figure><p><em>[Coauthor: Jacqueline Nolis]</em></p><p>Despite being an incredibly popular language for exploratory analysis, data scientists are repeatedly told that R is not sufficient for machine learning — especially if those ML models are destined for production. Though much exploratory analysis and modeling is done in R, these models must be rebuilt in Python to meet DevOps and enterprise requirements. Our team doesn’t see the value in this double work. We explore in R and immediately deploy in R. Our APIs are neural network models using R and TensorFlow in docker containers that are small and maintainable enough to make our DevOps team happy!</p><p>We want to empower R users to do proper engineering on their own terms by sharing our production-appropriate deep learning containers.</p><h3><strong>Who we are</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qsa_ygre4g5ibMZ5zUITAg.png" /></figure><p>When executives at T-Mobile decided to see if artificial intelligence and machine learning could truly improve the customer experience at T-Mobile, our team was created. We were given four months and a small budget to prove the worth of AI and ML to the business by creating a valuable machine learning model and deploying it into live systems. We had the freedom to use whatever tools we wanted, as long as they could be maintained continuously.</p><p>Our team is half data scientists (who prefer R) and half machine learning and software engineers (who prefer Java). We exist within Social &amp; Messaging Product Development (SMPD): an agile software development shop which creates the software that lets you text, tweet, or Facebook message T-Mobile care agents. Because SMPD is immersed in the world of text, we came across some really nice natural language processing opportunities which could be easily deployed. As a software development team with the goal of continuously running deep learning APIs, our approach to data science is unique within T-Mobile. The company is packed with teams of data scientists who build models to make decisions and keep the business in tip-top shape. Our team is different because our models are not run on demand to generate analyses. They continuously run as a service. As such, many well-honed data science practices had to be replaced with software development ones.</p><h3><strong>How we did it</strong></h3><p>[For an introduction to R as a microservice check out our blog posts on <a href="https://medium.com/@heathernolis/r-can-api-c184951a24a3">using R and plumber for web services</a>, and <a href="https://medium.com/@skyetetra/using-docker-to-deploy-an-r-plumber-api-863ccf91516d">using docker to deploy them</a>]</p><p>Once we found our first use case, the data scientists on our team trained a neural network to solve it. When faced with the decision on how to deploy the neural network, we felt that sticking with R was the best choice. The machine learning engineers snapped to R support and started figuring out how to make R work in the existing deployment pipeline. The SMPD group operates on a containerized microservices architecture, so we created a docker container that runs an R web service powered by the neural network.</p><p>We’ve open sourced a version of our implementation to gauge public interest. While our implementations are in production, prior to any production use, your IT department (if it exists) should review the source code for cybersecurity and suitability for your environment. Also, as this is a proof of concept release, feel free to modify as you need for your particular environment. Of course, T-Mobile cannot be responsible for maintaining the proof of concept so please Code Responsibly.</p><p>To work in our existing pipeline and with our team’s requirements, our web services needed to be:</p><ul><li><strong>Entirely written in R.</strong> — The data scientists had to create their models without learning new programming languages. To power the web service, we used the plumber R package. We structured the docker container so that an R user who is unfamiliar with docker shouldn’t need to modify anything except the R code itself.</li><li><strong>TensorFlow compatible.</strong> — The web service had to run neural network models created by keras and tensorflow libraries. These R libraries run Python on the backend, so the container had to include Python linked to R.</li><li><strong>Production ready.</strong> — The container had to be acceptable by our DevOps team, which in our case meant the image needed to be less than 2gb in size.</li><li><strong>HTTPS enabled.</strong> — Our internal security requirements forced us to encrypt all traffic to our web service. The plumber R library does not support HTTPS by default, so we had to add an Apache 2 server within our container.</li></ul><p>Many docker containers fulfill parts of these requirements, such as <a href="https://hub.docker.com/r/rocker/ml/~/dockerfile/">rocker/ml</a> for R and TensorFlow or <a href="https://hub.docker.com/r/trestletech/plumber/">trestletech/plumber</a> for R and plumber, the problem was that we could not find a single docker image that did it all — much less within the 2gb size requirement. We set out to create our own container, which ended up taking months of work. Our first pass at putting all these things in a working container was roughly 7 gigs! Now, we’ve gotten the container to a place we really like and decided to make it open source. You can try the container yourself at <a href="https://github.com/tmobile/r-tensorflow-api">tmobile/r-tensorflow-api</a>. This container is based on using R version 3.5.0, and using R libraries from MRAN’s July 2nd, 2018 snapshot, as well as Miniconda 3 version 4.4.10 for python.</p><p>Our repository example shows a simple neural network that generates new adorable pet names based on Seattle pet license data. It contains both HTTP and HTTPS versions to use depending on the use case. It clocks in at 1.86gb, which is <em>incredible</em>.</p><h3><strong>Why this matters</strong></h3><p>Since starting down this machine-learning-in-production journey, we’ve found many valuable use cases. These include:</p><ul><li>Determining if a person is a customer by the first question they message T-Mobile.</li><li>Predicting the intent of the conversation so the necessary data is ready for the T-Mobile care agent.</li><li>Looking for and presenting to the agent internal knowledge-base articles as the conversation progresses.</li></ul><p>Through all of this we’ve really enjoyed using R! We use it for all of our machine learning projects because it’s extremely easy to read, has powerful modeling capabilities, and can surface business-ready demos in just a few lines of code. We believe the future of machine learning is rooted in making these technologies more accessible for everyone. We also believe R is a viable language for development and analysis, and we hope this inspires others to recognize the same value.</p><p>By deploying R models to do this work, we quickly proved the value of machine learning at T-Mobile (and got our own name: AI @ T-Mobile). We are now growing our scope and team to cover new topics. We look forward to seeing what else we can do as we continue to explore the power of R in production.</p><blockquote><em>T-Mobile is Customer obsessed! We are constantly looking for ways to make our Customer interactions the best experience possible. We believe AI/ML can enhance those interactions by providing the intent and context to aid in resolving a Customer contact. We sponsored this project to validate our beliefs and to discover how to integrate AI/ML into our ecosystem. The project team has done an incredible job in a six-month time frame. They have validated that AI/ML can enhance Customer Interactions at T-Mobile, created an API to make their model accessible by our ecosystem, and created some pretty neat tech that can be shared with the community. With this new capability we not only have an additional tool to enhance our Customer interactions but also a blueprint on how to apply AI/ML to other products and services.</em></blockquote><blockquote>Chuck Knostman, Vice President of IT at T-Mobile</blockquote><p>[Originally posted on 2018–11–02 on T-Mobile’s Open Source Blog]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a09c1b100c11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tmobile-tech/enterprise-web-services-with-neural-networks-using-r-and-tensorflow-a09c1b100c11">Enterprise Web Services with Neural Networks Using R and TensorFlow</a> was originally published in <a href="https://medium.com/tmobile-tech">T-Mobile Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using docker to deploy an R plumber API]]></title>
            <link>https://medium.com/tmobile-tech/using-docker-to-deploy-an-r-plumber-api-863ccf91516d?source=rss----e283d0ff239a---4</link>
            <guid isPermaLink="false">https://medium.com/p/863ccf91516d</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jacqueline Nolis]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 17:57:56 GMT</pubDate>
            <atom:updated>2019-04-01T17:57:56.688Z</atom:updated>
            <content:encoded><![CDATA[<h4>Get your R code to run anywhere as a service</h4><p><em>[This post is co-authored by Heather Nolis, and is part of a series on R in production. We recommend you start with </em><a href="https://medium.com/@heathernolis/r-can-api-c184951a24a3"><em>part 1</em></a><em>.]</em></p><p>In the <a href="https://medium.com/@heathernolis/r-can-api-c184951a24a3">previous blog post</a> we learned how to use the R library plumber to create a RESTful API. We showed that by running a simple R script, we could have a web service running on our computer straight from RStudio. But what if you want to run the web service somewhere besides your computer? How do you get that code running somewhere else? And how can you do it in a way that’s quick to set up and easy to maintain?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UaV7hnXAgbNDNDbIDI2lw.png" /></figure><p><strong><em>[Before we begin, here is some legalese from our lawyers.]</em></strong></p><p><em>The code in this blog are examples we ran using Docker 18.06, which may need to be modified for your own environment. We will make our best effort to update but we make no guarantees on that. Feel free to modify the code as you see fit. In fact, if you want to fork the code, feel free to do so. All we ask is that you honor any open source licenses and attributions including from us. It goes without saying, but you are responsible for respecting the data you use and ensuring best practices for cybersecurity. In general, before using in production, please have your internal IT department (if they exist) review your code and your data. They know your environment better than we do, and we are not in a position to provide general support. In legalese, “Use is AS IS and without warranty.” Your IT department (if they exist) should be aware of the open source licenses for some of these tools. Most are Apache and BSD. R and Rocker are GPL based. Note that different departments have different policies about open source.</em></p><h4><strong>The </strong>☁️<strong><em>cloud</em></strong>☁️<strong> and virtual machines</strong></h4><p>As a data scientist, you sometimes want to have code running in places that are not your computer. In our case, we want to have our R script run an API continuously, regardless of if our laptop runs out of battery.</p><p>One way we could set this up would be to create a virtual machine in a place like Amazon Web Services. A virtual machine is like a computer that you’ve used before, but it’s simulated–it doesn’t have it’s own process, memory, or hardware. Instead, a different computer is running the machine. Virtual machines are great because many of them can run on a single server, and they can be easily started and stopped.</p><p>If you wanted to run the API on a virtual machine you would log onto AWS and:</p><ol><li><a href="https://www.infoworld.com/article/3223425/cloud-computing/windows-amazon-ec2-tutorial-how-to-set-up-an-ec2-instance.html">Start an EC2 instance</a> (a virtual machine) with the right operating system and set the security group to allow HTTP traffic.</li><li>Install the correct version of R.</li><li>Install the right R libraries, some of which may come from GitHub.</li><li>Put the R scripts for your plumber API on the instance.</li><li>Open port 80 within the virtual machine’s firewall.</li></ol><p>And that works! If you follow these steps you will be able to hit the API endpoint you created. But there are a few downsides with this process:</p><ul><li>Starting the EC2 instance and installing all of these programs takes a ton of time. If the EC2 instance was accidentally deleted, you would have to do it all again. If you no longer worked at your company, no one would know exactly what steps you took to create the EC2.</li><li>Virtual machines take a lot of computing resources. They are entirely simulated computers, so they require an entire OS running and all the programs that come with it.</li></ul><p>Both of these problems are fixed with docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlDYjmXhfVBpeJXNiMmCew.jpeg" /><figcaption>Docker will leave you feeling as calm and serene as this photo (copyright of flickr user <a href="https://www.flickr.com/photos/stanimirstoyanov/">stanimir.stoyanov</a>)</figcaption></figure><h4><strong>Enter Docker</strong></h4><p>Docker is a way to make the process of configuring and running computers smoother. With docker, you can create a single document that specifies how to set up the computer. The document lets you run these steps at a moments notice. More formally, docker is a way to run virtual machines as containers, which are lightweight executable packages of software. A container is an instance of an image, which is a snapshot of a computer at a moment in time. Images can be full snapshots, or they can just be a small addition to an earlier image. A dockerfile is the specification document for how to build the image.</p><p>Or to put it another way:</p><ul><li>A <em>dockerfile</em> lists how to build the computer we’ll want to run (like the list of steps in the section above).</li><li>An <em>image</em> is a file that’s a snapshot of that computer. Each step of the docker file constructs a new image. That image is used as the starting place for the next step in the docker file.</li><li>A <em>container</em> is when you take an image file and begin running it. Running an image creates a container.</li></ul><p>Docker containers are a great way to have computers set to exact specifications. Software developers love containers because they allow quick creation of many computers running the exact same code. Docker simplifies installation and maintenance of production-level code.</p><p>Docker containers are also smaller than virtual machines because they can share components amongst each other. If we have many docker containers that all need Linux with R installed, then they can all share those core Linux and R components.</p><p>By passing a docker image, you can immediately have someone else run your code! All the setup is taken care of, provided they have docker installed.</p><h4><strong>Using Docker for R and plumber</strong></h4><p>We’ll use the API we created in part 1 of this series as the code we want in our docker container. You can find the R code in our <a href="https://github.com/nolis-llc/r-api-tutorial">GitHub repository</a>. Let’s try making a container out of it and running it on our own machine. In our case we’ll want to set up a computer following roughly the steps above:</p><ol><li>Start a computer with Linux.</li><li>Install R on it.</li><li>Install our R libraries.</li><li>Transfer our R scripts to the computer.</li></ol><p>Since we’re using docker, performing each one of those steps will correspond with creating a new docker image. We’ll start with an image already setup to have Linux on it. Then we’ll create an image that has R installed on top of Linux. After that, we’ll add our R libraries into a third image. Lastly, we’ll transfer our files to the final image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dNQ6368kw6bZlG_mtAxgg.png" /><figcaption>Building our beautiful R plumber API image from other, smaller images</figcaption></figure><p>A great thing about docker is that since so many people use it, you can often find images that other people have made that do what you want to do. In our case, <a href="https://www.rocker-project.org/">the Rocker project</a> has a ton of docker images that support R, including ones with R+RStudio, Shiny, and more. This means we don’t have to devise these images ourselves; we can use those images as starting points for ours. To start on our container, we’ll use the <a href="https://hub.docker.com/r/rocker/r-ver/">“r-ver”</a> docker image, and thus the first two steps are done.</p><p>To use docker, you’ll first need to install it on the computer you’re using (here are links for <a href="https://store.docker.com/editions/community/docker-ce-desktop-windows">windows</a> or <a href="https://store.docker.com/editions/community/docker-ce-desktop-mac">mac</a>). This is relatively painless, but it requires admin rights and may require you to change some operating system settings. Begin by starting docker on your computer. You’ll know you’ve started it if this dashing looking whale stops moving:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*4882CvQqP8q5UK-iIPNnGQ.png" /><figcaption>Your new best nautical friend</figcaption></figure><p>Once docker has started, go to the terminal (or PowerShell in windows) and type:</p><pre>docker pull rocker/r-ver:3.5.0</pre><p>This will get the Rocker docker image from the internet that has R version 3.5.0 installed on a linux machine. So you are downloading a compressed file that has a full computer’s information in it. It’ll take a few seconds, and during this time you’ll see a screen like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjNB1AqiLYOe28PtiVmo2Q.png" /></figure><p>Each line represents a sub-image, starting with one that has just the operating system and ending with one that has R installed. All put together, these create the full rocker/r-ver:3.5.0 image.</p><p>Once complete you can run the following command:</p><pre>docker run -ti rocker/r-ver:3.5.0 </pre><p>This runs a rocker container that is set up to run interactive R. You should see the familiar R command line interface. <em>This works even if you don’t have R installed on your own computer!</em> 😱 It’s all happening in this tiny container running concurrently inside your computer. If you were to quit the interactive R session, the container would stop — meaning anything you did inside it would be lost. This makes sense since the container is not your computer, it’s just running <em>on</em> your computer.</p><p>For our example, running R alone isn’t sufficient. We also need to install plumber, copy our files, set up our rest controller, and open the container to port 80 so that it can receive HTTP traffic. To add onto this Rocker image, we need to make the dockerfile.</p><p>In the same directory as the plumber code from part 1, create a plaintext file called dockerfile. In order to build, docker always looks for a plain text file with no extension called dockerfile, so this is important.</p><p>To customize our docker container, we first specify our base container. For us, that’s the rocker/r-ver:3.5.0 image. We do this by using the `FROM` command:</p><pre>FROM rocker/r-ver:3.5.0</pre><p>Then, we need to install the linux packages that are required for the plumber using linux bash commands. To these commands while setting up the image, we use the RUN. We first check for the newest packages and then install two which aren’t included in the standard update.</p><pre>RUN apt-get update -qq &amp;&amp; apt-get install -y \<br>      libssl-dev \<br>      libcurl4-gnutls-dev</pre><p>Install plumber using RUN to execute one line of R code:</p><pre>RUN R -e &quot;install.packages(&#39;plumber&#39;)&quot;</pre><p>Now we have a container with all the required libraries and packages. But we still need to copy any R scripts that we use to run our webservice! To make it easy, let’s just copy everything from the folder containing our dockerfile and the code from part 1 into the image. The COPY command takes the first argument as the location on the computer with the dockerfile and copies it into the specified folder in the image:</p><pre>COPY / /</pre><p>Next we open port 80 to web traffic (since that’s the port plumber listens to) using the EXPOSE command:</p><pre>EXPOSE 80</pre><p>Lastly, we should specify what happens when the container starts. In <a href="https://medium.com/@heathernolis/r-can-api-c184951a24a3">part 1</a> we created a main.R file that starts the plumber web service in R. We want that to happen in our container. So we set the ENTRYPOINT of the container to run the main.R script.</p><pre>ENTRYPOINT [&quot;Rscript&quot;, &quot;main.R&quot;]</pre><p>And that’s our dockerfile! It builds everything we need to run our API from any machine, regardless of the setup! All together it looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bc26d20e2a427d2b8fbf7fbdc3cb2aa/href">https://medium.com/media/3bc26d20e2a427d2b8fbf7fbdc3cb2aa/href</a></iframe><p>To build our image, open a terminal in the project folder and run</p><pre>docker build -t plumber-demo .</pre><p>This builds the image and names it “plumber-demo”. Because installing plumber requires compiling several other R packages, this takes a few minutes. Don’t worry! Once the process is complete, you can run the container by using:</p><pre>docker run --rm -p 80:80 plumber-demo</pre><p>Now, you can run your API just like you did in part 1 — by navigating to this address: <a href="http://127.0.0.1/predict_petal_length?petal_width=1">http://127.0.0.1/predict_petal_length?petal_width=1</a>. Any other person can take your same project run and your web service on their computer — regardless of OS and programs installed.</p><p>Wow! When you’re ready you can stop all running containers by using:</p><pre>docker stop $(docker ps -a -q)</pre><p>If you want to have this web service running on a server in the cloud, it only takes a few more steps. One way to do this is to use a tool like <a href="https://aws.amazon.com/ecs/">Amazon Elastic Container Service (ECS)</a>. ECS lets you take a container you’ve created and deploy it to AWS. At that point your container is running within AWS systems, and you will get an endpoint that anyone can hit with a browser from anywhere. Wild!</p><p>With a better understanding of what docker is, why it’s super cool, and how it can be used to run R plumber APIs anywhere, you’re now empowered to make your own APIs. Take that, engineering team!</p><p>You should be able to create your own simple docker container and understand the basics of what is happening in a dockerfile.</p><p>There is still work left to do if you wanted to use R and plumber in an enterprise setting. In particular:</p><ul><li>You may need your container to support the keras and tensorflow libraries, which require Python.</li><li>You’ll want to make the container as small as reasonably possible</li><li>You definitely want your web service to support encryption via HTTPS, which isn’t supported by plumber.</li><li>You should make the dockerfile something that you never have to touch (so remove things like the list of R libraries to install).</li></ul><p>In the <a href="https://opensource.t-mobile.com/blog/posts/r-tensorflow-api/">final part of this series</a>, we’ll talk about the <a href="https://github.com/tmobile/r-tensorflow-api">r-tensorflow-api</a>. We crafted a small docker container for T-Mobile to run neural networks in R as a RESTful API in an enterprise environment.</p><p>Though docker seems complicated and mysterious at first pass, it is just a way to write a program to build environments for you that guarantee all your dependencies are present. It makes sharing code smooth — something that is a pain point for the vast majority of data scientists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=863ccf91516d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tmobile-tech/using-docker-to-deploy-an-r-plumber-api-863ccf91516d">Using docker to deploy an R plumber API</a> was originally published in <a href="https://medium.com/tmobile-tech">T-Mobile Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[R can API and So Can You!]]></title>
            <link>https://medium.com/tmobile-tech/r-can-api-c184951a24a3?source=rss----e283d0ff239a---4</link>
            <guid isPermaLink="false">https://medium.com/p/c184951a24a3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Heather Nolis]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 17:50:04 GMT</pubDate>
            <atom:updated>2019-01-15T20:18:52.645Z</atom:updated>
            <content:encoded><![CDATA[<h4>Empowering R Users From Analysis to Endpoint</h4><p><em>[This post is the first of a series on R in production co-authored by Jacqueline Nolis. Here is </em><a href="https://medium.com/@skyetetra/using-docker-to-deploy-an-r-plumber-api-863ccf91516d"><em>part 2 (using Docker) </em></a><em>and</em><a href="https://opensource.t-mobile.com/blog/posts/r-tensorflow-api/"><em> part 3 (production-quality API development in R)</em></a><em>]</em></p><p>As a machine learning engineer who came up through software development, some of the most fascinating yet frustrating parts of my job come from integrating with data scientists. Because most data scientists haven’t worked on a team that creates software, it often feels like we speak different languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ac6piiiYqnoSFJDjBlOFg.png" /><figcaption>me, trying to talk to data scientists</figcaption></figure><p>When our team was tasked with creating a customer-facing deep learning model, I proposed making it into an API– which was met with a swath of data science confusion. An API is the textbook way to allow other T-Mobile software to leverage our model. The most engineering-savvy data scientist on the team kept referring to it as “R as a web server.” While technically true, to me this as an amusingly spot-on, living example of the typical data scientist resistance towards API’s. On the opposite side of the fence is software engineering where <em>everything</em> is an API. Our API’s have API’s to check the health of dependent API’s. So how could API’s, something so fundamental to my job, be such a mystery to my data science comrades?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*H8Bn5KahK0ZLolCW.jpg" /><figcaption>trying to keep track of microservices API flow like</figcaption></figure><p>Finally, a data scientist on the team explained it to me. API’s sound complicated! They’re these big scary things that engineers design, build, and maintain. No way a data scientist is qualified to do that! But here’s the thing — if you can sit at your computer and analyze a dataset in R, you can build an API. And with an API, you’ll empower other people to start using the model you’ve made. The analysis needed to make the model is the hard part! After that, an API is easy. In this post I’ll walk through what API’s are and detail how you can use plumber to create your own API in R.</p><p><strong>Some notes on environment</strong></p><p>This is an experiment! We’re going to talk about how to make APIs in R. The more people who show interest, the further we can expand our efforts. So, think of this information as a bit of a beta test. We’re putting our code out into the world in hopes that people will also be interested in supporting R APIs, using our code as a baseline. If enough people are interested, we’ll officially release this as an open source project.So in legalese:</p><ol><li>The code in this blog are just examples. They will have to be modified for your own environment.</li><li>We will try to update our code as changes come out, but want to gauge interest first!</li><li>3. Please modify our code as you see fit. Fork it! Show us what you can do. All we ask is that you honor any open source licenses and attributations — including those from us.</li><li>You are responsible for respecting the data you use and ensuring best practices for cybersecurity. Before you just throw a model into production, please let your internal IT department review and security team review your code and data. They know more about your environment that I ever will and we’re not in a position to provide general support. In legalese, “Use is AS IS and without warrantee.”</li><li>Your IT department should be aware of the open source licenses for some of these tools. Most are Apache and BSD. R and Rocker are GPL based. Note that different departments have different policies about open source.</li></ol><p>With all that aside, now to the FUN STUFF!</p><h3><strong>Introduction to APIs</strong></h3><p>Technically, API stands for <em>Application Program Interface</em> — a name that’s both exactly what an API is and too vague to actually convey any meaning. But what are API’s really? They’re a simple way to set up a computer to pass information to other computers through the internet. 95% of the time, when people say API they mean a RESTful API, which is an API that uses HTTP to interact with other computers. HTTP is the same protocol your browser is using for you to read this article right now, as websites just APIs! When you type in a URL to a website, a computer receives your request and sends back HTML. RESTful API’s are the same thing, but instead of HTML they send back text or data.</p><p>When you call an API you typically do one of two things. You either request that computer to send you a specific piece of information (like the weather of a certain city you requested), or you ask the other computer to change the data it has stored (like adding a record to a table). Most simply, API’s are ways to — from your computer — call a function on another computer.</p><p>API’s are used everywhere in software development. Let’s walk through a quick example. When you open the weather app on your phone, it probably:</p><ol><li>Gets your GPS coordinates</li><li>Calls a location API with your GPS coordinates.</li><li>Gets back the nearest city to you.</li><li>Calls a weather.com API with your current city.</li><li>Gets back the forecast for your location.</li><li>Displays this information on your screen.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WX9yjojq5_HeWitrdEnDBw.png" /></figure><p>Because most APIs use HTTP, you can try using your browser to call them directly . For example, Open Notify has <a href="http://open-notify.org/Open-Notify-API/People-In-Space/">an API that tells you how many people are in space</a>. When you <a href="http://api.open-notify.org/astros.json">hit the API by opening this web page</a>, it tells you how many people are in space right now. See? It’s easy!</p><h3><strong>Using R and Plumber to Create an API</strong></h3><p>The easiest way to create an API in R is using the library plumber — a package which can convert existing R code into an API with just a few extra lines.</p><p>It’s easier to show than tell, so let’s start with a really simple R model. Here, we take in the classic iris dataset and create a linear model which correlates petal length to petal width. We’ll pretend that this model is so <em>interesting</em> that it should be exposed to the world, allowing other people to run it on their own data.</p><p>First, we create a script that loads the data and trains the model.</p><p>make_model.R</p><pre># load the dataset<br>dataset &lt;- iris</pre><pre># create the model<br>model &lt;- lm(Petal.Length ~ Petal.Width, data = dataset)</pre><p>Now that we trained the model we can try testing it. Set up a data frame containing one element — a petal width of two. Then, run the model we saved on our input data to get the result.</p><pre># example: run the model once<br>input_data &lt;- data.frame(Petal.Width=1)<br>predict(model,input_data)</pre><p>The output is</p><pre>&gt;`[3.3135]`</pre><p>That’s great! Unfortunately, to do this we had to manually alter the R code to contain 1. What if the people running our model don’t want to learn R? Or maybe don’t want to learn to code at all?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*-_j8Jq5PO7PenBUW.png" /><figcaption>your second favorite plumber</figcaption></figure><p>In that case, we can set up an API so that each time we pass in a parameter, the model will run once. In the rest controller, where all the logic for API’s lives, we first create the model by running the previous script. Then, we define our API endpoints. Since we want a simple endpoint that takes in a petal width and returns a prediction, a simple GET endpoint will do.</p><p>When a GET request containing a petal width is received, the code must:</p><p>1. Convert the input (petal width) into a number so R can use it</p><p>2. Create a data frame containing just that petal width.</p><p>3. Run the model and return the prediction.</p><p>The following code does just that:</p><p>rest_controller.R</p><pre># make the model<br>source(&quot;make_model.R&quot;)</pre><pre>#* @get /predict_petal_length<br>get_predict_length &lt;- function(petal_width){<br>    # convert the input to a number<br>    petal_width &lt;- as.numeric(petal_width)</pre><pre>    # create the prediction data frame<br>    input_data &lt;- data.frame(Petal.Width=as.numeric(petal_width))</pre><pre>    # create the prediction<br>    predict(model,input_data)<br>}</pre><p>Finally, we need to use plumber to set up our R code to accept HTTP requests and transform them into executable R code. This is the only thing new to you as an R user</p><p>We simply:</p><p>1. Import plumber.</p><p>2. Show plumber where our endpoints are.</p><p>3. Start the API service on port 80.</p><p>Since HTTP defaults to port 80, our service to that port allows things we type in our browser to be executed in the R on our computer.</p><p><em>Main.R</em></p><pre>library(plumber)<br>r &lt;- plumb(&quot;rest_controller.R&quot;)<br>r$run(port=80, host=&quot;0.0.0.0&quot;)</pre><p>Great! To see all of this code together, go to our <a href="https://github.com/nolis-llc/r-api-tutorial">GitHub repository </a>. After cloning the project, run</p><pre>install.packages(&#39;plumber&#39;)</pre><p>and then run main.R in RStudio. You should see:</p><pre>&gt;`Starting server to listen on port 80`</pre><p>To hit our API, open the browser to <a href="http://127.0.0.1/">http://127.0.0.1</a> — this is the port we opened in Plumber. You should see:</p><pre>&gt;`{“error”:[“404 — Resource Not Found”]}`</pre><p>This is expected! We’re opening our browser to the right place, but we haven’t navigated to the endpoint we defined in rest_controller.R. Now, add “predict_petal_length” to the end of the navigation bar, which should result in <a href="http://127.0.0.1/predict_petal_length.">http://127.0.0.1/predict_petal_length.</a> You’ll see:</p><pre>&gt;`{“error”:[“500 — Internal server error”],”message”:[“Error in (function (pedal_width) : argument \”pedal_width\” is missing, with no default\n”]}`</pre><p>Okay, so that didn’t work. The error code tells us exactly why though! We’re missing petal width, and the model can’t run on nothing. So let’s add our parameter petal width. This is done by adding a ? at the end of the navigation bar followed by the parameter name, an equals sign, and the value of that parameter. Let’s pass a petal width of 1. Now, our browser is pointing at <a href="http://127.0.0.1/predict_petal_length?petal_width=1">http://127.0.0.1/predict_petal_length?petal_width=1</a></p><p>BOOM! In your browser you should see</p><pre>&gt;`[3.3135]`</pre><p>This is the same output we ran from R Studio. Congratulations! You’ve made your first API. Now you can have your R code run by typing things into your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aO8EMfEENBwdn9nGnZN9sw.png" /></figure><p>But… what we’ve done is make an API that you can hit from your own computer. That’s not super useful! API’s are best used to enable computers to talk to each other. You could set your computer up as a server always open to port 80, jump a million security and networking hoops to let other people connect to your computer, and then just leave it on forever so other people can make nifty iris predictions, but that sounds exhausting, terrible, and like an utter waste of resources. You could go to Amazon AWS and get a virtual computer in the cloud that’s always on (aka an EC2 instance), leaving your laptop free to use. However, the programming setup alone is a huge hassle on your own computer, much less a virtual machine you can’t touch.</p><p>So how can you go about exposing this brilliant model to be always available, accessible by other machines, and able to handle varying volumes of requests?</p><p>Enter: <a href="https://medium.com/@skyetetra/using-docker-to-deploy-an-r-plumber-api-863ccf91516d">[Docker]</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c184951a24a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tmobile-tech/r-can-api-c184951a24a3">R can API and So Can You!</a> was originally published in <a href="https://medium.com/tmobile-tech">T-Mobile Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>