<?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[Inside Amp X - Medium]]></title>
        <description><![CDATA[A disruptive grid edge digital energy platform. The grid of the future is yours: clean, smart, resilient, connected. - Medium]]></description>
        <link>https://medium.com/amp-x?source=rss----209232ef7a3a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Inside Amp X - Medium</title>
            <link>https://medium.com/amp-x?source=rss----209232ef7a3a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:45:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/amp-x" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Streamlit how to guide: advanced tips for Data Scientists ]]></title>
            <link>https://medium.com/amp-x/streamlit-how-to-guide-advanced-tips-for-data-scientists-8b735a461ac0?source=rss----209232ef7a3a---4</link>
            <guid isPermaLink="false">https://medium.com/p/8b735a461ac0</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dean Shabi]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 13:00:22 GMT</pubDate>
            <atom:updated>2024-02-12T13:00:22.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fzg3L-LYtSuhZnU81nDmdg.png" /></figure><blockquote><a href="https://www.linkedin.com/company/65296009/admin/feed/posts/">Amp X</a> Data Scientist, <a href="https://www.linkedin.com/in/dean-shabi/">Dean Shabi</a>, provides his guide to navigating Streamlit.</blockquote><h4>Intro</h4><p>At <a href="https://www.linkedin.com/company/65296009/admin/feed/posts/">Amp X</a>, we use <a href="https://streamlit.io/">Streamlit</a> to create interactive Python-based web applications.</p><p>It allows our data scientists to convert their analyses into web apps without the need for front-end expertise.</p><p>In this blog post, we explore advanced Streamlit features and share tips for getting the most out of the tool. We cover topics such as creating a multipage app, adding a logo, setting page configuration, using third party libraries for additional functionality, caching data, and using query parameters to share contextual apps.</p><p>By leveraging these advanced techniques, you can enhance your data science workflow and create impressive Streamlit applications.</p><h3>Advanced Multipage Streamlit app</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w7lI2whGrjMI2E9i" /><figcaption>Example of a multipage app</figcaption></figure><p>Streamlit has native support for <a href="https://blog.streamlit.io/introducing-multipage-apps/">multipage apps</a>, where page file names are the source of truth for page settings. However, this approach has its limitations and can be confusing.</p><p>Page ordering is done by numbering the file names, and to add page icons you add emojis to the file name, a very non-pythonic method.</p><p>With a complex application, your files may look like this (from the official documentation):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*7jyhDWsUxOU3vKfG" /><figcaption>How streamlit requires pages file names</figcaption></figure><h4>Streamlit-Pages add-on</h4><p><a href="https://github.com/blackary/st_pages">Streamlit Pages</a> is an experimental, third-party add-on for Streamlit’s multipage apps, that allows you to set a page name, icon and order them as you wish.</p><p>There are two methods to configure the pages, by manually declaring them in code, or with a config file — which is easier to track and edit.</p><p>Here’s how we use it:</p><ul><li>Declare pages inside of a <strong>.streamlit/pages.toml</strong> config file</li></ul><pre>[[pages]]<br>path = &quot;main.py&quot;<br>name = &quot;Home&quot;<br>icon = &quot;🏠&quot;<br><br>[[pages]]<br>path = &quot;more_pages/plots.py&quot;<br>name = &quot;Plots&quot;<br>icon = &quot;📚&quot;</pre><ul><li>Call <strong>show_pages_from_config()</strong> at the top of each page, or scroll down to our <strong>set_streamlit_page_config_once()</strong> section below for an easier setup. You can also tweak the page title.</li></ul><pre>from st_pages import show_pages_from_config, add_page_title <br><br>show_pages_from_config()</pre><h4>Adding a logo to a Multipage App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*aZTrcGnJ7ZgO7e6h" /><figcaption>Branding your application can make it more appealing</figcaption></figure><p>Sometimes you want to add a custom logo to your app, for example when sharing it with a customer.</p><ul><li>With a multipage app, adding a picture to the sidebar will show below the page selection.</li><li>To add a logo across the app, above the pages, we will use HTML code:</li><li>change IMAGE_URL to the relevant link to the image.</li></ul><pre>def add_logo():<br>    &quot;&quot;&quot;<br>    Add logo to the sidebar, above multipage selection<br>    &quot;&quot;&quot;<br>    st.markdown(<br>        &quot;&quot;&quot;<br>        &lt;style&gt;<br>            [data-testid=&quot;stSidebarNav&quot;] {<br>                background-image: url(https://medium.com/IMAGE_URL);<br>                background-repeat: no-repeat;<br>                background-position: 20px 20px;<br>            }<br>        &lt;/style&gt;<br>        &quot;&quot;&quot;,<br>        unsafe_allow_html=True,<br>    )</pre><h4>Setting page configuration with a multipage Streamlit app</h4><ul><li><strong>st.set_page_config()</strong> helps <a href="https://docs.streamlit.io/library/api-reference/utilities/st.set_page_config">configuring the page settings</a>. It allows configuring titles, page icon, page layout and many more.</li><li>However, due to Streamlit’s nature, this must be the first command used on an app page, and must only be set once per page.</li><li>A known issue with multipage streamlit apps is that the layout can “reset” when navigating between the pages. If you want to configure each page, you’ll hit a StreamlitAPIException error.</li><li>A workaround for that is to use a function that does all the common setup that you want on each page, and then import and run that function on each of the pages.</li><li>Here’s how we did it, combining all of the above (setting config, streamlit-pages, adding a logo and more).</li></ul><pre>def set_streamlit_page_config_once():<br>    &quot;&quot;&quot;<br>    Set streamlit page config once<br>    This is a workaround around multiple pages in streamlit<br>    &quot;&quot;&quot;<br>    try:<br>        st.set_page_config(...)<br>        show_pages_from_config()<br>        add_logo()<br><br>    except st.errors.StreamlitAPIException as e:<br>        if &quot;can only be called once per app&quot; in e.__str__():<br>            # ignore this error<br>            return<br>        raise e</pre><p>Call <strong>set_streamlit_page_config_once()</strong> at the top of each page under /pages, and voila.</p><h3>Smaller bits and pieces</h3><h4>Streamlit alerts with timeout</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*c02EGyQryN57CbhS" /></figure><p>Streamlit alerts or banners are persistent by default.</p><ul><li>You can show Streamlit banners only for a short amount of time, to update your users on the progress of some processing.</li><li>This method will display a warning message and clear it out after 1 second.</li></ul><pre>def alert_with_timeout(alert: str, timeout: int = 1):<br>    alert = st.warning(alert)<br>    time.sleep(timeout) <br>    alert.empty() # hide alert</pre><ul><li>Then, call the <strong>alert_with_timeout()</strong>function with your custom message.</li></ul><h4>Use streamlit-extra to make your app shine</h4><p><a href="https://github.com/arnaudmiribel/streamlit-extras">Streamlit-extras</a> is a Python library putting together valuable Streamlit add-ons. It adds very useful functionalities to Streamlit, that we hope will be added to the library itself in the future.</p><p>You can explore all the little plugins by the <a href="https://arnaudmiribel.github.io/streamlit-extras/">documentation</a>.</p><p>Specifically, we’re using 📅 <strong>Mandatory Date Range Picker</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*g6IE8Z4vtxoUQ4JD" /></figure><p>Mandatory Date Range Picker will pause the app until date range is selected</p><ul><li>If you use <strong>st.date_input()</strong> to slice some pandas dataframe based on user’s choice, your code might run into exceptions while the user is choosing the ending time, as the app will run only with the first starting point.</li><li>Mandatory Date Range Picker is similar to st.date_input, but enforces that it always and only returns a start and end date, even if the user has only selected one of the dates. Until the user selects both dates, the app will not run.</li><li>Now, you don’t need to handle such exceptions in your code!</li><li>Import and use as a normal <strong>date_input()</strong> streamlit widget.</li></ul><pre>from streamlit_extras.mandatory_date_range import date_range_picker <br><br>start_time, end_time = date_range_picker(&quot;Select a date range&quot;)</pre><h4>Make sure your cached widgets work with multipage navigation</h4><ul><li>If you put Streamlit widgets inputs in the session state, you’ll discover that widget state for inputs with same keys is not synced when switching pages. What happens is that your session state will be preserved between pages, but your widgets will reset.</li><li>For example, you could store the output of <strong>date_range_picker()</strong> in a session state, to use in all of your pages, only to discover it gets reset when you come back to that page.</li><li>This is a <a href="https://github.com/streamlit/streamlit/issues/4989">known bug</a> that can be easily solved by calling this method at the top of each page.</li></ul><pre>def setup_widgets():<br>    for k, v in st.session_state.items():<br>        st.session_state[k] = v</pre><h4>The Magic of Caching</h4><p>Caching is a key feature in software development, and it’s especially important in Streamlit, though it’s often overlooked. In Streamlit, caching lets you save data in your app, meaning calculations only need to happen once, unless the input data changes.</p><p>Caching is crucial because it saves time. For example, if your Streamlit app is loading a large dataset from an API or doing a complex calculation, without caching, these tasks would have to be redone every time you make a change in the app. This can be very slow.</p><p>Streamlit offers two caching tools: <a href="https://docs.streamlit.io/library/api-reference/performance/st.cache_data">@st.cache_data</a> and <a href="https://docs.streamlit.io/library/api-reference/performance/st.cache_resource">@st.cache_resource</a>.</p><p>When used with a function, these tools enable Streamlit to remember and reuse the function’s result instead of recalculating it, as long as the inputs don’t change. This makes things faster and more efficient.</p><p>The difference between these two tools is in their use. <strong>@st.cache_resource</strong> is for functions that return global resources like database connections or machine learning models. On the other hand, <strong>@st.cache_data</strong> is for functions that return data, like data frame transformations, database queries, or machine learning predictions.</p><pre>st.cache_data()<br>def load_data():<br>    data = pd.read_csv(&#39;your_huge_dataset.csv&#39;)<br>    return data</pre><p>You can also set up time to clear the cache, like so:</p><pre>st.cache_resource(ttl = timedelta(days = 1))</pre><h4>Use Query Parameters to share contextual apps</h4><p>Streamlit allows using the app URL to share apps in the exact widget/state configuration. This feature allows you to share the exact view you’re experiencing, rather than just plots, images, or exports.</p><pre>https://your_app.streamlit.app/?first_key=1&amp;second_key=two</pre><pre>{<br>    &quot;first_key&quot; : &quot;1&quot;,<br>    &quot;second_key&quot; : &quot;two&quot;,<br>}</pre><p>The <strong>st.query_params()</strong> feature in Streamlit, introduced in version 1.30.0, provides a way to access and manipulate URL query parameters in Streamlit apps.</p><p>It offers a dictionary-like interface, allowing you to read and modify the parameters. Notably, it can handle repeated keys in the URL, but returns only the last value for each key using standard methods.</p><p>For more detailed information, you can refer to the official Streamlit documentation <a href="https://docs.streamlit.io/library/api-reference/utilities/st.query_params">here</a>.</p><h3>Wrapping Up</h3><p>Streamlit is an excellent tool for any data scientist, offering a simple, Pythonic way to build interactive and beautiful data applications. By utilising these advanced tips and tricks, you can maximise Streamlit’s capabilities and streamline your data science workflow.</p><p>Look out for our upcoming articles on Streamlit , where we’ll be looking at how to authenticate using Google Oath, and how to easily deploy a Streamlit app to k8s.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b735a461ac0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/amp-x/streamlit-how-to-guide-advanced-tips-for-data-scientists-8b735a461ac0">Streamlit how to guide: advanced tips for Data Scientists 📊🤖</a> was originally published in <a href="https://medium.com/amp-x">Inside Amp X</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Tips for Dask, vol3: Limited-fan Repartitions]]></title>
            <link>https://medium.com/amp-x/practical-tips-for-dask-vol3-limited-fan-repartitions-679b7cde16fa?source=rss----209232ef7a3a---4</link>
            <guid isPermaLink="false">https://medium.com/p/679b7cde16fa</guid>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <dc:creator><![CDATA[Vojtech Tuma]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 17:42:57 GMT</pubDate>
            <atom:updated>2022-03-28T17:42:57.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fQNmVDb3AADsjGd2_-amQ.jpeg" /></figure><p><em>Practical Tips for Dask </em>is a series of short blog posts accompanied with code snippets or notebooks, each focusing on a particular data engineering problem and its solution in <a href="https://dask.org/">Dask</a>.</p><p>Throughout the series, a common example of aggregating sensor measurements data will be used.</p><ol><li><a href="https://medium.com/amp-x/practical-tips-for-dask-vol1-7eca606e0e62">Schema transforms and parquet engines</a>.</li><li><a href="https://medium.com/amp-x/practical-tips-for-dask-vol2-partition-maps-df3498e036ab">Mapping partitions vs partition-wide groupby</a>.</li><li>Repartitioning with a limited fan-in/fan-out (this post).</li><li>… and more TBD.</li></ol><p>In this volume, I would like to demonstrate here how we managed to avoid an expensive repartition by using delayed tasks while solving a real problem with Dask.</p><h4>Problem Statement</h4><p>As in the previous post, we are analysing data from about five hundred sensors that provide measurements about once a minute. The required metrics to produce are uptimes and day-to-day differences in measured values. The data occupies about 4GB when stored in a snappy-compressed parquet. We had multiple files per day with sizes about 100MB — when read by Dask, those correspond to individual partitions, and are pretty right-sized (that is, uncompressed memory of the worker when working with those was between 50–80%).</p><p>In the previous post, we dealt with aggregation of the data, but made two important assumptions — the input data is not overlapping, and the aggregation is functorial. In this post, we remove those assumptions by making the input partitions larger, so that every resulting row in the aggregation can be computed from exactly one partition. This removes the need to run the intermediate aggregation, and thus the two assumptions as well.</p><p>In particular, we will want input partitions to correspond exactly to days, despite having possibly multiple parquet files per day. Our case was actually harder — our data was partitioned on disk by UTC timestamp, but the aggregation was supposed to be done by days from a different timezone. Thus, every partition we need to feed to aggregation requires some data from one input day, and other data from <em>another</em> input day.</p><h4>Solution</h4><p>Essentially, we want the result to look as if we did daskDf[&quot;local_timestamp&quot;] = convert(daskDf[&quot;utc_timestamp&quot;]) and then daskDf.groupby(daskDf.local_timestamp.dt.date). However, if we asked Dask just to run the groupby, it would do a terribly inefficient shuffle as it does not know that every group can be computed from a limited number of partitions — we call this property a <em>limited fan-in </em>of the partitions. Additionally, every input partition contributes to at most two real days — a <em>limited fan-out</em>. To achieve the computation efficiently and exploit those properties, we need to do some grindy coding.</p><p>In particular, we will not read the whole dataframe at once using Dask’s read_parquet. Instead, we start by creating a Dask delayed task which reads every parquet file. This has the additional boon of being easier to parallelize — by default, read_parquet itself does not launch a task but rather does the parquet crawl+scan from a single process. From reading a single file we don’t output a single partition, though — we rather split it by the local date, and output <em>two </em>partitions instead:</p><pre>@dask.delayed<br>def read_and_split(path, d1, d2):<br>  df = pd.read_parquet(path)<br>  df[“local_timestamp”] == &lt;conversion_function&gt;(df[&quot;timestamp&quot;])<br>  df1 = df[df.local_timestamp.dt.date == d1]<br>  df2 = df[df.local_timestamp.dt.date == d2]<br>  return df1, df2</pre><p>And we orchestrate this function as follows:</p><pre>daily_partition_lists = defaultdict(list)<br>for directory in glob(data_path_expression):<br>  day1, day2 = &lt;extract_dates_from_name&gt;(directory)<br>  delayed_result = read_and_split(directory, day1, day2)<br>  daily_partition_lists[day1].append(delayed_result[0])<br>  daily_partition_lists[day2].append(delayed_result[1])</pre><p>In the daily_partition_lists dictionary, for each day we have the list of input delayed tasks that consist just of the data which should comprise this partition — all we need is to combine them together into a single partition:</p><pre>def combine_one_day(daily_partition_list):<br>  combined_df = dask.DataFrame.from_delayed(daily_partition_list)<br>  repartitioned_df = combined_df.repartition(npartitions = 1)<br>  return repartitioned_df</pre><pre>dask_df = dask.DataFrame.concat(map(combine_one_day, daily_partition_lists.values))</pre><p>So far, we have done nothing beyond just reading some parquet file headers to get schemata, and constructing a rather large Dask task graph. We add the dask_df.map_partition(aggregation_function) to it, and then all the fun starts when we run compute. I think Dask handled this quite well — while there was some disk spilling of data, the default algorithm which determines the order in which tasks are computed behaved well, and no significant time overhead was introduced.</p><h4>Conclusion</h4><p>We have shown how to repartition input dataframe, in case of a limited fan-in &amp; fan-out, by directly reading individual partitions and using delayed tasks with multiple outputs. The more outputs you have, the larger is the memory overhead that needs possibly to be disk spilled. But it still may be way better than a full blown reindex with a shuffle. Another handy use case for this is when creating an input dataset for time series predictions — to predict for data from day D, you usually need a few rows from the end of D-1. So you repartition to create those short intra-day overlaps.</p><p>I try not to compare Dask and Spark generally, as each tool has its own strengths and weaknesses. In this particular regard, I believe that Dask triumphs for me— I’m not sure how I would solve this problem in Spark; possibly by going all the way down to the iterator representation of RDDs, and splitting/chaining them. And that would be way uglier than it is in Dask. However, both frameworks would benefit from having an explicit flatmap_partitions operation (limited so as to keep the task graph static), to be followed with a groupby_partitions (with explicit list of partitions, for the same reason)— which is exactly what we are doing here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=679b7cde16fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/amp-x/practical-tips-for-dask-vol3-limited-fan-repartitions-679b7cde16fa">Practical Tips for Dask, vol3: Limited-fan Repartitions</a> was originally published in <a href="https://medium.com/amp-x">Inside Amp X</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Tips for Dask, vol2: Partition Maps]]></title>
            <link>https://medium.com/amp-x/practical-tips-for-dask-vol2-partition-maps-df3498e036ab?source=rss----209232ef7a3a---4</link>
            <guid isPermaLink="false">https://medium.com/p/df3498e036ab</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dask]]></category>
            <dc:creator><![CDATA[Vojtech Tuma]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 15:45:13 GMT</pubDate>
            <atom:updated>2022-03-14T15:45:13.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYKBDtg8-WPSPw7gYYDbEw.jpeg" /></figure><p><em>Practical Tips for Dask </em>is a series of short blog posts accompanied with code snippets or notebooks, each focusing on a particular data engineering problem and its solution in <a href="https://dask.org/">Dask</a>.</p><p>Throughout the series, a common example of aggregating sensor measurements data will be used.</p><ol><li><a href="https://medium.com/amp-x/practical-tips-for-dask-vol1-7eca606e0e62">Schema transforms and parquet engines</a>.</li><li>Mapping partitions vs partition-wide groupby (this post).</li><li>Repartitioning with a limited fan-in (in progress).</li><li>… and more TBD.</li></ol><p>In this, volume I would like to demonstrate here how we managed to avoid an expensive groupby by just mapping partitions while solving a real problem with Dask.</p><h4>Problem Statement</h4><p>As in the previous post, we are analysing data from about five hundred sensors that provide measurements about once a minute. The required metrics to produce are uptimes and day-to-day differences in measured values. The data occupies about 4GB when stored in a snappy-compressed parquet. We had multiple files per day with sizes about 100MB — when read by Dask, those correspond to individual partitions, and are pretty right-sized (that is, uncompressed memory of the worker when working with those was between 50–80%).</p><p>In the previous post, we dealt with the data ingestion and initial transformation of the schema. In here, we will tackle the aggregation itself — essentially, we would like two things: for every day, compute the difference between the first and last measured value by the sensor, to obtain the delta; and calculate how many measurements did not arrive — that is, during which minutes the sensor failed to communicate. Both of these per day and sensor.</p><h4>Solution</h4><p>If the data was small, we would just read it in Pandas and run a groupby. However, the original raw data don’t fit, so we either have to aggregate in Dask itself, or reduce the data size first somehow, before descending to Pandas.</p><p>A naive approach starts by daskDf.groupby([&quot;sensorId&quot;, &quot;day&quot;]).agg(...). However, the problem is that this causes a wide shuffle. If there is no shuffle, Dask has each of its workers process partitions (at the start, the input parquet files) sequentially, discarding all intermediate results and keeping only the final outcome. This is quite efficient as you need much smaller memory capacity. But if you do a groupby out of the blue, you essentially require Dask to materialize all the data at once — which may cause memory errors, too much disk spilling, and overall slowness.</p><p>Dask best practice says “prefer groupby on indexes only” — why does it matter? If the column you groupby on is indexed, Dask knows that every resulting group of a groupby requires just a limited number of input partitions — and thus can run the whole operation without materialising the whole dataset first. Can we do that here? Our data is stored in partitions that correspond to dates — so if we were grouping by date only, we could explicitly tell Dask which boundaries our partitions correspond to. However, we also group by the sensor id, and those are spread across files randomly.</p><p>A solution is at hand by going down to Pandas with map_partitions again. For every partition, we run an intermediate aggregation that calculates for every sensor id how many measurements there were, and what was the delta of the sensor’s measurements. The dataframe that results from this aggregation is much smaller in size, and thus can be materialised to Pandas — and we can then run a standard groupby on it. We just need to be careful when combining the results correctly — sum the measurements counts (and then divide by the expected count, 24*60, to get the percentage uptime), and compute the delta by taking the first and the last intermediate aggregation results.</p><p>Note that this rests on two assumptions. The first is what can be called <em>functoriality </em>or <em>commutativity </em>of the aggregation. A function F has this property with respect to some combinator +, if F(input1) + F(input2) == F(input1+input2), which is just symbolic way of saying that a result can be computed by dividing the problem into two, computing subresults, and then combining. For example, computing percentage uptime is <em>not</em> functorial — if I tell you that in some part of the day the uptime was 70%, and in another, 85%, you cannot compute the uptime for a day. But, if I instead give you just counts of events in those parts, you can then combine by summing those numbers — and divide by the expected number only at the very end. A similar example is that computing the average of a list is <em>not </em>functorial, whereas outputting the sum of the list and its number is. A notorious example that cannot be essentially made functorial is counting distinct IDs across events — you basically need to output all the distinct IDs at every stage, leading to large intermediate datasets (or resort to hyperloglog and pay with lesser accuracy).</p><p>A second assumption is that the input partitions are not overlapping — that is, there are not duplicated measurements that would be spread across multiple input partitions. The proper way here would be to merge input partitions that are possibly containing duplicates, and de-duplicate in the intermediate aggregation step. This is of course possible only if those merged partitions are not too large. We show in the next post how to do this in a slightly more general way.</p><h4>Conclusion</h4><p>Instead of groupby on a Dask dataframe on un-indexed columns, consider instead one of:</p><ul><li>Set index explicitly if it corresponds to how input data came to be.</li><li>Compute an intermediate aggregation to reduce the size, and then descend to Pandas.</li></ul><p>A shuffle of data on Dask is a major source of degraded performance, and requires more careful memory/IO management, so it is really worthwhile to do some more thinking and coding to avoid it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df3498e036ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/amp-x/practical-tips-for-dask-vol2-partition-maps-df3498e036ab">Practical Tips for Dask, vol2: Partition Maps</a> was originally published in <a href="https://medium.com/amp-x">Inside Amp X</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Tips for Dask, vol1]]></title>
            <link>https://medium.com/amp-x/practical-tips-for-dask-vol1-7eca606e0e62?source=rss----209232ef7a3a---4</link>
            <guid isPermaLink="false">https://medium.com/p/7eca606e0e62</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[sofware-development]]></category>
            <dc:creator><![CDATA[Vojtech Tuma]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 12:24:26 GMT</pubDate>
            <atom:updated>2022-03-07T12:24:26.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYKBDtg8-WPSPw7gYYDbEw.jpeg" /></figure><p><em>Practical Tips for Dask </em>is a series of short blog posts accompanied with code snippets or notebooks, each focusing on a particular data engineering problem and its solution in <a href="https://dask.org/">Dask</a>.</p><p>Throughout the series, a common example of aggregating sensor measurements data will be used.</p><p>Expected volumes (names not final):</p><ol><li>Schema transforms and parquet engines (this post).</li><li>Mapping partitions vs partition-wide groupby (in progress).</li><li>Repartitioning with a limited fan-in (in progress).</li><li>… and more TBD.</li></ol><h3>Schema transformation and parquet engines</h3><p>I would like to demonstrate here two best practices we applied while solving a real problem with Dask — applying transformations carefully, and picking an engine suitable to the format.</p><h4>Problem Statement</h4><p>We are analysing data from a few hundred sensors that provide measurements about once a minute. The required metrics to produce are uptimes and day-to-day differences in measured values. The data occupies about 4GB when stored in a snappy-compressed parquet. We had multiple files per day with sizes about 100MB — when read by Dask, those correspond to individual partitions, and are pretty right-sized (that is, uncompressed memory of the worker when working with those was between 50–80%).</p><p>Parquet is a great format for larger tabular data, as it reduces the I/O volume at the cost of CPU, which is often a desirable tradeoff. It was clear from the start we wanted to use it, but what was not clear is the schema. The source of the data are events in Kafka as produced by some microservices in Avro format — and since those events reflect objects used in those services, the schema is not flat but rather nested: the top level fields are not scalars (e.g., time, measurement value, sensor id) but rather structures such as SensorIdentification or MeasurementsCollection, which themselves contain the scalar fields. Since we wanted the code that ingests the events from Kafka to our storage for analytics (just S3) to be as simple as possible, we deployed a Kafka Connect with just parquet conversion and no transformations applied.</p><h4>Solution</h4><p>The first attempt to work with the data in Dask encountered an issue — the columns were the top-level structures, and their values were dictionaries, so we cannot do like df[&quot;measurementsCollection.temperatureValue&quot;].mean(). A naive attempt to get around would be “ok so we just transform every dictionary into individual columns, and then work with them”. Dask has the apply function, similar to pandas but it works only on row levels — so we define lambda row: {&quot;temperature&quot;: row[&quot;measuremensCollection&quot;].get(&quot;temperature&quot;, np.nan), &quot;power&quot;: ...} and pass it to apply with result_type = &quot;expand&quot; . Dask happily applies this in a distributed fashion across the partitions.</p><p>However, as we compute, we get warned that workers are spending too much time in garbage collection, instead of doing useful work. Why is this? For every row, we allocate a new python dictionary, which is not exactly a lightweight object, and discard it right away as it is converted back to numpy representation — and this causes a frequent GC. We try replacing dictionaries with lists but that does not help, and going with pd.Series is even worse.</p><p>Now is a good time to remember that even in Pandas, it is best to stick to operations on whole numpy arrays, not on individual rows, to have good speed. Dask’s apply does not accept column-axis (for imo good reasons) — but Dask is “just” distributed pandas, so the trick here is to use map_partitions, which is a very efficient operation as it is directly executable in parallel, and feed it a function which transforms the Pandas dataframe that represents the partition — in our case, it is just lambda pdDf: pd.DataFrame(df[&quot;meaurementsCollection&quot;].to_numpy().tollist())).</p><p>The speed difference is really significant — on a single node with 6 process-workers with 2GB memory each, the whole pipeline took 25 minutes with the row-level apply, but just 4 with the column-level numpy transformation. So even as simple thing as data schema preparation can make a big difference.</p><p>Could we do even better? It turns out that the whole preprocessing could be avoided in the first place! We were using the pyarrow engine at the beginning — and I was not able to come up with means of making it expand the columns automatically. However, when switching to fastparquet, I’ve noticed that it does expand the structures by default, so I already can access the columns via df[&quot;measurementsCollection.temperature&quot;]. I’m not comparing fastparquet and pyarrow generally, as there are many other factors — but in this simple case, fastparquet was a better fit, speeding down to 3 minutes. That said, there are conceivable cases where some flattening transformation would still be required regardless of engine, e.g., if the data contained arrays or maps within rows. Another tricky situation is where fastparquet has trouble parsing the data— recently, I’ve encountered such case where it may have to do something with fields nested in distinct substructures having same name but a different schema.</p><h4>Conclusion &amp; Addenda</h4><ul><li>Use apply on the row axis very carefully; prefer numpy operations.</li><li>Make sure you use the correct engine for parquet, and that you use it correctly (further factors are e.g. pushdown predicates, column filters, compression algorithms, row groups — to be discussed in future posts).</li><li>Engines matter for CSVs as well, see e.g. <a href="https://pythonspeed.com/articles/pandas-read-csv-fast/">https://pythonspeed.com/articles/pandas-read-csv-fast/</a>.</li><li>We encountered what looks like a weird bug in Pandas: when a parquet file has just one row, and you use apply on it which returns a dictionary with result_type=&quot;expand&quot; and axis=&quot;rows&quot;, the columns in the result are not in the order you prescribed but sorted alphabetically. This of course breaks the result, and Dask helpfully reports it early due to actively comparing the resulting schema with the provided meta. However, list or pd.Series don’t exhibit this behaviour. I did not investigate this further — maybe it is intended as a subtle nudge for not using the row-level apply.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eca606e0e62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/amp-x/practical-tips-for-dask-vol1-7eca606e0e62">Practical Tips for Dask, vol1</a> was originally published in <a href="https://medium.com/amp-x">Inside Amp X</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speeding up Google’s Temporal Fusion Transformer in TensorFlow 2.0]]></title>
            <link>https://medium.com/amp-x/speeding-up-googles-temporal-fusion-transformer-in-tensorflow-2-0-b45721e5663a?source=rss----209232ef7a3a---4</link>
            <guid isPermaLink="false">https://medium.com/p/b45721e5663a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Amp X]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 09:05:00 GMT</pubDate>
            <atom:updated>2020-09-03T12:08:01.835Z</atom:updated>
            <content:encoded><![CDATA[<p><em>by Martin Holecek, </em><a href="http://ampx.energy/"><em>Amp X</em></a><em> Machine learning</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*OmDRzmuE_zBdV-QhGO0qaQ.png" /></figure><p>Deep learning has conclusively conquered many areas of machine learning like image recognition, natural language processing etc. Time series forecasting, however, is one of the last holdouts, where despite deep neural networks having won several battles, the war is not yet decidedly won.</p><p>One of the most recent innovations in this area is the Temporal Fusion Transformer (TFT) neural network architecture introduced in <a href="https://arxiv.org/abs/1912.09363">Lim et al. 2019</a> accompanied with implementation covered <a href="https://github.com/google-research/google-research/tree/master/tft">here</a>.</p><p>TFT brings together several interesting ideas for time series modelling. We wanted to explore the architecture and benchmark it with respect to well established models like the <a href="https://ieeexplore.ieee.org/document/8489522/">SeriesNet architecture</a> by Shen et al. 2018, based on the popular <a href="https://arxiv.org/abs/1609.03499">WaveNet</a> model by Google’s DeepMind.</p><p>There is a major difference between TFT and SeriesNet both in architectures and implementations.</p><p>SeriesNet has convolutional architecture that can operate on whole sequences, giving results as the convolutional window slides over the data set.</p><p>The TFT architecture is derived from the Seq2Seq approach (with encoder and decoder), thus when operating on a sequence, it needs a specifically prepared (windowed) input. Consequently the training times of TFT are significantly longer than for SeriesNet.</p><p>Fortunately, there is a way to build the moving window algorithm to work in an accelerated manner on GPU with TensorFlow.</p><p>We have developed, and are sharing <a href="https://github.com/AmpX-AI/tft-speedup">here</a> our solutions in TensorFlow model engineering. We have tried to make the code as similar to the original while adding those updates and options for the model:</p><ul><li>Converting the model from TensorFlow version 1 to 2</li><li>Creating the model with named inputs (and thus removing the part where it needed to decode all the information from the windows).</li><li>Creating the model wrapped in vectorizing routines.</li><li>Propagating the vectorization deeper in the model only where it is needed.</li></ul><p>(<em>All these steps have their corresponding parameterized examples included in the tests provided, we will occasionally mention the routine names here to make it easier to look everything up in the code </em>.)</p><p>The reason for all those steps is to make the work more accessible, and to showcase the vectorization technique first by regarding the TFT as a ‘blackbox’.</p><h4>Towards vectorization</h4><p>The basic idea is that every TensorFlow model already works in a vectorizable manner — as the model needs to be able to call itself (in parallel) over the batch dimension(s) of the data.</p><p><strong>Batch dimensions</strong></p><p>Some models do accept more than one batch dimension. In these cases, we can squash all the batch dimensions into one, call the model and then restore the dimensions from the result.</p><p>Both operations however need to be done in TensorFlow to not introduce any slowdown:</p><pre>def squash_batch_dimensions(seq, batch_dims):<br>    &quot;&quot;&quot;Squashes first (batch_dims) dimensions into 1 batch dimension.&quot;&quot;&quot;<br>    batch_shape_orig = tf.shape(seq)[:batch_dims]<br>    retain_shape = tf.shape(seq)[batch_dims:]<br>    new_shape = tf.concat([[-1], retain_shape], axis=-1)<br>    seq_squashed = tf.reshape(seq, new_shape)<br>    return seq_squashed, batch_shape_orig</pre><pre>def unsquash_batch_dimensions(seq: tf.Tensor, batch_shape_orig: Union[list, tf.Tensor]):<br>    &quot;&quot;&quot;Restores additional dimensions previously squashed to the first batch dimension&quot;&quot;&quot;<br>    batch_dims = 1<br>    retain_shape = tf.shape(seq)[batch_dims:]<br>    new_shape = tf.concat([batch_shape_orig, retain_shape], axis=-1)<br>    seq = tf.reshape(seq, new_shape)<br>    return seq</pre><p>So lets imagine we have disentangled the inputs in TFT from windowed encoding.</p><p>Now in its pure form, TFT needs to know historical (H) and future inputs (F) at each point in time (where some historical features are in fact included in the future if those are known in advance or are repetitive):</p><pre>H ##############################<br>F -----##############################</pre><p>Note that the sequence F is longer, since future known inputs need to be known also for the last historical input. The character ‘-’ means, that this input will never be used and so is omitted.</p><p>Windowed approach takes — at each timestep — a specific number of H inputs and also the needed future inputs from F:</p><pre>H XXXXXXXXXX####################<br>F -----#####XXXXX####################<br>           ^ as source data at each timepoint</pre><p>And so if we want to introduce a parallel/vectorized approach for windowing, we need our data (labelled for better understanding):</p><pre>H 123456789012345678901234567890<br>F -----FGHIJKLMNOPQRSTUVWXYZABCDEFGHI</pre><p>To be reshaped as follows (read as columns, from top to bottom):</p><pre>1234...901 ^<br>2345...012 |<br>3456...123 |<br>4567...234 |<br>5678...345 |  Model&#39;s historical inputs<br>6789...456 |<br>7890...567 |<br>8901...678 |<br>9012...789 |<br>0123...890 V &lt;- last (H) inputs<br>KLMN...CDE ^ &lt;- first (F) inputs<br>LMNO...DEF |<br>MNOP...EFG |  Model&#39;s future inputs<br>NOPQ...FGH |<br>OPQR...GHI V</pre><p>Now if we accept that our model needs to get executed on individual columns of data, we have just introduced a new batch dimension. Note, that it is still just a windowing technique applied on two streams (H and F) of data.</p><p><strong>Implementing windowing</strong></p><p>A technical detail on how to implement the windowing in TensorFlow needs to be discussed.<br>There are several possibilities — if there would be any vectorized version of slice or roll operation, that would be preferred. However, since those operations are not present in vectorized version, we could also imagine using matrix multiplication, which is unfortunately too memory heavy.</p><p>Our final design uses the gather function. We first generate the integer indices and then just reshape the array to fit the target rectangle. (Target rectangle with the shape of the given window length and number of repeats. Number of repeats being the original sequence length — window length + 1.)</p><p>Overall tf documentation is full of similar ideas (see for example <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/math/fill_triangular">here</a>).</p><p>The TensorFlow function we get needs also to respect existing batch dimensions:</p><pre>def windowing_mechanism(seq_data, batch_dims, window_len):<br>    &quot;&quot;&quot;Reformats data in timesequence dimension into two dimensions of [number of windows, window length] by windowing.</pre><pre>    :param seq_data: Original data with time dimension at seq_data.shape[batch_dims] position<br>        and features at seq_data.shape[batch_dims:]<br>    :param batch_dims: Defines the number of dimensions to regard as batch at the start. Expects non-tensor.<br>    :param window_len: Window length to produce. Expects non-tensor (?)<br>    :return: windowed original sequence of shape:<br>        list(data.shape[:batch_dims])<br>        + [data.shape[batch_dims] - window_len + 1, window_len]<br>        + list(data.shape[batch_dims + 1 :])<br>    &quot;&quot;&quot;</pre><pre>    rep = (<br>        get_shape_fixed_if_possible(seq_data)[batch_dims] - window_len + 1<br>    )  # when windowing, we will repeat that many times</pre><pre>    # as is first nonbatch dimension - window len + 1<br>    i = tf.range(0, window_len * rep, delta=1, dtype=None, name=&quot;range&quot;)  # now we will produce indexes for gather<br>    indices_orig = tf.math.floormod(i, window_len) + tf.math.floordiv(i, window_len)<br>    # in this manner: [[ 1,  2,  3,  4,  5,  ..  2,  3,  4,  5,  6,  ..  3,  4,  5,  6,  7, .. ]]</pre><pre>    # expand indices for aligning with batch dimension to use tf.gather on batched data:<br>    indices = expand_to_match_first_dims(indices_orig, seq_data, batch_dims)<br>    # should match all the batch dims before!</pre><pre>    result = tf.gather(seq_data, indices, batch_dims=batch_dims,)<br>    # now reshape it in the form of the matrix we want:<br>    new_shape = tf.concat(<br>        [tf.shape(seq_data)[:batch_dims], [rep, window_len], tf.shape(seq_data)[batch_dims + 1 :]], axis=-1<br>    )<br>    windowed = tf.reshape(result, new_shape)<br>    return windowed<br>    # ... now regard the first (batch_dims+1) dimensions as batches for any model to apply</pre><p>Now, if we regard TFT only as a batchable blackbox, the function needs to be used on both F and H inputs. Together with a batch dimension squash:</p><pre># windowing described in the docstring ^<br>historical_windowed = windowing_mechanism(<br>    historical_inputs, batch_dims=1, window_len=self.num_encoder_steps<br>)<br># since the insides of the model are not easily used on 4 dim sequence with first two dimesnions being batch<br># we need to squash the dimensions into the batch dimension:<br>historical_windowed_squashed, historical_windowed_orig_size = squash_batch_dimensions(<br>    historical_windowed, batch_dims=2<br>)</pre><pre># now we must repeat the batch dimension for static inputs to match the new batch dimension of &quot;squashed&quot;<br>static_emb_repeated = repeat_multiply_batch_dimension(static_emb, tf.shape(historical_windowed)[1])</pre><pre>future_windowed = windowing_mechanism(future_emb, batch_dims=1, window_len=self.get_future_fork_size())<br>future_windowed_squashed, future_windowed_orig_size = squash_batch_dimensions(future_windowed, batch_dims=2)</pre><pre>transformer_layer_squashed, attention_components = self.build_base_tft_graph(<br>    historical_windowed_squashed, future_windowed_squashed, static_emb_repeated<br>)<br># back to 4D: (from 3D squashed to batch dimension)<br>transformer_layer = unsquash_batch_dimensions(transformer_layer_squashed, historical_windowed_orig_size)</pre><p>The beauty of this approach lies in the fact it can be used on any other model with even more simplicity (when it does not need both F and H streams).</p><p>(<em>This version of the model is tested in</em> test_tft_model_vectorized_saving<em> that it saves and executes the graph properly</em>).</p><h3>Deeper into the provided code</h3><p>By delving deeper into the model, we could make the model to accept only one stream (masking some inputs from H when F was needed) and using the batching-unbatching tricks only at the places needed.<br>It turns out that only LSTM (and probably attention) did need the batch dimension trick, everything else was vectorizable nicely (with some minor tinkering around fixing the negative dimensions).</p><p>(<em>The final version is tested in</em> test_tft_single_sequence.)</p><p><strong>Technical notes</strong></p><ul><li>All the tests are separated in their own processes to not mangle the TF graphs</li><li>The TFT objects do keep their original interface, but some parameters are now unused in the new approaches. That is some sort of a balance by trying to keep the original code as intact as possible and providing new means of execution.</li><li>The difference between acting as blackbox and propagating vectorization deep inside the model is based on a parameter to allow experimentation.</li></ul><p><strong>Benchmark setup</strong></p><p>We have created an experimental setup with an artificial series featuring some noise and some hidden computational rules to test both model variants on a GPU.<br>To make the test as close to reality as possible, we have allowed the base version to use a bigger batch size than the vectorized one.<br>First, from the point of view of epoch times, we can see a tremendous speedup:</p><ul><li>from 18 seconds per epoch (base version):</li></ul><pre>Epoch 4/4<br>901/901 [==============================] - 21s 23ms/step - loss: 0.4995 - val_loss: 0.5315</pre><ul><li>to 5 seconds per epoch (vectorized version):</li></ul><pre>Epoch 4/13<br>32/32 [==============================] - 5s 151ms/step - loss: 0.5060 - val_loss: 0.5298</pre><p>Per step times are bigger in the vectorized version, since one step means looping over the whole sequence (while we feature 32 sequences per epoch).</p><p>While the engineering victory of a more than factor 4 speedup in epoch is very encouraging, we need to also check the time to reach the same level of validation loss.</p><p>The vectorized approach is summing all gradients and applying them all at once per epoch. Therefore, the number of required epochs increases slightly, as the technique provides also a smaller number of gradient updates.</p><p>Despite the increased number of epochs, the code runs faster in total in training. Inference benefits massively from the vectorization, since it does not require gradients.</p><p>We have plotted the times to an epoch together with its validation loss for both setups (green being vectorized, blue basic):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*0wYNDOm6gjS2ralT-XTGqg.jpeg" /></figure><p>If we look at the logs of both epochs #4 again, we can see that the basic version got near the level of 0.5315 in 88 seconds. While the vectorized version was at 0.5298 before 30 seconds elapsed.</p><p>So in this experiment, the vectorized version is roughly 3 times faster in terms of loss.</p><p>Even though we have fixed the seeds and random generators before each experiment to the same value, the ‘race’ can never be fair. Each method is exploring the space differently and can have some sort of a numerical ‘luck’, which depends on the problem and data itself. The code is provided for experimenting and we encourage deeper benchmarking. You can also notice, that by setting the artificially generated data to an easier problem, the basic version can win, because it propagates gradients more often (i.e. after each timestep).</p><p>We note that our proprietary application of the TFT model shows a speed-up consistent with the experimental setup presented here.</p><h3>Conclusion</h3><p>We translated the TFT model into TensorFlow 2.0 and have demonstrated a vectorization technique for windowing.<br>The vectorization brings performance speed-up both in terms of per epoch time and time to to reach same validation loss.</p><p>In a simple benchmark (which you can reproduce by cloning from our <a href="https://github.com/AmpX-AI/tft-speedup">github</a>), we demonstrated reduction of the time per epoch by factor ~4 and the ‘time to same loss’ by factor ~3, consistent with our in-house real-world data applications.</p><p>The presented method is not a direct replacement for any windowing technique, but should serve as an addition to a library of techniques (as would, for example, a new optimizer serve in the context of all existing optimizers).</p><h3>Acknowledgements</h3><p>We would like to thank the google engineering team for their initial work on TFT model, and of course to our collegues in AMP and AMPX, namely Simon Ondracek and Robert Suhada for their contributions to the project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b45721e5663a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/amp-x/speeding-up-googles-temporal-fusion-transformer-in-tensorflow-2-0-b45721e5663a">Speeding up Google’s Temporal Fusion Transformer in TensorFlow 2.0</a> was originally published in <a href="https://medium.com/amp-x">Inside Amp X</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>