<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Christopher Grainger</title><link>https://cigrainger.com/</link><description>Notes on software, data, and machine learning.</description><language>en</language><lastBuildDate>Thu, 09 May 2024 00:00:00 +0000</lastBuildDate><atom:link href="https://cigrainger.com/feed.xml" rel="self" type="application/rss+xml"/><item><title>What I mean when I say that machine learning in Elixir is production-ready</title><link>https://cigrainger.com/blog/elixirconf-eu-2024-keynote/</link><guid isPermaLink="true">https://cigrainger.com/blog/elixirconf-eu-2024-keynote/</guid><pubDate>Thu, 09 May 2024 00:00:00 +0000</pubDate><description><![CDATA[<p>My ElixirConf EU 2024 keynote <a href="https://youtu.be/5FlZHkc4Mq4?si=agofn18zjoKHZw6S">&quot;Ship it! A roadmap for putting Nx into production&quot;</a> is up on youtube. I'm hoping it will help folks gain the confidence to go out and... ship it!</p>
<p>I often say 'machine learning in Elixir is ready for production'. On further reflection, I realised that this statement dramatically undersells the true potential and capabilities of machine learning within the Elixir ecosystem. (I already posted these reflections <a href="https://twitter.com/cigrainger/status/1788147429021237592">on Twitter</a>).</p>
<p>When I say &quot;production-ready,&quot; it's not just about the ability to deploy machine learning models in a live environment. In the context of Elixir, being production-ready means deep integration with the weird and wonderful thing called the BEAM (Bogdan/Björn's Erlang Abstract Machine). It means seamless compatibility with OTP (Open Telecom Platform) primitives, which are the building blocks of Elixir applications.</p>
<p>This deep integration is what makes machine learning in Elixir so powerful. Just as Elixir has proven to be a cheat code for building web applications and distributed systems, it now offers the same advantage for machine learning tasks. The Elixir ecosystem provides a secret weapon that empowers developers to build and deploy machine learning solutions with unparalleled ease and efficiency.</p>
<p>For a growing set of areas where Elixir's machine learning ecosystem is applicable (which is already pretty extensive), I firmly believe that you're better off shipping inference with Elixir than basically anything else. In many cases, it's even worthwhile to conduct experiments and model training in Elixir, despite the relative youth of that part of the ecosystem.</p>
<p>So, what makes machine learning in Elixir so powerful? Mainly: OTP. Also: good choices. <a href="https://github.com/elixir-nx/nx">Nx</a> was built from the ground up with inspiration from JAX, a popular machine learning framework. By leveraging metaprogramming and embracing pluggable backends and compilers from day one, Nx benefits from a significant second-mover advantage. This architectural decision, which I covered in more detail during my ElixirConf EU talk, unlocks huge potential that we see play out in the libraries built on top of it like <a href="https://github.com/elixir-nx/axon">Axon</a>, <a href="https://github.com/elixir-nx/bumblebee">Bumblebee</a>, and <a href="https://github.com/elixir-nx/scholar">Scholar</a>.</p>
<p>Thanks to these foundational choices, the entire Elixir machine learning ecosystem can reap the benefits. With <code>defn</code>, a macro provided by Nx, machine learning capabilities are practically built into the language itself. Take a moment to reflect on the significance of this: by simply writing Elixir code, you gain access to multi-stage compilation that targets various hardware platforms, including GPUs and TPUs.</p>
<p>Moreover, <a href="https://hexdocs.pm/nx/Nx.Serving.html"><code>Nx.Serving</code></a>, a module in <code>Nx</code> for serving machine learning models, is just wild. You get out-of-the-box distributed, clustered, hardware-agnostic automatic batching without the caller needing to concern itself with any of that? Just wild. It's the right separation of concerns.</p>
<p>The actor model of concurrency, which is at the heart of Elixir, proves to be the perfect abstraction for serving machine learning workloads and, just as importantly, integrating them into broader systems. By encapsulating models within processes, you can leverage all the built-in features that make the BEAM so powerful. <code>Nx.Serving</code> is just another application in your supervision tree, making it just another component of your robust and fault-tolerant system.</p>
<p>So integrating machine learning into a Phoenix application becomes a breeze. You can take advantage of libraries like Oban for durable and robust job processing, Broadway for concurrent data processing pipelines with backpressure, and FLAME for lambda-like execution on the BEAM. You can send pubsub messages about progress, results, etc to LiveViews (which are, of course, just processes). And of course those updates can trigger changes in views like I describe in <a href="https://x.com/cigrainger/status/1788490429341532351">this thread</a>.</p>
<p>The beauty of the Elixir ecosystem lies in its ability to create brilliant features for end users with minimal effort. We routinely handle thousands and millions of messages per day over pubsub and between processes, showcasing the scalability and efficiency of the system.</p>
<p>You can add machine learning to Saša Jurić's famous chart. So if Rails is considered the &quot;one person framework,&quot; then Phoenix can be seen as the &quot;half person framework,&quot; from basic CRUD operations to the cutting edge of LLMs.</p>
<p>Machine learning in Elixir is production-ready. In this ecosystem, that statement means a lot.</p>
<div class="video"><iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen loading="lazy" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/5FlZHkc4Mq4" title="YouTube video player"></iframe></div>]]></description></item><item><title>Explorer 0.8: The dtype release</title><link>https://cigrainger.com/blog/explorer-0-8-0/</link><guid isPermaLink="true">https://cigrainger.com/blog/explorer-0-8-0/</guid><pubDate>Mon, 22 Jan 2024 00:00:00 +0000</pubDate><description><![CDATA[<p>Well... it's been a while. Almost two years in fact! I would opine that time flies but it terrifies me so let's leave it there (everybody loves a bit of existential dread with their code blogs). I <a href="https://cigrainger.com/introducing-explorer/">last posted</a> having published <code>v0.1.0</code>  of <a href="https://hexdocs.pm/explorer/Explorer.html"><code>Explorer</code></a>, a dataframe library for Elixir. Since then, this little library has grown up &mdash; a lot. I moved to the other side of the world and between that and some big work stuff that took all my time and meant we stopped using dataframes in our ETL, I drifted away from the project a bit. <a href="https://github.com/philss">Philip Sampaio</a> and <a href="https://github.com/josevalim">José Valim</a> took over maintenance of the project in my absence and really drove it forward. And in November, we added another member to the core team: <a href="https://github.com/billylanchantin">Billy Lanchantin</a>!</p>
<p>There have been a ton of milestones that have made Explorer a unique contender among dataframe libraries:</p>
<ul><li><a href="https://hexdocs.pm/explorer/Explorer.Query.html"><code>Explorer.Query</code></a> brought macros to the main <code>DataFrame</code> verbs, enabling the use of regular Elixir code like infix operators, <code>if</code>, <code>unless</code>, <code>cond</code>, and for-comprehensions to compile to efficient dataframe operations. This makes writing <code>Explorer</code> much more concise and readable, and stands alone when compared to <code>pandas</code> and <code>dplyr</code> even in terms of reducing impedance mismatch between the dataframe library and the rest of the language. I could (and should) write a blog post about this one alone, but go check out <a href="https://hexdocs.pm/explorer/Explorer.Query.html">the docs</a> in the meantime.</li><li>José and <a href="https://github.com/cocoa-xu">Cocoa</a> (and others in the community) put together <a href="https://github.com/elixir-explorer/adbc">ADBC</a> bindings for Elixir (which José <a href="https://www.twitch.tv/collections/W_3_kJ4ncRcYhw">livestreamed</a>). This permits us to get data from databases over <a href="https://arrow.apache.org/docs/format/ADBC.html">ADBC</a> and use it in Explorer without copying or marshalling. Explorer now has <a href="https://hexdocs.pm/explorer/Explorer.DataFrame.html#from_query/4"><code>Explorer.DataFrame.from_query/4</code></a>, so you can get a dataframe directly from an SQL query.</li><li>Phils and others put together <a href="https://github.com/elixir-explorer/fss">FSS</a> so we can work with CSVs, IPC (Arrow), and Parquet files directly from S3 or HTTP. So you can pass in a URI instead of a filepath to load a dataset.</li><li><a href="https://github.com/cristineguadelupe">Christine Guadelupe</a> spearheaded the <a href="https://github.com/livebook-dev/kino_explorer"><code>KinoExplorer</code></a> project, which integrates <code>Explorer</code> with <a href="https://github.com/livebook-dev/livebook">Livebook</a>. You can use the Data Transform Smart Cell (as highlighted in Livebook's launch week <a href="https://news.livebook.dev/data-wrangling-in-elixir-with-explorer-the-power-of-rust-the-elegance-of-r---launch-week-1---day-5-1xqwCI">here</a>) to build Explorer queries with a graphical interface. As with other smart cells, this is generating code behind the scenes and you can convert it to raw code and manipulate it from there!</li><li>Innumerable improvements to the code from so many different contributors. It's been an absolute blast to see people improving the Rust, suggesting and implementing functions, and generally just taking the bare bones of a library that I put up and making it into something great. Thank you all.</li></ul>
<p><code>0.8.0</code> brings a number of other exciting developments closer to completion, so I'm going to lump them all in together. Let's get into it.</p>
<h2 id="dtypes-galore"><code>dtypes</code> galore</h2>
<h3 id="precision">Precision</h3>
<p>When I first put together <code>Explorer</code>, I wanted to match the simplicity of working with data types in <code>R</code>. It can be overwhelming when you're doing data analysis to have to think about precision, casting, and all that fun stuff. Most of the time, you want an <code>integer</code> to be an <code>integer</code> and a <code>float</code> to be a <code>float</code> and not have to think more about it. Until you don't. Because <code>Explorer</code> supports <em>zero copy</em> conversion <a href="https://hexdocs.pm/explorer/Explorer.Series.html#to_tensor/2">to Nx tensors</a>, you can go straight from ADBC -&gt; <code>Nx.Tensor</code> or IPC -&gt; <code>Nx.Tensor</code>, or whatever you want. If you're doing machine learning, you care about precision and you care about speed of dataloading. So <code>Explorer</code> now supports <code>{:f, size}</code> for 64- or 32-bit floats, <code>{:s, size}</code> for 8-, 16-, 32-, or 64-bit signed integers, and <code>{:u, size}</code> for the same for unsigned integers. This follows on from improvements made earlier to add precision to <code>:datetime</code> and <code>:duration</code> dtypes.</p>
<p>To avoid complicating this for everyday data analysis, however, we retained <code>:float</code> and <code>:integer</code> as aliases for <code>{:f, 64}</code> and <code>{:s, 64}</code> respectively. These match Elixir's floats and integers. So if you don't want to worry about precision, <em>you don't have to</em>. And a note on the notation (which also can be written as <code>:f64</code>, <code>:s64</code>, etc.): this matches <a href="https://github.com/elixir-nx/nx/tree/main/nx#readme"><code>Nx</code>'s notation</a> &mdash; just one more way we try to keep Explorer aligned with core Elixir and major libraries.</p>
<h3 id="lists-and-structs">Lists and Structs</h3>
<p>The <code>:list</code> dtype was introduced in <code>v0.7.2</code>. I'm discussing it here because I'm catching up on blogging, and because we've added additional functionality to really flesh it out. List is really <code>{:list, any()}</code> where <code>any()</code> is any valid dtype, including lists. It's a recursive dtype, and we can do some powerful stuff with it. Let's have a look at some code.</p>
<pre><code class="language-elixir">alias Explorer.Series

s =
  1..100
  |&gt; Stream.map(fn _ -&gt; :random.uniform(100) end)
  |&gt; Enum.chunk_every(10)
  |&gt; Series.from_list()</code></pre>
<pre><code class="language-elixir">#Explorer.Series&lt;
  Polars[10]
  list[s64] [
    [46, 55, 76, 68, 37, 51, 7, 62, 4, 37],
    [20, 40, 81, 35, 74, 95, 10, 94, 46, 5],
    [77, 79, 28, 56, 10, 18, 65, 8, 35, 4],
    [27, 95, 88, 46, 55, 76, 79, 35, 5, 20],
    [89, 21, 94, 1, 51, 13, 46, 72, 96, 32],
    [12, 39, 14, 88, 39, 43, 79, 55, 99, 3],
    [9, 76, 47, 67, 78, 77, 82, 3, 87, 72],
    [72, 94, 17, 2, 56, 25, 64, 5, 57, 77],
    [68, 61, 74, 69, 21, 81, 17, 89, 84, 45],
    [67, 28, 90, 71, 45, 96, 2, 50, 23, 29]
  ]
&gt;</code></pre>
<p>Okay, so we can see we've got a <code>list</code> of <code>s64</code> here. Unsurprisingly, sometimes you have a column of lists. Maybe names, maybe (like I've got) an array of sentences. In this case, we've got something that allows us to work with 2d-tensor-like data without needing a separate column for each element. The API for lists is currently very limited. The goal initially was just basic support to avoid blocking IO with data from Parquet, IPC, etc. There are a number of useful functions now, like <a href="https://hexdocs.pm/explorer/Explorer.Series.html#join/2"><code>Series.join/2</code></a>, which allows us to join lists into strings like <a href="https://hexdocs.pm/elixir/1.16.0/Enum.html#join/2"><code>Enum.join/2</code></a>:</p>
<pre><code class="language-elixir">s =
  Series.from_list([
    [&quot;José&quot;, &quot;Valim&quot;],
    [&quot;Philip&quot;, &quot;Sampaio&quot;],
    [&quot;Billy&quot;, &quot;Lanchantin&quot;],
    [&quot;Christopher&quot;, &quot;Grainger&quot;]
  ])</code></pre>
<pre><code class="language-elixir">#Explorer.Series&lt;
  Polars[4]
  list[string] [
    [&quot;José&quot;, &quot;Valim&quot;],
    [&quot;Philip&quot;, &quot;Sampaio&quot;],
    [&quot;Billy&quot;, &quot;Lanchantin&quot;],
    [&quot;Christopher&quot;, &quot;Grainger&quot;]
  ]
&gt;</code></pre>
<pre><code class="language-elixir">Series.join(s, &quot; &quot;)</code></pre>
<pre><code class="language-elixir">#Explorer.Series&lt;
  Polars[4]
  string [&quot;José Valim&quot;, &quot;Philip Sampaio&quot;, &quot;Billy Lanchantin&quot;, &quot;Christopher Grainger&quot;]
&gt;</code></pre>
<p>Now for structs.</p>
<p>Thanks to <a href="https://github.com/costaraphael">Raphael Costa</a> (who has provided a number of excellent contributions), we now have <a href="https://github.com/elixir-explorer/explorer/pull/756">initial support for the struct dtype</a>!</p>
<p>I'm particularly excited about this one, as it more fully unlocks common patterns with Parquet and NDJSON. It also makes Explorer more useful in the hands of folks who don't have a background in data science. Let's say you're working with Ecto and you're using associations. A typical schema will have assocs, which can be a struct or a list of structs. Let's flesh that out a bit.</p>
<p>I work with a lot of patent data, and our data warehouse is a bunch of XML in postgres in a star-like schema. It all revolves around a <code>PatentDocument</code>.</p>
<pre><code class="language-elixir">import Ecto.Query

data =
  Warehouse.PatentDocument
  |&gt; select([p], %{publication_id: p.publication_id, published: p.published, ucid: p.ucid})
  |&gt; limit(2)
  |&gt; Connie.Warehouse.Repo.all()</code></pre>
<pre><code class="language-elixir">[
  %{publication_id: 89474253, published: ~D[2008-06-04], ucid: &quot;JP-4096750-B2&quot;},
  %{publication_id: 114561913, published: ~D[2011-04-13], ucid: &quot;EP-2309729-A1&quot;}
]</code></pre>
<p>Which I can turn into a dataframe easily, because a list of maps implements the <a href="https://hexdocs.pm/table/Table.html"><code>Table</code> protocol</a>:</p>
<pre><code class="language-elixir">df = DataFrame.new(data)</code></pre>
<pre><code class="language-elixir">#Explorer.DataFrame&lt;
  Polars[2 x 3]
  publication_id integer [89474253, 114561913]
  published date [2008-06-04, 2011-04-13]
  ucid string [&quot;JP-4096750-B2&quot;, &quot;EP-2309729-A1&quot;]
&gt;</code></pre>
<p>Now, I could have just used ADBC and in practice I do. But I also appreciate how Ecto handles joins and unmarshalling. But it can be tough to deal with in a dataframe!</p>
<pre><code class="language-elixir">data =
  Warehouse.PatentDocument
  |&gt; join(:inner, [p], a in assoc(p, :abstracts))
  |&gt; select([p, a], %{
    publication_id: p.publication_id,
    published: p.published,
    ucid: p.ucid,
    abstract: a
  })
  |&gt; limit(2)
  |&gt; Connie.Warehouse.Repo.all()
  |&gt; Enum.map(
    &amp;Map.update!(&amp;1, :abstract, fn a -&gt;
      a |&gt; Map.from_struct() |&gt; Map.drop([:publication_id, :__meta__, :patent_document])
    end)
  )</code></pre>
<pre><code class="language-elixir">[
  %{
    abstract: %{
      status: &quot;v&quot;,
      modified_load_id: 445358,
      content: &quot;&lt;abstract mxw-id=\&quot;PA2805192\&quot; lang=\&quot;EN\&quot; source=\&quot;translation\&quot; load-source=\&quot;docdb\&quot;&gt;&lt;p&gt;A process for the production of a nanoparticle-containing medium, especially paint, in which the nanoparticles are produced by hydrolysis and condensation of metal alkoxide in the medium itself. An Independent claim is also included for a similar process using nanoparticles obtained by hydrolysis and condensation of silanes, also in the medium.&lt;/p&gt;&lt;/abstract&gt;&quot;,
      abstract_id: 657383904
    },
    publication_id: 16788813,
    ucid: &quot;DE-19924644-A1&quot;,
    published: ~D[2000-11-30]
  },
  %{
    abstract: %{
      status: &quot;v&quot;,
      modified_load_id: 445358,
      content: &quot;&lt;abstract mxw-id=\&quot;PA2805191\&quot; lang=\&quot;DE\&quot; source=\&quot;national office\&quot; load-source=\&quot;docdb\&quot;&gt;&lt;p&gt;Ein Verfahren zum Herstellen eines Nanopartikel enthaltenden Lackes sieht vor, daß die Nanopartikel durch Hydrolyse von Metallalkoxid und/oder Silanen im Lack selbst erzeugt werden.&lt;/p&gt;&lt;/abstract&gt;&quot;,
      abstract_id: 657383905
    },
    publication_id: 16788813,
    ucid: &quot;DE-19924644-A1&quot;,
    published: ~D[2000-11-30]
  }
]</code></pre>
<p>Let's see what we get!</p>
<pre><code class="language-elixir">df = DataFrame.new(data)</code></pre>
<pre><code class="language-elixir">#Explorer.DataFrame&lt;
  Polars[2 x 4]
  abstract struct[4] [
    %{&quot;abstract_id&quot; =&gt; 657383904,
     &quot;content&quot; =&gt; &quot;&lt;abstract mxw-id=\&quot;PA2805192\&quot; lang=\&quot;EN\&quot; source=\&quot;translation\&quot; load-source=\&quot;docdb\&quot;&gt;&lt;p&gt;A process for the production of a nanoparticle-containing medium, especially paint, in which the nanoparticles are produced by hydrolysis and condensation of metal alkoxide in the medium itself. An Independent claim is also included for a similar process using nanoparticles obtained by hydrolysis and condensation of silanes, also in the medium.&lt;/p&gt;&lt;/abstract&gt;&quot;,
     &quot;modified_load_id&quot; =&gt; 445358, &quot;status&quot; =&gt; &quot;v&quot;},
    %{&quot;abstract_id&quot; =&gt; 657383905,
     &quot;content&quot; =&gt; &quot;&lt;abstract mxw-id=\&quot;PA2805191\&quot; lang=\&quot;DE\&quot; source=\&quot;national office\&quot; load-source=\&quot;docdb\&quot;&gt;&lt;p&gt;Ein Verfahren zum Herstellen eines Nanopartikel enthaltenden Lackes sieht vor, daß die Nanopartikel durch Hydrolyse von Metallalkoxid und/oder Silanen im Lack selbst erzeugt werden.&lt;/p&gt;&lt;/abstract&gt;&quot;,
     &quot;modified_load_id&quot; =&gt; 445358, ...}
  ]
  publication_id s64 [16788813, 16788813]
  published date [2000-11-30, 2000-11-30]
  ucid string [&quot;DE-19924644-A1&quot;, &quot;DE-19924644-A1&quot;]
&gt;</code></pre>
<p>That's pretty exciting. With <code>FSS</code> you could take this and send it directly to <code>S3</code> as is. But you can do more:</p>
<pre><code class="language-elixir">DataFrame.unnest(df)</code></pre>
<pre><code class="language-elixir">#Explorer.DataFrame&lt;
  Polars[2 x 7]
  abstract_id s64 [657383904, 657383905]
  content string [&quot;&lt;abstract mxw-id=\&quot;PA2805192\&quot; lang=\&quot;EN\&quot; source=\&quot;translation\&quot; load-source=\&quot;docdb\&quot;&gt;&lt;p&gt;A process for the production of a nanoparticle-containing medium, especially paint, in which the nanoparticles are produced by hydrolysis and condensation of metal alkoxide in the medium itself. An Independent claim is also included for a similar process using nanoparticles obtained by hydrolysis and condensation of silanes, also in the medium.&lt;/p&gt;&lt;/abstract&gt;&quot;,
   &quot;&lt;abstract mxw-id=\&quot;PA2805191\&quot; lang=\&quot;DE\&quot; source=\&quot;national office\&quot; load-source=\&quot;docdb\&quot;&gt;&lt;p&gt;Ein Verfahren zum Herstellen eines Nanopartikel enthaltenden Lackes sieht vor, daß die Nanopartikel durch Hydrolyse von Metallalkoxid und/oder Silanen im Lack selbst erzeugt werden.&lt;/p&gt;&lt;/abstract&gt;&quot;]
  modified_load_id s64 [445358, 445358]
  status string [&quot;v&quot;, &quot;v&quot;]
  publication_id s64 [16788813, 16788813]
  published date [2000-11-30, 2000-11-30]
  ucid string [&quot;DE-19924644-A1&quot;, &quot;DE-19924644-A1&quot;]
&gt;</code></pre>
<p>Unnesting can be really powerful. For now, these features mostly give us IO parity and the ability to get at the data. Later, we can add more functionality to expand on our ability to do data analysis directly on lists and structs. I'm looking at you, <a href="https://tidyr.tidyverse.org/articles/nest.html">nested tibbles</a>.</p>
<h2 id="series-macros">Series macros</h2>
<p>Back in November, Billy raised <a href="https://github.com/elixir-explorer/explorer/pull/728">a PR</a> in which he argued we should use macros with <code>Series</code>. At first we were unsure, but I think we came to a pretty elegant solution. Now before, you needed to pass a callback, like so:</p>
<pre><code class="language-elixir">series = S.from_list([1, 2, 3])

S.filter(series, &amp;(&amp;1 |&gt; S.remainder(2) |&gt; S.equal(1)))</code></pre>
<p>Now I don't this this is too bad, but it's definitely verbose. But now, we can use macros and it's much nicer:</p>
<pre><code class="language-elixir">require Explorer.Series, as: Series

S.filter(series, remainder(_, 2) == 1)</code></pre>
<p>We decided to use <code>_</code>, which is a bit unorthodox in Elixir and was a tough choice when we focus so much on avoiding impedance mismatch. But I do think it's really nice, and it makes sense because of the arbitrariness of names here. You can't pattern match within queries, so no risk of confusion there.</p>
<p>For <code>v0.8.0</code> Billy has added macro support for <code>sort</code> (which is now <a href="https://hexdocs.pm/explorer/Explorer.Series.html#sort_by/3"><code>sort_by</code></a>) and <a href="https://hexdocs.pm/explorer/Explorer.Series.html#map/2"><code>map</code></a>. I think these are just really nice. From the docs:</p>
<pre><code class="language-elixir">s = Explorer.Series.from_list([1, 2, 3])
Explorer.Series.map(s, _ * 2)
#Explorer.Series&lt;
  Polars[3]
  s64 [2, 4, 6]
&gt;</code></pre>
<p>A note on <code>sort_by</code>: we brought <code>DataFrame</code> into line with <code>Series</code> here &mdash; now instead of <code>arrange</code> and <code>sort</code>, they both use <code>sort_by</code>. Nice.</p>
<h2 id="what-s-next">What's next?</h2>
<p>I think Explorer is more than functional today. For <em>most</em> data science workflows, I think you could switch from R or Python and get your work done in Elixir, with all the benefits that implies.</p>
<p>First up is more complete support for <code>List</code> and <code>Struct</code> dtypes. I've raised that issue <a href="https://github.com/elixir-explorer/explorer/issues/835">here</a> if you'd like to track progress.</p>
<p>After that, we want to make <code>lazy</code> mode more complete. In particular, this is useful for OLAP-style work, but it will make regular day to day work faster and more intuitive. What do I mean by that? Today, <a href="https://github.com/elixir-explorer/explorer/issues/494">lazy doesn't work with groups</a>. Making it work requires a reorganisation of where we accumulate lazy functions, introducing a stack to lazy dataframes.</p>
<p>Getting this right will be key for the next big step, which is to finally introduce our first non-Polars backend. The original design of pluggable backends was a conscious decision from someone who lived and loved <code>dplyr</code> and <code>dbplyr</code>. I think it's still the thing that folks who don't work in that world struggle to understand the most. <code>dbplyr</code> allows you to write dataframe functions in <code>dplyr</code> and then apply them against remote database tables. But I don't mean 'execute a query to bring data into memory' (though you can), I mean 'execute this query and keep it in a tmp table on the server until I ask'. I mean 'join this local table to a remote table'. I mean 'my data analysis pipeline is identical whether I'm running it in-memory, in Postgres, or on DuckDB'. I'm really excited to bring this to Elixir and we're nearly ready to do it.</p>
<p>We also have plans in the works to leverage Elixir's most powerful weapon: distribution. Keep an eye on this space!</p>
<h3 id="acknowledgments">Acknowledgments</h3>
<p>A huge thank you to all our contributors for this release and for all the work between <code>v0.1.0</code> and this one. An especially big thanks goes to those who are joining us for the first time. Your efforts continue to make Explorer something special.</p>
<p>Explore the full <a href="https://hexdocs.pm/explorer/changelog.html#v0-8-0-2024-01-20">changelog</a> and come join us in shaping the future of data science in Elixir. For me, it's been your feedback and contributions that make this project so special. I really believe Elixir has a unique opportunity to combine the best of many (all?) worlds for data science.</p>]]></description></item><item><title>Introducing Explorer</title><link>https://cigrainger.com/blog/introducing-explorer/</link><guid isPermaLink="true">https://cigrainger.com/blog/introducing-explorer/</guid><pubDate>Thu, 28 Apr 2022 00:00:00 +0000</pubDate><description><![CDATA[<p>Tuesday night, I published <a href="https://hexdocs.pm/explorer/Explorer.html"><code>v0.1.0</code></a> of <a href="https://github.com/elixir-nx/explorer"><code>Explorer</code></a>, a library I've been working on to bring dataframes to Elixir. It's been available through GitHub for a while, but the Hex release is more than just a milestone: by publishing the package on Hex, we've enabled <a href="https://dashbit.co/blog/rustler-precompiled">Rustler Precompiled</a> to do its thing. That means that now you can use Explorer without a Rust toolchain installed and without waiting for it to compile. Before you'd wait for up to five minutes to try it out, and now it's basically instant.</p>
<p>In this post, I'd like to lay out some of what led to Explorer and the philosophy behind it. I'll follow up in coming weeks with more 'how-to' style posts, but I think the unique nature of Explorer merits some discussion first.</p>
<h2 id="background">Background</h2>
<p>When I first heard about the <a href="https://dashbit.co/blog/nx-numerical-elixir-is-now-publicly-available"><code>Nx</code></a> project, I was thrilled. At <a href="https://amplified.ai">Amplified</a>, we've been using Elixir in production since 2018. We switched over to <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html"><code>LiveView</code></a> in early 2020 and haven't looked back. We really love working with Elixir.</p>
<p>And we do deep learning. A bunch of it. And I'm endlessly grateful to all the folks who have made the Python machine learning ecosystem as robust as it is, but... it's painful. We don't have teams dedicated to different languages. With the machine learning, it's just me. I think there are objective reasons why Python is problematic for machine learning. I'm <a href="https://www.fast.ai/2019/03/06/fastai-swift/">not the only one</a>. But this isn't the post for that. At a minimum, Nx meant the prospect of deploying our machine learning models as part of our Elixir app instead of maintaining Python microservices alongside.</p>
<p>Immediately, however, I knew there was a potential challenge to adoption and an opportunity to make something I knew that I'd really love and thought others would too. Something I've commented on wistfully a bunch of times but never had an incentive to allocate the time or energy to championing. Dataframes in Elixir.</p>
<p>See, I cut my data science teeth in R. I love R. I love the <a href="https://www.tidyverse.org"><code>tidyverse</code></a>. I pray at the alter of <a href="https://hadley.nz">Hadley Wickham</a>. But I also know that <a href="http://www.talyarkoni.org/blog/2012/06/08/r-the-master-troll-of-statistical-languages/">R is a crazy language</a>. Much of the effort of the <code>tidyverse</code> has been to emphasise functional paradigms in R. Because what is data science but piping data through functions? And R is great at that now. You can read this and &mdash; even if you have no knowledge of R &mdash; you know what's going on:</p>
<pre><code class="language-r">df |&gt;
  select(sepal_length, sepal_width, species) |&gt;
  filter(sepal_length &lt; 5.0) |&gt;
  group_by(species) |&gt;
  summarise(max_sepal_width = max(sepal_width),
            mean_sepal_length = mean(sepal_length))</code></pre>
<p>Compare that to <a href="https://pandas.pydata.org"><code>pandas</code></a>.</p>
<pre><code class="language-python">df[df.sepal_length &lt; 5.0].filter(
    items=[&quot;sepal_length&quot;, &quot;sepal_width&quot;, &quot;species&quot;]
).groupby(by=[&quot;species&quot;]).agg({&quot;sepal_width&quot;: &quot;max&quot;, &quot;sepal_length&quot;: &quot;mean&quot;})</code></pre>
<p>... I think? And that's formatted with <a href="https://github.com/psf/black"><code>black</code></a>. Pandas is <a href="https://qz.com/1126615/the-story-of-the-most-important-tool-in-data-science/">'the most important tool in data science'</a> but it's also one of the most loathed. Or not &mdash; one thing I find is that people don't realise <em>there are alternatives</em>.</p>
<p>Look, I'm not here to throw grenades or start holy wars. Pandas is just not my cup of tea. It's not how my brain works when it comes to data science. Again, I'm <a href="https://wesmckinney.com/blog/apache-arrow-pandas-internals/">not the</a> <a href="https://www.reddit.com/r/datascience/comments/c3lr9n/am_i_the_only_one_who_hates_working_with_pandas/">only one</a>. At the end of the day, we're writing code to investigate and manipulate data. There should be as little friction as possible between your brain and the computer. I think the <code>tidyverse</code> mostly gets that right. But the deep learning ecosystem in R is minimal and it's <em>not</em> a general purpose programming language. Elixir is.</p>
<p>And this brings me to my point about the potential blocker to adoption. I <a href="https://groups.google.com/g/elixir-nx/c/axSar20AyEI">started making noise early</a> about the need to be able to do the data <em>manipulation</em> tasks leading into and following on from the actual machine learning. They say data science is &gt;90% data 'munging' and time and time again I've found this to be true in my work.</p>
<p>I was thinking of Nx like high speed rail: intercity trains are fantastic, but how do you get to the station and what happens once you arrive? Successful machine learning tooling must provide great &quot;door to door&quot; service. High speed rail without easy travel from home to station and from station to destination won't succeed. So before you start throwing data into a neural net, you need to understand your data, and you need to get it in the right format, which might be distant from how it's provided to you. You may even need to normalise, combine, or engineer variables.</p>
<h2 id="enter-rust">Enter Rust</h2>
<p>Given that I'm the cofounder and CTO of a startup, there was no way I would have the time to write a dataframe library from scratch. But part of my job is keeping across trends and big movements in tech, and I noticed two things happening in my particular little world of interests. The first is that <a href="https://github.com/rusterlium/rustler">Rustler</a> seemed to be more and more prominent. It's a way to easily write Rust NIFs (Native Implemented Functions) for Elixir. And the other thing was the emergence of <a href="https://github.com/pola-rs/polars"><code>Polars</code></a>, a dataframe library written in Rust. Combine these with the need for dataframes in Elixir and all of a sudden there's a way to make it happen without creating something from the ground up!</p>
<p>It just so happened that someone else had this idea too. I found bindings to <code>polars</code> in <a href="https://github.com/tyrchen/ex_polars"><code>ex_polars</code></a>, but the project seemed abandoned. Now's the time to mention I had little to no experience with Rust. But this seemed like a good way to learn! So I picked it up and started running.</p>
<p>I fell down, a lot.</p>
<p>I learned that Rust/Elixir interop isn't always the rosy picture that folks make it out to be. They're rightly very enthusiastic: Rust is an excellent language, <code>rustler</code> is a phenomenal project, and writing NIFs without worrying about bringing down the BEAM is an excellent premise. But there are sharp corners and <em>very</em> little documentation. For a Rust novice, I cut myself on those sharp corners a whole bunch. And I'm still rectifying a lot of things in the Rust side of the Explorer codebase.</p>
<p>There are some things that I just didn't even realise were possible. As an example, we needed to deserialise dates. I wrote a <code>NifMap</code> with a <code>__struct__</code> field with a value of <code>Elixir.Date</code>. <code>rust-analyzer</code> complained, but I kept on. Turns out, <a href="https://github.com/elixir-nx/explorer/pull/143">you can just use a <code>NifStruct</code> for the core Elixir Date struct</a>.</p>
<p>What became apparent early on, however, was that building bindings to <code>polars</code> provided the opportunity to design an API effectively from scratch on top of an engine with power to spare. Polars is crazy fast. But that speed comes with restrictions and some quirks. That's not to detract from Polars in the least &mdash; it just meant that there was work to do to have my cake and eat it too.</p>
<p>But it was possible.</p>
<h2 id="the-elegance-of-dplyr-the-speed-of-polars-the-joy-of-elixir">The elegance of <code>dplyr</code>, the speed of <code>polars</code>, the joy of Elixir</h2>
<p>I didn't just want &quot;<code>dplyr</code> in Elixir&quot;. But the premise behind <code>dplyr</code>, that of making a 'grammar of data manipulation' &mdash; that's what I'm after!</p>
<p>So before we go any further, let's have a look at the <code>iris</code> example above in Explorer:</p>
<pre><code class="language-elixir">df
  |&gt; DataFrame.select([&quot;sepal_length&quot;, &quot;sepal_width&quot;, &quot;species&quot;])
  |&gt; DataFrame.filter(fn df -&gt; Series.less(df[&quot;sepal_length&quot;], 5.0) end)
  |&gt; DataFrame.group_by([&quot;species&quot;])
  |&gt; DataFrame.summarise(sepal_width: [:max], sepal_length: [:mean])</code></pre>
<p>So what do we notice? First, this looks a lot like <code>dplyr</code> in terms of verbs. Second, there are callbacks! The second argument in <code>DataFrame.filter/2</code> takes a callback function against the dataframe. There's some cool stuff we can do with that, and I think callbacks against the dataframe are a natural way to work. This is especially true for <code>DataFrame.mutate/2</code> where the idea is that you're creating new columns by combining existing ones.</p>
<p>This (and the list passed to <code>DataFrame.select/3</code> above it and <code>DataFrame.group_by/2</code> below it) differ from <code>dplyr</code> in that there's no <a href="https://dplyr.tidyverse.org/reference/dplyr_tidy_select.html">tidy-select</a>. This makes things a little more visually cluttered, but more explicit. There are pros and cons, but this is something we'll be looking into in the future.</p>
<p>The next thing is that <code>DataFrame.summarise/2</code> looks a bit more like the <code>pandas</code> example. This is mainly a restriction of Elixir/Rust interop and the way <code>polars</code> is designed. A major hurdle in all of this is that we can't pass arbitrary Elixir functions to <code>polars</code>. Ways of working around this and keeping things performant are also in the works.</p>
<p>So why do I think this is a good solution?</p>
<h3 id="verbs">Verbs</h3>
<p>Like <code>dplyr</code>, <code>Explorer</code> is centred around SQL-like 'verbs' of data manipulation. Mainly <code>select</code>, <code>mutate</code>, <code>filter</code>, <code>arrange</code>, and <code>summarise</code>. There are a few others, but using these verbs along with the ability to <code>group_by</code> and <code>pivot</code> gives you almost everything you need to massage data and get answers from it.</p>
<p>Reading the code above top to bottom, you know what's happening and in what order. The dataframe is being piped through a series of idempotent functions. Each returns a new dataframe (it would be very surprising to have mutated the underlying dataframe in Elixir, a language built around immutability), which is then piped to the next function. This makes data analysis pipelines eminently composable.</p>
<p>Dataframes are the nouns, and the functions are the verbs. Simple.</p>
<h3 id="multiple-backends">Multiple backends</h3>
<p>And that leads us to the thing I'm most excited above. The API above is not tied to Polars. Polars is, instead, the <em>first backend</em> for Explorer. What does that mean?</p>
<p>The Explorer DataFrame (and Series) API is <a href="https://github.com/elixir-nx/explorer/blob/v0.1.0/lib/explorer/backend/data_frame.ex#L1">a behaviour</a>. A behaviour in Elixir is a contract, a way to describe an API in a public way that allows you to fulfill the contract with any module with functions matching the typespecs.</p>
<p>This means that it will be possible to provide a SQL backend for Explorer. Or a <a href="https://github.com/apache/arrow-datafusion">Ballista</a> backend for distributed compute. Or whatever cool new dataframe library comes out. Or hell, <code>pandas</code> if you really want.</p>
<p>And the API will remain the same. This is one of the coolest things about <code>dplyr</code> and I think it can be taken even further with Elixir and <code>Explorer</code>.</p>
<p>As an example, you could write Explorer analyses that you can apply to tables in a remote database that are computed <em>on the remote database</em> and then you could pull down the results. Or you could even <em>join</em> against a remote table by transferring your local table to the remote database or vice versa.</p>
<p>The same applies to distributed dataframes on Ballista. Or on disk with an OLAP engine. The possibilities are extensive and I'm really excited to see what we can do.</p>
<h2 id="downsides">Downsides</h2>
<p>I've alluded to a few problems above. One is in the nature of the Elixir and Rust interop. Dataframes are stored 'Rust-side' as <a href="https://www.erlang.org/doc/man/erl_nif.html">resource objects</a>. That means that they're just pointers to native Rust data structures in Elixir. Serialising and deserialising the dataframes on every function call would be way too much overhead, so instead we pass the pointer around and operate against that.</p>
<p>This is a very cool thing. Especially because those pointers are atomic reference counted, and once there are no more references to them, the memory is dropped. But the Erlang garbage collector may not run fast enough to keep up with the operations you may want to do on dataframes. And in order to keep things immutable in practice Elixir-side, every dataframe operation copies the entire dataframe. As far as I know, nobody has been bitten yet, but this is <em>not</em> ideal for memory useage.</p>
<p>The obvious answer to this for us was to explore the <code>polars</code> <a href="https://pola-rs.github.io/polars/polars/docs/lazy/index.html">lazy API</a>. I tried to use the lazy API in an opaque way, hidden from the end user, so that we'd minimise copying and maybe get performance benefits. This ended up being a dead end due to the differences in the way the API is structured. We intend on making lazy opt-in and explicit. There will still be eager-mode footguns, but this should alleviate the issue if you run into memory problems.</p>
<p>The other major challenge is the inability to execute arbitrary Elixir functions 'Rust-side'. That means if you want to apply a function to a <code>Series</code>, it has to be serialised into an Elixir list and then deserialised back into a Rust <code>Series</code>. Needless to say this is not ideal. I don't have a good answer for this right now. It's no big deal on smaller datasets but for long ones it can be a big performance penalty. If you have ideas I'd love to hear them!</p>
<h2 id="next-steps">Next steps</h2>
<p>Okay, so you can use Explorer in your workflows <em>today</em>. It works and it's <em>fast</em>. It's not as mature as <code>dplyr</code> or <code>pandas</code>, but if you're already working in Elixir you should be able to get work done with <code>Explorer</code>. And Elixir is rapidly developing a really phenomenal ecosystem of ML tooling. <a href="https://livebook.dev">Livebook</a>, for example, is the absolute bees knees. I gave a talk at Elixir Melbourne a few weeks back and folks's faces when I clicked the <code>Run in Livebook</code> badge in <code>ExDoc</code> and could run documentation locally were priceless.</p>
<p>The immediate next step is to get the lazy Polars backend going. Then I think SQL. Then Ballista. In the meantime, we're <a href="https://github.com/elixir-nx/explorer/issues/169">improving</a> <a href="https://github.com/elixir-nx/explorer/issues/167">the API</a>, <a href="https://github.com/elixir-nx/explorer/pull/138">improving performance through better interop</a>, and <a href="https://github.com/elixir-nx/explorer/pull/170">writing more documentation</a>.</p>
<p>It's worth noting here that I keep saying 'we' because the community piled on and it's really a team effort now. There have been really excellent contributions and even some regular contributors. It's honestly such an amazing thing to see this thing being used and improved by folks in the real world.</p>
<p>With the rest of the ecosystem improving by leaps and bounds, Elixir is poised to be a better and better choice for data science all the time. Many of the tools are already there. Come try it out!</p>]]></description></item></channel></rss>
