<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hugo Shi on Medium]]></title>
        <description><![CDATA[Stories by Hugo Shi on Medium]]></description>
        <link>https://medium.com/@hhuuggoo?source=rss-58d7b003c928------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OJK2MNTP7VfpRlmY</url>
            <title>Stories by Hugo Shi on Medium</title>
            <link>https://medium.com/@hhuuggoo?source=rss-58d7b003c928------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:15:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hhuuggoo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build or Buy Data Science Tools]]></title>
            <link>https://medium.com/hackernoon/build-or-buy-data-science-tools-71f924fac6d2?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/71f924fac6d2</guid>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 00:00:11 GMT</pubDate>
            <atom:updated>2022-08-18T01:06:33.466Z</atom:updated>
            <content:encoded><![CDATA[<p>Looking at lower total cost of ownership isn’t a helpful framework. Here are the questions to consider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MVECSS1yWQcRgvFn" /><figcaption>Photo by <a href="https://unsplash.com/@etiennegirardet?utm_source=medium&amp;utm_medium=referral">Etienne Girardet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>We’re kicking off a series of blog posts on setting up data science infrastructure. Infrastructure decisions around data science often fall to the first data scientist hired by the company. The company may have hired a new head of data science or a single data scientist who reports up to the head of analytics. These articles will be written with that audience in mind — people who need functional data science infrastructure and who may not have substantial DevOps knowledge.</em></p><p>Your team is looking at a new data science tool — <strong>how do you decide whether to purchase one off the shelf, or build one from scratch</strong>? Most articles about this subject are written by a vendor (I’m a vendor too) and are trying to convince you that adopting their product has a much lower TCO (total cost of ownership). I don’t think that’s a useful framework — an off-the-shelf product <strong>almost always</strong> has a lower TCO, since the cost of developing the product is amortized across all customers.</p><h3>What then?</h3><p>This article focuses on asking the questions you might not be thinking about, or re-thinking old questions in different ways. We assume that the product you’re considering is a good fit to solve your problems — otherwise, you would not be considering that product in the first place. You should think about:</p><ol><li><strong>Can you live without a solution to this problem?</strong></li><li><strong>What is your real cost to build and maintain the solution?</strong></li><li><strong>How much vendor lock-in is there?</strong></li><li><strong>What type of behavior does the product encourage?</strong></li></ol><h3>Can you live without a solution?</h3><p>In reality, the answer to this question is never black and white, but it’s important to understand whether a tool is a must-have or a nice-to-have. <strong>You should never build a solution for a nice-to-have. You should be willing to pay more for a must-have.</strong></p><p>Let’s use <a href="https://www.notion.so/Build-or-Buy-Data-Science-Tools-c28fdf8323c44b6392b091236d53fbe9">Saturn Cloud</a> as an example. If your data is large, then you can’t do data science on your laptop. Solving this problem becomes a must-have. If deploying jobs and dashboards is part of your business function, solving this problem is also a must-have. If your data is small, and you’re happy working on your laptop, then Saturn Cloud becomes a nice-to-have. It’s important to understand the severity of your problem first, without thinking about specific vendors.</p><h3>How expensive is this to build?</h3><p>This is <strong>the most</strong> deceptive question. Developers always think that it (whatever it is) can be built on a weekend.</p><ol><li>You could probably solve your problem on a weekend. Your built-in-a-weekend solution is really a prototype, so think about how much you want to rely on that as a must-have.</li><li>The last mile — getting all the details right to go from a prototype to a real solution — consumes much more time than the first mile.</li><li>Don’t forget about maintenance. Your weekend prototype is going to need care and feeding <strong>for the rest of its existence</strong>.</li><li>If you’re not building this tool, what other cooler, more useful stuff could you be doing with your time?</li></ol><p>Again, let’s use Saturn Cloud as an example. Many Saturn Cloud customers have in the past set up JupyterHub on Kubernetes, ran Dask clusters on EMR, and spun up EC2 instances manually for data scientists. The work that has gone into the last mile and maintenance is what has convinced these customers to use Saturn Cloud.</p><ol><li>Reliability is a significant issue with home-built solutions. Most solutions work well as a prototype, but once data scientists are blowing up memory limits and doing other terrible things, reliability suffers.</li><li>Maintenance and support for homegrown solutions become exceedingly difficult, especially ensuring that data scientists have the flexibility to install all the packages they need, without accidentally breaking their environments.</li></ol><h3>What about vendor lock-in?</h3><p>Data Science is heavily focused on R&amp;D which means there are many unknowns and your needs are likely to change in the future.</p><p><strong>The amount of vendor lock-in you face with a product or tool should count significantly <em>against</em> that vendor.</strong> Let’s look at a few concrete examples.</p><p><a href="http://www.saturncloud.io/"><strong>Saturn Cloud</strong></a>: Saturn Cloud was designed with this metric in mind so we score quite high here. Everything that runs in Saturn Cloud is your docker images, hosted in your ECR, running code from your git repositories. If you can run it in Saturn Cloud, it should be very easy to run elsewhere.</p><p><a href="https://www.databricks.com/"><strong>Databricks</strong></a>: Databricks is probably the worst offender. If you’ve got all of your code defined in Databricks notebooks, some of which are sourcing other Databricks notebooks, It’s going to be challenging to run that code anywhere else.</p><p>: If you’re only using Jupyter notebooks in SageMaker and you’ve managed to build and load your own Docker images into SageMaker, it will probably be easy to run your workflows <em>outside</em> of SageMaker. However, if you rely on the SageMaker image, or if you use any of the SageMaker libraries, <a href="https://saturncloud.io/alternatives/sagemaker/">good luck training your model outside of SageMaker</a>.</p><h3>What type of behavior does a product encourage?</h3><p>Any tool you incorporate is going to encourage certain behaviors. Ideally, they encourage behavior that you would like to encourage for your team. There are 2 examples that I’m thinking about where Saturn Cloud has succeeded in some ways, and failed in others.</p><h3>Does Saturn Cloud encourage software development best practices?</h3><p>Most tools that focus on notebooks encourage code to be developed in notebooks. This can be bad because notebooks don’t encourage software development best practices. How many notebooks have you worked with that are copy-pastes of one another?</p><p>Saturn Cloud partially succeeds in encouraging software development best practices. Saturn Cloud makes Jupyter Lab available, and also has <a href="https://saturncloud.io/docs/using-saturn-cloud/ide_ssh/">SSH integration</a> which allows data scientists to also use PyCharm and VS Code to write code, which does encourage software development best practices. However, Jupyter notebooks are still the easiest thing to use when getting started with Saturn Cloud.</p><h3>Does Saturn Cloud encourage containerized workloads?</h3><p>Once you start running in <a href="https://www.notion.so/Build-or-Buy-Data-Science-Tools-c28fdf8323c44b6392b091236d53fbe9">docker</a> containers, reproducibility becomes much easier. Saturn Cloud partially succeeds in encouraging containerized workloads because everything that runs in Saturn Cloud runs in a container. Saturn Cloud has an image-building tool to help data scientists build and customize their docker containers. Many Saturn Cloud customers are building containers in their CI systems that are automatically pushed to Saturn Cloud.</p><p>However, Saturn Cloud also allows for customization on container startup, which is typically used for installing additional packages. This is especially convenient because it makes sure you don’t need to build a whole new container to make a small change, but reproducibility definitely takes a hit.</p><h3>Conclusion</h3><p>As you stand up a new data science team, you’re going to need to consider purchasing data science products. The data science product landscape is richer than ever. Purchasing a product is almost always cheaper than building a product, but you need to make sure that the amount of vendor lock-in is acceptable, and that the product encourages the behavior you want to encourage in your team.</p><p><em>Originally published at </em><a href="https://saturncloud.io/blog/build-vs-buy-data-science-tools/"><em>https://saturncloud.io</em></a><em> on August 17, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71f924fac6d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/build-or-buy-data-science-tools-71f924fac6d2">Build or Buy Data Science Tools</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dask DataFrame is not Pandas]]></title>
            <link>https://medium.com/data-science/dask-dataframe-is-not-pandas-6764da1291b1?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/6764da1291b1</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Tue, 26 Oct 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-11-04T15:00:27.885Z</atom:updated>
            <content:encoded><![CDATA[<h4>The most reliable ways to re-use your Pandas code with Dask</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8sPzcQIb-aewxw7vwG70A.jpeg" /><figcaption>Photo by CHUTTERSNAP on Unsplash</figcaption></figure><p><em>This article is the second article of an ongoing series on using Dask in practice. Each article in this series will be simple enough for beginners, but provide useful tips for real work. The next article in the series is about </em><a href="https://saturncloud.io/blog/dask-for-beginners/"><em>parallelizing for loops, and other embarrassingly parallel operations with dask.delayed</em></a></p><h3>The Allure</h3><p>You start with medium-sized data sets. Pandas does quite well. Then the data sets get larger, and so you scale up to a larger machine. But eventually, you run out of memory on that machine, or you need to find a way to leverage more cores because your code is running slowly. At that point, you replace your Pandas DataFrame object with a Dask DataFrame.</p><p>Unfortunately, this doesn’t usually go well, and results in a good amount of pain. Either some of the methods you rely on in Pandas, are not implemented in Dask DataFrame (I’m looking at you, MultiIndex), the behavior of the methods is slightly different, or the corresponding Dask operation fails, runs out of memory and crashes (I thought it wasn’t supposed to do that!)</p><p>Pandas is a library designed for a single Python process. Distributed algorithms and data structures are fundamentally different. There is work that can be done on the Dask DataFrame side to make this better, but single processes, and clusters of machines, will always have very different performance characteristics. You should not try to fight this fundamental truth.</p><p><strong>Dask is a great way to scale up your Pandas code. Naively converting your Pandas DataFrame into a Dask DataFrame is not the right way to do it.</strong> The fundamental shift should not be to replace Pandas with Dask, but to re-use the algorithms, code, and methods you wrote for a single Python process. That’s the meat of this article. Once you reframe your thinking, the rest isn’t rocket science.</p><p><strong>There are 3 main ways to leverage your Pandas code with Dask</strong></p><ul><li>Break up your big problem into many small problems</li><li>Use group by and aggregations</li><li>Use dask dataframes as a container for other distributed algorithms.</li></ul><h3>Break up your big problem into many small problems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*J4qdAgObBKaHhiod.jpeg" /><figcaption>Photo by Jackson Simmer on Unsplash</figcaption></figure><p>A Dask DataFrame is made up of many Pandas DataFrames. It’s really good at moving rows from those Pandas DataFrames around, so that you can use them in your own functions. The general approach here is to express your problem in a split-apply-combine pattern.</p><ul><li>Split your big dataset (Dask DataFrame) into smaller datasets (Pandas DataFrame)</li><li>Apply a function (a Pandas function, not a Dask function) to those smaller datasets</li><li>Combine the results back into a big dataset (Dask DataFrame)</li></ul><p>There are 2 main approaches to splitting your data:</p><p>set_index will make one column of the Dask DataFrame the index, and sort the data according to that index. It will by default estimate the data distribution of that column so that you end up with evenly sized partitions (Pandas DataFrames).</p><p>shuffle will group rows together, so that rows with the same values for shuffle columns are in the same partition. This is different than set_index in that there are no sorting guarantees on the result, but you can group by multiple columns.</p><p>Once your data has been split up, map_partitions is a good way to apply a function to each Pandas DataFrame, and combine the results back into a Dask DataFrame.</p><h4>But I have more than one DataFrame</h4><p>No problem! As long as you can split all the Dask DataFrames used in your computation the same way, you’re good to go.</p><h3>A concrete example</h3><p>I’m not going to go into code here. The objective is to put a concrete example on top of this theoretical description to gain some intuition for what this looks like. Imagine that I have one Dask DataFrame of stock prices, and another Dask DataFrame of analyst estimates for the same stocks, and I want to figure out if the analysts were right.</p><ol><li>write a function that takes prices for a single stock, and analyst estimates for that same stock and figures out if they were right.</li><li>call set_index on stock prices, to sort them by ticker. The index of your resulting DataFrame will have a divisions attribute which describes which tickers are in which partitions. (Everything before B is in the first parittion, everything between B and D in the second partition, etc..). Call set_index on the Dask DataFrame of analyst estimates using the stock price divisions.</li><li>use map_partitions to apply a function to the partitions of both Dask DataFrames. That function will look at the tickers within each dataframe, and then apply your function.</li></ol><h3>Use Group By Aggregations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EgUubA5tXzGZ0ygf.jpg" /><figcaption>Diagram by Hugo Shi</figcaption></figure><p>Dask has an excellent implementation of Pandas <a href="https://saturncloud.io/docs/reference/dask_groupby_aggregations/">GroupBy Aggregation algorithms</a>. The actual algorithm is pretty complicated, but we have a detailed write up in our <a href="https://saturncloud.io/docs/reference/dask_groupby_aggregations/">docs</a>. If your problem fits this pattern, you are in good hands. Dask uses a tree reduction in the implementation of the GroupBy Aggregation. There are 2 parameters you may need to tune, split_out controls how many partitions your results end up in, and split_every helps dask compute how many layers there are in the tree. Both parameters can be tuned based on the size of your data to ensure that you don&#39;t run out of memory.</p><h3>Use Dask as a container for other algorithms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*_hdsIr7DFNVl_40F.jpeg" /><figcaption>Photo by Rinson Chory on Unsplash</figcaption></figure><p>Many libraries have Dask integrations built-in. dask-ml integrates with scikit-learn. cuML has multi-node multi-GPU implementations of many common ML algorithms. tsfresh for timeseries. scanpy for single cell analysis. xgboost and lightgbm all have parallel algorithms that are Dask enabled.</p><h3>Conclusions</h3><p>Dask is a great way to scale up your Pandas code. Naively converting your Pandas DataFrame into a Dask DataFrame is not the right way to do it. But Dask makes it easy for you to break your big dataset into smaller parts, and leverage your existing Pandas code.</p><p><em>Originally published at </em><a href="https://saturncloud.io/blog/dask-is-not-pandas/"><em>https://saturncloud.io</em></a><em> on October 26, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6764da1291b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/dask-dataframe-is-not-pandas-6764da1291b1">Dask DataFrame is not Pandas</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just a little recap of what we’ve published recently]]></title>
            <link>https://hhuuggoo.medium.com/just-a-little-recap-of-what-weve-published-recently-590b8029732e?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/590b8029732e</guid>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 00:40:41 GMT</pubDate>
            <atom:updated>2021-10-13T00:43:09.827Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is mostly for myself to organize in my brain the various things Saturn Cloud has published.</p><h3>Dask</h3><h4>Beginner’s Guide</h4><p>I recently started a series of articles, aimed at beginner’s, but incorporating practical tips we’ve picked up working with customers.</p><p><a href="https://saturncloud.io/blog/local-cluster/">Just Start with the Dask LocalCluster</a>: There is a lot out there about different ways to deploy dask. <a href="https://saturncloud.io/blog/practical-issues-setting-up-kubernetes-for-data-science-on-aws/">Dask can be deployed on Kubernetes</a> with the <a href="https://github.com/dask/dask-kubernetes">dask-kubernetes project (which we use as a building block for Saturn),</a> as well as directly on to most clouds with <a href="https://github.com/dask/dask-cloudprovider">dask-cloudprovider</a>. At certain scales, these deployment patterns make sense. I fundamentally believe in simplicity — which is why I argue that <a href="https://saturncloud.io/blog/local-cluster/">for most people, the Dask LocalCluster is the right way to go</a>.</p><p><a href="https://saturncloud.io/blog/dask-for-beginners/">If You Can Write Functions, You Can Use Dask</a>: I think that Dask is heavily under-utilized. There is a lot of content out there about advanced use cases of Dask for machine learning, implementing geo-spatial algorithms, and other advanced use cases, however most people can leverage <a href="https://saturncloud.io/blog/dask-for-beginners/">Dask for embarassingly parallel workloads with dask delayed</a>.</p><h4>Deep Learning</h4><p><a href="https://saturncloud.io/blog/dask-with-gpus/">Speeding up Neural Network Training With Multiple GPUs and Das</a>k and Combining Dask and PyTorch for Better, Faster Transfer Learning. These 2 articles were written about <a href="https://github.com/saturncloud/dask-pytorch-ddp">parallel training with PyTorch and Dask</a> using the dask-pytorch-ddp library that we developed specifically for this work. This approach tends to work quite well in practice, however work usually must be done to load data across the cluster efficiently.</p><p><a href="https://saturncloud.io/blog/computer-vision-at-scale-with-dask-and-py-torch/">Computer Vision at Scale With Dask and PyTorch</a> and <a href="https://saturncloud.io/blog/the-future-of-computer-vision-with-ai-pioneer-senseye/">The Future of Computer Vision with AI Pioneer Senseye</a>. These 2 articles cover the classical example of using <a href="https://saturncloud.io/blog/computer-vision-at-scale-with-dask-and-py-torch/">Dask for batch inference with PyTorch</a>. Including a case study with one of our first forays into Dask and deep learning with <a href="https://senseye.co/">Senseye</a>.</p><p><a href="https://saturncloud.io/blog/unstructured-data-with-snowflake/">Modeling Unstructured Data Using Snowflake and Saturn Cloud</a>. This last piece that we demoed at the Snowflake Build Summit covered training and inference with Dask, leveraging the new unstructured data support that is new to Snowflake.</p><h4>Technical Choices</h4><p>We have a few articles covering some technical choices related to Dask and optimizations.</p><p><a href="https://saturncloud.io/docs/reference/dask_groupby_aggregations/">Troubleshooting Dask GroupBy Aggregation Performance</a>. This is one of the pieces that took me the longest to write, but it gives a good overview of how dask groupby + agg works.</p><p><a href="https://saturncloud.io/blog/should-i-use-dask/">Should I Use Dask?</a>. As mentioned earlier — I fundamentally believe that simplicity is extremely important. If you can avoid parallel computation — you should</p><p><a href="https://saturncloud.io/blog/snowflake-and-dask/">Leveraging Snowflake and Dask</a>. That article is a bit outdated, but it covers loading query shards into Dask dataframes.</p><h3>Data Science Operations</h3><p>We’ve also written some articles covering the business of making data science useful for companies.</p><p><a href="https://saturncloud.io/blog/big-data-strategies/">Strategies for managing big data</a>. You don’t always have to use <a href="https://saturncloud.io/blog/what-is-dask/">Dask</a>. This article covers practical strategies for dealing with big datasets in your company.</p><p><a href="https://saturncloud.io/blog/notebook-apis/">Host a Jupyter Notebook as an API</a>. Ok, this article covers quite a bit. <a href="https://saturncloud.io/blog/notebook-apis/#using-a-saturn-cloud-job-to-run-a-notebook">Running a notebook as a job using Papermill</a>, As well as triggering <a href="https://saturncloud.io/blog/notebook-apis/#running-a-saturn-cloud-job-as-an-api">data science jobs via a CI/CD pipeline</a>.</p><p><a href="https://saturncloud.io/blog/deploy-ml-models-1/">Deploy Your Machine Learning Model</a> — This is a 3 article series on deploying ML models and building a dashboard out of it.</p><p><a href="https://saturncloud.io/blog/deploying-data-pipelines-at-saturn/">Deploying Data Pipelines at Saturn Cloud with Dask and Prefect</a>. This article covers how we use Dask at Saturn for our internal production jobs.</p><p><a href="https://saturncloud.io/docs/examples/dask/cli-tools/">Using Dask to Execute CLI Calls</a>. We’ve worked with a few companies in the life sciences that need to execute <a href="https://saturncloud.io/docs/examples/dask/cli-tools/">shell scripts with Dask</a>. That piece of documentation covers some practical advice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=590b8029732e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If You Can Write Functions, You Can Use Dask]]></title>
            <link>https://medium.com/data-science/if-you-can-write-functions-you-can-use-dask-bbb6d8b3a248?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbb6d8b3a248</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-11-04T14:58:35.151Z</atom:updated>
            <content:encoded><![CDATA[<h4>Speed up your code immediately without spending a bunch of time learning new things.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2SE-QC-MN1UWTRxa" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This article is the second article of an ongoing series on using Dask in practice. Each article in this series will be simple enough for beginners, but provide useful tips for real work. The first article in the series is about using </em><a href="https://saturncloud.io/blog/local-cluster/"><em>LocalCluster</em></a><em>. The next article in the series is about using </em><a href="https://saturncloud.io/blog/dask-is-not-pandas/"><em>Dask DataFrame</em></a><em>.</em></p><p>At Saturn Cloud, <a href="https://www.saturncloud.io/">we manage a data science platform</a> that provides Jupyter notebooks, Dask clusters and ways to deploy models, dashboards and jobs. We’ve seen a few customers start with multi-node clusters when that’s completely unecessary. When you first use Dask, LocalCluster is the way to go.</p><p>I’ve been chatting with many data scientists who’ve heard of Dask, the Python framework for distributed computing, but don’t know where to start. They know that Dask can probably speed up many of there workflows by having them run in parallel across a cluster of machines, but the task of learning a whole new methodology can seem daunting. But I am here to tell you that you can start getting value from Dask without having to learn the entire framework. If <strong>you</strong> spend time waiting for notebook cells to execute, there is a good chance Dask can save you time. If you even just know how to write Python functions you can take advantage of this without learning anything else! This blog post is a “how to use Dask without learning the whole thing” tutorial.</p><h3>Dask, dataframes, bags, arrays, schedulers, workers, graphs, RAPIDS, oh no!</h3><p>There is a lot of complicated content out there about Dask, which can be overwhelming. This is because Dask can utilize a cluster of worker machines to do many cool things! But forget about all that for now. This article focuses on simple techniques that can save you time, without having to change much about how you work.</p><h3>For loops and functions</h3><p>Pretty much every data scientist has done something like this, where you have a set of dataframes stored in separate files and you use a for loop to read them all, do some logic, then combine them:</p><pre>results <strong>=</strong> <strong>[]</strong><br><strong>for</strong> file <strong>in</strong> files<strong>:</strong><br>    defer <strong>=</strong> pd<strong>.</strong>read_csv<strong>(</strong>file<strong>)</strong></pre><pre>    <em>## begin genius algorithm</em><br><br>    brilliant_features <strong>=</strong> <strong>[]</strong><br>    <strong>for</strong> feature <strong>in</strong> features<strong>:</strong><br>        brilliant_features<strong>.</strong>append<strong>(</strong>compute_brilliant_feature<strong>(</strong>df<strong>,</strong> feature<strong>))</strong><br>    magical_business_insight <strong>=</strong> make_the_magic<strong>(</strong>brilliant_features<strong>)</strong><br><br>    results<strong>.</strong>append<strong>(</strong>magical_business_insight<strong>)</strong></pre><p>Over time, you end up with more files, or the genius_algorithm gets more complicated and takes longer to run. And you end up waiting. And waiting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yYA3rEIF1yseszLy" /><figcaption>Photo by <a href="https://unsplash.com/@rruprrup?utm_source=medium&amp;utm_medium=referral">Aleksandra Sapozhnikova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Step 1</strong> is to encapsulate your code in a function. You want to encapsulate the stuff that goes inside the for loop. This makes it easier to understand what the code is doing (converting a file to something useful via magic). More importantly, it makes it easier to use that code in ways besides for loops.</p><pre><strong>def</strong> make_all_the_magics<strong>(</strong>file<strong>):</strong><br>    df <strong>=</strong> pd<strong>.</strong>read_csv<strong>(</strong>file<strong>)</strong><br>    brilliant_features <strong>=</strong> <strong>[]</strong><br>    <strong>for</strong> feature <strong>in</strong> features<strong>:</strong><br>        brilliant_features<strong>.</strong>append<strong>(</strong>compute_brilliant_feature<strong>(</strong>df<strong>,</strong> feature<strong>))</strong><br>    magical_business_insight <strong>=</strong> make_the_magic<strong>(</strong>brilliant_features<strong>)</strong><br>    <strong>return</strong> magical_business_insight<br><br>results <strong>=</strong> <strong>[]</strong><br><br><strong>for</strong> file <strong>in</strong> files<strong>:</strong><br>    magical_business_insight <strong>=</strong> make_all_the_magics<strong>(</strong>file<strong>)</strong><br>    results<strong>.</strong>append<strong>(</strong>magical_business_insight<strong>)</strong></pre><p><strong>Step 2</strong> is to parallelize it with Dask. Now instead of using a for loop, where each iteration happens after the previous one, instead Dask will run them in parallel on a cluster. This should give us results far faster, and is only <em>three lines longer</em> than the for-loop code!</p><pre><strong>from</strong> dask <strong>import</strong> delayed<br><strong>from</strong> dask.distributed <strong>import</strong> Client<br><br><em># same function but with a Dask delayed decorator</em><br><strong>@delayed</strong><br><strong>def</strong> make_all_the_magics<strong>(</strong>file<strong>):</strong><br>    df <strong>=</strong> pd<strong>.</strong>read_csv<strong>(</strong>file<strong>)</strong><br>    brilliant_features <strong>=</strong> <strong>[]</strong><br>    <strong>for</strong> feature <strong>in</strong> features<strong>:</strong><br>        brilliant_features<strong>.</strong>append<strong>(</strong>compute_brilliant_feature<strong>(</strong>df<strong>,</strong> feature<strong>))</strong><br>    magical_business_insight <strong>=</strong> make_the_magic<strong>(</strong>brilliant_features<strong>)</strong><br>    <strong>return</strong> magical_business_insight<br><br>results <strong>=</strong> <strong>[]</strong><br><strong>for</strong> file <strong>in</strong> files<strong>:</strong><br>    magical_business_insight <strong>=</strong> make_all_the_magics<strong>(</strong>file<strong>)</strong><br>    results<strong>.</strong>append<strong>(</strong>magical_business_insight<strong>)</strong><br><br><em># new Dask code</em><br>c <strong>=</strong> Client<strong>()</strong><br>results <strong>=</strong> c<strong>.</strong>compute<strong>(</strong>results<strong>,</strong> sync<strong>=</strong>True<strong>)</strong></pre><p>How it works:</p><ul><li>The delayed decorator, transforms your function. Now when you call it, it isn’t evaluated. Instead you get back a delayed object, which Dask can execute later.</li><li>Client().compute sends all those delayed objects to the Dask cluster, where they are evaluated in parallel! That&#39;s it, you win!</li><li>Instantiating a Client automatically provisions a LocalCluster. This means that the Dask parallel workers are all processes on the same machine as the one calling Dask. This makes for a concise example. For real work, I recommend creating <a href="https://saturncloud.io/blog/local-cluster">local clusters in the terminal</a>.</li></ul><h3>Practical Topics</h3><p>The above stops where most Dask tutorials stop. I’ve used this approach with my own work, and with numerous customers, and a couple practical issues always arise. These next tips will help you go from that textbook example above to more useful methods in practice by covering two topics that constantly come up: large objects and error handling.</p><h3>Large Objects</h3><p>In order to compute functions on a distributed cluster, the objects that the functions are called on need to be sent to the workers. This can lead to performance issues, since those need to be serialized (pickled) on your computer, and sent over the network. Imagine you were doing processes on gigabytes of data-you don’t want to have to transfer that each time a function runs on it. If you accidentally send large objects, you may see a message from Dask like this:</p><pre>Consider scattering large objects ahead of time with client.scatter to reduce scheduler burden and keep data on workers</pre><p>There are two ways to avoid this happening, you can send smaller objects to workers so the burden isn’t so bad, or you can try to send each object to a worker only once so you don’t keep having to make transfers.</p><h4>Fix 1: send small objects when possible</h4><p>This example is good, because we’re sending a file path (small string), instead of the dataframe.</p><pre><em># good, do this</em><br>results <strong>=</strong> <strong>[]</strong><br><strong>for</strong> file <strong>in</strong> files<strong>:</strong><br>    magical_business_insight <strong>=</strong> make_all_the_magics<strong>(</strong>file<strong>)</strong><br>    results<strong>.</strong>append<strong>(</strong>magical_business_insight<strong>)</strong></pre><p>Below is what <em>not</em> to do. Both because you would be doing CSV reading (expensive and slow) in the loop, which is not parallel, but also because now we’re sending dataframes (which can be large).</p><pre><em># bad, do not do this</em><br>results <strong>=</strong> <strong>[]</strong><br><strong>for</strong> file <strong>in</strong> files<strong>:</strong><br>    df <strong>=</strong> pd<strong>.</strong>read_csv<strong>(</strong>file<strong>)</strong><br>    magical_business_insight <strong>=</strong> make_all_the_magics<strong>(</strong>df<strong>)</strong><br>    results<strong>.</strong>append<strong>(</strong>magical_business_insight<strong>)</strong></pre><p>Often times code can be rewritten to change where data is being managed-either on the client or on the workers. Depending on your situation there may be huge time savings by thinking through what functions take as input and how data transfers can be minimized.</p><h4>Fix 2: send objects only once</h4><p>If you have to send a big object, don’t send it multiple times. For example, if I need to send a big model object in order to compute, simply adding the parameter will serialize the model multiple times (once per file)</p><pre><em># bad, do not do this</em><br>results <strong>=</strong> <strong>[]</strong><br><strong>for</strong> file <strong>in</strong> files<strong>:</strong><br>    <em># big model has to be sent to a worker each time the function is called</em><br>    magical_business_insight <strong>=</strong> make_all_the_magics<strong>(</strong>file<strong>,</strong> big_model<strong>)</strong><br>    results<strong>.</strong>append<strong>(</strong>magical_business_insight<strong>)</strong></pre><p>I can tell Dask not to do that, by wrapping it in a delayed object.</p><pre><em># good, do this</em><br>results <strong>=</strong> <strong>[]</strong><br>big_model <strong>=</strong> client<strong>.</strong>scatter<strong>(</strong>big_model<strong>)</strong> <em>#send the model to the workers first</em><br><br><strong>for</strong> file <strong>in</strong> files<strong>:</strong><br>    magical_business_insight <strong>=</strong> make_all_the_magics<strong>(</strong>file<strong>,</strong> big_model<strong>)</strong><br>    results<strong>.</strong>append<strong>(</strong>magical_business_insight<strong>)</strong></pre><h3>Handling Failure</h3><p>As your computational tasks grow, often times you’ll want to be able to power through failure. In this case, maybe 5% of my CSVs have bad data that I can’t handle. I’d like to process 95% of the CSVs successfully, but keep track of the failures so I can adjust my methods and try again.</p><p>This loop does this.</p><pre><strong>import</strong> traceback<br><strong>from</strong> distributed.client <strong>import</strong> wait<strong>,</strong> FIRST_COMPLETED<strong>,</strong> ALL_COMPLETED<br><br>queue <strong>=</strong> c<strong>.</strong>compute<strong>(</strong>results<strong>)</strong><br>futures_to_index <strong>=</strong> <strong>{</strong>fut<strong>:</strong> i <strong>for</strong> i<strong>,</strong> fut <strong>in</strong> enumerate<strong>(</strong>queue<strong>)}</strong><br>results <strong>=</strong> <strong>[</strong>None <strong>for</strong> x <strong>in</strong> range<strong>(</strong>len<strong>(</strong>queue<strong>))]</strong><br><br><strong>while</strong> queue<strong>:</strong><br>    result <strong>=</strong> wait<strong>(</strong>queue<strong>,</strong> return_when<strong>=</strong>FIRST_COMPLETED<strong>)</strong><br>    <strong>for</strong> future <strong>in</strong> result<strong>.</strong>done<strong>:</strong><br>        index <strong>=</strong> futures_to_index<strong>[</strong>future<strong>]</strong><br>        <strong>if</strong> future<strong>.</strong>status <strong>==</strong> &#39;finished&#39;<strong>:</strong><br>            <strong>print(</strong>f&#39;finished computation #{index}&#39;<strong>)</strong><br>            results<strong>[</strong>index<strong>]</strong> <strong>=</strong> future<strong>.</strong>result<strong>()</strong><br>        <strong>else:</strong><br>            <strong>print(</strong>f&#39;errored #{index}&#39;<strong>)</strong><br>            <strong>try:</strong><br>                future<strong>.</strong>result<strong>()</strong><br>            <strong>except</strong> <strong>Exception</strong> <strong>as</strong> e<strong>:</strong><br>                results<strong>[</strong>index<strong>]</strong> <strong>=</strong> e<br>                traceback<strong>.</strong>print_exc<strong>()</strong><br>    queue <strong>=</strong> result<strong>.</strong>not_done<br><br><strong>print(</strong>results<strong>)</strong></pre><p>Since this function is fairly complicated at first glance, let’s break it down.</p><pre>queue <strong>=</strong> c<strong>.</strong>compute<strong>(</strong>results<strong>)</strong><br>futures_to_index <strong>=</strong> <strong>{</strong>fut<strong>:</strong> i <strong>for</strong> i<strong>,</strong> fut <strong>in</strong> enumerate<strong>(</strong>queue<strong>)}</strong><br>results <strong>=</strong> <strong>[</strong>None <strong>for</strong> x <strong>in</strong> range<strong>(</strong>len<strong>(</strong>queue<strong>))]</strong></pre><p>We call compute on results, but since we&#39;re not passing sync=True, we immediately get back futures which represent the computation which has not completed yet. We also create a mapping from the future itself, to the _n_th input argument that generated it. Finally, we populate a list of results filled with Nones for now.</p><pre><strong>while</strong> queue<strong>:</strong><br>    result <strong>=</strong> wait<strong>(</strong>queue<strong>,</strong> return_when<strong>=</strong>FIRST_COMPLETED<strong>)</strong></pre><p>Next, we wait for results, and we process them as they come in. When we wait for futures, they are separated into futures that are done, and those that are not_done.</p><pre><strong>        if</strong> future<strong>.</strong>status <strong>==</strong> &#39;finished&#39;<strong>:</strong><br>            <strong>print(</strong>f&#39;finished computation #{index}&#39;<strong>)</strong><br>            results<strong>[</strong>index<strong>]</strong> <strong>=</strong> future<strong>.</strong>result<strong>()</strong></pre><p>If the future is finished, then we print that we succeeded, and we store the result.</p><pre><strong>        else:</strong><br>            <strong>print(</strong>f&#39;errored #{index}&#39;<strong>)</strong><br>            <strong>try:</strong><br>                future<strong>.</strong>result<strong>()</strong><br>            <strong>except</strong> <strong>Exception</strong> <strong>as</strong> e<strong>:</strong><br>                results<strong>[</strong>index<strong>]</strong> <strong>=</strong> e<br>                traceback<strong>.</strong>print_exc<strong>()</strong></pre><p>Otherwise we store the exception, and print the stack trace.</p><pre>    queue <strong>=</strong> result<strong>.</strong>not_done</pre><p>Finally, we set the queue to those futures that have not yet been completed.</p><h3>Conclusion</h3><p>Dask can definitely save you time. If you spend time waiting for code to run, you should use these simple tips to parallelize your work. There are also many advanced things you can do with Dask, but this is a good starting point.</p><p>Disclaimer: I’m the CTO of <a href="https://www.saturncloud.io/s/home/">Saturn Cloud</a>. We make it easy to connect your team with cloud resources. Want to use Jupyter and Dask? Deploy models, dashboards or jobs? Work from your laptop, or a 4 TB Jupyter instance? Get complete transparency into who is consuming what cloud resources? We do all of that, and more.</p><p><em>Originally published at </em><a href="https://saturncloud.io/blog/dask-for-beginners/"><em>https://saturncloud.io</em></a><em> on August 26, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbb6d8b3a248" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/if-you-can-write-functions-you-can-use-dask-bbb6d8b3a248">If You Can Write Functions, You Can Use Dask</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with Long Running Jupyter Notebooks]]></title>
            <link>https://medium.com/data-science/dealing-with-long-running-jupyter-notebooks-83ab7fca7692?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/83ab7fca7692</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Thu, 15 Jul 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-08-04T23:14:06.690Z</atom:updated>
            <content:encoded><![CDATA[<h4>It’s pretty frustrating when your browser disconnects from a Jupyter Notebook!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E34R89ZjbN9He9of" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=medium&amp;utm_medium=referral">Nathan Dumlao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>At Saturn Cloud, <a href="https://www.saturncloud.io/">we manage a data science platform</a> that provides Jupyter notebooks, Dask clusters and ways to deploy models, dashboards and jobs. As a result, we often help customers troubleshoot their notebooks, and network disconnects is a common issue.</p><p>We’ve gotten a number of customers struggling with long running Jupyter notebooks-ones that take several hours or more to execute. Often they would come to us because these long running notebooks would at some point lose connectivity between the server and the browser, as it common with cloud services. Normally cloud services gracefully reconnect and there are no issues, but in the case of Jupyter if the connection is lost then Jupyter stops saving any output. Jupyter notebooks store all the state in the browser, meaning if there is a connectivity issue between the server running the code and the browser viewing it then the state of the notebook is lost.</p><p>If our customer’s long running code has an error in it and the connection ever cuts out, then the user has no ability to see what the output of the code was and the error messages that it created. Trying to debug these models without output is an exercise in futility. This isn’t an issue when using Jupyter locally because a computer’s connection to itself is infinitely stable, but it’s an issue when working in the cloud.</p><h3>Background</h3><p>Jupyter notebooks store all their state in the browser and thus require constant network connectivity. This is a well known design issue, with many implications. While having network issues won’t cause the code in a notebook to stop executing, it will affect how the output gets saved to your notebook.</p><p>The flow of a Jupyter notebook is:</p><ul><li>the server pushes output to your browser.</li><li>your browser adds it to the notebook object (and renders it to the screen).</li><li>your browser saves the notebook back to the server.</li></ul><p>In the case when the network cuts out then this flow breaks, and no output is saved. The long term solution is for Jupyter itself to be modified to handle intermittent connections, <a href="https://github.com/jupyter/notebook/issues/1647">which is a pretty active area of discussion</a>. There is no current timeline for this to be added to the open source Jupyter.</p><p>However there is a short term strategy.</p><h3>Solution</h3><p>We can adjust Jupyter with just a pinch of code so that it saved the output directly to a file on the server. By doing so, even if the network connectivity cuts out the server will still have the output stored to it. It’s not perfect-in an ideal world this output would still show up in the notebook itself, but it’s an improvement to have them stored somewhere instead of lost. Put this code at the top of your long-running notebook:</p><p>Execute that at the top of your notebook. <em>TADA!</em> Now when you’re running the notebook all output will be mirror in the data.log flat file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N5R5sbGIbaMeOPQD.jpg" /></figure><p><strong>How it works:</strong> In the Jupyter notebook, the normal stdout and stderr File objects are replaced with ipykernel.iostream.OutStream objects (that&#39;s how they get displayed in the browser). This object has an echo object, which defaults to None which can propagate output. So the first set of lines sticks a Python file object in place of the echo, and all your normal stdout and stderr is now also being copied to disk. Exceptions are handled by the python logging system. In the default configuration, that&#39;s not outputting to stdout or stderr, so the second set of lines patches it to do so, and sets the log leve.</p><h3>Conclusion</h3><p>With this workaround, the worst pain of having long running Jupyter notebooks is gone. That said, aat Saturn we generally recommend making use of better hardware (GPUs) or parallelization (Dask) to avoid having to wait 10 hours for your notebook to run. However, if your problem isn’t parallelizable — this is a reasonable workaround. However if <strong>you don’t know how to parallelize it but wish you did</strong>, you should talk to us! We’re really good at it!</p><p>Disclaimer: I’m the CTO of <a href="https://www.saturncloud.io/s/home/">Saturn Cloud</a>. We make it easy to connect your team with cloud resources. Want to use Jupyter and Dask? Deploy models, dashboards or jobs? Work from your laptop, or a 4 TB Jupyter instance? Get complete transparency into who is consuming what cloud resources? We do all of that, and more.</p><p><em>Originally published at </em><a href="https://saturncloud.io/blog/long-running-notebooks/"><em>https://saturncloud.io</em></a><em> on July 15, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83ab7fca7692" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/dealing-with-long-running-jupyter-notebooks-83ab7fca7692">Dealing with Long Running Jupyter Notebooks</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just Start with the Dask LocalCluster]]></title>
            <link>https://medium.com/data-science/just-start-with-the-dask-localcluster-saturn-cloud-7dbfe5a89c9a?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dbfe5a89c9a</guid>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Wed, 14 Jul 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-11-04T14:55:08.910Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dask is great, and the LocalCluster is the easiest way to start</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elTofpDMMRW3SW7g0q4isA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@christinhumephoto?utm_source=medium&amp;utm_medium=referral">Christin Hume</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This article is the first article of an ongoing series on using Dask in practice. Each article in this series will be simple enough for beginners, but provide useful tips for real work. The next article in the series is about </em><a href="https://saturncloud.io/blog/local-cluster/"><em>parallelizing for loops, and other embarssingly parallel operations with dask.delayed</em></a><em>.</em></p><p>At Saturn Cloud, <a href="https://www.saturncloud.io/">we manage a data science platform</a> that provides Jupyter notebooks, Dask clusters and ways to deploy models, dashboards and jobs. We’ve seen a few customers start with multi-node clusters when that’s completely unecessary. When you first use Dask, LocalCluster is the way to go.</p><p>There are many ways to run Dask clusters. This article urges users to start as simplistically as possible, and runs through easy ways of doing just that.</p><h3>Go simple whenever possible</h3><p>We host and manage multi-node Dask clusters. These clusters can even use GPUs. With Saturn users can access a cluster with hundreds of GPUs with a few clicks.</p><p>But wait.</p><p>Just because you have a Ferarri, doesn’t mean you should drive it to the grocery store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LDhBjQ854dWjzZ83" /><figcaption>Photo by <a href="https://unsplash.com/@b_atchison98?utm_source=medium&amp;utm_medium=referral">Brandon Atchison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Simpler is usually better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EvyZLhJ2hGapIggm" /><figcaption>Photo by <a href="https://unsplash.com/@dolfoto?utm_source=medium&amp;utm_medium=referral">Rodolfo Mari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your order of scaling should be:</p><ol><li>Start with Pandas. That’s usually enough.</li><li>Running out of memory? Use Pandas with a bigger machine. <a href="https://www.linkedin.com/feed/update/urn:li:activity:6799017968677330944">Saturn now has Jupyter instances with 4 terabytes of RAM</a></li><li>Try a Dask Local Cluster</li><li>Try a multi-node (and possibly multi-GPU) Dask Cluster</li></ol><p>In general, the simpler your stack, the less time you’ll spend tinkering, and the more time you’ll spend being productive. I’m writing this article because I’ve spent time talking to users who use multi-node clusters when they don’t need to. It’s kind of our fault — we make them really easy to spin up.</p><h3>Why LocalCluster?</h3><p>Your computer has multiple cores (mine has 4). If you’re writing regular Python code, you’re probably only leveraging 1 of those cores. Some of your code (specifically code that calls NumPy, for things like matrix multiplication) is leveraging multiple cores because NumPy knows how to do so. Python <strong>doesn’t</strong> know how to execute the code you’re writing automatically on multiple cores.</p><p>Using a Dask cluster (along with a library that understands how to parallelize over dask) allows you to take advantage of all the cores on your system. Dask comes with some parallelized modules such as dask.dataframe and dask.array. Other libraries like Xarray and dask-ml` also integrate with Dask.</p><p>Dask can help you scale to enormous data sets with multi-node clusters. Dask can also help you take advantage of all the cores on your computer with LocalCluster</p><h4>LocalCluster is easier than a multi-node Dask cluster</h4><p>It’s just easier working with a single machine. On a single machine, <a href="https://htop.dev/">htop</a> can help you understand how your system is doing. On a single machine, you don’t have to worry about copying your code, or data files to your cluster of computers. On a single machine, you can see all the logs for your entire Dask cluster in the terminal.</p><h4>What about multiprocessing?</h4><p>Multiprocessing is great for embarrassingly parallel problems. For non-embarrassingly parallel problems, you’ll need a tool like Dask that knows how to parallelize complex operations over multiple cores. Since Dask can handle both types of parallel problems, you only have to learn one syntax. Plus, you get the fabulous Dask dashboard to monitor your work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoPmULFGWyPSaSpSa8xzyw.jpeg" /><figcaption>Screenshot by Hugo Shi</figcaption></figure><p>For non-embarassingly parallel problems, you’ll need a tool like Dask that knows how to paraellelize complex operations over multiple cores.</p><h3>How do I use LocalCluster</h3><p>There are many ways to use LocalCluster. I’ll show you the best one.</p><h3>What not to do</h3><p>Dask makes it really really easy to get started. Create a Dask client, and you’ve automatically got a LocalCluster</p><pre>&gt;&gt;&gt; from dask.distributed import Client &gt;&gt;&gt; c = Client() &gt;&gt;&gt; c.cluster LocalCluster(16ff34f9, &#39;tcp://127.0.0.1:35257&#39;, workers=4, threads=8, memory=41.92 GB) &gt;&gt;&gt;</pre><p>You can also use LocalCluster explicitly in Python</p><pre>&gt;&gt;&gt; from dask.distributed import Client &gt;&gt;&gt; from dask.distributed import LocalCluster &gt;&gt;&gt; cluster = LocalCluster() &gt;&gt;&gt; client = Client(cluster)</pre><p>I use this approach when I deploy production data pipelines, but I don’t like doing this for research. If you have multiple Python sessions or notebooks, this approach makes it easy for you to accidentally end up with multiple clusters on your computer. It also makes it harder to view the logs, and find the address of the Dask dashboard.</p><h3>What to do</h3><p>Open a terminal.</p><pre>$ dask-scheduler</pre><p>Open a second terminal.</p><pre>$ dask-worker tcp://127.0.0.1:8786</pre><p>In your Python session (possibly a Jupyter notebook), execute the following:</p><pre>from dask.distributed import Client client = Client(&#39;tcp://127.0.0.1:8786&#39;)</pre><p>There you go. The default address for the dask-scheduler is tcp://127.0.0.1:8786 and that second command was enough to set up Dask workers connected to the scheduler. The best part of this approach is that all the logs for all of your work will be in the second terminal. To shut it down, just hit ctrl-c in both terminals.</p><h4>Processes and Threads</h4><p>Python has this annoying thing called the <a href="https://wiki.python.org/moin/GlobalInterpreterLock">global interpreter lock</a>. You don’t need to understand too much about it, except that it means that Python can’t really leverage multiple threads very well. The general exceptions to this rule are code that is mostly doing I/O (downloading data), or code that is leveraging mostly C++ and other non-python libraries (NumPy, for example).</p><p>Most users that we’ve worked with are best served using processes over threads (you can mix them as well). This is how I do this on my machine.</p><ol><li>I have 40 GB of RAM (Thank you <a href="https://system76.com/laptops/lemur">System76!</a>!)</li><li>I have 4 cores. So I want 4 workers.</li><li>This means each worker can consume 10 GB of RAM.</li></ol><pre>$ dask-worker tcp://127.0.0.1:8786 --nprocs 4 --memory-limit 10GB</pre><h3>Conclusion</h3><p>Start simple, and scale up gradually. At Saturn, we can give you 4 terabyte instances for all your local cluster needs. And if that’s not enough, you can then run the same code on a multi-node (and multi-GPU) cluster, with a few clicks. Happy Dask-ing!</p><p>Disclaimer: I’m the CTO of <a href="https://www.saturncloud.io/s/home/">Saturn Cloud</a>. We make it easy to connect your team with cloud resources. Want to use Jupyter and Dask? Deploy models, dashboards or jobs? Work from your laptop, or a 4 TB Jupyter instance? Get complete transparency into who is consuming what cloud resources? We do all of that, and more.</p><p><em>Originally published at </em><a href="https://saturncloud.io/blog/local-cluster/"><em>https://saturncloud.io</em></a><em> on August 8, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dbfe5a89c9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/just-start-with-the-dask-localcluster-saturn-cloud-7dbfe5a89c9a">Just Start with the Dask LocalCluster</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Troubleshooting Dask GroupBy Aggregation Performance]]></title>
            <link>https://medium.com/data-science/troubleshooting-dask-groupby-aggregation-performance-1c39599598c1?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c39599598c1</guid>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Sun, 23 May 2021 19:05:57 GMT</pubDate>
            <atom:updated>2021-05-24T13:25:48.483Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to troubleshoot performance issues with Dask GroupBy Aggregations. A deep dive into the algorithm.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJOahX-rDQQJOUabSqzgYQ.png" /><figcaption>Example GroupBy Task Graph — courtsey of <a href="https://medium.com/u/b865b2668619">Julia Signell</a></figcaption></figure><p>At Saturn Cloud, <a href="https://www.saturncloud.io/">we manage a data science platform</a> that provides Jupyter notebooks, Dask clusters and ways to deploy models, dashboards and jobs. As a result, we often help customers troubleshoot Dask operations. Issues with GroupBys come up quite often.</p><p>Dask DataFrames are amazing for interactively exploring large datasets. However, using them on big datasets can be a little tricky. You’ve probably already hit a KilledWorker exception trying to do a GroupBy. If you haven&#39;t, you will soon!</p><p>The goal of this article is to arm you with a set of options to try if your GroupBy fails. First, we’ll take a deep dive into how DataFrame GroupBy Aggregations are implemented. This is necessary to understand how to work around any obstacles you stumble upon.</p><h3>Dask GroupBy Aggregation</h3><p>Dask GroupBy aggregations use the apply_concat_apply() method, which applies 3 functions, a chunk(), combine() and an aggregate() function to a dask.DataFrame. This is a very powerful paradigm because it enables you to build your own custom aggregations by supplying these functions. We will be referring to these functions in the example.</p><ul><li><strong>chunk</strong> : This method is applied to each partition of the Dask DataFrame.</li><li><strong>combine</strong>: Outputs from the chunk() step are concatenated, and then combined together with combine().</li><li><strong>aggregate</strong>: Outputs from the combine() step are concatenated, and then aggregated with aggregate(). This is the last step. After this transformation, your result is complete.</li></ul><h3>Dask GroupBy Aggregation: The Simplest Example</h3><p>In this example, we’ll walk through a Dask GroupBy with default parameters to show how the algorithm works. We’re using a dummy dataset that has been split into 4 partitions. We’ve chosen numerical values for score to have separate decimal places to make it obvious when data is being aggregated.</p><p>This example applies the following transformation:</p><p>The Dask GroupBy Aggregation breaks the algorithm into chunk(), combine() and aggregate() steps. In this case (the simplest one), we only use the chunk() and aggregate() steps. This particular aggregation is elegant in that each of these steps is implemented in the same way, by grouping by the animal and summing the score ( df.groupby(&#39;animal&#39;)[&#39;zscore&#39;].sum()). By summing the partitions and then summing those sums, we can compute the desired result. Other algorithms like var() require different operations at the different stages. This diagram lays out the relevant operations, and shows us what the data looks like every step of the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nUebFgL8deP7gPT_.jpg" /></figure><p>Our sample dataset has been split up into 4 partitions. <strong>Step 1</strong> applies the chunk() function to each partition. This is an important step because its output is a reduction, and is much smaller than the original partition. <strong>Step 2</strong> concatenates the outputs of <strong>Step 1</strong> into a single dataframe, and then applies the aggregate() function to the result.</p><h4>Issues</h4><p>The simple case returns 1 partition with the entire result in it. If your GroupBy results in a small dataframe, this approach is great. If your GroupBy results in a large dataframe (if you have a large number of groups), you&#39;ll run out of memory, which often manifests itself in KilledWorker exceptions.</p><h3>Dealing with Memory: split_out</h3><p>Dask provides 2 parameters, split_out and split_every to control the data flow. split_out controls the number of partitions that are generated. If we set split_out=4, the group by will result in 4 partitions, instead of 1. We&#39;ll get to split_every later. Let&#39;s redo the previous example with split_out=4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jhP6WP4tHNkIi3qZ.jpg" /></figure><p><strong>Step 1</strong> is the same as the previous example. The output of <strong>Step 1</strong> (applying the chunk() function) is 1 dataframe per partition. <strong>Step 2</strong> breaks each of those dataframes into split_out=4 dataframes by hashing the groups. Looking at the diagram, you&#39;ll see that the Nth dataframe from each partition has the same animal in it. That consistency is the objective of the hashing. We&#39;ll refer to each group as a shard (Shard 1 contains the 1st DataFrame from each partition, Shard 2 contains the 2nd DataFrame from each partition, and so on). <strong>Step 3</strong> concatenates all dataframes that make up each Shard (again using this hashing) such that the data from the same animals end up in the same dataframe. Then the aggregate() function is applied. The result is now a Dask DataFrame made up of split_out=4 partitions.</p><h3>Advanced Options: split_every</h3><p>In the previous example, <strong>Step 3,</strong> Dask concatenated data by shard, for every partition. By default, Dask will concatenate data by shard for up to 8 partitions at a time. Since our dataset only has 4 partitions, all the data was handled at once. Let’s re-run the previous example, with split_every=2. Everything up to <strong>Step 2</strong> is the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KocAt_QsxQmGvGdk.jpg" /></figure><p>With split_every=2, instead of concatenating all dataframes from a single shard (in our example each shard has 4 dataframes), we concatenate them 2 at a time, and then combine them with the combine() function in <strong>Step 3</strong>. <strong>Step 4</strong> concatenates those results and then calls aggregate(). The reduction with combine() and finally aggregate() is a tree reduction. Because we only have 4 partitions, we can complete this operation in 1 combine() step, and 1 aggregate() step. However if we had 8 partitions, there would be 2 combine() steps and 1 aggregate() step. aggregate() is always the last step.</p><h3>What Do We Do About It</h3><p>There are really only 2 things that can be done. I know this may seem a bit anti-climactic, given the length explanation we just went through about how the algorithm works, however understanding the algorithm is important for understanding how to tune it.</p><h3>Tune split_out</h3><p>The split_out parameter can be passed into the aggregation function.</p><p>This section is going to be a bit approximate and hand-wavy. Ultimately you’re going to need to experiment with your dataset and figure out what parameters work. This section may provide you with some guidance on how to think about it.</p><h4>Understanding your data</h4><p>How many groups am I going to have? Hopefully you understand your data well enough to get a rough estimate for the number of groups that will be in your result. If not, you may need to compute it somehow. So for example, I have a dataset with 50 million animals. I take a subset of the data, execute the computation, and observe that my result has 5 million animals and takes 500 mb in memory. 5 million animals is 1/10th of the 50 million I have in the dataset, so my final result will be roughly 5GB.</p><h4>Partition Sizes</h4><p>Partition sizing is a different topic that won’t be covered here. In general you should size your partitions so that many partitions can fit on a worker but ideal partition sizes depend on how much memory your workers have.</p><p>Let’s say I have 8GB workers. If my final result is 5GB, I could set split_out to be 5, so that each 1GB result fits comfortably on the worker. However, the default split_every parameter is set to 8. If every partition is 1GB, in the worst case I could be concatenating 8GB - which would blow out my 8GB worker. Instead, I select split_out to be 25 so that each partition is 200MB.</p><p>Reality won’t be this precise. Exact memory usage is going to depend on how your data is laid out between different machines, and how much memory is used in the actual pandas computation itself. If your data is sorted according to your groupby column, your memory usage will be close to ideal. If you have data from every group on every machine, your memory usage will be closer to the worst case scenario. But this approach can serve as a rough guidelines to choosing split_out .</p><p>I don’t recommend tuning split_every. It&#39;s much easier to tune a single parameter, and the default value of 8 is similar to how much extra memory head room you would want in your Dask workers.</p><h3>Use map_partitions Instead</h3><p>map_partitions() is a method on a Dask DataFrame (it is also used in other Dask collections) that applies a function to all partitions of the Dask DataFrame, and then builds another Dask DataFrame over those results.</p><p>Using map_partitions() is only a good strategy if your data is already sorted by one of the fields you wish to group by. In this example dataset, if my data is already sorted by animal, and I know that all cats are in one partition, and all dogs are in another partition, then I know that I don&#39;t need data from other partitions in order to compute statistics about each animal. This means I can replace</p><pre>ddf<strong>.</strong>groupby<strong>(</strong>&#39;animal&#39;<strong>)[</strong>&#39;scores&#39;<strong>].</strong>sum<strong>()</strong></pre><p>with</p><pre>ddf<strong>.</strong>map_partitions<strong>(lambda</strong> x<strong>:</strong> x<strong>.</strong>groupby<strong>(</strong>&#39;animal&#39;<strong>)[</strong>&#39;scores&#39;<strong>].</strong>sum<strong>()</strong></pre><h4>Don’t sort your data</h4><p>If my data is not sorted, I could sort it using set_index() or shuffle. Then I can apply map_partitions() . This probably isn&#39;t worth it. The data movement in a groupby aggregation should be less than the data movement in set_index() because the chunk() operation, which is the first step, reduces the data volume significantly.</p><h4>Don’t use GroupBy and then Apply</h4><p>map_partition is how a Dask GroupBy with an Apply is implemented when the data is already sorted. This means I could write my aggregation as</p><p>This will likely be much slower than the original example, purely because pandas groupby applys are much slower than groupby aggregations.</p><h3>Conclusion</h3><p>Dask does a lot in order to implement GroupBy aggregations on a cluster. In most cases, it works really well out of the box. When it doesn’t, you can tune split_out to make Dask produce smaller chunks. If your data is already sorted, you can implement the operation more efficiently with map_partitions(). The actual algorithm can be a bit tricky to understand, but understanding it can help you gain intuition about how to tune the parameters.</p><p>Disclaimer: I’m the CTO of <a href="https://www.saturncloud.io/s/home/">Saturn Cloud</a>. We make it easy to connect your team with cloud resources. Want to use Jupyter and Dask? Deploy models, dashboards or jobs? Work from your laptop, or a 4 TB Jupyter instance? Get complete transparency into who is consuming what cloud resources? We do all of that, and more.</p><p><em>Originally published at </em><a href="https://www.saturncloud.io/docs/reference/dask_groupby_aggregations/"><em>https://www.saturncloud.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c39599598c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/troubleshooting-dask-groupby-aggregation-performance-1c39599598c1">Troubleshooting Dask GroupBy Aggregation Performance</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake & Saturn Cloud Launch 100x Faster Machine Learning Platform]]></title>
            <link>https://hhuuggoo.medium.com/snowflake-saturn-cloud-launch-100x-faster-machine-learning-platform-80d99c2e9289?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/80d99c2e9289</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Fri, 08 Jan 2021 17:00:23 GMT</pubDate>
            <atom:updated>2021-01-08T17:04:43.010Z</atom:updated>
            <content:encoded><![CDATA[<p>Bringing 100x Faster Data Science to Millions of Python Users</p><figure><a href="https://hopin.com/events/using-snowflake-saturn-cloud-for-100x-faster-machine-learning"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fXHo8TRVjreVUp1Q4I7Xg.png" /></a></figure><p>Snowflake (NYSE:SNOW), the cloud data platform, is partnering, integrating products, and pursuing joint go-to-market with Saturn Cloud to help data science teams get 100x faster results. Check out our <a href="https://hopin.com/events/using-snowflake-saturn-cloud-for-100x-faster-machine-learning?utm_source=linkedin&amp;utm_medium=organic_social_&amp;utm_campaign=saturn-cloud-snowflake">January 13 webinar</a> if that intrigues you.</p><p>Now SQL users can go one step further to easily get advanced analytics and machine learning capabilities through Snowflake. Snowflake users will be able to build models with <a href="https://dask.org/">Dask</a>, a Python-native parallel computing framework, and <a href="https://rapids.ai/">RAPIDS</a>, a GPU data science framework that parallelizes across clusters with Dask.</p><p>The joint platform is behind groundbreaking speedups for data scientists, outperforming serial Python and Apache Spark by <strong>100x faster</strong>. Senseye, an AI company that uses the tooling, recently <a href="https://towardsdatascience.com/the-future-of-computer-vision-with-ai-pioneer-senseye-3e617d030c5b">revealed</a> a model improvement that drove runtime down from 60 days to 11 hours. The 130x speedup enables them to make breakthroughs on their computer vision accuracy, with iterations possible at a daily pace.</p><h3>An Example with NYC Taxi Data</h3><p>Let’s illustrate this with an example that is similar to general machine learning challenges that face every data scientist. In this example, we want to understand how to improve ride sharing in New York City. As you would expect, there are millions of rows of data to analyze, which takes days to begin to process. We are going to use Snowflake and Saturn Cloud to get to performance fit for a business where time is money. We will use 3 years of NYC Taxi data stored in Snowflake. We do the feature engineering in Snowflake, and then load the data into a distributed GPU dataframe with dask_cudf, and then train a random forest model on GPUs using cuML. Check out the <a href="https://github.com/saturncloud/saturn-cloud-examples/blob/main/machine_learning/random_forest/rf-rapids-snowflake.ipynb">full notebook on GitHub</a>.</p><h3>Connecting to Dask and Snowflake</h3><p>Let’s look at how it works. We’re using a 20 node Dask cluster using g4dn.xlarge instances on AWS. A Saturn Cloud cluster is provisioned with the following code:</p><p>Note: If your Dask clusters are hosted with a different platform, you will need to adapt this code chunk.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50e93e0aab84b79fa067e59ed3c71ac0/href">https://medium.com/media/50e93e0aab84b79fa067e59ed3c71ac0/href</a></iframe><p>Next, we’ll connect to Snowflake. In our notebook, we’re pulling in the relevant connection information and environment variables. You will need to replace these values with your own Snowflake connection information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3458e98b9ac5b36aed1bf0fe9e25dd89/href">https://medium.com/media/3458e98b9ac5b36aed1bf0fe9e25dd89/href</a></iframe><h3>Loading data and feature engineering</h3><p>We’re going to use Snowflake to compute some predictive features, and then have each of our 20 Dask workers load a piece of the resulting training set. The NYC taxi data has the pickup time of each ride, and the data is fairly evenly distributed across days, weeks, and months. Our approach here is to divide up the entire 3 year time period into 20 chunks based on the day of the ride, and load each chunk into a Dask worker. First, we write a function to calculate our date chunks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f43c1893e3caaa7e18611a685bf481c/href">https://medium.com/media/0f43c1893e3caaa7e18611a685bf481c/href</a></iframe><p>After calculating the date chunks, we set up a Snowflake query that performs feature engineering, and put in <a href="https://docs.snowflake.com/en/user-guide/python-connector-example.html#binding-data">bindings</a> that we will use later for grabbing the appropriate date chunks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31c17524ef4c43f10008db0a95ba9102/href">https://medium.com/media/31c17524ef4c43f10008db0a95ba9102/href</a></iframe><p>First I want to point out that we’re just scratching the surface of Snowflake’s analytical capabilities. That’s probably worth an entirely separate blog post, but we’re using a bunch of mathematical and date based routines to highlight yearly, weekly, and daily seasonality (WEEKOFYEAR, DAYOFWEEKISO and HOUR).</p><p>Now comes the fun part! Let’s load the data into a distributed GPU dataframe with Dask and RAPIDS.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26f0de6106155d855bafb5786d4793c8/href">https://medium.com/media/26f0de6106155d855bafb5786d4793c8/href</a></iframe><p>There’s a lot to unpack here, but we’ll walk through each step. Our load function is a Dask delayed function. This means that when you call it, nothing happens, but an object is returned that keeps track of the operations that need to happen, and can be executed at the appropriate time. In the load function, we’re calling the Snowflake query defined above to pass through the date chunks that need to be pulled out of Snowflake. The results are pulled into Python using fetch_pandas_all(). This is an <a href="https://docs.snowflake.com/en/user-guide/python-connector-pandas.html">optimized routine which loads data from Snowflake directly using Arrow</a>, which can be efficiently loaded into Pandas. Finally we turn it into a GPU dataframe.</p><p>The load function defines what needs to happen for one chunk of the larger dataframe. We’re creating a bunch of these calls which return a chunk of the training data set, and then passing them to dask_cudf.from_delayed, which creates a Dask GPU DataFrame out of many small GPU dataframes.</p><p>You may also notice the meta parameter that we’re passing around. This isn’t strictly necessary, however many Pandas routines infer datatypes based on the data. A chunk that has an integer field with no missing data may return that as an integer type, but another chunk that is missing some datapoints for that same field may cast it as a float. As a result, it’s useful to pass the metadata through, and coerce types using metadata to ensure consistency across every chunk.</p><h3>Snowflake Caching and Configuration</h3><p>Snowflake has 2 primary caching mechanisms that are great for ML workloads. The first is the local disk cache. The local disk cache stores the underlying data on the local disk of the machines that make up your Snowflake warehouse. The result cache stores the results of previous queries so they can be accessed quickly.</p><p>For ML workloads, both caches are useful. The local disk cache can speed up every query, especially as data sizes grow. The result cache is useful if you’re re-executing the same query, such as iterating on the ML model without changing your feature engineering, this can be very advantageous.</p><p>Snowflake tables can also be configured to use data clustering. In data clustering, one or more columns or expressions on the table can be designated as the clustering key. Data clustering co-locates similar rows and helps Snowflake understand what data to skip for a particular query.</p><p>In this article, we are disabling the result cache to show accurate benchmarks (the local disk cache cannot be disabled) and we are clustering on PICKUP_DATETIME since that’s how we’ve chosen to partition the result set.</p><h3>Machine Learning</h3><p>Now that we have our training dataset loaded, we can train our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7586c24001c4a40d6ac2f1366d3a1913/href">https://medium.com/media/7586c24001c4a40d6ac2f1366d3a1913/href</a></iframe><p>Here, taxi_train is a dask_cudf dataframe and we’re importing RandomForestClassifier from the RAPIDS cuML package. As a result, the training happens entirely on the GPU. Note the call to .persist() — this tells Dask to perform the Snowflake queries and data loading across the cluster and checkpoint the results in GPU memory. If we don’t do this, the Snowflake queries would be executed each time the random forest model needed to pull some data.</p><h3>Summary and performance</h3><p>We <a href="https://www.saturncloud.io/s/random-forest-on-gpus-2000x-faster-than-apache-spark/">previously did the same exercise with Apache Spark</a>. Loading data, feature engineering, and training a RandomForestClassifier on Spark took 38.5 Minutes. Loading data and feature engineering in Snowflake, and training the RandomForestClassifier in Saturn with Dask and Rapids takes 35 seconds. That’s a 60x speedup with minimal work, and has the added benefit of being able to use Python end to end.</p><p>In terms of computational cost, the Snowflake and Saturn solutions are quite cost-effective because the runtime is so short. Snowflake has a minimum charge of 1 minute. The x-large warehouse we’re running costs us $0.53, and the 20 g4dn.4xlarge machines used in machine learning cost 12 cents for that time period. The equivalent Spark cluster costs $7.19 for the 38 minutes it takes to complete the workload</p><p><strong>Get Started Today</strong></p><p>If you work in data science and machine learning, you can <a href="https://www.saturncloud.io/s/?utm_source=tds&amp;utm_medium=snowflake%20blog">try Saturn Cloud &amp; Snowflake for free</a> and start building models in minutes. You can also join our <a href="https://www.saturncloud.io/s/events/?utm_source=tds&amp;utm_medium=snowflake%20blog">upcoming events about 100x faster data science</a>.</p><p>Also, be sure to join the <a href="https://hopin.to/events/using-snowflake-saturn-cloud-for-100x-faster-machine-learning">webinar</a> on January 13th to learn how to work with your data without limits on scale, performance, or flexibility.</p><figure><a href="https://hopin.com/events/using-snowflake-saturn-cloud-for-100x-faster-machine-learning"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O6Rp56XNYR-L6H4j" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80d99c2e9289" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Issues Setting up Kubernetes for Data Science on AWS]]></title>
            <link>https://medium.com/data-science/practical-issues-setting-up-kubernetes-for-data-science-on-aws-6e009f045f65?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e009f045f65</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Sun, 19 Jul 2020 23:22:35 GMT</pubDate>
            <atom:updated>2020-07-20T02:03:16.894Z</atom:updated>
            <content:encoded><![CDATA[<h4>Kubernetes provides a ton of useful primitives in setting up your own infrastructure. However, the standard way of provisioning Kubernetes isn’t set up very well for data science workflows. This article describes those problems, and how we think of them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5xdV9f55mREfPSTs" /><figcaption>Photo by <a href="https://unsplash.com/@amyames?utm_source=medium&amp;utm_medium=referral">Amy Elting</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Disclaimer: I’m the CTO of <a href="https://www.saturncloud.io/s/">Saturn Cloud </a>— we build an enterprise data science platform focusing on huge performance gains leveraging Dask and RAPIDS.</p><h3>Multiple AZ (Availability Zones) interact poorly with EBS (Elastic Block Store) and Jupyter</h3><p>Love it or hate it, Jupyter is the most common data science tool IDE today. If you are provisioning a Kubernetes cluster for data scientists, they will definitely want to run Jupyter notebooks. And if they are running Jupyter notebooks they are going to want persistent storage — working in an IDE where your filesystem is erased whenever you shut down the machine is a very bad experience!. This is very different than conventional Kubernetes workloads which are often stateless.</p><p>This also means that if you are supporting multiple AZs, you need to make sure that Jupyter instances are always started in the same AZ, since your persistent storage (EBS) cannot be automatically migrated to other regions. One option is to use EFS instead of EBS. We do not do that at Saturn because most data scientists want to store data on their drives as well, and once you start getting into massively parallel cluster compute, EFS is not reliable. At Saturn, we route all Jupyter instances to the same AZ, and setup ASGs(auto scaling groups) that are specific to this AZ. You trade off high availability, but you never really had that anyways, unless you are backing up snapshots to multiple AZs and are prepared to restore an EBS snapshot to another AZ if your primary goes down.</p><h3>Standard VPCs run into EIP(Elastic IP) limits</h3><p>The standard Kubernetes setup keeps workers in a private subnet. Most people end up creating private subnets with CIDR blocks that allocate roughly 256 IP addresses. This seems reasonable because you probably aren’t going to need more than 256 machines right? WRONG! With EKS, the instance type determines the defaults (and maximum) number of <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI">IP addresses allocated per instance</a>. By default, some of the larger instances (r5.16xlarge with 512 GB of ram for example) consumes 50 IP addresses. This means that a team of 5 data scientists, each using 1 r5.16xlarge, can easily exhaust the number of IP addresses in your private subnet. We recommend allocating really big subnets (our default configuration has 8000 available in the CIDR block)</p><h3>Standard Secure Networking Configurations with Calico are unstable as nodes scale up.</h3><p>Many data science tools don’t provide much built in security. This is completely reasonable for an OSS project, but a huge problem for enterprise deployments. For example, by default Dask clusters don’t protect the scheduler, which means that anyone that has access to the cluster, can submit jobs to any Dask cluster(Dask has other ways to mitigate this, however for us dealing with this at the network level is the most flexible). Even if you are securing access into the Kubernetes cluster, it’s a good idea to protect data science tools by using Kubernetes networking policies to control to lock down resources.</p><p>The current standard for secure networking in EKS is Calico. The standard Calico setup will horizontally autoscale the metadata store based on the number of nodes — and is overly aggressive for most data science workloads because we’re typically running 1 user pod per machine (more on this later). This horizontal autoscaling behavior causes instability in Calico which results in nodes failing to communicate. We solve this by controlling the number of replicas in the metadata store manually — this has been very stable for our data science workloads.</p><h3>ASG(Auto Scaling Groups) and the cluster-autoscaler</h3><p>Data science work loads are very different from normal Kubernetes workloads because they are almost always memory bound. EC2 pricing is mostly driven by memory, you don’t get very much value out of multi-tenancy with data science workloads. Data science workloads are often long running (many data scientists will provision a jupyter instance, and leave it up for an entire month). You are much better off allocating one entire node per data science pod. If you do not do this, it’s very likely that you’ll end up scheduling a pod that should only cost $30 a month on a node that costs $3000 a month.<br>At Saturn we create many ASGs (4GB/16GB/64GB/128GB/256GB/512GB) to waste as little RAM as possible.</p><p>Data science workloads are also very spikey. One day, a data scientist might need to edit code on a 4GB instance which costs $30/month. The next day, they might want a 512 GB jupyter instance ($3000/mo) which connects to a 10 node Dask cluster (5TB /ram total). Being able to autoscale Kubernetes is very important.</p><h3>The Kubernetes cluster-autoscaler</h3><p>The Kubernetes cluster-autoscaler is a sophisticated genius and can figure out the optimal node to spin up in order to accomodate a new pod, as well as which pods should be shuffled around in order to free up nodes that can be spun down. However if you’ve bought into the one-pod-per-instance configuration, this sophistication a ton of added complexity which almost always causes problems.</p><h4>Problem — ASG selection</h4><p>The Kubernetes cluster autoscaler is configured with expanders which determine how it allocates new EC2 instances. The standard for cost concious users is least-waste However the least-waste expander computes waste in percentage terms. This means that if you create a pod, and you forget to specify any CPU or RAM requests (you request 0), the cluster autoscaler will determine that every node type results in 100% waste. When an expander decides it has a tie, everything is routed to the random expander. Congratulations! your $30/month pod now costs $3000/month.</p><h4>Problem — wasted capacity</h4><p>Kubernetes pods are scheduled based on what nodes currently have capacity before falling back on the cluster autoscaler. Once a pod vacates a node, it takes 10 minutes before the node is torn down. For active clusters, I’ve often seen small pods (4GB) which accidentally get scheduled on large nodes (512 GB). The data scientists thinks they’re consuming 4GB of ram, and so they’re happy leaving this pod up forever. Congratulations! your $30/month pod now costs $3000/month.</p><h4>Solution — being specific about ASGs.</h4><p>Data science workloads are almost always memory bound, and should monopolize the entire instance. Data science workloads are also very spikey, and so autoscaling in Kubernetes is very important. at Saturn, we solve this problem by explicitly tagging the node selector of every pod, so that it can only be scheduled on the correct ASG.</p><h3>Instance configuration</h3><p>This section assumes you are configuring EKS with terraform.</p><p>Should users be able to build docker images? This might be necessary if you want to do things like run <a href="https://binderhub.readthedocs.io/en/latest/">binderhub</a>. At Saturn, we allow certain pods to build docker images because we want to enable our docker image building service from standard data science configuration files. If so you’ll want to configure your ASGs with</p><pre>bootstrap_extra_args = &quot;--enable-docker-bridge true&quot;</pre><h3>But not for GPU machines!</h3><p>The docker bridge does not work on GPU nodes, so you should set</p><pre>bootstrap_extra_args = &quot;--enable-docker-bridge false&quot;</pre><p>terraform-aws-eks defaults ASGs to use the CPU AMI. If you are provisioning GPU nodes, you will have to find the GPU ami ID for your region, and pass that in to terraform. Here is the Python code we use to do this</p><pre>def get_gpu_ami(region):<br>    eks_owner = &quot;602401143452&quot;<br>    client = boto3.client(&quot;ec2&quot;, region_name=region_name)<br>    images = client.describe_images(Owners=eks_owner)[&quot;Images&quot;]<br>    ami_prefix = f&quot;amazon-eks-gpu-node-{settings.kubernetes_version}&quot;<br>    images = [x for x in images if x[&quot;Name&quot;].startswith(ami_prefix)]<br>    images = sorted(images, key=lambda x: x[&quot;CreationDate&quot;])<br>    image = images[-1]<br>    return image[&quot;ImageId&quot;]</pre><p>If you configure the wrong AMI, your nodes will come up like normal, but your expensive GPUs will not be available inside Kubernetes pods.</p><h3>Don’t forget the cluster-autoscaler.</h3><p>You need to tag ASGs to indicate how many GPUs are available, or else the autoscaler won’t know that your deep learning pod which needs 4 V100s can be scheduled on this box.</p><pre>{<br>          key = &quot;k8s.io/cluster-autoscaler/node-template/resources/nvidia.com/gpu&quot;<br>          value = &quot;4&quot;<br>          propagate_at_launch = true<br>        }</pre><h3>What Now?</h3><p>If you’ve read this far you must be thinking about setting up your own Kubernetes cluster for your data science team. I just have one question for you.</p><p><strong>Is this really the best use of your time?</strong></p><p>Your company can probably jerry rig a Kubernetes deployment, and set up a bunch of ASGs, and deploy jupyterhub, and then figure out how to deploy dask cluster, and then make sure that the dependencies you need are built into docker images that work well for both jupyter, and dask, and then make sure you configure EBS volumes properly so that data scientists don’t lose their work, and make sure you configure Calico, and nginx-ingress, and the load balancer so that traffic into your applications is secure. Are you planning to deploy dashboards? or models? Is there any sensitive information there? Do you need to provide access control and security around them? Don’t forget to set up jupyter-server-proxy, so that data scientists working in Jupyter/Lab need to use the dask dashboard and experiment with bokeh/plotly/voila as well right? Did you remember to bind one dask worker per GPU? Are you configuring RMM, and do you have proper GPU to Host memory spillover configured?</p><p><strong>Is this really the best use of your time?</strong></p><p><a href="https://www.saturncloud.io/s/pricing/">Our pricing</a> is pay as you go, billed through the AWS marketplace. I’d recommend renting our software rather than building your own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e009f045f65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/practical-issues-setting-up-kubernetes-for-data-science-on-aws-6e009f045f65">Practical Issues Setting up Kubernetes for Data Science on AWS</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake and Dask]]></title>
            <link>https://medium.com/data-science/snowflake-and-dask-33c84ce0bc36?source=rss-58d7b003c928------2</link>
            <guid isPermaLink="false">https://medium.com/p/33c84ce0bc36</guid>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Hugo Shi]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 01:49:44 GMT</pubDate>
            <atom:updated>2020-07-17T05:11:00.411Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to load data efficiently from Snowflake into Dask</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1eMuTOOVhrwG3Bod" /><figcaption>Photo by <a href="https://unsplash.com/@dariuscotoi?utm_source=medium&amp;utm_medium=referral">Darius Cotoi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Snowflake is the most popular data warehouse among our Saturn users. This article will cover efficient ways to load Snowflake data into Dask so you can do non-sql operations (think machine learning) at scale. Disclaimer: I’m the CTO of Saturn Cloud — we focus on enterprise Dask.</p><h3>The Basics</h3><p>First, some basics, the standard way to load Snowflake data into Pandas:</p><pre>import snowflake.connector<br>import pandas as pd</pre><pre>ctx = snowflake.connector.connect(<br>    user=&#39;YOUR_USER&#39;,<br>    password=&#39;YOUR_PASSWORD&#39;,<br>    account=&#39;YOUR_ACCOUNT&#39;<br>)<br>query = &quot;SELECT * FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1.CUSTOMER&quot;<br>pd.read_sql(query, ctx)</pre><p>Snowflake recently introduced a much faster method for this operation, fetch_pandas_all, and fetch_pandas_batches which leverages <a href="https://arrow.apache.org/">Arrow</a></p><pre>cur = ctx.cursor()<br>cur.execute(query)<br>df = cur.fetch_pandas_all()</pre><p>fetch_pandas_batches returns an iterator, but since we’re going to focus on loading this into a distributed dataframe (pulling from multiple machines), we’re going to setup our query to shard the data, and use fetch_pandas_all on our workers.</p><h3>What is Snowflake good for?</h3><p>It can be very tempting to rip all the data out of snowflake so that you can work with it in Dask. That definitely works, however, snowflake is going to be much faster at applying sql-like operations to the data. Snowflake stores the data and has highly optimized routines to get every ounce of performance out of your query. These examples will pretend like we’re loading the entire data into Dask — in your case, you will probably have some SQL query, which performs the sql-like transformations you care about, and you’ll be loading the result set into Dask, for the things that Dask is good at (possibly some types of feature engineering, and machine learning). <a href="https://www.saturncloud.io/s/">Saturn Cloud</a> has native integration with <a href="https://www.saturncloud.io/s/snowflake/">Dask and Snowflake</a>, so <a href="https://https//manager.aws.saturnenterprise.io/register">check that out if this is interesting to you</a>.</p><h3>How does Dask load data?</h3><p>You can think about a Dask dataframe as a giant Pandas dataframe that has been chopped up and scattered across a bunch of computers. When we are loading data from Snowflake (assuming that the data is large), it’s not efficient to load all the data on one machine, and then scatter that out to your cluster. We are going to focus on having all machines in your Dask cluster load a partition (a small slice) of your data.</p><h3>Data Clustering</h3><p>We need a way to split the data into little partitions so that we can load it into the cluster. Data in SQL doesn’t necessarily have any natural ordering. You can’t just say that you’re going to throw the first 10k rows into one partition, and the second 10k rows into another partition. That partitioning has to be based on a column of the data. For example, you can partition the data by a date field. Or you can create a row number by adding an identity column into your Snowflake table.</p><p>Once you’ve decided what column you want to partition your data on, it’s important to set up data clustering on the snowflake side. Every single worker is going to ask for a small slice of the data. Something like</p><pre>select * from table where id &lt; 20000 and id &gt;= 10000</pre><p>If you don’t set up data clustering, every single query is going to trigger a full table scan on the resulting database (I’m probably overstating the problem, but without data clustering, performance here can be quite bad)</p><h3>Load it!</h3><p>We aren’t going to use read_sql_table from the dask library here. I prefer to have more control over how we load the data from Snowflake, and we want to call fetch_pandas_all, which is a Snowflake specific function, and therefore not supported with read_sql_table</p><pre>import snowflake.connector<br>from dask.dataframe import from_delayed<br>from dask.distributed import delayed<br></pre><pre>@delayed<br>def load(connection_info, query, start, end):<br>    conn = snowflake.connector.connect(**connection_info)<br>    cur = conn.cursor()<br>    cur.execute(query, start, end)<br>    return cur.fetch_pandas_all()<br></pre><pre>ddf = from_delayed(*[load(connection_info, query, st, ed) for st, ed in partitions])<br>ddf.persist()</pre><p>This code assumes that partitions is a list of starting/ending partitions, for example:</p><pre>partitions = [(0, 10000), (10000, 20000), ...]</pre><p>delayed is a decorator that turns a Python function into a function suitable for running on the dask cluster. When you execute it, instead of executing, it returns a delayed result that represents what the return value of the function will be. from_delayed takes a list of these delayed objects, and concatenates them into a giant dataframe.</p><h3>Memory Optimizations</h3><p>This is advanced concepts, but I urge you to read this section, it can save you alot of time and headache from running out of memory on your workstation. Don’t assume that just because Snowflake says that a dataset is 20GB that it will be 20GB when you load it into pandas. The pandas in memory representation is always much larger, though you can get better by being good about data types.</p><h3>Diagnosing Memory Usage</h3><p>df.memory_usage(deep=True) is a good way to understand how much memory each column is using. This can help you understand what benefit you are getting from converting your data to appropriate DTypes.</p><h3>StringDType</h3><p>Python strings have roughly 40 bytes of overhead. That doesn’t sound like a lot, but if you have a billion strings, it can add up quickly. The new StringDType can help here.</p><pre>df[&#39;column&#39;] = df[&#39;column&#39;].astype(pd.StringDType())</pre><h3>Categorical DTypes</h3><p>Many string and numerical fields are actually categorical. Take a column named “Household Income”. Instead of a numerical value, you usually get data in bands, like “0-$40,000” or “more than $100,000”.</p><p>As a general guideline, I usually look for columns where the ratio of the number of unique values, to the number of rows is less than 1%.</p><p>In pandas, this is the relevant code.</p><pre>df[&#39;column&#39;] = df[&#39;column&#39;].astype(&quot;category&quot;)</pre><p>However, I’m assuming that loading the entire column out of snowflake in order to compute the categorical dtype is not feasible. I recommend the following type of query to identify which columns are good candidates for categorical dtypes:</p><pre>select <br>  count(distinct(col1)),<br>  count(distinct(col2)),<br>  ...<br> from table</pre><p>You can compare that result to the number of rows in your table in order to figure out which columns should be categorical.</p><p>Then to figure out the unique values</p><pre>select distinct(col1) from table</pre><h3>Putting it all together</h3><p>Assuming you’ve done some of the memory optimizations listed above, and you’ve figured out some fields that should be converted to StringDType, some that should be categoricals. And assuming that you have a dictionary called dtypes which is a mapping of column names, to the dtype you wish to coerce the result to.</p><pre>import snowflake.connector<br>from dask.dataframe import from_delayed<br>from dask.distributed import delayed<br></pre><pre>@delayed<br>def load(connection_info, query, start, end, dtypes):<br>    conn = snowflake.connector.connect(**connection_info)<br>    cur = conn.cursor()<br>    cur.execute(query, start, end)<br>    return cur.fetch_pandas_all().astype(dtypes)<br></pre><pre>ddf = from_delayed(*[load(connection_info, query, st, ed) for st, ed in partitions])<br>ddf.persist()</pre><p>Thanks for reading. If you’re interested in using <a href="https://www.saturncloud.io/s/snowflake/">Dask with Snowflake</a>, then <a href="https://manager.aws.saturnenterprise.io/register?trackid=17314f965cd13a-02aa54870e0bee-24414032-317040-17314f965ce320">I recommend you check out Saturn Cloud</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33c84ce0bc36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/snowflake-and-dask-33c84ce0bc36">Snowflake and Dask</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>