<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.ahl27.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.ahl27.com/" rel="alternate" type="text/html" /><updated>2026-09-01T05:19:47-04:00</updated><id>https://www.ahl27.com/feed.xml</id><title type="html">Aidan Lakshman</title><subtitle>Aidan Lakshman&apos;s personal webpage</subtitle><author><name>Aidan Lakshman</name></author><entry><title type="html">My SWE Interview Experiences: Amazon vs. Meta vs. Google</title><link href="https://www.ahl27.com/posts/2025/04/faang-interviews/" rel="alternate" type="text/html" title="My SWE Interview Experiences: Amazon vs. Meta vs. Google" /><published>2025-04-18T00:00:00-04:00</published><updated>2025-04-18T00:00:00-04:00</updated><id>https://www.ahl27.com/posts/2025/04/allinterviews</id><content type="html" xml:base="https://www.ahl27.com/posts/2025/04/faang-interviews/"><![CDATA[<p>I just finished an interview at Google that I wasn’t initially expecting to get. I prepared for it like I had for my Meta interviews, but the experience was significantly different. I feel like people online treat FAANG/tech interviews as if they’re all the same, but these experiences could not have been more different…so I figured it would be helpful for someone out there if I documented how they compared to each other.</p>

<h2 id="background">Background</h2>

<p>Everyone online is always asking about GPA/major/background/etc. when people post about FAANG interviews. I don’t have a crazy resume, so I’m not sure how much this really matters. My undergrad degree is in math, and I did some CS research during the degree. After that, I got my PhD in bioinformatics focusing on building software tools for large-scale comparative genomics. If you’re reading this, you’re already on my website, so you can see my resume for yourself on the <a href="https://www.ahl27.com/cv/">CV page</a>.</p>

<p>All of these interview experiences are for software engineering (SDE/SWE) roles, not research or data science. Meta and Google were New Grad PhD positions, and Amazon was a New Grad position for undergrads that I applied for at the end of my bachelor’s degree. I’ll detail them sequentially and then compare how they went at the end.</p>

<p>Additionally, I mention job levels multiple times throughout this post and try to give comparison points. There’s a very nice chart online that shows how they measure up to each other available <a href="https://www.hellointerview.com/blog/understanding-job-levels-at-faang-companies">here</a>.</p>

<h2 id="amazon">Amazon</h2>

<p><em>Position: New Grad SDE-I</em></p>

<p>The funny thing about this role is that I applied for it by accident. At the end of my undergrad degree I was searching desperately for an internship I could do in the summer between undergrad and starting my PhD, and I was having absolutely no luck. I ended getting up a single interview, at what I thought was an internship at Amazon AWS. It turns out that I had accidentally applied for a full-time new grad role, and I didn’t realize until the final round of the process! After I got the role, they let me downgrade it to an internship because I was returning to school.</p>

<p>I interviewed for this position around September 2019 with an intended start date in Summer 2020. This was pre-COVID, but Amazon was trialling a new fully virtual interview process for new grad roles. I’ll note that I also re-applied to a New Grad SDE-II (PhD) position at Amazon in 2025 and went through an almost identical interview experience.</p>

<p>My Amazon interview process had a total of five rounds.</p>

<p>First, the debugging round. This consisted of around five problems in 20 minutes. Each problem was a short piece of code containing a bug and the expected behavior of the code. You could run it to check the output. It sounds like a lot, but the bugs were pretty small (e.g., flipping a <code class="language-plaintext highlighter-rouge">&lt;</code> sign to <code class="language-plaintext highlighter-rouge">&gt;</code>) so they were pretty easy. All of the bugs were logic errors, meaning that the original code ran fine, it just produced the wrong output.</p>

<p>Next, the coding round. This consisted of two LeetCode problems in 70 minutes, both around easy to medium difficulty. I remember prepping really hard for this in undergrad, but when I took it again in 2025, it was easier than I remembered. In my original interview, I solved one problem with a suboptimal solution because I couldn’t figure out the optimal one and still passed. For this interview, getting a working solution that passes all the test cases is much more important than getting most of an optimal solution that doesn’t run.</p>

<p>The third round is a workplace simulation round, which honestly I felt was pretty fun. You get a simulated email and Slack, and you get messages from virtual coworkers about things happening throughout the day. The “day” is really like an hour and all the solutions are abridged (so more like just saying what you would do and then skipping to the consequences). I won’t reveal details on the simulation since it was literally exactly the same when I took it again in 2025, but my advice would be to just think about your decisions, remember the Amazon LPs, and be a team player.</p>

<p>The fourth round is like a math / logic test combined with a personality test. I don’t have much to say about this one except that I think it’s pretty silly. I’m not a fan of brainteasers/logic puzzles or personality quizzes for interviews…if you need to evaluate how someone works, just give a behavioral interview. Regardless, this is the kind of test where you just need to be yourself, but if necessary, be a version of yourself that the company would love to have on the team.</p>

<p>Finally, I had a quick phone interview with an Amazon SWE to talk over my answers to the coding rounds. He asked me about my one suboptimal solution and I described how I would have improved it if I had had more time.</p>

<h2 id="meta">Meta</h2>

<p><em>Position: Research Scientist (Systems/Infrastructure, PhD)</em></p>

<p>I talked in depth about my interview experience at Meta in a <a href="/posts/2025/02/meta-interview/">previous blog post</a>. This position is pretty similar to an E4/IC4 SWE role (or SDE-II at Amazon, L4/SWE-III at Google). If you want a detailed description of the process, see my previous post – I’ll just briefly recap here and then contrast it with other roles at the end.</p>

<p>My interview at Meta had six rounds: the phone screen, three coding rounds, one systems design round, and then one behavioral round. The phone screen was identical to the coding rounds, so it was basically four coding rounds. One coding round was extra; they often assign an extra round for training purposes that may or may not count (just act like it does, if you get one). Every round had 35 minutes for the main content, 5 minutes for questions at the end, and 5 minutes of buffer for things like technical issues. These were hard stops; the interviewers would start the interview, and then 35 minutes later they had to close their notetaking / interviewing portals before answering other questions.</p>

<p>Each coding round was two LeetCode problems in 35 minutes with a live interviewer. Each pair of problems averaged about medium difficulty, but on the harder end. Meta doesn’t add new questions very often, so you can get great prep by drilling the LeetCode Meta 3-month question list (need LeetCode premium, it’s definitely worth it for this). My interviewers were available to give some feedback / assistance, but there wasn’t really time to have detailed discussions with them. I’d personally just plan on not getting any interviewer hints. You aren’t able to run any code, so you have to know your stuff without google/AI and be able to debug your code by hand.</p>

<p>Systems design and behavioral interviews were pretty standard. At Meta, the behavioral is required to be with someone that has a PhD if you’re interviewing for a position that requires a PhD. The other rounds are with anyone that’s qualified.</p>

<h2 id="google">Google</h2>

<p><em>Position: New Grad SWE (PhD)</em></p>

<p>My Google interview was quicker than most because I already had an offer from Meta (and potentially also because I had a referral, though I’m not sure). I skipped straight to the full loop interview, so no phone screen. This consisted of three coding rounds and a behavioral interview. This role is for an L4 position (Google SWE III, same as Meta E4/IC4, Amazon SDE II).</p>

<p>Each coding round was scheduled for 45 minutes, though most of my interviewers stayed on longer to talk with me more. The format was working through one coding problem, which was LeetCode-style but not directly from LeetCode. The problems were a lot more ambiguous than Meta or Amazon; the interviewer would start with a very general problem description, and you’d have to spend some time talking with the interviewer to clarify the exact details and expectations.</p>

<p>All my interviewers had PhDs, so maybe they try to get PhD interviewers for the PhD SWE roles (could also have been coincidence). The interviewers were super helpful and I had great discussions in all of them – it really felt like working on a problem with someone and less like a super intense interview. The problems themselves I would put at around LeetCode medium difficulty. Like at Meta, you couldn’t actually run any code, you’d basically just type code into a shared google doc with syntax highlighting.</p>

<p>The last round is called the “Googleyness round”, but it’s really just a standard behavioral interview. The questions are pretty much exactly what you’d get at any other behavioral.</p>

<p>Note that Google is a bit unique in that there is another phase after the full loop of interviews. To actually get an offer, you have to successfully match with a team that wants you and has sufficient headcount. If you take a quick look at Reddit or Blind, you’ll see some people that have been stuck in team matching for months. It seems to me like Google is slightly more inclined to pass people through the full loop because there’s an additional check before receiving an offer (though that could just be my imagination).</p>

<p>On team matching, it’s also worth noting that the order of full loop and team matching isn’t fixed. From reading a lot of sources online, I’ve gathered that the process is typically full loop -&gt; hiring committee -&gt; team match, but that changes from time to time. Recruiters also have the ability to delay your hiring committee review until you’ve matched with a team if they think your interview results were borderline (a manager that wants you can be enough of a boost to pass with slightly worse interview results). I went through a partial team match phase proir to even doing my full loop because I had another offer, so that’s also on the table. The good news is that (at least in my experience) Google recruiters are a lot more open about the process than Meta or Amazon, so you may be able to find out where you are in the process by just asking.</p>

<h2 id="how-do-they-compare">How do they compare?</h2>

<p>From my perspective, the interviews were all quite different despite all being roughly a pre-screen, some coding rounds, and a behavioral.</p>

<p>Meta was by far the most intense coding interview I have ever done. Solving two medium-hard LeetCode problems optimally in 35 minutes with good code and no external help (autocompletion, google, etc.) is a really, really fast pace. This felt like I was sitting for an exam; I had minimal help from interviewers and had to work extremely quickly on relatively difficult problems. The upside is that it’s easy to study for Meta, since you mostly know what problems they’re going to ask. I will mention that I got a LC-Hard level question that isn’t on LeetCode and managed to solve it optimally, and to this day I’m pretty proud of myself for that.</p>

<p>Amazon wasn’t as intense, but there’s no margin for error. Since there’s no human in the loop, it’s a lot tougher to get partial credit. In one of my Meta rounds I couldn’t get my code perfect in time, but I could describe the logic enough that the interviewer knew I could do it if I had had more time – this was not the case at Amazon. Being able to run code is a double-edged sword; yes, you can check your work faster, but it also means you have to deal with syntax errors and knowing the correct functions. At Meta/Google we could just agree on syntax for functions I couldn’t completely remember, but not at Amazon. Overall, I’d say it’s the easiest interview technically, it’s just an all-or-nothing scenario. (<em>Note: This only applies to the online New Grad process. There’s also an on-site interview loop with live interviewers that I’ve heard is much more intense, but I don’t have any experience with that one.</em>)</p>

<p>Google was my favorite out of these interviews. It was the same pace as Amazon (one problem per ~35min), but the actual experience was the exact opposite. A lot of my time was spent discussing the problem details with the interviewers, who were all very responsive. What I liked about the experience was I felt like the interview allowed me to showcase how I approach solving software engineering problems, rather than just testing my memorization of LeetCode. I felt less pressure, which I think helped me do better. The interviewers themselves also seemed more focused on working with me on the problem, rather than just evaluating if my final solution was optimal. Along those lines, the problems I got were mostly challenging from a problem-solving standpoint – once you figured out the solution, coding it up was fairly simple. I’ll note that I didn’t get any dynamic programming or graph problems, so my experience may have been atypical.</p>

<p>Overall, I think the interview formats are better for different kinds of people. If you love grinding LeetCode (and are good at it), you could probably crush it at Meta. If you’re a good programmer that isn’t as fast at LeetCode, you’d probably do better at Google. If you’re the kind of person that can do LC easy-medium problems that work without syntax errors or failed test cases on the first try, you’d probably do great at Amazon. Personally, the Google style felt the best for me.</p>

<h2 id="conclusion">Conclusion</h2>

<p>As always, I’ll close by mentioning that the most important factor in passing FAANG interviews is being lucky enough to get them in the first place. It feels like a lottery on who gets selected. If you get an interview at one of these places, that’s definitely something to be proud of, even if you don’t end up passing–the whole process is brutal. Keep at it and stay sharp on DSA fundamentals, and you’ll break through eventually.</p>

<p>Thanks for reading.</p>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><summary type="html"><![CDATA[I just finished an interview at Google that I wasn’t initially expecting to get. I prepared for it like I had for my Meta interviews, but the experience was significantly different. I feel like people online treat FAANG/tech interviews as if they’re all the same, but these experiences could not have been more different…so I figured it would be helpful for someone out there if I documented how they compared to each other.]]></summary></entry><entry><title type="html">The ExoLabel Post: Clustering Massive Networks with Limited Resources</title><link href="https://www.ahl27.com/posts/2025/04/exolabel-full/" rel="alternate" type="text/html" title="The ExoLabel Post: Clustering Massive Networks with Limited Resources" /><published>2025-04-11T00:00:00-04:00</published><updated>2025-04-11T00:00:00-04:00</updated><id>https://www.ahl27.com/posts/2025/04/exolabel-full</id><content type="html" xml:base="https://www.ahl27.com/posts/2025/04/exolabel-full/"><![CDATA[<p>I’ve made a lot of posts about ExoLabel, but the project has been moving so quickly that they’ve become out of date almost as soon as I post them. I’m finally close to the end of this project, so I thought it was high time I write out the entire project (partly for my own reference, so I don’t forget).</p>

<h2 id="the-problem">The Problem</h2>

<p>ExoLabel is an algorithm to cluster big networks, but…why would anyone want to do that?</p>

<p>There’s a lot of use-cases for network clustering (also sometimes referred to as community detection for graphs/networks), but our specific need came from a a problem we encountered in our workflow.</p>

<p>You may be shocked to learn that the field of comparative genomics revolves around being able to compare genomic data. This assumes we have an answer to a critical foundational question: how do we know what genomic data are comparable? Typically, genomic analyses are performed on “related” genes. For phylogenetic reconstruction, this would be groups of genes we assume derived from a common ancestor. The notion of genes being related is a little tricky to define, but a lot of it stems from genes that have similarity in their sequence.</p>

<p>We can get a measure of how similar sequences are by using tools for pairwise sequence similarity comparisons, like BLAST or DIAMOND. This gets us part of the way to a solution, but natural evolutionary processes introduce a lot of noise into the data we analyze. This means that truly related genes could appear to have low similarity, and unrelated genes could spuriously appear to be very similar.</p>

<p>One approach to get around this is to cluster the network formed by these genes when we connect them by their sequence similarity. In other words, we build a <em>sequence similarity network</em>, which is a graph where each node is a gene sequence, and each edge is the sequence similarity of the genes it connects. Clusters from these networks are typically a good estimate to get groups of genes we can analyze with other methods. With sufficient data, the true signal becomes distinguishable from background noise.</p>

<p>The problem we encountered is that we didn’t have enough resources to actually find clusters in these networks. We get better results with more data, but the size of sequence similarity networks scales quickly as we add more data. The average <em>E. coli</em> genome has around 4,200 genes. If we sequence 1,000 of these genomes, that’s 4,200,000 genes. We typically use reciprocal best-BLAST hits, so each gene will only have a similarity to one gene per other genome, but even with that, we’re looking at around 2.1 billion edges.</p>

<p>Let’s think about that in terms of computational requirements. Each edge is undirected, so it needs at least two IDs corresponding to the nodes it connects. They’re also weighted, so they need a representation of the weight of the edge. 4.2M is just barely small enough to fit into an unsigned 32-bit integer, but if we grew at all it would be insufficient. That means we’ll need two 64-bit integers (16 bytes) and one float (4 bytes) per edge. 20B per edge with 2.1 billion edges is 40GB of space. Now note here that this is just to store the network, and doesn’t include any additional processing overhead (e.g., clustering, or even how to get node labels into nicely indexed 64-bit integers).</p>

<p>A thousand genomes isn’t even that large – our current analysis is looking 4,422 complete genomes from RefSeq, which comprises around 12 million nodes and 20 billion edges. Storing that in the aforementioned format would take 400GB of RAM just for the network itself. Maybe we leverage some sparse encoding techniques to shave off one of the integers from the edge representation; even with that, we’re still looking at 12 bytes per edge, and 240GB to hold the network.</p>

<p>This isn’t our end goal. We’re looking to scale way past 4,422 genomes, but the scaling of these networks is not sustainable with current hardware. Sure, there are systems that have terabytes of RAM, but note the scaling of memory requirements with input size. When we moved from 4M genes to 12M (roughly 3x more), the RAM requirement increased by 10x. By that logic, going to 36M genomes would take at least 4TB of RAM, and 108M genes would take at least 40TB. The actual scaling is nonlinear, so we’d probably require a lot more than 40TB of RAM.</p>

<p>This is where ExoLabel comes in. We can’t simply keep buying bigger hardware to process networks of this size, at least in our current compute environment. Maybe Big Tech has the resources to keep pace with this, but few academic labs have access to machines with multiple terabytes of RAM. Could we cluster networks in a way that somehow uses less RAM?</p>

<h2 id="the-solution">The Solution</h2>

<p>There’s a solution to this issue that’s very simple in theory: why not just offload the data from RAM to other storage? Much like a SQL database, we could store all the graph information somewhere on disk and just query for what we need, when we need it. If the clustering algorithm we use only needs data on a single node and its neighbors, we could reduce our memory complexity from scaling with the number of edges to scaling with the maximum node degree (asymptotically equivalent to scaling with the number of nodes, but much better for sparse networks). The critical issue is that read/writes to disk are extremely slow compared to RAM, even with SSDs. Solving memory complexity at the cost of infinite runtime is by no means a solution, so I had to spend a lot of time optimizing our implementation to work nicely with disk drives.</p>

<p>I’ll start with the core clustering algorithm. I expected this to be the hardest part of the project, but it ended up being much easier than the database construction portion. I chose <a href="https://doi.org/10.1038/s41598-023-29610-z">Fast Label Propagation</a> for a couple reasons. First, it’s a recently published algorithm, so I have relatively high confidence that it’s competitive with prior approaches. Second, the core algorithm only needs information on a single node and its neighbors to cluster that node, which meets my algorithmic needs to leverage a database structure. Third, it’s fast (it says so in the name!). Lastly, label propagation is a relatively well-studied and commonly used approach for clustering sequence similarity networks.</p>

<p>Label propagation is a pretty simple algorithm at its core. We start by setting each node to be in its own cluster. Then, for each node, we consider all the incoming edges to that node. Each incoming edge starts at a different node in some cluster. We add up the incoming weights for each of these clusters, and then assign the node to the highest weighted cluster. For instance, suppose we have a node <code class="language-plaintext highlighter-rouge">A</code> with three neighbors, <code class="language-plaintext highlighter-rouge">B,C,D</code>. Nodes <code class="language-plaintext highlighter-rouge">B,C</code> are in cluster 1 and node <code class="language-plaintext highlighter-rouge">D</code> is in cluster 2, and all the edges have weight 1.0. Then cluster 1 has a total incoming weight of 2, and cluster 2 has a total incoming weight of 1. We then assign <code class="language-plaintext highlighter-rouge">A</code> to cluster 1. In fast label propagation, we keep a queue of nodes we’re going to process (initially containing all nodes). Whenever a node changes its cluster, we add all neighbors in different clusters to the queue (if they’re not already in it). There’s a few more optimizations I added to this algorithm, but I’ll come back to those in the deep dive section.</p>

<p>Next, let’s talk about the database construction. Since I’m using label propagation, I needed a way to quickly look up the incoming edges for any particular node. It’s also important to be aware of the problem setting: most networks I’m going to process are going to be relatively sparse in general, so something like an adjacency matrix would be way overkill. I settled on using an adaptation of a compressed-sparse row (CSR) format for the database. A CSR-encoding stores the end vertices for each edge back to back, and then stores an index somewhere that determines where the edges for each node live (note that this can be swapped to store the start vertices for each edge, I’m just using this representation because it’s most efficient for label propagation). It’s more easily described with an example.</p>

<p>Suppose we have a network with four nodes, <code class="language-plaintext highlighter-rouge">A,B,C,D</code>, and the following connections: <code class="language-plaintext highlighter-rouge">A-&gt;B</code>, <code class="language-plaintext highlighter-rouge">B-&gt;C</code>, <code class="language-plaintext highlighter-rouge">C-&gt;D</code>, <code class="language-plaintext highlighter-rouge">D-&gt;A</code>, <code class="language-plaintext highlighter-rouge">A-&gt;C</code>, <code class="language-plaintext highlighter-rouge">B-&gt;D</code>. We start by counting the number of incoming connections for each node:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>A: 1 (D-&gt;A)
B: 1 (A-&gt;B)
C: 2 (A-&gt;C, B-&gt;C)
D: 2 (B-&gt;D, C-&gt;D)
</code></pre></div></div>

<p>We then form an index using the cumulative counts of these node degrees, and then store the start nodes inline afterward:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1 1 2 2 -&gt; 0 1 2 4 6 (add a 0 at the beginning)

CSR:
0 1 2 4 6
D A A B B C
</code></pre></div></div>
<p>Why do this? This actually gives us a fast way to look up incoming connections if we know how what order the vertices come in. Here we ordered our representation as <code class="language-plaintext highlighter-rouge">A,B,C,D</code>. Suppose we wanted to get the incoming edges for node <code class="language-plaintext highlighter-rouge">C</code>. We know that <code class="language-plaintext highlighter-rouge">C</code> is the 2nd node (if we’re using 0-indexing), so we look at the 2nd and 3rd values of the index, which corresponds to <code class="language-plaintext highlighter-rouge">[2,4]</code>. This tells us that the edges at positions <code class="language-plaintext highlighter-rouge">[2,4)</code> (not including the end position) belong to node C. This is also the reason we had to add a 0 to the beginning of the index – we need <code class="language-plaintext highlighter-rouge">n+1</code> indices to store <code class="language-plaintext highlighter-rouge">n</code> nodes, since each node <code class="language-plaintext highlighter-rouge">i</code> is defined by a range <code class="language-plaintext highlighter-rouge">[index[i], index[i+1])</code>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0 1 [2 4] 6
D A [A B] B C

Node C has two connections (4-2=2)
They are from nodes B and A
</code></pre></div></div>

<p>This is a nice representation for a couple key reasons. First, it stores all the edges for a particular node in a contiguous block. Disk drives are most efficient at sequential reads, so this allows ExoLabel to read all the edges for a particular node sequentially rather than jumping around in the database. Second, it stores the minimum amount of data necessary for each edge – since we know the destination node implicitly using the index, we only have to store the source node (for directed graphs – for undirected graphs, we have to store each edge as two directed edges). For weighted graphs, we can either store the weights inline with the edges or in a second table with matched format.</p>

<h2 id="performance">Performance</h2>

<p>Before digging into the details, I’ll give a brief description of its performance. Note that this is a work in progress – I’ll update this section as I finish the rest of my benchmarks. Note that the RAM consumption doesn’t include the amount of RAM required for R and the SynExtend package, which is around 300MB on my machine. These tests were performed on an M1 MacBook Pro with 16GB RAM and graphs stored on an internal SSD. All these test cases are real sequence similarity networks. The final test read the input file from an external HDD connected via USB-C, with intermediate files stored on the internal SSD. Edges are directed, so the number reported is twice the number of undirected edges.</p>

<table>
  <thead>
    <tr>
      <th style="text-align: center">Vertices</th>
      <th style="text-align: center">Edges</th>
      <th style="text-align: center">Runtime (MM:SS)</th>
      <th style="text-align: center">RAM Consumption</th>
      <th style="text-align: center">Disk Consumption</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center">56,266</td>
      <td style="text-align: center">686,286</td>
      <td style="text-align: center">00:02</td>
      <td style="text-align: center">113 MB</td>
      <td style="text-align: center">22.0 MB</td>
    </tr>
    <tr>
      <td style="text-align: center">128,008</td>
      <td style="text-align: center">1,503,044</td>
      <td style="text-align: center">00:02</td>
      <td style="text-align: center">132 MB</td>
      <td style="text-align: center">50.7 MB</td>
    </tr>
    <tr>
      <td style="text-align: center">1,375,735</td>
      <td style="text-align: center">156,434,932</td>
      <td style="text-align: center">01:43</td>
      <td style="text-align: center">271 MB</td>
      <td style="text-align: center">5.0 GB</td>
    </tr>
    <tr>
      <td style="text-align: center">3,500,903</td>
      <td style="text-align: center">937,020,456</td>
      <td style="text-align: center">15:17</td>
      <td style="text-align: center">380 MB</td>
      <td style="text-align: center">29.9 GB</td>
    </tr>
  </tbody>
</table>

<p>Accuracy benchmarks are forthcoming. Anecdotally, it produces pretty good results. For reference, <a href="https://doi.org/10.1093/nar/gkx1313">HipMCL</a> required 240 cores and 15TB of unified RAM to process a similar sized network to ExoLabel’s final trial (with roughly 3.5M nodes, 700M directed edges) in 30 min. MCL scales quadratically so it’s not the most fair comparison, but it is the standard approach in the field.</p>

<p>That’s the high-level view of ExoLabel. We first read the input data into a CSR format on disk, and then we use fast label propagation, querying the CSR table for relevant data when we process each node. Doing that in an efficient way results in pretty good runtime – not as good as a completely in-memory algorithm with access to infinite RAM, but much better than a limited machine that has to rely on swap. The next section will detail all the nitty-gritty, so if you’re not interested in that, feel free to stop reading here.</p>

<h2 id="deep-dive-how-does-it-really-work">Deep Dive: How does it <em>really</em> work?</h2>

<p>Let’s now go through how ExoLabel actually works in detail. There are 5 key steps:</p>
<ol>
  <li>Reindex the nodes</li>
  <li>Record the edges (happens in parallel with (1))</li>
  <li>Sort the edgelist file</li>
  <li>Do the clustering</li>
  <li>Write out the results</li>
</ol>

<h3 id="step-1-reindexing">Step 1: Reindexing</h3>

<p>ExoLabel uses integer-indexed nodes, but the input data won’t be formatted in that nice format. The output of BLAST searches is usually in plain text and stored like the following:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>VERTEX1 VERTEX2 SIMILARITY
VERTEX1 VERTEX2 SIMILARITY
VERTEX1 VERTEX2 SIMILARITY
</code></pre></div></div>

<p>For example:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>abc def 0.0451
abc ghi 0.8713
def ghi 0.2301
def xyz 0.5678
</code></pre></div></div>

<p>I don’t want to use string-based indexing. Strings are messy – they’re slow to compare (relative to integers) and have highly variable space requirements. I’m working in C for this, so I don’t have a simple string class. Each string could take any number of bytes, potentially even more than the 8-bytes per node required of integer indexing. Variable width fields also make it hard to read in edges from the CSR compression. With integer indexes, if I know that there are 10 edges starting from index 20, I can just move the file pointer to position 20 and read in 10*8 bytes. With strings, I’d have to also store the number of bytes to read and the lengths of each string in the field.</p>

<p>In order to transform the string input to integers, I’m using a <a href="https://en.wikipedia.org/wiki/Trie">trie</a>. Tries are not the most efficient way to map strings to integers; we could theoretically just hash the string. However, we have to be able to write out the clusters at the end of the function. Users aren’t going to want random indexes, they’re going to want the labels they provided. This means I have to store all the vertex names <em>somewhere</em> on the computer. It’s technically possible to store them on disk, but this ends up getting extremely complicated (mainly because of variable length fields, again). I settled on an in-memory trie because it has fast access and the space complexity is very good for solutions that store the entire string.</p>

<p>The trie structure has two types of components: internal nodes and leaf nodes.</p>

<p>First, the leaf nodes:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="n">leaf</span> <span class="p">{</span>
  <span class="kt">uint64_t</span> <span class="n">count</span><span class="p">;</span> <span class="c1">// also tracks the cluster number</span>
  <span class="kt">uint64_t</span> <span class="n">index</span><span class="p">;</span>
  <span class="kt">uint64_t</span> <span class="n">edge_start</span><span class="p">;</span> <span class="c1">// start position of edges in the disk file</span>
  <span class="kt">uint32_t</span> <span class="n">dist</span><span class="p">;</span> <span class="c1">// distance to original label, used for attentuation</span>
<span class="p">}</span> <span class="n">leaf</span><span class="p">;</span>
</code></pre></div></div>

<p>The leaf nodes have a number of attributes. <code class="language-plaintext highlighter-rouge">index</code> is the most important one here; it stores the index of a given string in a 64-bit unsigned integer. As I read in each node, I try to insert it into the tree. If it doesn’t exist, we insert it and assign it to the next available index.</p>

<p>The other attributes are for later clustering steps. <code class="language-plaintext highlighter-rouge">count</code> stores the in-degree of each node, which we need for the CSR compression later. During the clustering step, it stores the cluster the node is currently assigned to. This makes some of the variable names a little confusing, but is worth it because it saves a lot of memory. <code class="language-plaintext highlighter-rouge">edge_start</code> stores the offsets for the CSR compression. In a typicaly CSR format, this is stored in the file itself, but moving it into memory saves a lot of runtime by reducing how much we have to jump around in the file. The cost is 8 bytes per node, which isn’t a ton (100M nodes would only be 800MB). <code class="language-plaintext highlighter-rouge">dist</code> is for attenuation, which I’ll talk about in Step 3.</p>

<p>I’m planning to eventually combine the <code class="language-plaintext highlighter-rouge">index</code> and <code class="language-plaintext highlighter-rouge">edge_start</code> variables, since they’re never used at the same time…I just haven’t gotten to it yet.</p>

<p>Next, the internal node:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="n">prefix</span> <span class="p">{</span>
  <span class="kt">uint64_t</span> <span class="n">bmap1</span> <span class="o">:</span> <span class="mi">56</span><span class="p">;</span> <span class="c1">// 0, 32-86</span>
  <span class="kt">uint8_t</span> <span class="n">count1</span> <span class="o">:</span> <span class="mi">8</span><span class="p">;</span>  <span class="c1">// counts in this bitmap</span>
  <span class="kt">uint64_t</span> <span class="n">bmap2</span> <span class="o">:</span> <span class="mi">42</span><span class="p">;</span> <span class="c1">// 87-127</span>
  <span class="kt">uint8_t</span> <span class="n">count2</span> <span class="o">:</span> <span class="mi">8</span><span class="p">;</span>   <span class="c1">// counts in this bitmap</span>
  <span class="kt">void</span> <span class="o">**</span><span class="n">child_nodes</span><span class="p">;</span>  <span class="c1">// 0 will be leaf, else will be prefix</span>
<span class="p">}</span> <span class="n">prefix</span><span class="p">;</span>
</code></pre></div></div>

<p>This structure is designed to be as light on memory as possible. There are 128  ASCII codes, of which only the values 32-126 are printable (I also included 127 by accident…it’s not needed though, and it doesn’t hurt). Internal nodes have a total of 3 elements: a 98-bit bitmap, a count of how many values are in the tree, and a pointer to an array of pointers. Let’s suppose I only supported the numbers 0-7, and wanted to insert one of them into a leaf:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>leaf structure:
  bitmap: 0000 0000
  count: 0
  children: []

&gt;&gt; insert 6 &lt;&lt;
bitmap = bitmap OR 6
count++
children.append(child6)

leaf structure:
  bitmap: 0000 0100
  count: 1
  children: [child6]
</code></pre></div></div>

<p>To find children, we shift through the valid bits of the bitmap to figure out which character the next child in <code class="language-plaintext highlighter-rouge">children</code> corresponds to. In this case, <code class="language-plaintext highlighter-rouge">children[0]</code> is a child node corresponding to the current prefix plus the number 6. This allows each prefix to store <em>up to</em> 98 children, but without requiring that we allocate 98 pointers at each node on initialization. It’s basically a sparse format. The reason there are two bitfields is because there are 98 characters, so a single 64-bit integer wasn’t large enough (and 128-bit integers aren’t portable).</p>

<p>This takes care of prefixes, but what if the current node is the end of a string? If we knew that every child was another internal node, we could make <code class="language-plaintext highlighter-rouge">children</code> of type <code class="language-plaintext highlighter-rouge">struct prefix**</code>. However, sometimes we have a child that is of type <code class="language-plaintext highlighter-rouge">struct leaf</code>, so <code class="language-plaintext highlighter-rouge">children</code> has to be <code class="language-plaintext highlighter-rouge">void**</code>. I didn’t just make a single struct for both because the <code class="language-plaintext highlighter-rouge">leaf</code> structure has to hold a lot more data. If internal nodes also had the same fields, I’d be wasting tons of RAM.</p>

<p>The leaves are always stored at the first bit of the bitmap, so if <code class="language-plaintext highlighter-rouge">prefix.bmap1 &amp; 1 == 1</code>, then the first entry in <code class="language-plaintext highlighter-rouge">children</code> is a pointer to a <code class="language-plaintext highlighter-rouge">struct leaf</code> object. The first bit is used because it corresponds to an ASCII code of 0, which is the null-terminator for strings. All other entries in <code class="language-plaintext highlighter-rouge">children</code> are pointers to <code class="language-plaintext highlighter-rouge">struct prefix</code> elements. The <code class="language-plaintext highlighter-rouge">count</code> variables allow for a little bit of optimization so I don’t have to exhaustively check every bit every time.</p>

<p>The first step passes through the input edgelist files. The separator between entries is provided as a parameter and typically set to <code class="language-plaintext highlighter-rouge">\t</code> (as in a <code class="language-plaintext highlighter-rouge">.tsv</code>). The algorithm reads characters into a buffer and looks for the separator. When the separator is encountered, it <em>tries</em> (lol) to insert the prefix into the trie. If it exists already, we increment the <code class="language-plaintext highlighter-rouge">count</code> value of the leaf. If it doesn’t, we make a new leaf and set its <code class="language-plaintext highlighter-rouge">count</code> value to 1. If we’re reading in undirected edges, we only increment <code class="language-plaintext highlighter-rouge">count</code> if the node is the destination node for the edge.</p>

<h3 id="step-2-recording-edges">Step 2: Recording edges</h3>

<p>In an earlier implementation of ExoLabel, this step happened after step 1. However, due to some other optimizations, it now happens at the same time as step 1.</p>

<p>In step 1, ExoLabel indexes all the nodes and records the in-degree of each node. At the same time, we write all the edges that will eventually become the CSR-format to a file. This step won’t make any sense without a brief description of what’s coming, so let’s briefly take a detour to talk about step 3.</p>

<p>Recall that we’re trying to build a CSR-representation of the network. In order to do that, we have to have all the source nodes for each edge ending at each node in contiguous blocks in the file. At first, I did this by recording the in-degree of each node in the first pass through the file, then recording the values at the correct position during a second pass. This makes a lot of sense if you’re operating in-memory, but it is a terrible decision when working with disk drives. Because of how spinning-disk drives operate, moving to a random position on a file that lives on a drive is closer to a linear worst-case time complexity, rather than the constant time complexity you’d expect in RAM. SSDs are a lot better at this, but even they struggle with random read/writes due to things like caching/prefetching and write amplification.</p>

<p>The right approach is to play to the strengths of physical disk drives: sequential read/writes. Pretty much everything comes back to minimizing the total number of reads/writes, and making the remaining necessary read/writes sequential.</p>

<p>Think back to the CSR compression. We have to have each node’s edges be contiguous, and every node is indexed by an integer. The key idea here is that if we record each edge as <code class="language-plaintext highlighter-rouge">[end, start]</code> and then sort them by their first entry, the resulting edges will be grouped in CSR format. For example, with the case from earlier:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input network:
A-&gt;B, B-&gt;C, C-&gt;D, D-&gt;A, A-&gt;C, B-&gt;D

Sort edges by destination node:
D-&gt;A, A-&gt;B, A-&gt;C, B-&gt;C, B-&gt;D, C-&gt;D

Discard destination node:
D A A B B C
</code></pre></div></div>

<p>This gets us a CSR format graph, assuming we have the index stored somewhere else. Since the in-degree for each node is stored in the trie as they’re read, it’s easy to construct an index after all edges are recorded.</p>

<p>Sorting the list of edges is a good idea because we can do it entirely with sequential read/writes using merge sort. While this has <code class="language-plaintext highlighter-rouge">n*log n</code> complexity (<code class="language-plaintext highlighter-rouge">n</code> the number of edges), it ends up being significantly faster than the naive approach because sequential read/write is constant time complexity, whereas random read/write is effectively linear (making the naive approach closer to <code class="language-plaintext highlighter-rouge">n^2</code> scaling).</p>

<p>As we traverse the file in step 1, we also record the edges. Since step 3 involves merge sort, I frontload part of the operation by sorting fixed size buffers prior to writing. Practically, this means that ExoLabel reads in around 40,000 edges at a time (converting strings to indices as they’re read in), sorts the list of ~40k edges, then writes those to the file and clears the buffer. These writes are all sequential and at the end of the file, so they’re extremely fast. This pre-sort step saves a lot of time later – merge sort is most time-consuming at the early stages when it’s merging small blocks (especially when those blocks are on disk and not in RAM), and it technically only adds linear time complexity since each sort is on a constant-size array.</p>

<p>It’s important to note that the buffer used to hold edges has to be global; when reading in multiple input files, the ends of files may not match up perfectly with buffer sizes. In tihs case, the next file should continue writing edges to the buffer prior to sorting and flushing the buffer so that all blocks in the resulting file are the same size (except potentially the very last block).</p>

<p>The catch is that this approach requires that both vertices be recorded. One of the big advantages of CSR compression is only one of the nodes has to be saved. We also need to record the weight (4 bytes if using <code class="language-plaintext highlighter-rouge">float</code>), for a total of 12 bytes. Recording both vertices theoretically causes the overall disk space requirements to increase to 20 bytes per edge. Optimal merge sort requires a second copy of the file as well, so we’re up to 40 bytes per edge. Not great.</p>

<p>I solved this by compressing each edge into a smaller format. Rather than recording each edge as <code class="language-plaintext highlighter-rouge">end, start, weight</code>, I’m using two 64-bit integers <code class="language-plaintext highlighter-rouge">end, comp</code>. Here, <code class="language-plaintext highlighter-rouge">comp</code> is a compressed combination of the start node and the weight.</p>

<p>This compression happens as the nodes are read in. For each index, the first 44 bits are reserved for the index of the source node. This reduces the total number of nodes we can process, but 2^44 is over 17 trillion, which should be more than enough nodes. When compressing the weight, I left shift it until the topmost bit is 1 or I’ve made 15 shifts (the max amount that fits into 4 bits). The number of shifts is stored in the next 4 bits. Finally, the transformed weight is truncated to the topmost 16 bits, which are stored at the final 16 bits. It’s essentially a modified 16-bit floating point number that doesn’t allow negative values or exponents.</p>

<p>Using this compression, each edge occupies 16 bytes. Factoring in the merge sort, the maximal bytes per edge is 32 bytes. This is an extra 20 bytes per edge over the original implementation that didn’t use sorting, but it takes one fewer pass through the edgelist files and writes to disk an order of magnitude faster. Although I’d love to have less disk consumption, the practical consumption is around the same size as the input edgefiles in most tests, so it’s not a huge deal. I would be more concerned if there were orders of magnitude more disk consumption than the input file size. Worst case, I can add a flag to delete input files as they’re read in (and potentially rewrite them at the end), which would drastically reduce overhead at the cost of modifying input data.</p>

<p>There is also slight loss of precision, but it’s on the order of 0.01% or less for nearly all input values. The highest loss of precision by percentage is at extremely small weights, where the loss in precision isn’t super meaningful. The absolute error scales with the magnitude of the weights, but again this isn’t a huge cause for concern. For weights of around 60k, the error is around 10. If clustering is dependent on extremely small variations in weights then this may not be a good approach, but I imagine these scenarios to be very limited. The number of bits allocated for weights can also be adjusted to get more precision, though each additional bit for weights or exponents halves the maximum number of nodes supported.</p>

<h3 id="step-3-sorting">Step 3: Sorting</h3>

<p>I already mentioned that the next step is sorting the edges in the file. I’m using an external merge sort for this operation. I’ve actually already written a very in-depth explanation of what’s going on here, so I’ll just link to my previous <a href="/posts/2024/12/loser-trees-io/">blog post on loser trees</a>. In short, I use a tournament tree (also known as a loser tree) to perform a multi-way merge sort on the file. Classical merge sort is a 2-way merge because it merges two blocks at a time. This implementation uses up to a 64-way merge depending on how many blocks are present in the file. Merging more blocks at a time reduces the number of iterations required at the cost of making the merge step take longer. While this doesn’t change the asymptotic runtime, it’s important for files because the slowest operation is disk I/O (even if it’s sequential). Each iteration requires reading and writing the file once, whereas each merge step happens in RAM. Thus, reducing the number of iterations decreases the practical runtime by a lot, since disk I/O dominates the function runtime.</p>

<p>At the end of the sorting step, I have a sorted file containing compressed edges. I then iterate through this file, overwriting the file from the front with just the second entry of each edge (i.e., the compressed <code class="language-plaintext highlighter-rouge">source/weight</code> value). I truncate the file, then iterate over it a second time to split each compressed edge into a decompressed source node index and weight. The index overwrites the current file, and the weight is written to a second file. The file of indexes is called the neighbors table, and the file of weights is called the weights table.</p>

<p>I do this in two passes to reduce the total disk consumption – by first discarding the end node index, I reduce the size of the file by half. The next step of decompressing the edges increases the size of the file by 50%, which makes the overall maximal disk consumption less than that of the merge sort. We’d technically have less disk consumption than the merge sort step even if we decompressed first, but only if the merge sort isn’t in-place. I do have an in-place merge sort implemented, so doing it this way is consistent across both methods and ensures the same maximal consumption.</p>

<h3 id="step-4-clustering">Step 4: Clustering</h3>

<p>I’ve already somewhat described the clustering step, but there are a few more aspects to it that I skimmed over.</p>

<p>First, let’s review the core algorithm. I initialize a queue of nodes to process. For each node, we get the start and end index for its edges in the CSR database. Those edges are read in (from both the neighbors table and the weights table), and then the cluster with the highest weight is assigned to the current node. Each neighbor in a different cluster to the one I just assigned is added to the queue (if it wasn’t in the queue already). The clusters are stored in the <code class="language-plaintext highlighter-rouge">count</code> attribute of each leaf nodes.</p>

<p>The start indexes and clusters are stored in the leaf nodes of the trie, so how do we get to them quickly? Prior to clustering, I traverse the trie to build an array of pointers to each leaf node. This array is constructed such that <code class="language-plaintext highlighter-rouge">array[i]</code> is the leaf node corresponding to node <code class="language-plaintext highlighter-rouge">i</code>. Thus, <code class="language-plaintext highlighter-rouge">array[i+1]-&gt;edge_start - array[i]-&gt;edge_start</code> is the number of edges for node <code class="language-plaintext highlighter-rouge">i</code>. This means I can look up node data for any random node in constant time.</p>

<p>Label propagation has pretty good practical runtime, but can theoretically run forever. We stop once there are no more nodes in the queue, but cycles can appear that never terminate. To solve this, ExoLabel keeps count of how many times it’s seen each node. Once it’s seen a given node more than a predetermined amount (by default, the square root of the maximum node degree), it will no longer add the node to the queue. This prevents the algorithm from running forever.</p>

<p>I also mentioned that there’s a distance attribute in the leaf nodes. This is to solve the monster group problem that plagues label propagation algorithms. Label propagation is susceptible to grouping all nodes into a single giant cluster, which isn’t super informative. I use dynamically-scaling label hop attenuation (as introduced by <a href="https://doi.org/10.1103/PhysRevE.79.066107">Leung et al., 2009</a>), which reduces the contribution of a cluster the farther it’s traveled from its original point. The amount that the weights are attenuated scales based on the proportion of nodes that changed label in the previous iteration. The distance attribute in the leaf nodes stores the minimum distance to the origin of the current cluster, so it can be calculated in constant time.</p>

<h3 id="step-5-output">Step 5: Output</h3>

<p>At this stage, each node’s final cluster is stored in the <code class="language-plaintext highlighter-rouge">count</code> attribute of the corresponding leaf node in the trie. Additionally, each label is stored along the paths of the trie. This means that the labels and their corresponding clusters can be recovered with a simple depth-first traversal of the trie structure. The labels are cached along each node as the trie is traversed with a standard backtracking algorithm. When a leaf node is encountered, the current label and the cluster are written to the outfile.</p>

<h2 id="conclusion">Conclusion</h2>

<p>I think this is one of my longest blog posts, ever. If you’ve made it this far, thanks for reading. Check out the code for ExoLabel in the SynExtend package on <a href="https://github.com/ahl27/SynExtend/tree/master/src/ExoLabel">GitHub</a>, and stay tuned for a paper on it in the near future!</p>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><category term="C" /><category term="R" /><summary type="html"><![CDATA[I’ve made a lot of posts about ExoLabel, but the project has been moving so quickly that they’ve become out of date almost as soon as I post them. I’m finally close to the end of this project, so I thought it was high time I write out the entire project (partly for my own reference, so I don’t forget).]]></summary></entry><entry><title type="html">A Story of a Sneaky Bug</title><link href="https://www.ahl27.com/posts/2025/04/overflow-bug/" rel="alternate" type="text/html" title="A Story of a Sneaky Bug" /><published>2025-04-04T00:00:00-04:00</published><updated>2025-04-04T00:00:00-04:00</updated><id>https://www.ahl27.com/posts/2025/04/OverflowBug</id><content type="html" xml:base="https://www.ahl27.com/posts/2025/04/overflow-bug/"><![CDATA[<p>I solved a really tricky bug in <a href="/posts/2024/03/oomcluster/">ExoLabel</a> recently and thought it would be an interesting experience to share.</p>

<h2 id="context-monster-groups">Context: Monster Groups</h2>

<p>At this point, I’ve been working on ExoLabel for a while. I have a working clustering algorithm that performs fast label propagation on graphs of arbitrary size. Throughout development, I’ve been fighting this phenomenon I like to think of as the “monster group effect”. Traditional label propagation is very susceptible to agglomerating all nodes into one giant cluster, similar to what you’d get out of single-linkage clustering. This is a well-known drawback of label propagation (and graph clustering algorithms in general), and there are a lot of proposed solutions that have varying effectiveness.</p>

<p>The issue is that not every solution scales well as graphs get larger. To showcase this, let’s look at a common approach: adding self-loops. Self-loops essentially add “inertia” to each node, making it resist changes from incoming edges. However, the number of edges in a network typically scales quadratically with the number of nodes. If we assume that spurious edges occur with any probability, the weight of spuriously connected communities will also scale quadratically with the network size. Self-loops are constant, so eventually they’ll be outscaled by larger and larger networks.</p>

<p>I implemented two measures to combat the monster group problem. First, I use a self-loop cutoff rather than a fixed self-loop. This means that, in order for a node to be assigned to a neighboring community, at least one of the edges carrying that community must have a weight past the self-loop cutoff. This ensures that there is at least one non-spurious edge before propagating a label.</p>

<p>Second, I use label-hop attenuation. This is a technique I found in a previous paper on label propagation variants (see <a href="https://doi.org/10.1016/j.physa.2019.122058">Garza and Schaeffer, 2019</a>). In label propagation, we begin by initializing each node to its own cluster. With label-hop attenuation, we track how far each label is from the original node it started with. These distances are initialized to zero, and when a node is assigned to a new cluster, its distance becomes one more than the minimum distance from that cluster. This distance is used to attenuate the edge weights to decrease the influence of edges the farther they’ve spread from the initial node. There’s a lot more details on how that works, but they’re not really relevant to this story – essentially the farther you get from the source, the less your influence, and we track that distance in terms of number of steps it takes to travel back to the source.</p>

<h2 id="the-problem">The Problem</h2>

<p>My development process followed a maddening cycle:</p>

<ol>
  <li>I’d validate that everything is working correctly</li>
  <li>I’d ensure that my results matched previous examples of correct performance</li>
  <li>I’d check that it works on slightly larger graphs (it would)</li>
  <li>I’d happily determine that I’ve finished</li>
  <li>I’d test on much larger graphs, and it fails</li>
</ol>

<p>The issue is that a lot of the errors only revealed themselves at sufficiently sized networks. Testing on networks with 1,000 nodes worked fine, but then I’d get monster groups again on networks with 100,000 nodes. I’d fix those issues and it would work again, only to return a monster group for networks with 1,000,000 nodes.</p>

<p>After a lot of debugging, I finally got it to work with the largest subset of my complete testing data that I could handle on my computer in reasonable time (around 3.5 million nodes and 500 million edges). I figured that I had finally finished catching all the little bugs, and we applied it to the complete network I’ve been building towards during this whole process (around 16 million nodes and 40 billion edges).</p>

<p>And…..it failed.</p>

<p>Once again, I was seeing a lot of nodes clumped into one giant monster group. By “a lot”, I mean over 15 million of the 16 million total nodes. Way, way too more than should belong to a single cluster for this input data.</p>

<p>This set off some alarm bells in my head. First, I’ve gone through this process a bunch of times, and I’d like to think that there are less and less chances of having <em>another</em> conceptual issue that only affects cases where I have 10x more nodes than my last test case. Most of these issues were major conceptual problems, like when I realized self-loops fail to scale and moved to self-loop filters. Surely this can’t keep happening forever, right?</p>

<p>The other weird thing is that this wasn’t <em>that</em> much larger than the previous test case. In other times doing debugging like this, I had issues with graphs 10x larger than then previous one. I did some additional checking and validated that it worked fine for a network with five million nodes, which is only 3x less than the network that failed. This also seems to suggest that there isn’t a major conceptual issue, more likely a small bug.</p>

<h2 id="so-where-is-the-problem">So, where is the problem?</h2>

<p>The next step was to figure out where the issue is. I’ve said it before, but I have been through this code many times with a fine-toothed comb. At this point I’m not sure what to look at that I haven’t already checked.</p>

<p>I started by going through what I knew about the problem. I know it appears on my full dataset, but not on some of the smaller subsets I can constructed for testing. The full dataset is around 3-5x larger than the largest subset, and significantly more connected (i.e., it has fewer disjoint communities).</p>

<p>Now, I’d love to take the time and walk through all the things I thought of and looked at, but unfortunately they won’t make a ton of sense without a deep knowledge of the codebase. If you really want to try for yourself, I’ll leave a permalink to the commit right before I fixed the bug here: <a href="https://github.com/ahl27/SynExtend/tree/6c5cf30533e8abc2e962b597827826e1aa663b64">commit 6c5cf30</a> (may not be stable if you’re reading this years in the future).</p>

<p>Instead, I’ll just cut to the chase. Remember how I’m storing the distances for label-hop attenuation? Previously, I was using <code class="language-plaintext highlighter-rouge">uint16_t</code> to store this distance. The rationale for this decision is essentially that once we get to 65,535 steps away from the soruce, we can just stop incrementing and assume the weight is going to be really small. A minimum distance of 65,535 in a network structure is <em>really</em> far, even arbitrary people on social media are typically connected by something like 4-5 hops.</p>

<p>In code, I’d do this by only incrementing if the value isn’t about to overflow. My previous code looked like this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">update_node_cluster</span><span class="p">(...){</span>
  <span class="cm">/*
   * lots of preprocessing stuff and other code ...
   */</span>

  <span class="c1">// max_clust is the highest weight cluster neighboring the current node</span>
  <span class="k">if</span><span class="p">(</span><span class="n">max_clust</span> <span class="o">!=</span> <span class="n">original_cluster</span><span class="p">){</span>
    <span class="c1">// record that the node is changed</span>
    <span class="n">GLOBAL_verts_changed</span><span class="o">++</span><span class="p">;</span>

    <span class="c1">// update the node's cluster</span>
    <span class="n">original_node</span><span class="o">-&gt;</span><span class="n">count</span> <span class="o">=</span> <span class="n">max_clust</span><span class="p">;</span>

    <span class="c1">// increment distance while handling overflow</span>
    <span class="c1">// (if it overflows to 0, evaluates to FALSE and then skips increment)</span>
    <span class="n">new_dist</span> <span class="o">=</span> <span class="n">new_dist</span><span class="o">+</span><span class="mi">1</span> <span class="o">?</span> <span class="n">new_dist</span><span class="o">+</span><span class="mi">1</span> <span class="o">:</span> <span class="n">new_dist</span><span class="p">;</span>

    <span class="c1">// assign new distance to the node</span>
    <span class="n">original_node</span><span class="o">-&gt;</span><span class="n">dist</span> <span class="o">=</span> <span class="n">new_dist</span><span class="p">;</span>

    <span class="c1">// put any nodes we still need to process back into the queue</span>
    <span class="n">add_remaining_to_queue</span><span class="p">(</span><span class="n">max_clust</span><span class="p">,</span> <span class="n">neighbors</span><span class="p">,</span> <span class="n">weights_arr</span><span class="p">,</span> <span class="n">num_edges</span><span class="p">,</span> <span class="n">queue</span><span class="p">);</span>
  <span class="p">}</span>

  <span class="cm">/*
   * lots of postprocessing stuff and other code ...
   */</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="casting-bugs">Casting Bugs</h2>

<p>Where is the bug? Well, it turns out that I misunderstood how C handles simple arithmetic with variables of different types. The erroneous line is here:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// increment distance while handling overflow</span>
<span class="c1">// (if it overflows to 0, evaluates to FALSE and then skips increment)</span>
<span class="n">new_dist</span> <span class="o">=</span> <span class="n">new_dist</span><span class="o">+</span><span class="mi">1</span> <span class="o">?</span> <span class="n">new_dist</span><span class="o">+</span><span class="mi">1</span> <span class="o">:</span> <span class="n">new_dist</span><span class="p">;</span>
</code></pre></div></div>

<p>My assumption was that <code class="language-plaintext highlighter-rouge">new_dist + 1</code> would be of type <code class="language-plaintext highlighter-rouge">uint16_t</code>. This is…sort of correct, but mostly wrong. There are a couple pieces to this line:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">new_dist</code> is of type <code class="language-plaintext highlighter-rouge">uint16_t</code></li>
  <li><code class="language-plaintext highlighter-rouge">1</code> is a constant, which is implicitly of type <code class="language-plaintext highlighter-rouge">int</code></li>
  <li><code class="language-plaintext highlighter-rouge">int</code> is a 32-bit type on my machine (and most modern machines, but not guaranteed)</li>
</ul>

<p>C adds the two numbers together and then casts them to <code class="language-plaintext highlighter-rouge">uint16_t</code>. The trick is <em>when</em> that happens. For comparison, the following seemingly identical code <em>does</em> work:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">new_dist</span> <span class="o">=</span> <span class="n">new_dist</span> <span class="o">+</span> <span class="mi">1</span><span class="p">;</span>
<span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">new_dist</span><span class="p">)</span>
  <span class="n">new_dist</span> <span class="o">=</span> <span class="n">new_dist</span> <span class="o">-</span> <span class="mi">1</span><span class="p">;</span>
</code></pre></div></div>

<p>Hopefully that starts to clarify the issue. The cast to <code class="language-plaintext highlighter-rouge">uint16_t</code> happens on <em>assignment</em>, not midway through calculations. Casting does happen during calculations, but this is usually just upcasting to the largest type. This means we have the following order of evaluation:</p>

<ol>
  <li><code class="language-plaintext highlighter-rouge">1</code> is implicitly of type <code class="language-plaintext highlighter-rouge">int</code></li>
  <li><code class="language-plaintext highlighter-rouge">new_dist</code> is of type <code class="language-plaintext highlighter-rouge">uint16_t</code>, so it gets promoted to type <code class="language-plaintext highlighter-rouge">int</code> for addition</li>
  <li>the result of <code class="language-plaintext highlighter-rouge">new_dist + 1</code> is <strong>not</strong> cast to <code class="language-plaintext highlighter-rouge">uint16_t</code> prior to evaluating the <code class="language-plaintext highlighter-rouge">true/false</code> check of the ternary operator</li>
  <li>the ternary check is always <code class="language-plaintext highlighter-rouge">true</code>, so we return <code class="language-plaintext highlighter-rouge">new_dist+1</code></li>
  <li><code class="language-plaintext highlighter-rouge">new_dist+1</code> is cast to <code class="language-plaintext highlighter-rouge">uint16_t</code>, which may overflow to <code class="language-plaintext highlighter-rouge">0</code>.</li>
</ol>

<p>The reason the second code block works is because there’s an assignment in the middle, so <code class="language-plaintext highlighter-rouge">new_dist = new_dist+1</code> forces a cast before the <code class="language-plaintext highlighter-rouge">true/false</code> check.</p>

<p>Why does this cause an issue? Well, after 65,535 hops, the distance overflows to 0. That means the algorithm regards this node as an origin, allowing it to cheat the attenuation mechanism. Given sufficient hops, it could create a new fake source node as well, intensifying the problem. The kicker is that a sufficiently long chain only has to appear once at any point for it to take over, so one could appear early on before the algorithm starts to converge and then rapidly dominate. Using self-loop filters also increases the chance of a long chain appearing since spurious links have a harder time breaking up chains (which is what we want, but it does also exacerbate the problem).</p>

<h2 id="the-fix">The Fix</h2>

<p>Fortunately, the hardest part of this process is finding the single line causing this problem in over 3,000 lines of C and R code. The fix itself is pretty simple.</p>

<p>First, I upgraded the type to <code class="language-plaintext highlighter-rouge">uint32_t</code> to allow for longer chains prior to a potential overflow. Second, I fixed the check to instead check if the value is less than the max allowable value, rather than relying on overflow behavior:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#define DIST_UINT_MAX 4294967295ULL
</span>
<span class="c1">// ...other code</span>

<span class="c1">// new_dist now of type uint32_t</span>
<span class="k">if</span><span class="p">(</span><span class="n">new_dist</span> <span class="o">&lt;</span> <span class="n">DIST_UINT_MAX</span><span class="p">)</span>
  <span class="n">new_dist</span><span class="o">++</span><span class="p">;</span>
</code></pre></div></div>

<p>Like I mentioned, it’s a pretty simple solution. Finding it in the first place was most of the issue! These are the kinds of problems that are super frustrating in the moment, but feels awesome when you finally figure it out.</p>

<p>Anyway, thanks for reading!</p>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><category term="C" /><summary type="html"><![CDATA[I solved a really tricky bug in ExoLabel recently and thought it would be an interesting experience to share.]]></summary></entry><entry><title type="html">The ‘Research Scientist’ Role at Meta: What is it, exactly?</title><link href="https://www.ahl27.com/posts/2025/03/meta-rs-types/" rel="alternate" type="text/html" title="The ‘Research Scientist’ Role at Meta: What is it, exactly?" /><published>2025-03-19T00:00:00-04:00</published><updated>2025-03-19T00:00:00-04:00</updated><id>https://www.ahl27.com/posts/2025/03/MetaRSTypes</id><content type="html" xml:base="https://www.ahl27.com/posts/2025/03/meta-rs-types/"><![CDATA[<p>My <a href="https://www.ahl27.com/posts/2025/02/meta-interview/">last post</a> detailed my interview experience at Meta for a “Research Scientist” role. However, some people I know also interviewed for “Research Scientist” positions and had <em>completely</em> different experiences. It seems like the title “Research Scientist” is what’s given to employees with a PhD, and their actual responsibilities can vary widely. I did some research (no pun intended) on this and thought I’d share what the difference in the process for each position looks like, both based on my experience and what I’ve read online.</p>

<p>Research Scientist (RS) positions seem to fall into four broad categories:</p>
<ul>
  <li>Software engineering (SWE) focused positions</li>
  <li>Data science focused positions</li>
  <li>Machine learning focused positions</li>
</ul>

<p>This isn’t exhaustive, but they’re the most common types of roles you can find on the Meta careers website. You can determine what you’re interviewing for based on the job title, the qualifications and responsibilities, and the interview process itself.</p>

<h2 id="swe-focused-positions">SWE-focused positions</h2>

<p>SWE-type RS roles tend to be similar to a mid-level software engineer. This is the position I interviewed for (and ended up accepting). This position seems to be more focused on standard software engineering, and based on conversations I’ve had with current employees, the evaluation metrics are identical to standard SWEs. Positions like these tend to be listed as “Research Scientist (PhD) – Systems and Infrastructure” (or similar mention of Infrastructure/Product), and look for strong coding experience. The full interview loop typically consists of:</p>

<ul>
  <li>Coding Rounds (2): SWE coding interviews, usually LeetCode-style and averaging LC Medium difficulty. Expectation is to solve two per interview.</li>
  <li>Systems Design: This is a SWE-style systems design interview, meaning you’ll be designing a software product. Think of like “Design Yelp” or “Design a Web Crawler”.</li>
  <li>Behavioral: Standard behavioral interview, they’re pretty much always the same at Meta. The only difference between this and a SWE behavioral interview is that it’ll be conducted by someone with a PhD, so they’ll have a similar background to you.</li>
</ul>

<p>The phone screen is a single coding round, identical to the full loop coding rounds. The expectation with these roles is that you’ll be doing mostly standard software development, but you may be able to do some research-type problems. You are most likely not going to be publishing research. I covered this process in a lot more detail in <a href="https://www.ahl27.com/posts/2025/02/meta-interview/">my previous blog post</a>.</p>

<h2 id="data-science-y-positions">Data Science-y positions</h2>

<p>DS-style roles are usually marked as “Research Scientist (PhD) – Central Applied Science”. Central Applied Science (CAS) is a recent organization; it was called “Core Data Science” until at least mid-2022, which indicates what the focus in these sorts of roles is. An old overview of their goals can be found <a href="https://research.facebook.com/blog/2022/6/research-highlights-from-the-core-data-science-team-at-meta/">here</a>. I believe that Quantitative UX Research roles also fall into this category. The interview loop for CAS consists of the following rounds:</p>

<ul>
  <li>Research presentation: Present some paper or work you’ve done to a group of CAS research scientists.</li>
  <li>Specialized Coding: Basically just exploratory data analysis. You’ll be given a dataset and you’ll have to do exploration, analysis, and modeling, and then suggest some future avenues to extend analyses in the future.</li>
  <li>Software Engineering: Easier version of a SWE coding round, they ask fewer questions and the questions tend to be more data science-y. That’s not to say it’s easy; you definitely still need to have solid LeetCode skills for this part.</li>
  <li>System Design: Closer to ML systems design than the standard SWE “systems design” interview. Example questions are provided <a href="https://huyenchip.com/machine-learning-systems-design/exercises.html#exercises-rWl8SQW">here</a>, but they’re usually variants of recommender systems. For example, how would you build a system to suggest related questions in a website like StackOverflow?</li>
  <li>In-Domain Technical: This is a statistics/math exam, but the exact details depend on your background. People that have interviewed in the past have mentioned they’ll ask foundational questions like using Bayes’ Theorem and explaining the intuition behind it, as well as more open-ended questions like talking through which statistical analyses are appropriate for a given question about data.</li>
  <li>Behavioral: Same as the SWE-focused positions, advice that applies to any Meta behavioral interview probably works here too.</li>
</ul>

<p>The phone screen is basically a single interview combining aspects of all of these interviews. This is the kind of role you’d want to end up in if you’re in economics, social science, data science, statistics, or related fields. These positions have more opportunity to publish (depending on the team), and they typically investigate research questions related to Meta’s products.</p>

<h2 id="aiml-research-positions">AI/ML Research positions</h2>

<p>I don’t have as much reference for these types of positions, and they tend to be the most competitive from the groups on this list. There’s a much more in-depth description of ML research interview processes across multiple companies available <a href="https://generalizederror.github.io/My-Machine-Learning-Research-Jobhunt/">here</a>. Based on my research online, the interview processes for these positions are pretty varied. There are some roles that go through a centralized process, and others that are more team-specific.</p>

<p>The centralized AI/ML roles seem to sit halfway between CAS and the SWE positions. They’re usually advertised as positions prefixed with “Research Scientist, ML”. The typical full loop interview consists of the following:</p>

<ul>
  <li>Coding Interviews (2): SWE coding interviews, usually LeetCode-style and averaging LC Medium difficulty. Expectation is to solve two per interview.</li>
  <li>ML System Design: Same as the CAS RS Systems Design interview. If you’re interviewing for a specific team then expect to see systems design questions related to what they work on.</li>
  <li>Behavioral Interview: Same as previous, can also touch on experience in research.</li>
</ul>

<p>The phone screen is a LeetCode-style interview with a little discussion about research experience. These positions seem to have pretty broad responsibilities vary based on the specific team. There are definitely more options to publish than a SWE-style RS position, but the exact prioritization of publishing is team-dependent.</p>

<p>The previous sections tend to be general pipelines, where you’ll go through a centralized process and then go through team matching at the end to determine what you’ll actually be doing. However, there are some teams that recruit specifically for research scientist positions via non-centralized pathways, which may be via less advertised methods. Plenty of people online have been brought into the interview pipeline based on presentations at conferences.</p>

<p>I’d put most of the FAIR positions in this category, but they’re sort of their own beast. The expectation for those is that you already have several first-author publications at high impact conferences, and you’d continue to be publishing regularly at Meta. It’s basically like a postdoc / faculty position (depending on level). There’s not a lot of reports on what that interview process is like, but if you’re qualifying for those sorts of roles then you probably don’t need any help with the interview anyway.</p>

<h2 id="conclusion">Conclusion</h2>

<p>That’s it! I unfortunately can’t share in-depth interview experience for any interviews except the ones I personally did. However, if you read this and want to share your experience with me (or you think something is totally incorrect), feel free to send me an email and I’d be happy to update the blog post (and give you a shout-out, if you’d like!).</p>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><summary type="html"><![CDATA[My last post detailed my interview experience at Meta for a “Research Scientist” role. However, some people I know also interviewed for “Research Scientist” positions and had completely different experiences. It seems like the title “Research Scientist” is what’s given to employees with a PhD, and their actual responsibilities can vary widely. I did some research (no pun intended) on this and thought I’d share what the difference in the process for each position looks like, both based on my experience and what I’ve read online.]]></summary></entry><entry><title type="html">So what is it like to interview at Meta/Facebook? (Research Scientist)</title><link href="https://www.ahl27.com/posts/2025/02/meta-interview/" rel="alternate" type="text/html" title="So what is it like to interview at Meta/Facebook? (Research Scientist)" /><published>2025-02-17T00:00:00-05:00</published><updated>2025-02-17T00:00:00-05:00</updated><id>https://www.ahl27.com/posts/2025/02/MetaInterview</id><content type="html" xml:base="https://www.ahl27.com/posts/2025/02/meta-interview/"><![CDATA[<p>I recently accepted an offer to join Meta as a Research Scientist following graduation from my PhD program. I’ve gotten a lot of questions on what the process looks like and how I prepared, so I figured I’d put together a blog post to keep everything organized in one place.</p>

<p>Note: This is all based on my impression of the interviews. Meta doesn’t share interview results, so I have no idea how well I actually did. I could be way offbase for any of these descriptions. I did pass, so I feel like I at least did well on most of them, but who knows.</p>

<p>The process was a pretty standard interview loop for Meta:</p>

<ol>
  <li>Recruiter</li>
  <li>Phone Screening</li>
  <li>Full Loop</li>
  <li>Results/Offer</li>
</ol>

<p>I’ll include the resources I used for each step in the corresponding section.</p>

<p>The position I was interviewing for was titled “Research Scientist (PhD) – Systems and Infrastructure”. From what I understand, this is more similar to a mid-level software engineering (SWE) position. Meta hires research scientists to do both research and SWE roles; what they actually do depends a little more on the team you end up on. In this case, my interview process was very similar to a standard SWE interview loop, and I’m expecting the teams I interview with to expect me to primarily write software for backend/tooling. Some of my peers have interviewed in Central Applied Science, which seems to be a more research-oriented role with interviews looking more like what you’d do as a data scientist. I’ve written a brief summary of the difference between the various “Research Scientist” roles in <a href="https://www.ahl27.com/posts/2025/03/meta-rs-types/">a different blog post</a>.</p>

<p>There seems to be more variance in the first phase than any other component of the process. One of the biggest barriers is making it to this stage. I’ve gotten a lot of questions that are variants of “how did you get to the recruiter?”, and sadly, I don’t have any advice here. A recruiter reached out to me on LinkedIn via InMail, I sent back some basic info about myself, and then my phone screening interview was scheduled. Feel free to check out <a href="https://www.linkedin.com/in/aidan-lakshman-894804b8/">my LinkedIn</a> if it helps, but I think getting lucky is a big factor in this stage.</p>

<p>The phone screening is really just a mini version of the full loop. I did a single coding interview at this stage, and then the full loop had more interviews. The overall process contained the following interviews:</p>

<ul>
  <li>Coding (Phone screen)</li>
  <li>Coding #1</li>
  <li>Coding #2</li>
  <li>Coding #3</li>
  <li>Systems Design</li>
  <li>Behavioral</li>
</ul>

<p>Typically, the full loop is two Coding, one Systems Design, one Behavioral. However, they sometimes add in additional interviews to train people learning to interview. These may or may not count, or they may count to a lower extent. You also probably won’t know which interview is the additional one until you get there, so my advice is always just to try your hardest in every interview.</p>

<h2 id="coding-interviews">Coding Interviews</h2>

<p>All of Meta’s coding interviews followed the same format. All the interviewers were very well prepared and rehearsed, so I’d expect any other interview to follow the same format.</p>

<p>Each interview is 45 minutes. The first 5 minutes are essentially buffer, 35 minutes go to the technical portion, and then there are 5 minutes at the end for questions/buffer. The time limits are very strict, they’ll cut you off after that time is elapsed. I really enjoyed this format, it meant there wasn’t any ambiguity or any concern that the initial interviews would run over and you’d have less time for the questions. In pretty much every interview, they’d say “I’m [name], I’m a [job name] at Meta. You’ll have 35 minutes for two questions, are you ready?”. No small talk, just interviewing.</p>

<p>Each interview was two LeetCode-style questions. They average a medium difficulty–some are asked that are <em>technically</em> easy but with a medium/hard optimal solution, and there are also some hards asked.</p>

<p><em>Note: I’m not allowed to share the specific questions that I was asked due to NDA, so instead I’ll share coding questions that would be good preparation for the interviews I had. None of the questions mentioned here were asked in my interviews.</em></p>

<p>To give an idea of questions that would be good preparation, below is a list of questions with similar difficulty to what I experienced. I did my phone screen in C, and then the full loop in C++.</p>

<ul>
  <li><a href="https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/description/">LC 1249</a>: Minimum Remove to Make Valid Parentheses</li>
  <li><a href="https://leetcode.com/problems/continuous-subarray-sum/description/">LC 523</a>: Continuous Subarray Sum</li>
  <li><a href="https://leetcode.com/problems/search-in-rotated-sorted-array">LC 33</a>: Search in Rotated Sorted Array</li>
  <li><a href="https://leetcode.com/problems/robot-room-cleaner">LC 489</a>: Robot Room Cleaner</li>
  <li><a href="https://leetcode.com/problems/generate-binary-strings-without-adjacent-zeros">LC 3211</a>: Generate Binary Strings Without Adjacent Zeros</li>
  <li><a href="https://leetcode.com/problems/design-most-recently-used-queue/">LC 1756</a>: Design Most Recently Used Queue</li>
  <li><a href="https://leetcode.com/problems/sparse-matrix-multiplication/description/">LC 311</a>: Sparse Matrix Multiplication</li>
  <li><a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/">LC 235</a>: Lowest Common Ancestor of a Binary Search Tree</li>
</ul>

<p>I think people focus too much on memorizing solutions for these. From what I’ve gathered by doing these interviews (one of which with someone learning to interview) and watching interviewers talk about this online, they’re not strictly grading on correctness. A perfect solution could be a no-hire if you don’t display what they’re looking for.</p>

<p>A good solution for a coding problem looks like this:</p>

<ol>
  <li>Clarify the problem, asking about edge cases or other constraints. For example, in a subarray sum problem, does the array have only positive values?</li>
  <li>Describe your solution <em>without</em> code. Write a rough sketch of the approach, either in plaintext or in pseudocode. Make sure you and the reviewer are on the same page. You can mention runtime/memory complexity here if you know it, otherwise I’d mention it around (4) or (5) (or they’ll ask you).</li>
  <li>Code the solution, making sure variable names are descriptive and the code is well formatted. Use good coding practices, they absolutely do look for them!</li>
  <li>Test your code by walking through the test cases provided by hand. I like to record relevant variables below the code and update their values as I step through the code. If you find bugs, fix them!</li>
  <li>If time allows, think of other test cases and test them, prioritizing edge cases.</li>
</ol>

<p>I’ll include an example of that below. Note that the block quotes <code class="language-plaintext highlighter-rouge">/* */</code> aren’t stuff I would actually include, it’s just to call out the steps of the above framework!</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Question: Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).</span>

<span class="cm">/*
 * 1. Clarify the problem.
 * I'd ask if negative exponents are acceptable and what types we expect the
 * input data to be.
 * Let's say that the interviewer clarifies it the function should expect x to
 * be a double, n to be an int, and negative exponents are supported.
*/</span>

<span class="cm">/*
 * 2. Describe your solution.
 *
 * I like to do this with steps that I can add in to the code later
 */</span>

<span class="c1">// 1. convert n to long (so we don't have overflow issues)</span>
<span class="c1">// 2. invert x if n is negative (so we only deal with positive values)</span>
<span class="c1">// 3. while n is positive:</span>
<span class="c1">//    - if n is odd, multiply result by x and subtract 1 from n</span>
<span class="c1">//    - multiply x by x and divide n by two</span>

<span class="cm">/* here I would check with the reviewer BEFORE proceeding! */</span>

<span class="cm">/*
 * 3. Code your solution (with good code! Descriptive names!)
 */</span>

<span class="kt">double</span> <span class="nf">pow</span><span class="p">(</span><span class="kt">double</span> <span class="n">x</span><span class="p">,</span> <span class="kt">int</span> <span class="n">n</span><span class="p">){</span>
  <span class="c1">// 1. convert n to long</span>
  <span class="kt">long</span> <span class="n">exponent</span> <span class="o">=</span> <span class="p">(</span><span class="kt">long</span><span class="p">)</span><span class="n">n</span><span class="p">;</span>

  <span class="c1">// 2. invert x if exponent is negative</span>
  <span class="k">if</span><span class="p">(</span><span class="n">exponent</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">){</span>
    <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span> <span class="o">/</span> <span class="n">x</span><span class="p">;</span>
    <span class="n">exponent</span> <span class="o">*=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="c1">// initialize result</span>
  <span class="kt">double</span> <span class="n">result</span> <span class="o">=</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">;</span>

  <span class="c1">// 3. while n is positive...</span>
  <span class="k">while</span><span class="p">(</span><span class="n">exponent</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">){</span>
    <span class="c1">// if exponent is odd, update result</span>
    <span class="k">if</span><span class="p">(</span><span class="n">exponent</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">1</span><span class="p">){</span>
      <span class="n">res</span> <span class="o">*=</span> <span class="n">x</span><span class="p">;</span>
      <span class="n">exponent</span><span class="o">--</span><span class="p">;</span> <span class="c1">// this line isn't really necessary bc of integer division</span>
                  <span class="c1">// but keeping it in for clarity</span>
    <span class="p">}</span>
    <span class="c1">// square x and half exponent</span>
    <span class="n">x</span> <span class="o">*=</span> <span class="n">x</span><span class="p">;</span>
    <span class="n">exponent</span> <span class="o">/=</span> <span class="mi">2</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>

<span class="cm">/*
 * 4 &amp; 5. Test cases
 * Here I like to write down the variables and update them as I step through code.
 */</span>

<span class="c1">// x = 10</span>
<span class="c1">// exponent = 5</span>
<span class="c1">// result = 1</span>
<span class="cm">/* I'd update these as we go through... */</span>
</code></pre></div></div>

<p>There’s a couple lines that could be simplified slightly (e.g. <code class="language-plaintext highlighter-rouge">if(exponent)</code> is the same as <code class="language-plaintext highlighter-rouge">if(exponent &gt; 0)</code>), but if it doesn’t affect your runtime, I’d err on the side of readability. You could do it like the below code block, but it would be a lot less readable:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// much less readable code!</span>
<span class="kt">double</span> <span class="nf">pow</span><span class="p">(</span><span class="kt">double</span> <span class="n">x</span><span class="p">,</span> <span class="kt">int</span> <span class="n">n</span><span class="p">){</span>
  <span class="k">if</span><span class="p">(</span><span class="n">n</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="o">/</span><span class="n">x</span><span class="p">;</span>
  <span class="kt">double</span> <span class="n">r</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
  <span class="kt">long</span> <span class="n">e</span> <span class="o">=</span> <span class="n">fabs</span><span class="p">(</span><span class="n">n</span><span class="p">);</span>
  <span class="k">while</span><span class="p">(</span><span class="n">e</span><span class="p">){</span>
    <span class="k">if</span><span class="p">(</span><span class="n">e</span> <span class="o">%</span> <span class="mi">2</span><span class="p">)</span> <span class="n">r</span> <span class="o">*=</span> <span class="n">x</span><span class="p">;</span>
    <span class="n">x</span> <span class="o">*=</span> <span class="n">x</span><span class="p">;</span>
    <span class="n">e</span> <span class="o">/=</span> <span class="mi">2</span><span class="p">;</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="n">r</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Of note is that Meta interviews don’t allow any code execution. You basically get a text editor with syntax highlighting. That also means no autocomplete and no AI code generation. Make sure you know your stuff – they won’t care as much about small syntax issues (e.g., missing semicolon, arguments maybe in wrong order), but they will care about not knowing functions.</p>

<p>I think it’s a good idea to try this out with friends. Sublime Text is a great representation of what you’ll get in an interview. Focus on making sure you’re always talking – don’t talk over the interviewer, but talk through what you’re doing as you go so that they know what you’re trying to do. Silently failing is much, much worse because the interviewer won’t even know what you were attempting! This can also help you if you don’t quite remember a function; there were a couple times where I said some variant of “This function does x, I can’t remember if the arguments are in this order or the other but the result of passing these two inputs should be this output”. That demonstrates you know what you’re talking about, and any bugs that may be present are ones you’d be able to fix very easily. Doing that in practice is harder than it sounds, so it’s worth working through.</p>

<p>Another thing to note is that the test cases are primarily there to help <em>you</em>, not the interviewer! Don’t skip through the testing unless you’re really pressed for time. It’s really easy to fall into the trap of thinking “I know what I tried to write so I’ll just walk through what that does”. Testing is half to validate your logic, and half to validate your actual code. Step through your code, doing <strong>exactly</strong> what it says, not what you assume it’s doing. It’ll seem tedious, but you’ll be much more likely to catch bugs. I usually started going through test cases extremely meticulously for the first few iterations, and then gradually sped up as I confirmed the functionality was what I wanted.</p>

<p>For Meta specifically, I’d highly recommend LeetCode premium so you can sort questions by company and frequency. Meta tends to draw from the same question bank, so going to questions frequently asked in the last 3 months and sorting by decreasing frequency gives a really solid list of questions to study.</p>

<p>If you’re starting from scratch, I really recommend going through <a href="https://www.neetcode.io/roadmap">Neetcode</a>, especially the first set of topics. I think dynamic programming, “Advanced Graphs”, “Bit Manipulation”, and “Math &amp; Geometry” are overkill, I’d just skip them. I basically accepted that if I got a question that could only be solved with DP, I’d give it my best shot and probably just fail. Sometimes you have to optimize where you spend your time.</p>

<h2 id="systems-design">Systems Design</h2>

<p>Systems design is what I was most nervous about, since I didn’t have a ton of experience in that area and it seems really daunting. However, it’s really not as bad as it sounds. Again, I can’t share specific questions, but if you could successfully design Yelp, you would’ve done fine in my interview. These interviews definitely get more challenging as you get to higher levels, but at E4 (mid-level) the expectation is that you’re pretty new to systems design. They’re looking for breadth of knowledge and good logical reasoning, but not necessarily the kind of in-depth knowledge that would be expected at the senior-staff level.</p>

<p>For prep resources, I really can’t recommend <a href="https://www.hellointerview.com">HelloInterview</a> highly enough. They do a terrific job, and the resources I got from premium were super, super useful (not sponsored lol). The full list of resources I used were the following:</p>

<ul>
  <li>HelloInterview: as I mentioned, great stuff. Start with <a href="https://www.hellointerview.com/learn/system-design/in-a-hurry/introduction">Systems Design in a Hurry</a>, specifically “Key Technologies” and “Patterns”. If you like that, the in-depth guides and AI mocks available with premium are totally worth it.</li>
  <li><a href="https://www.youtube.com/watch?v=iYIjJ7utdDI">Jordan Has No Life</a>: Jordan and HelloInterview are the best Systems Design resources out there, no joke.</li>
  <li>Designing Data Intensive Applications: I got this as an audiobook (you can get it free with an Audible trial). I almost feel like it’s too in-depth if you’re totally new to systems design, but all the concepts are great to know. Good resource to have in your back pocket to reference in the future (or listen to in the background while you also do other study materials). The more you learn, the more valuable this will be.</li>
  <li>Grokking the Systems Design Interview: Honestly, I didn’t feel like this was worth it. HelloInterview provided everything in GSDI and with more up-to-date materials and references. I noticed several parts of GSDI that were relatively outdated, which isn’t what you want to be learning for this kind of interview.</li>
</ul>

<p>The interview itself was pretty standard. It went through <a href="https://excalidraw.com/">Excalidraw</a>, which I’d recommend checking out in advance if you have an interview with it. Nothing crazy, interviewer defined the problem, I had 35 minutes to work through a solution, 5 minutes at the end for questions. Interview probed my knowledge a bit on some topics; I had to describe some data structures and write a little bit of code/pseudocode. I followed the HelloInterview delivery framework, which worked out well. Retrospectively, I felt a little overprepared for this interview.</p>

<h2 id="behavioral-interviews">Behavioral Interviews</h2>

<p>I feel like behavioral interviews are one of the trickiest sections because they’re just so subjective. At the end of coding interview or systems design, you’ll probably have a good idea of roughly how well it went. Behaviorals don’t have that fixed goal of “design/solve X”, so it’s harder to know how well you did. The reality is that this is one of the most important sections of the interview process, so you really want to nail it.</p>

<p>I’ll note here that this is the only part of the interview process that meaningfully diverged from the standard E4 SWE interview loop. According to my interviewer, behavioral interviews for research scientist positions at Meta are always conducted by someone with a PhD (so ostensibly also a research scientist, though I’m not 100% sure), and they focus more on your research/background.</p>

<p>I swear I’m not sponsored by HelloInterview…but one of their founders recently did an interview with someone that did a lot of behavioral interviews at Meta, and it was really helpful to understand where interviewers are coming from. Highly recommend watching/listening to it.</p>

<iframe width="560" height="315" src="https://www.youtube.com/embed/bBvPQZmPXwQ?si=8DsvDDCkaqqoGxw7" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen=""></iframe>

<p>Aside from that, I looked at some example questions and wrote out stories that I think fit them well. I did a bunch of mock interviews with friends and family and tried to nail down stories that felt good to me, came across well, and had enough depth that I could continue talking about them if the interviewer wanted to drill down. I’m not personally a fan of the STAR framework, I feel like it gets a little stuffy and can easily start becoming over-rehearsed…but that’s just my personal preference.</p>

<p>For the actual interview experience, it went very well. I had a lot of stories prepared, but the interviewer had me drill down on the first one I mentioned. That naturally led into other stories/experiences, so it was a relatively fluid conversation. I felt like this was my best interview overall.</p>

<h2 id="the-timeline">The Timeline</h2>

<p>As someone that agonized over the waiting periods, I know how much people value hearing about others’ experiences with turnaround times. My timeline looked like the following:</p>

<ul>
  <li>Recruiter reached out, asked for availability for the phone screen on the same day.</li>
  <li>I scheduled my phone screen for four weeks out to give me time to prepare.</li>
  <li>About two weeks after the phone screen, I was notified that I passed. This was over the winter holiday break, so it was likely longer than usual.</li>
  <li>I gave my availabilty and scheduled my full loop: the first two interviews were three weeks from notification, and the other three interviews were a week  after that.</li>
  <li>Got a call from the recruiter that my materials were being submitted to the hiring committee three days after my final interview finished.</li>
  <li>Received a verbal offer from the recruiter the three days after that, in the morning.</li>
  <li>Did a some market research and negotiating, then officially accepted about a week later.</li>
</ul>

<p>From start to end, the process took almost exactly two months, comprising seven interviews and the initial recruiter screen. The recruiters and interviewers were all extremely nice and helpful; I don’t think it could have been an easier experience given how many steps/interviews had to happen.</p>

<h2 id="some-closing-thoughts">Some Closing Thoughts</h2>

<p>I don’t think I can emphasize enough how luck-driven the process is. However, I find myself continuing to come back to the following well-known quote usually attributed to Roman philospher Seneca:</p>

<p><em>Luck is when preparation meets opportunity.</em></p>

<p>Getting an opportunity to interview for a position like this is incredibly driven by chance. There are many ways to increase your chances (most of which can be politely summarized as “networking”), but then you have to actually succeed at that opportunity. Plenty of people have lots of skills but never get an opportunity to prove it, and plenty of people have no skills but get lots of opportunity (and often don’t pass).</p>

<p>Everyone wants to know how you get an interview at FAANG, and for that I have absolutely no idea…but I would say be ready/prepared enough that if you do get the chance, you can knock it out of the park.</p>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><summary type="html"><![CDATA[I recently accepted an offer to join Meta as a Research Scientist following graduation from my PhD program. I’ve gotten a lot of questions on what the process looks like and how I prepared, so I figured I’d put together a blog post to keep everything organized in one place.]]></summary></entry><entry><title type="html">Efficient File I/O, Part 4: In-Place External Sorting</title><link href="https://www.ahl27.com/posts/2024/12/inplace-external-io/" rel="alternate" type="text/html" title="Efficient File I/O, Part 4: In-Place External Sorting" /><published>2024-12-13T00:00:00-05:00</published><updated>2024-12-13T00:00:00-05:00</updated><id>https://www.ahl27.com/posts/2024/12/fileio4</id><content type="html" xml:base="https://www.ahl27.com/posts/2024/12/inplace-external-io/"><![CDATA[<p>If you’ve been following all the posts in this series, you’ll know that by know I have a pretty good way to read in edges for ExoLabel due primarily to faster I/O and an optimized external sorting function (if you haven’t, check out the first post <a href="https://www.ahl27.com/posts/2024/10/fseek/">here</a>!). I left off in <a href="https://www.ahl27.com/posts/2024/12/loser-trees-io/">my last post</a> by mentioning that I wanted to change my external sort to work in-place, but I didn’t really explain why.</p>

<p>Ideally, I’d like to minimize the total footprint of my algorithm. My first approach to reading in graph edges (allocating the exact amount of space they require and then recording them as the edgelist file is read) was horrendously slow, but only consumed 12 bytes per edge of the graph. The approach with loser trees and external merge sorts first requires that we record all the edges. This would normally require 20 bytes per edge (two <code class="language-plaintext highlighter-rouge">unsigned long int</code> values and one <code class="language-plaintext highlighter-rouge">float</code>), but I compressed this further by packing the <code class="language-plaintext highlighter-rouge">float</code> and second <code class="language-plaintext highlighter-rouge">unsigned long</code> into a single value. If we assume we have less than $2^k$ indices, then we can pack a <code class="language-plaintext highlighter-rouge">float</code> and <code class="language-plaintext highlighter-rouge">uint64_t</code> into one value with the following approach:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">uint64_t</span> <span class="n">pack_ind_and_weight</span><span class="p">(</span><span class="kt">uint64_t</span> <span class="n">index</span><span class="p">,</span> <span class="kt">float</span> <span class="n">weight</span><span class="p">,</span> <span class="kt">int</span> <span class="n">k</span><span class="p">)</span><span class="o">:</span>
  <span class="kt">int</span> <span class="n">bits_to_shift</span> <span class="o">=</span> <span class="mi">64</span><span class="o">-</span><span class="n">k</span><span class="p">;</span>
  <span class="kt">uint64_t</span> <span class="n">max_value</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="n">bits_to_shift</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span><span class="p">;</span>

  <span class="c1">// minimize loss of precision by using doubles</span>
  <span class="kt">uint64_t</span> <span class="n">quantized_weight</span> <span class="o">=</span> <span class="p">(</span><span class="kt">uint64_t</span><span class="p">)</span> <span class="n">floor</span><span class="p">(((</span><span class="kt">double</span><span class="p">)</span><span class="n">weight</span><span class="p">)</span> <span class="o">*</span> <span class="n">max_value</span><span class="p">);</span>
  <span class="n">index</span> <span class="o">&lt;&lt;=</span> <span class="n">bits_to_shift</span><span class="p">;</span>

  <span class="k">return</span> <span class="p">(</span><span class="n">index</span> <span class="o">|</span> <span class="n">quantized_weight</span><span class="p">);</span>
</code></pre></div></div>

<p>With this approach, it only takes 16 bytes per edge, which is only a little more than the initial slow approach. However, the problem is in the external sorting algorithm. As we’re mergesorting the file, we copy the sorted values into a new file. The values swap between these two files until everything is completely sorted. There isn’t a way to shrink the size of a file from the top while you’re in it, so this means that the only way to free up the space consumed by the file being sorted is to delete it at the end of the pass. As a result, right before the file is deleted, we have each edge stored twice (once in each file)…which makes our actual total disk consumption 32 bytes.</p>

<p>Sometimes I get trapped in a cycle of overoptimizing when I don’t really need to. Before going any further, it’s worth considering what the actual impact of this is. Does it really matter if we have an extra 22 bytes of overhead per edge of the graph to process? Here’s my rationale for why the answer is “probably yes”.</p>

<p>First, this sorting operation has the maximal disk consumption of any part of ExoLabel. If a later step consumed more disk space, I could safely use this approach since I would’ve needed that space anyway. Unfortunately, though, I don’t.</p>

<p>Second, 22 bytes per edge is a lot of data when you’re working with really large graphs. Imagine we have an undirected network with a billion nodes, average node degree of 100, vertex labels with around 10 characters, and weights with three digits of precision (e.g., <code class="language-plaintext highlighter-rouge">0.912</code>). Each line of the edgelist will consume an average of 28 bytes ($2 \times 10$ bytes for the two labels, two tab separators, five bytes for the weight, and one byte for the newline). A billion nodes, average node outdegree of 100, and undirected edges means that we have 50 billion edges. This means our input file size is going to be around $28 \times 50 \times 10^9=1.4\text{TB}$ of space. If the network is undirected, we have to record each edge twice in the CSR representation. The original slow approach would consume $12 \times 2 \times 50 \times 10^9 = 1.2\text{TB}$, whereas the external sort would consume $32 \times 2 \times 50 \times 10^9=3.2\text{TB}$. That’s more than double the original file size, which is not ideal.</p>

<p>So what can we do? The most straightforward solution is to see if we can make the external sort in-place rather than copying between different files. This would reduce the overhead by a factor of two, meaning that we’re looking at $1.6\text{TB}$ of space, or roughly the same size as the initial file. That seems more reasonable to me.</p>

<h2 id="an-in-place-k-way-merge-sort">An In-Place k-Way Merge Sort</h2>

<p>So I’ve identified that I want to do this merge in-place. How do we actually accomplish that? Let’s first review the flow of the merging algorithm. At each stage, we have some number of sorted blocks. We take the first <code class="language-plaintext highlighter-rouge">k</code> blocks, load the first <code class="language-plaintext highlighter-rouge">n</code> values of each block into <code class="language-plaintext highlighter-rouge">k</code> buffers, and then run a loser tree to output the smallest number from them. This smallest number is written to a buffer, which dumps its contents to a new file when it gets full. When one of the buffers empties, we reload it with the next <code class="language-plaintext highlighter-rouge">n</code> values (or the number of values remaining, whichever is smaller) from its corresponding block.</p>

<p>What I’d like to do is to instead dump that output buffer into the same file that we’re currently reading from. The trick is making sure we’re not overwriting any values we might need to read later.</p>

<p>I’m going to set up a really simple example. Suppose our file has 16 values, comprised of four sorted blocks of length four. Let’s call these blocks <code class="language-plaintext highlighter-rouge">A,B,C,D</code>, and their values <code class="language-plaintext highlighter-rouge">a1, a2, ... d3, d4</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>FILE START
============
a1 a2 a3 a4
b1 b2 b3 b4
c1 c2 c3 c4
d1 d2 d3 d4
============
    FILE END
</code></pre></div></div>
<p>The loser tree will load up to two values at a time from each block. Once a value is loaded into the loser tree, I don’t need it in the file anymore, so I’ll mark it as <code class="language-plaintext highlighter-rouge">xx</code>. I’ll also give it an output buffer of size two. After the initial file load, the file looks like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>FILE START
============
xx xx a3 a4
xx xx b3 b4
xx xx c3 c4
xx xx d3 d4
============
    FILE END

Input Buffers:
[a1, a2] [b1, b2] [c1, c2] [d1, d2]

Output Buffer:
[-, -]
</code></pre></div></div>

<p>There are some deceptively simple cases that might arise. For example, if the file is already in sorted order, then the tree pops <code class="language-plaintext highlighter-rouge">[a1, a2]</code>, I write them to the top of the file, refill the now-empty <code class="language-plaintext highlighter-rouge">A</code> bucket, and get to:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>FILE START
============
a1 a2 xx xx
xx xx b3 b4
xx xx c3 c4
xx xx d3 d4
============
    FILE END

Input Buffers:
[a3, a4] [b1, b2] [c1, c2] [d1, d2]

Previous Output Buffer:
[a1, a2]
</code></pre></div></div>

<p>The next buffer would go into the next empty space, we’d and then the next…and that would just continue down the file forever. Unfortunately, this doesn’t work for a variety of reasons. Rather than cover every possible scenario, I’ll just skip to the worst-case one. The worst-case scenario to consider is when all of the first entries come from the final block. This would mean that we essentially need to move the entire last block to the front of the file, and shift everything else down. A final output that would result from such a scenario could look like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>SORTED FILE START
=================
d1 d2 d3 d4
a1 a2 a3 a4
b1 b2 b3 b4
c1 c2 c3 c4
=================
  SORTED FILE END
</code></pre></div></div>

<p>Maybe there’s something to be learned from this case, though. If we knew that block was going to be moved to the top from the beginning, we could have shifted all the other elements down before writing the elements. In fact, this is the beginning of an algorithm that will work. If you want to see if you can come up with a solution on your own, here are the facts that I considered when I was looking at this problem:</p>

<ul>
  <li>The loser tree will always load values into its output buffer from its input buffers.</li>
  <li>The loser tree only dumps its output when either the output buffer is full, or all its input buffers are empty.</li>
  <li>Once a value is loaded into an input buffer, it can safely be overwritten in the tree.</li>
</ul>

<p>This may not seem like much, but it leads to a critical insight on the problem. Again, any value in the input buffer does not need to be maintained in the file, and the output buffer only gets its values from the input buffers. This means that when the output buffer wants to dump its contents to the file, we are guaranteed to have enough <code class="language-plaintext highlighter-rouge">xx</code> values <em>somewhere</em> to be able to place all the values in the output buffer into the <code class="language-plaintext highlighter-rouge">k</code> blocks we’re currently processing.</p>

<p>Let’s go back to the example, but this time suppose that the output buffer has length four. Imagine that it’s already been filled, but we don’t know what the values are. I’ll just label them <code class="language-plaintext highlighter-rouge">y1, y2, y3, y4</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>FILE START
============
xx xx a3 a4
xx xx b3 b4
xx xx c3 c4
xx xx d3 d4
============
    FILE END

Output Buffer:
[y1, y2, y3, y4]
</code></pre></div></div>

<p>We want to write that buffer to the beginning of this block, but doing so would overwrite <code class="language-plaintext highlighter-rouge">a3, a4</code>, which we haven’t processed yet. However, we know for certain that there are enough <code class="language-plaintext highlighter-rouge">xx</code> values <em>somewhere</em> in the file to support this block, so there must be some way to shuffle around the gaps to make space.</p>

<p>I came up with a solution that I think is pretty straightforward and reasonably efficient. There are many papers published on this type of algorithm that include more more optimal solutions, but I think this is optimal enough for the problem. I’ll leave further optimization to future work if it becomes a problem.</p>

<p>Anyway, I know that I want to write to the top of the file, and I know that there’s a block of elements that haven’t yet been processed in that section about to be overwritten. To fix this, I essentially slide the unprocessed blocks to the end of the file. Starting with the last block, I align each block’s end to the next block’s beginning (or the end of the file, for the final block). Note that if the <code class="language-plaintext highlighter-rouge">k</code> blocks being processed don’t end at the absolute end of the file, we can treat the end of block <code class="language-plaintext highlighter-rouge">k</code> as the end of the file. This pushes the blocks downward:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>FILE START
============
xx xx xx xx
xx xx xx xx
a3 a4 b3 b4
c3 c4 d3 d4
============
    FILE END

Output Buffer:
[y1, y2, y3, y4]
</code></pre></div></div>

<p>All the empty spaces are now at the top of the file, and since I know that there are guaranteed to be at least enough spaces to write the contents of the output buffer, I can safely write the output buffer to the file:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>FILE START
============
y1 y2 y3 y4
xx xx xx xx
a3 a4 b3 b4
c3 c4 d3 d4
============
    FILE END

Output Buffer:
[-, -, -, -]
</code></pre></div></div>

<p>You can see that there’s actually room for another full output buffer, so the next time my buffer fills, I won’t have to do any moving at all. This operation of shuffling blocks is pretty expensive computationally because it bounces around the file (see my previous posts for more detail on this). Because of this, I only move blocks when there exists at least one unprocessed element within the region I’m about to write to. Moving all the blocks to the end of the segment moves all gaps to the beginning of the block, so theoretically we won’t need to move as many times. If you’re interested in a optimal algorithms for this problem (in terms of minimizing block shuffle operations), you could check out <a href="https://www.sciencedirect.com/science/article/pii/S0304397502007752">this paper</a> as a starting point. Fair warning, they get pretty dense.</p>

<h2 id="how-does-it-perform">How Does It Perform?</h2>

<p>If you remember my last post, I improved the runtime over the naive method from 640 seconds to under a minute. It’s not exactly clear to me how the choice of <code class="language-plaintext highlighter-rouge">k</code> impacts runtime – you might expect that more bins means lower runtime, since we need fewer passes through the file. However, more bins also means more comparisons and potentially more long-distance jumps throughout the file, which may cause slowdowns due to cache inefficiency. Benchmarking this kind of stuff is also really challenging, since the OS may have lots of other unrelated stuff going on in the background that could limit your performance.</p>

<p>Anyway, my implementation using a non-in-place 64-way merge took around 62 seconds in my last test on a file with 74 million undirected edges. Using an in-place merge, it went up to 84 seconds. A huge chunk of both of those times is reading in the edges in the first place (i.e., not the sorting), but the in-place merge does contribute an additional 22 seconds of runtime over the non-in-place version. I think the tradeoff is worth it, though, given the enormous reduction in disk consumption obtained in response. I also added an argument <code class="language-plaintext highlighter-rouge">use_fast_sort</code> to ExoLabel that lets users employ the faster sort when disk consumption isn’t an issue.</p>

<h2 id="one-last-thing">One Last Thing…</h2>

<p>There’s one more issue I had to solve here – remember when I mentioned that I’m compressing edges by packing a <code class="language-plaintext highlighter-rouge">long</code> and a <code class="language-plaintext highlighter-rouge">double</code> into one <code class="language-plaintext highlighter-rouge">uint64_t</code>? Each edge I write has two <code class="language-plaintext highlighter-rouge">uint64_t</code> values (one of which is packed), but my subsequent functions need this to be split into a single <code class="language-plaintext highlighter-rouge">long</code> and a single <code class="language-plaintext highlighter-rouge">float</code> per edge. If we just decompress the values and write them to a new file, we’ll end up incurring an extra 12 bytes per edge (28 total), which basically undoes all the work I did here.</p>

<p>I mentioned that it isn’t possible to shrink a file from the beginning while you’re in it, but it is possible to truncate it from the end. Of the two <code class="language-plaintext highlighter-rouge">uint64_t</code> values in the <code class="language-plaintext highlighter-rouge">edge</code> structure, the first value isn’t needed after we’re done sorting. Thus, I can start by overwriting the whole file with just the second packed <code class="language-plaintext highlighter-rouge">uint64_t</code> from each edge. This doesn’t shrink the file, though – it only replaces the first half of the file with other values. However, we can call platform-specific instructions (<code class="language-plaintext highlighter-rouge">truncate</code> on POSIX systems and <code class="language-plaintext highlighter-rouge">_chsize_s</code> for Windows) to tell the OS to shrink the file by truncating the it to a specified size. That function to truncate a file looks like this (<code class="language-plaintext highlighter-rouge">fname</code> is the file, <code class="language-plaintext highlighter-rouge">size</code> is the size to truncate to):</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">truncate_file</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span><span class="o">*</span> <span class="n">fname</span><span class="p">,</span> <span class="kt">size_t</span> <span class="n">size</span><span class="p">){</span>
  <span class="kt">int</span> <span class="n">retval</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="cp">#ifdef HAVE_UNISTD_H
</span>  <span class="c1">// unistd.h is imported earlier in a similar ifdef</span>
  <span class="n">retval</span> <span class="o">=</span> <span class="n">truncate</span><span class="p">(</span><span class="n">fname</span><span class="p">,</span> <span class="n">size</span><span class="p">);</span>
<span class="cp">#else
</span>  <span class="cp">#ifdef WIN32
</span>    <span class="kt">int</span> <span class="n">filehandler</span> <span class="o">=</span> <span class="n">_open</span><span class="p">(</span><span class="n">fname</span><span class="p">,</span> <span class="n">_O_BINARY</span> <span class="o">|</span> <span class="n">_O_RDWR</span><span class="p">);</span>
    <span class="n">retval</span> <span class="o">=</span> <span class="n">_chsize_s</span><span class="p">(</span><span class="n">filehandler</span><span class="p">,</span> <span class="n">size</span><span class="p">);</span>
    <span class="n">_close</span><span class="p">(</span><span class="n">filehandler</span><span class="p">);</span>
  <span class="cp">#else
</span>    <span class="k">return</span><span class="p">;</span>
  <span class="cp">#endif
#endif
</span>  <span class="k">if</span><span class="p">(</span><span class="n">retval</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span> <span class="n">error</span><span class="p">(</span><span class="s">"Failed to truncate file!"</span><span class="p">);</span>
  <span class="k">return</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Once that’s done, we have a file that encodes all the edges in 8 bytes per edge. It’s then fairly simple to read each edge, decompress the packed <code class="language-plaintext highlighter-rouge">uint64_t</code>, and then write the index and weight. The index overwrites the value just written, and the weight goes into a new file. In total, the sequence looks like:</p>

<ul>
  <li>Overwrite first half of file with second number (16b / edge)</li>
  <li>Truncate file by 50% (8b / edge)</li>
  <li>Decompress edges (12b / edge)</li>
</ul>

<p>This keeps our maximum disk usage at 16 bytes per edge.</p>

<h2 id="conclusion-and-code">Conclusion and Code</h2>

<p>As with the last post, I’ll include the code I wrote below. There’s definitely more improvements that could be made to my in-place external sort, but I think for now it’s in a good place. The clustering step is now much larger part of the runtime for medium-sized graphs, so I think further optimization would likely be directed there before revisiting this step. You can always check out the most up-to-date version of this on <a href="https://github.com/ahl27/SynExtend/tree/master/src/ExoLabel">my GitHub</a>. Thanks for reading!</p>

<p>Note: Code below only includes elements that were added for in-place merging; see my previous post for the rest of the code if necessary.</p>

<details>
  <summary>In-Place k-Way Merge Code</summary>

  <div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">reorganize_blocks</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">size_t</span> <span class="n">block_end</span><span class="p">,</span> <span class="kt">FILE</span> <span class="o">*</span><span class="n">f</span><span class="p">,</span>
                        <span class="kt">long</span> <span class="kt">int</span> <span class="o">*</span><span class="n">remaining</span><span class="p">,</span> <span class="kt">long</span> <span class="kt">int</span> <span class="o">**</span><span class="n">offsets</span><span class="p">){</span>
  <span class="cm">/*
   * Reorganize blocks by shuffling all unprocessed blocks to the end
   */</span>
  <span class="kt">size_t</span> <span class="n">size</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">e_size</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">output_size</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span><span class="p">;</span>
  <span class="kt">long</span> <span class="kt">int</span> <span class="o">*</span><span class="n">offs</span> <span class="o">=</span> <span class="o">*</span><span class="n">offsets</span><span class="p">;</span>
  <span class="c1">// use as much space as possible, minimize r/w calls</span>
  <span class="kt">void</span> <span class="o">*</span><span class="n">scratch_buf</span> <span class="o">=</span> <span class="n">malloc</span><span class="p">(</span><span class="n">size</span><span class="o">*</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">output_size</span><span class="p">);</span>
  <span class="kt">int</span> <span class="n">nbins</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nbins</span><span class="p">;</span>
  <span class="kt">long</span> <span class="kt">int</span> <span class="n">write_start</span><span class="p">,</span> <span class="n">write_end</span><span class="p">,</span> <span class="n">read_start</span><span class="p">,</span> <span class="n">read_end</span><span class="p">,</span> <span class="n">to_read</span><span class="p">;</span>

  <span class="kt">int</span> <span class="n">last_bin</span> <span class="o">=</span> <span class="n">nbins</span><span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="k">while</span><span class="p">(</span><span class="o">!</span><span class="n">remaining</span><span class="p">[</span><span class="n">last_bin</span><span class="p">])</span> <span class="n">last_bin</span><span class="o">--</span><span class="p">;</span>
  <span class="n">write_end</span> <span class="o">=</span> <span class="n">block_end</span><span class="p">;</span>
  <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="n">last_bin</span><span class="p">;</span> <span class="n">i</span><span class="o">&gt;=</span><span class="mi">0</span><span class="p">;</span> <span class="n">i</span><span class="o">--</span><span class="p">){</span>
    <span class="c1">// last bin is always in the right place</span>
    <span class="c1">// have to move all the rest of the bins down</span>
    <span class="k">if</span><span class="p">(</span><span class="n">remaining</span><span class="p">[</span><span class="n">i</span><span class="p">]){</span>
      <span class="n">read_start</span> <span class="o">=</span> <span class="n">offs</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
      <span class="n">read_end</span> <span class="o">=</span> <span class="n">offs</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">remaining</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
      <span class="k">while</span><span class="p">(</span><span class="n">read_end</span> <span class="o">!=</span> <span class="n">offs</span><span class="p">[</span><span class="n">i</span><span class="p">]){</span>
        <span class="n">R_CheckUserInterrupt</span><span class="p">();</span>
        <span class="n">to_read</span> <span class="o">=</span> <span class="n">output_size</span><span class="p">;</span>
        <span class="k">if</span><span class="p">(</span><span class="n">read_end</span> <span class="o">&lt;</span> <span class="n">offs</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">to_read</span><span class="p">)</span> <span class="n">to_read</span> <span class="o">=</span> <span class="n">read_end</span> <span class="o">-</span> <span class="n">offs</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
        <span class="n">read_start</span> <span class="o">=</span> <span class="n">read_end</span> <span class="o">-</span> <span class="n">to_read</span><span class="p">;</span>
        <span class="n">write_start</span> <span class="o">=</span> <span class="n">write_end</span> <span class="o">-</span> <span class="n">to_read</span><span class="p">;</span>
        <span class="n">fseek</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">read_start</span><span class="o">*</span><span class="n">size</span><span class="p">,</span> <span class="n">SEEK_SET</span><span class="p">);</span>
        <span class="n">fread</span><span class="p">(</span><span class="n">scratch_buf</span><span class="p">,</span> <span class="n">size</span><span class="p">,</span> <span class="n">to_read</span><span class="p">,</span> <span class="n">f</span><span class="p">);</span>
        <span class="n">fseek</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">write_start</span><span class="o">*</span><span class="n">size</span><span class="p">,</span> <span class="n">SEEK_SET</span><span class="p">);</span>
        <span class="n">fwrite</span><span class="p">(</span><span class="n">scratch_buf</span><span class="p">,</span> <span class="n">size</span><span class="p">,</span> <span class="n">to_read</span><span class="p">,</span> <span class="n">f</span><span class="p">);</span>
        <span class="n">read_end</span> <span class="o">=</span> <span class="n">read_start</span><span class="p">;</span>
        <span class="n">write_end</span> <span class="o">=</span> <span class="n">write_start</span><span class="p">;</span>
      <span class="p">}</span>
      <span class="n">offs</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">write_start</span><span class="p">;</span>
    <span class="p">}</span>
  <span class="p">}</span>

  <span class="n">free</span><span class="p">(</span><span class="n">scratch_buf</span><span class="p">);</span>
  <span class="k">return</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">size_t</span> <span class="nf">LT_fdumpOutputInplace</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">size_t</span> <span class="n">block_end</span><span class="p">,</span>
                            <span class="kt">FILE</span> <span class="o">*</span><span class="n">f</span><span class="p">,</span> <span class="kt">long</span> <span class="kt">int</span> <span class="o">*</span><span class="n">remaining</span><span class="p">,</span> <span class="kt">long</span> <span class="kt">int</span> <span class="o">**</span><span class="n">offsets</span><span class="p">){</span>
  <span class="cm">/*
   * Function to dump output in-place
   * Requires a bunch of extra values so we can keep track of stuff
   * Input Variables:
   *  -      tree: LoserTree structure
   *  -         f: file pointer for reading values
   *  - f_writing: file pointer for writing values
   *  -     start: starting line for the set of all blocks in current iteration
   *  - remaining: pointer to int* containing # of elements remaining per block
   *  -   offsets: pointer to int* with start position of each block
   */</span>

  <span class="kt">size_t</span> <span class="n">size</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">e_size</span><span class="p">;</span>
  <span class="kt">size_t</span> <span class="n">start</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nwritten</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">output_size</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">nbins</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nbins</span><span class="p">;</span>
  <span class="kt">long</span> <span class="kt">int</span> <span class="o">*</span><span class="n">offs</span> <span class="o">=</span> <span class="o">*</span><span class="n">offsets</span><span class="p">;</span>

  <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">output_size</span><span class="p">)</span> <span class="k">return</span> <span class="n">start</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">first_bin</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">while</span><span class="p">(</span><span class="n">first_bin</span> <span class="o">&lt;</span> <span class="n">nbins</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="n">remaining</span><span class="p">[</span><span class="n">first_bin</span><span class="p">])</span> <span class="n">first_bin</span><span class="o">++</span><span class="p">;</span>

  <span class="k">if</span><span class="p">(</span><span class="n">first_bin</span> <span class="o">&lt;</span> <span class="n">nbins</span> <span class="o">&amp;&amp;</span> <span class="n">offs</span><span class="p">[</span><span class="n">first_bin</span><span class="p">]</span> <span class="o">&lt;</span> <span class="p">(</span><span class="n">start</span><span class="o">+</span><span class="n">output_size</span><span class="p">))</span>
    <span class="n">reorganize_blocks</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="n">block_end</span><span class="p">,</span> <span class="n">f</span><span class="p">,</span> <span class="n">remaining</span><span class="p">,</span> <span class="n">offsets</span><span class="p">);</span>

  <span class="c1">// reset the writing pointer</span>
  <span class="c1">// note tree-&gt;nwritten gives us the position of the last sorted value written</span>
  <span class="c1">// (which is where we need to write next)</span>
  <span class="n">fseek</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">nwritten</span><span class="p">)</span><span class="o">*</span><span class="n">size</span><span class="p">,</span> <span class="n">SEEK_SET</span><span class="p">);</span>
  <span class="n">LT_fdumpOutput</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="n">f</span><span class="p">);</span>

  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">int</span> <span class="nf">LT_runInplaceFileGame</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">size_t</span> <span class="n">block_end</span><span class="p">,</span>
                          <span class="kt">FILE</span> <span class="o">*</span><span class="n">f</span><span class="p">,</span> <span class="kt">long</span> <span class="kt">int</span> <span class="o">*</span><span class="n">remaining</span><span class="p">,</span> <span class="kt">long</span> <span class="kt">int</span> <span class="o">**</span><span class="n">offsets</span><span class="p">){</span>
  <span class="cm">/*
   * Same as LT_runFileGame(), but does it in-place
   * see LT_fdumpOutputInplace for argument description
   */</span>
  <span class="kt">int</span> <span class="n">retval</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="k">while</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">full_bins</span><span class="p">){</span>
    <span class="n">LT_popOutput</span><span class="p">(</span><span class="n">tree</span><span class="p">);</span>
    <span class="k">if</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span> <span class="o">==</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">output_size</span><span class="p">)</span>
      <span class="n">LT_fdumpOutputInplace</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="n">block_end</span><span class="p">,</span> <span class="n">f</span><span class="p">,</span> <span class="n">remaining</span><span class="p">,</span> <span class="n">offsets</span><span class="p">);</span>
    <span class="k">if</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span><span class="p">){</span>
      <span class="n">retval</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span><span class="p">;</span>
      <span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
      <span class="k">return</span> <span class="n">retval</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">LT_updateTree</span><span class="p">(</span><span class="n">tree</span><span class="p">);</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>  </div>

</details>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><category term="C" /><summary type="html"><![CDATA[If you’ve been following all the posts in this series, you’ll know that by know I have a pretty good way to read in edges for ExoLabel due primarily to faster I/O and an optimized external sorting function (if you haven’t, check out the first post here!). I left off in my last post by mentioning that I wanted to change my external sort to work in-place, but I didn’t really explain why.]]></summary></entry><entry><title type="html">Efficient File I/O, Part 3: Loser Trees and External Sorting</title><link href="https://www.ahl27.com/posts/2024/12/loser-trees-io/" rel="alternate" type="text/html" title="Efficient File I/O, Part 3: Loser Trees and External Sorting" /><published>2024-12-09T00:00:00-05:00</published><updated>2024-12-09T00:00:00-05:00</updated><id>https://www.ahl27.com/posts/2024/12/fileio3</id><content type="html" xml:base="https://www.ahl27.com/posts/2024/12/loser-trees-io/"><![CDATA[<p>In <a href="https://www.ahl27.com/posts/2024/12/fwrite-io/">my last post</a>, I talked about ways to improve the efficiency of <code class="language-plaintext highlighter-rouge">fwrite</code> calls. Essentially, it boils down to prioritizing sequential read/writes. At the end of that post, I mentioned that I need a way to sort a file on disk. These are called <a href="https://en.wikipedia.org/wiki/External_sorting">external sorting algorithms</a>. While they’re not used very often today, they were incredibly important in the past. Back in the days of tape drives, computers rarely had enough RAM to load a dataset into memory for sorting, and so external sorts were used instead.</p>

<p>The good news is that these algorithms are very well studied, so there’s a lot of information already available on them. Wikipedia notes that k-way merges are commonly used, and even mentions that the best way to implement a k-way merge is using a data structure called a Loser Tree (I had never heard of this structure before reading about external sorting algorithms). The bad news is that the information available from places like Wikipedia are pretty sparse, and sometimes wrong. I found a terrific talk by Bryan Boreham entitled <a href="https://www.youtube.com/watch?v=AmLtlXEo4UU">“Blazing fast merge with loser trees”</a>, which did an amazing job of describing the structure (and gave some great performance benchmarks!), but since his code is written in Go, I had to adapt it for C.</p>

<h2 id="why-do-this">Why do this?</h2>

<p>If you’re like me, the first question you may ask is “why do this at all?”. The algorithm I’m working on benefits greatly from sorting the values to work with prior to working with them, so ideally I want a sorting algorithm that runs fast enough to not undo the gains we get later from having sorted values. The largest constraint on this problem is that all the values are stored in a <em>file</em>, and there are too many values to read into RAM. This means that I’ll have to use an external sorting algorithm.</p>

<p>Merge sort is a pretty standard way to sort files, since the process is very compatible with continuously streaming in data from one or more files. However, it says online that a “k-way” merge is often a better strategy for merging files. A k-way merge is a generalized version of merge sort, where instead of merging two blocks at a time, we merge k. If <code class="language-plaintext highlighter-rouge">k=2</code> then we get a standard merge sort. You don’t often hear about this in the context of sorting algorithms because it doesn’t provide a huge benefit–in terms of asymptotic runtime, the sum of the number of comparisons and the number of data read/writes can be shown to be a fixed value (if all algorithms are optimal) regardless of the value of k. When we’re working in RAM, this means that there isn’t usually much value to doing more than standard merge sort, since the cost of a comparison and a data read/write are roughly the same. However, when we’re working with data stored on files, the cost of data read/writes is orders of magnitude higher than the cost of a comparison between values, so we get a big performance boost from increasing the value of k to decrease the number of file read/writes even though it similarly increases the number of comparisons. Large values of k need fewer passes through the file – standard merge sort will take $\log_2 n$ passes through <code class="language-plaintext highlighter-rouge">n</code> elements, whereas a k-way merge will take $\log_k n$ passes. Each pass involves reading and writing all <code class="language-plaintext highlighter-rouge">n</code> elements, so one less pass means <code class="language-plaintext highlighter-rouge">n</code> fewer reads and writes.</p>

<p>Conceptually, the process by which we merge k blocks is pretty simple:</p>

<ol>
  <li>Load in <code class="language-plaintext highlighter-rouge">k</code> blocks of memory</li>
  <li>Find the block, <code class="language-plaintext highlighter-rouge">i</code>, that has the smallest value</li>
  <li>Write the value in block <code class="language-plaintext highlighter-rouge">i</code> to the new file</li>
  <li>Advance block <code class="language-plaintext highlighter-rouge">i</code> by one value</li>
</ol>

<p>Unfortunately, step (2) in this process holds a lot of hidden complexity. If we take a naive approach and simply scan all <code class="language-plaintext highlighter-rouge">k</code> blocks to find the lowest value each time, we’ll end up with an algorithm with runtime $\Theta(nk)$ and lose out on all our performance benefits.</p>

<p>If you’re like me, you’re probably thinking that this sounds like a great problem for a heap. This line of thinking is mostly correct, but unfortunately it’s not the right answer. Wikipedia’s “k-way merge algorithm” page says that “The heap is more commonly used, although a tournament tree is faster in practice”, but it maddeningly doesn’t (or didn’t at least, at the time) provide much further explanation. Both these algorithms have worst-case $\Theta(n \log k)$ runtime, where <code class="language-plaintext highlighter-rouge">n</code> is the number of elements and <code class="language-plaintext highlighter-rouge">k</code> is the number of blocks to use. Heaps are <em>significantly</em> easier to implement, so if you don’t need to eke out every last drop of performance, I’d just go with a heap. That said, I do need to eke out every last drop of performance, so I went ahead with the tournament tree approach.</p>

<h2 id="loser-tournament-trees">Loser (Tournament) Trees</h2>

<p>Conceptually, a “tournament tree” is a tournament bracket, like you might see at the World Cup or March Madness. For anyone unaware of what that is, it’s a structure with the following setup:</p>

<ul>
  <li>participants start at the leaves of a tree structure</li>
  <li>at each internal node starting from the bottom, the two child nodes “play a game” against each other</li>
  <li>the loser of the game stays at that node, and the winner of the game progresses to play another game at the parent node.</li>
</ul>

<p>If we consider a theoretical (incredibly boring) game where the higher rated player always wins, the below is an example of how the tree might unfold:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Initialization (ratings are in parentheses):
          ?? vs ??
       /            \
    A vs B        C vs D
   /      \      /      \
A(1.0) B(2.2) C(3.2) D(1.5)


B beats A, C beats D:
           B vs C
       /            \
      A              D
   /      \      /      \
A(1.0) B(2.2) C(3.2) D(1.5)


C beats B, so C is the overall winner:
            (C)
             |
             B
       /            \
      A              D
   /      \      /      \
A(1.0) B(2.2) C(3.2) D(1.5)
</code></pre></div></div>
<p>When we update a value in the tree, we start by changing the value at the leaf. Let’s say that player C really slacked off, and down to a 0.9 rating. We don’t actually have to replay all the games, since we already know the result of most of them. Instead, we just update the value of C at the leaf, and then only replay the games that are a parent of the current node:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Previous Tree:
            (C)
             |
             B
       /            \
      A              D
   /      \      /      \
A(1.0) B(2.2) C(3.2) D(1.5)


C moves down to 0.9:
             ?
             |
             B
       /            \
      A              D
   /      \      /      \
A(1.0) B(2.2) C(0.9) D(1.5)


Replay parent game:
             ?
             |
             B
       /            \
      A           C vs D: D wins
   /      \      /      \
A(1.0) B(2.2) C(0.9) D(1.5)


Continue:
             ?
             |
          B vs D: B wins
       /            \
      A              C
   /      \      /      \
A(1.0) B(2.2) C(0.9) D(1.5)

Return new overall winner:
             B
             |
             D
       /            \
      A              C
   /      \      /      \
A(1.0) B(2.2) C(0.9) D(1.5)
</code></pre></div></div>

<p>This optimization only works if we update the value of the overall winner. However, that’s a very easy restraint to work around – when we’re sorting, we just want to pull out the largest (or smallest) value, so we’ll only be messing with the values at the top of the tree. I’ll show how that works shortly.</p>

<p>A <em>loser tree</em> is a type of tournament tree in which the <em>loser</em> advances to the next round, rather than the winner. In code, the “game” played is just asking which value is larger. This means that the larger value (the winner) will stay at the internal nodes, and the smaller value (the loser) will continue on up the tree. Eventually, the smallest value from the leaves ends up at the top of the tree.</p>

<h2 id="how-does-a-loser-tree-do-a-k-way-merge">How Does a Loser Tree Do a k-way Merge?</h2>

<p>So we have this weird data structure – how does it help us actually merge blocks? Imagine that I have <code class="language-plaintext highlighter-rouge">k</code> presorted blocks, maybe stored ascending in separate arrays, and I want to merge them together into one big array sorted in ascending order. If I use a loser tree, the smallest value from the four arrays will always be stored on top. For example, let’s look at the following example of four arrays, each of size 2:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         ?
         |
         ?
    /        \
   ?          ?
 /   \      /   \
3     1    2     6
4     5    8     7
A     B    C     D
</code></pre></div></div>

<p>Here <code class="language-plaintext highlighter-rouge">A,B,C,D</code> are the names of the four blocks. I’m going to use their names to store the losers/winners of each game, rather than use the values themselves. If we initialize our loser tree, we’ll find that B loses to A and C loses to D, then C loses to B, so B is the overall loser. Remember, the <em>winners</em> stay, and the <em>losers</em> continue up the tree:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         B
         |
         C
    /        \
   A          D
 /   \      /   \
3     1    2     6
4     5    8     7
A     B    C     D
</code></pre></div></div>

<p>Now we know that the value in B is the smallest value, so we can take its topmost value out of B and put it in our output array:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         B
         |
         C
    /        \
   A          D
 /   \      /   \
3     5    2     6
4          8     7
A     B    C     D

Output: [1]
</code></pre></div></div>

<p>This means that we’ve changed the value of B (it’s now 5), so it may no longer be the smallest value in our array. However, this is okay! We’ve only changed the topmost value of the tree, so we can update the tree with the optimization previously described. We start at B and play games with each parent to update the values stored in parent nodes:</p>

<ul>
  <li>B vs. A results in B winning and A continuing up the tree</li>
  <li>A vs. C results in A winning and C continuing up the tree</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         C
         |
         A
    /        \
   B          D
 /   \      /   \
3     5    2     6
4          8     7
A     B    C     D

Output: [1, ]
</code></pre></div></div>

<p>Then we pop the value out of C as we did before:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         C
         |
         A
    /        \
   B          D
 /   \      /   \
3     5    8     6
4                7
A     B    C     D

Output: [1,2]
</code></pre></div></div>

<p>And since the value of C is now changed, we update its parents and continue until all the arrays are depleted. One question that arises is what happens when one array is depleted but the others are not. In this case, we just treat its value as infinity. For example, after a few more runs the tree will look like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         A
         |
         D
    /        \
   B          C
 /   \      /   \
4     5    8     6
                 7
A     B    C     D

Output: [1,2,3]
</code></pre></div></div>

<p>Popping A results in that array being empty, so we just treat its next value as infinity. Infinity always wins, so the tree updates to:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         B
         |
         D
    /        \
   A          C
 /   \      /   \
-     5    8     6
                 7
A     B    C     D

Output: [1,2,3,4]
</code></pre></div></div>

<p>Once all the arrays are empty, we return our sorted list.</p>

<p>Another reason these are great for files is that we can “refill” these arrays instead of setting them to infinity. Suppose we want to merge four blocks, each with a million elements. We could load all four million elements at once, but this would take a lot of RAM. Instead, we can just allocate four buffers of size <code class="language-plaintext highlighter-rouge">m</code>, and load the first <code class="language-plaintext highlighter-rouge">m</code> elements from each block. When the buffer empties, we can refill it with the next <code class="language-plaintext highlighter-rouge">m</code> elements before we update our tree again. Similarly, we can buffer output values into a fixed size array and then dump it to an output file when it gets full. This strategy allows us to work with arbitrarily large blocks in constant space while also being relatively optimized in terms of read/write since we’re writing sequentially and reading large blocks sequentially.</p>

<p>While the internal structure of a loser tree is a binary tree, we can actually use a trick to represent it as a flat array. If you’re familiar with heaps, this probably won’t be super surprising. Consider the above tree, and suppose we start numbering the nodes in level order starting from the top:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Number each node starting from the top in level order:
         0
         |
         1
    /        \
   2          3
 /   \      /   \
4     5    6     7
</code></pre></div></div>

<p>This gives us a really nice property: the index of the parent of each node is half the indices of its children (integer division will truncate the result of dividing an odd number by two). In other words, for a k-way merge, we can easily store the entire binary tree in an array of size <code class="language-plaintext highlighter-rouge">2k</code>. The leaves will be populated in indices <code class="language-plaintext highlighter-rouge">k, k+1, ..., 2k-1</code>, and the internal nodes will exist in <code class="language-plaintext highlighter-rouge">0, 1, ..., k-1</code>. When we update the value of leaf <code class="language-plaintext highlighter-rouge">i</code>, we just change the value of index <code class="language-plaintext highlighter-rouge">k+i</code> and then find its children by repeatedly halving the index until we get to zero.</p>

<h2 id="heaps-vs-loser-trees">Heaps vs. Loser Trees</h2>

<p>The first time I learned about tournament trees is via Wikipedia telling me that they’re more efficient than heaps. But, why? What makes a tournament tree “faster in practice” than a heap? Both these data structures are essentially identical internally, right?</p>

<p>Suppose I have the values <code class="language-plaintext highlighter-rouge">2,4,3,1,6,5,3,7</code>. A heap might look like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>     1
   /   \
  2     5
 / \   / \
3   4 6   7
</code></pre></div></div>

<p>Whereas a loser tree would look like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>           1
           |
           5
      /         \
     3           7
   /   \       /   \
  2     4     6     -
 / \   / \   / \   / \
1   2 3   4 5   6 7   -
</code></pre></div></div>

<p>What happens if I change the <code class="language-plaintext highlighter-rouge">1</code> to <code class="language-plaintext highlighter-rouge">8</code>?</p>

<p>In the heap approach, we have the following steps:</p>
<ul>
  <li>replace 1 with 8</li>
  <li>compare 8 to both children (2, 5)</li>
  <li>swap 8 with child 5, since 8 &gt; 5</li>
  <li>compare 8 with new children (6,7)</li>
  <li>swap 8 with child 7, since 8 &gt; 7</li>
</ul>

<p>In a loser tree, we would do the following:</p>
<ul>
  <li>replace 1 with 8</li>
  <li>compare 8 against parent (2)</li>
  <li>8 &gt; 2, so store winner (8) at node and continue with loser (2)</li>
  <li>compare 2 against parent (3)</li>
  <li>2 &gt; 3, so store winner (3) at node and continue with loser (2)</li>
  <li>compare 2 against parent (5)</li>
  <li>2 &gt; 5, so store winner (5) at node and continue with loser (2)</li>
  <li>this is the top node, so return 2 as overall loser</li>
</ul>

<p>This seems like more steps, but it actually isn’t. When we move down the tree in the heap approach, we have to make two comparisons at each node. Notice how we do two pairs of comparisons (8 vs 2,3; 8 vs 6,7) to update the heap in the above example. In contrast, the loser tree approach moves up the tree, so we only compare with the parent of the current node in each case. Thus, the tournament tree uses $\log k$ comparisons to update a value in the tree, whereas a heap uses $2\log k$. If we’re processing a lot of data, that difference will add up over time. The tradeoff is that the tournament tree takes twice as much space as the heap (<code class="language-plaintext highlighter-rouge">2k</code> values instead of <code class="language-plaintext highlighter-rouge">k</code>), but given that the value of k is nearly always going to be orders of magnitude smaller than the amount of data to process, this isn’t a big deal.</p>

<h2 id="performance-and-implementation">Performance and Implementation</h2>

<p>This post focuses on the conceptual implementation, but I’ll also include the code below. One of the goals of this process was to speed up how fast we could read in edges from a <code class="language-plaintext highlighter-rouge">tsv</code> file. Here’s how this looks in practice on a dataset with 74 million lines each encoding a bidirectional edge (percentage improvements are versus the naive approach):</p>

<ul>
  <li>Naive approach (random writes): 640 seconds</li>
  <li>Merge sort: 189 seconds (70.5% faster)</li>
  <li>Loser tree 8-way merge: <strong>42 seconds</strong> (93.4% faster)</li>
</ul>

<p>I agree with Bryan Boreham – that’s blazingly fast.</p>

<p>The main remaining issue with this implementation is it doubles our disk space consumption, since I’m sorting by reading from one file and outputting to another. The next task will be implementing this strategy with an in-place sort, which is much more complicated than it might initially seem…but that’s a task for another blog post (which you can now check out <a href="https://www.ahl27.com/posts/2024/12/inplace-external-io/">here</a>!).</p>

<p>If you’re interested in the code, it’s included below. The data structure I wrote is data-agnostic, so it should work with any input datatype.</p>

<details>
  <summary>Header File: LoserTree.h</summary>

  <div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#ifndef LOSERTREE_H
#define LOSERTREE_H
</span>
<span class="cm">/*
 * This is intended to be a type-unaware LoserTree (Tournament Tree)
 * implementation that supports dynamic refilling of bins for external sorting.
 *
 * The expected usage is the following:
 *  - Initialize tree with LT_alloc()
 *  - for each block to merge:
 *      | read some number of elements into a buffer b
 *      | call LT_fillBin() to assign the bin to b
 *  - initialize tree values with LT_initGame()
 *  - while elements remain in blocks:
 *      | call LT_popOutput(tree)
 *      | if output buffer is full, call LT_dumpOutput
 *      | if tree-&gt;empty_bin != -1, refill the empty bin
 *          (e.g., read new elements into buffer, then LT_fillBin() again)
 *      | call LT_updateTree(tree)
 *
 *
 * For processing with output streamed to a file, use LT_runFileGame(). This
 * will keep running games until a bin is emptied, at which point the index
 * of the bin is returned. The calling function should then call LT_refillBin().
 * If the bin does not need to be refilled, the caller still needs to call
 * LT_refillBin(tree, i, 0, NULL). Pseudocode would look like:
 *  - Initialize tree with LT_alloc()
 *  - for each block to merge:
 *      | read some number of elements into a buffer b
 *      | call LT_fillBin() to assign the bin to b
 *  - initialize tree values with LT_initGame()
 *  - while blocks remain in files:
 *      | call LT_runFileGame(), returns index of empty bin
 *      | refill empty bin with LT_fillBin()
 *      | (if no elements remain, still call with nelem=0 to clear set flags)
 *  - call LT_fdumpOutput() to dump any remaining values to file
 *
 * If you don't care about dynamic bin refilling this could be greatly
 * streamlined, but because I'm assuming block size &gt;&gt; bin size, this
 * added complexity is necessary.
 *
 *
 * NOTE: the responsibility of keeping track of the buffers is placed on the
 *  calling function, NOT the LoserTree struct. LoserTree-&gt;bins is simply an
 *  array of pointers that will iterate along allocated void* memory. The memory
 *  pointed to by each LoserTree-&gt;bins[i] will NOT be alloc'd or free'd, only
 *  the pointers themselves.
 */</span>

<span class="k">typedef</span> <span class="k">struct</span> <span class="n">LoserTree</span> <span class="p">{</span>
  <span class="kt">int</span> <span class="n">nbins</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">full_bins</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">empty_bin</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">output_size</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">cur_output_i</span><span class="p">;</span>
  <span class="kt">size_t</span> <span class="n">e_size</span><span class="p">;</span> <span class="c1">// element size, in bytes</span>
  <span class="kt">int</span> <span class="o">*</span><span class="n">binsize</span><span class="p">;</span>
  <span class="kt">void</span> <span class="o">**</span><span class="n">bins</span><span class="p">;</span>
  <span class="kt">void</span> <span class="o">*</span><span class="n">output</span><span class="p">;</span>
  <span class="kt">int</span> <span class="o">*</span><span class="n">values</span><span class="p">;</span>
  <span class="kt">long</span> <span class="n">nwritten</span><span class="p">;</span>
  <span class="kt">int</span> <span class="p">(</span><span class="o">*</span><span class="n">compare</span><span class="p">)(</span><span class="k">const</span> <span class="kt">void</span> <span class="o">*</span><span class="n">a</span><span class="p">,</span> <span class="k">const</span> <span class="kt">void</span> <span class="o">*</span><span class="n">b</span><span class="p">);</span>
<span class="p">}</span> <span class="n">LoserTree</span><span class="p">;</span>

<span class="n">LoserTree</span><span class="o">*</span> <span class="nf">LT_alloc</span><span class="p">(</span><span class="kt">int</span> <span class="n">nbins</span><span class="p">,</span> <span class="kt">int</span> <span class="n">output_size</span><span class="p">,</span> <span class="kt">size_t</span> <span class="n">element_size</span><span class="p">,</span>
                    <span class="kt">int</span> <span class="p">(</span><span class="o">*</span><span class="n">compare</span><span class="p">)(</span><span class="k">const</span> <span class="kt">void</span> <span class="o">*</span><span class="n">a</span><span class="p">,</span> <span class="k">const</span> <span class="kt">void</span> <span class="o">*</span><span class="n">b</span><span class="p">));</span>
<span class="kt">void</span> <span class="nf">LT_fillBin</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">int</span> <span class="n">bin</span><span class="p">,</span> <span class="kt">int</span> <span class="n">nelem</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">input</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">LT_initGame</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">LT_popOutput</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">LT_updateTree</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">LT_refillBin</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">int</span> <span class="n">bin</span><span class="p">,</span> <span class="kt">int</span> <span class="n">nelem</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">input</span><span class="p">);</span>
<span class="kt">size_t</span> <span class="nf">LT_dumpOutput</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">output_buffer</span><span class="p">);</span>
<span class="kt">size_t</span> <span class="nf">LT_fdumpOutput</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">FILE</span> <span class="o">*</span><span class="n">f</span><span class="p">);</span>
<span class="kt">int</span> <span class="nf">LT_runFileGame</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">FILE</span> <span class="o">*</span><span class="n">f</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">LT_free</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">);</span>

<span class="cp">#endif
</span></code></pre></div>  </div>
</details>

<details>
  <summary>Main File: LoserTree.c</summary>

  <div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">"LoserTree.h"</span><span class="cp">
</span>
<span class="cm">/*
 * See comments on expected usage in LoserTree.h
 *
 * Other small notes:
 *  - error() is included from Rdefines.h since it's used with R. perror() also works.
 *  - LT_dumpOutput() dumps to a buffer, not really used since this is used with files.
 */</span>

<span class="n">LoserTree</span><span class="o">*</span> <span class="nf">LT_alloc</span><span class="p">(</span><span class="kt">int</span> <span class="n">nbins</span><span class="p">,</span> <span class="kt">int</span> <span class="n">output_size</span><span class="p">,</span> <span class="kt">size_t</span> <span class="n">element_size</span><span class="p">,</span>
                    <span class="kt">int</span> <span class="p">(</span><span class="o">*</span><span class="n">compare</span><span class="p">)(</span><span class="k">const</span> <span class="kt">void</span> <span class="o">*</span><span class="n">a</span><span class="p">,</span> <span class="k">const</span> <span class="kt">void</span> <span class="o">*</span><span class="n">b</span><span class="p">)){</span>
  <span class="c1">// going to fill bins later, for now just leave them</span>

  <span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span> <span class="o">=</span> <span class="n">malloc</span><span class="p">(</span><span class="k">sizeof</span><span class="p">(</span><span class="n">LoserTree</span><span class="p">));</span>

  <span class="c1">// we need an even power of two for the number of bins</span>
  <span class="kt">int</span> <span class="n">actual_bins</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
  <span class="k">while</span><span class="p">(</span><span class="n">actual_bins</span> <span class="o">&lt;</span> <span class="n">nbins</span><span class="p">)</span> <span class="n">actual_bins</span> <span class="o">&lt;&lt;=</span> <span class="mi">1</span><span class="p">;</span>

  <span class="c1">// allocating the bins</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nbins</span> <span class="o">=</span> <span class="n">actual_bins</span><span class="p">;</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">full_bins</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// values will always hold indices, so we know it'll be ints</span>
  <span class="kt">int</span> <span class="o">*</span><span class="n">values</span> <span class="o">=</span> <span class="n">malloc</span><span class="p">(</span><span class="k">sizeof</span><span class="p">(</span><span class="kt">int</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="n">actual_bins</span><span class="p">)</span> <span class="o">*</span> <span class="mi">2</span><span class="p">);</span>
  <span class="kt">int</span> <span class="o">*</span><span class="n">binsize</span> <span class="o">=</span> <span class="n">malloc</span><span class="p">(</span><span class="k">sizeof</span><span class="p">(</span><span class="kt">int</span><span class="p">)</span> <span class="o">*</span> <span class="n">actual_bins</span><span class="p">);</span>
  <span class="kt">void</span> <span class="o">**</span><span class="n">bins</span> <span class="o">=</span> <span class="n">malloc</span><span class="p">(</span><span class="k">sizeof</span><span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span> <span class="o">*</span> <span class="n">actual_bins</span><span class="p">);</span>

  <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span> <span class="n">i</span><span class="o">&lt;</span><span class="n">actual_bins</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">){</span>
    <span class="n">binsize</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">bins</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">values</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="n">values</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="n">actual_bins</span><span class="p">]</span> <span class="o">=</span> <span class="n">i</span><span class="p">;</span> <span class="c1">// fill second half of array with indices</span>
  <span class="p">}</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span> <span class="o">=</span> <span class="n">binsize</span><span class="p">;</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span> <span class="o">=</span> <span class="n">bins</span><span class="p">;</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">values</span> <span class="o">=</span> <span class="n">values</span><span class="p">;</span>

  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">output_size</span> <span class="o">=</span> <span class="n">output_size</span><span class="p">;</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">output</span> <span class="o">=</span> <span class="n">malloc</span><span class="p">(</span><span class="n">output_size</span><span class="o">*</span><span class="n">element_size</span><span class="p">);</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">e_size</span> <span class="o">=</span> <span class="n">element_size</span><span class="p">;</span>

  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">compare</span> <span class="o">=</span> <span class="n">compare</span><span class="p">;</span>

  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nwritten</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">return</span> <span class="n">tree</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="nf">LT_playgame</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">int</span> <span class="o">*</span><span class="n">a</span><span class="p">,</span> <span class="kt">int</span> <span class="o">*</span><span class="n">b</span><span class="p">){</span>
  <span class="c1">// helper function</span>
  <span class="c1">// assigns the index of smaller value (loser) to a, and the other to b</span>
  <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span><span class="p">[</span><span class="o">*</span><span class="n">b</span><span class="p">])</span> <span class="k">return</span><span class="p">;</span>
  <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span><span class="p">[</span><span class="o">*</span><span class="n">a</span><span class="p">]</span> <span class="o">||</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">compare</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">[</span><span class="o">*</span><span class="n">a</span><span class="p">],</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">[</span><span class="o">*</span><span class="n">b</span><span class="p">])</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">){</span>
    <span class="c1">// need to swap the values</span>
    <span class="kt">int</span> <span class="n">tmp</span> <span class="o">=</span> <span class="o">*</span><span class="n">a</span><span class="p">;</span>
    <span class="o">*</span><span class="n">a</span> <span class="o">=</span> <span class="o">*</span><span class="n">b</span><span class="p">;</span>
    <span class="o">*</span><span class="n">b</span> <span class="o">=</span> <span class="n">tmp</span><span class="p">;</span>
  <span class="p">}</span>
  <span class="k">return</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span> <span class="nf">LT_playRecursiveGameAtNodeI</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">int</span> <span class="n">i</span><span class="p">){</span>
  <span class="k">if</span><span class="p">(</span><span class="n">i</span> <span class="o">&gt;=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nbins</span><span class="p">)</span> <span class="k">return</span> <span class="p">(</span><span class="n">i</span> <span class="o">-</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nbins</span><span class="p">);</span>

  <span class="kt">int</span> <span class="n">left</span> <span class="o">=</span> <span class="n">LT_playRecursiveGameAtNodeI</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="mi">2</span><span class="o">*</span><span class="n">i</span><span class="p">);</span> <span class="c1">// left</span>
  <span class="kt">int</span> <span class="n">right</span> <span class="o">=</span> <span class="n">LT_playRecursiveGameAtNodeI</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="mi">2</span><span class="o">*</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">);</span> <span class="c1">// right</span>

  <span class="kt">int</span> <span class="n">smaller</span><span class="o">=</span><span class="n">left</span><span class="p">,</span> <span class="n">larger</span><span class="o">=</span><span class="n">right</span><span class="p">;</span>
  <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span><span class="p">[</span><span class="n">right</span><span class="p">]){</span>
    <span class="c1">// if right doesn't exist, it counts as infinity (larger)</span>
    <span class="n">larger</span> <span class="o">=</span> <span class="n">right</span><span class="p">;</span>
    <span class="n">smaller</span> <span class="o">=</span> <span class="n">left</span><span class="p">;</span>
  <span class="p">}</span> <span class="k">else</span> <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span><span class="p">[</span><span class="n">left</span><span class="p">]){</span>
    <span class="c1">// if left doesn't exist, it counts as infinity (larger)</span>
    <span class="n">larger</span> <span class="o">=</span> <span class="n">left</span><span class="p">;</span>
    <span class="n">smaller</span> <span class="o">=</span> <span class="n">right</span><span class="p">;</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// otherwise, larger is left if cmp(a,b) &gt; 0</span>
    <span class="n">larger</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">compare</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">[</span><span class="n">left</span><span class="p">],</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">[</span><span class="n">right</span><span class="p">])</span> <span class="o">&lt;</span> <span class="mi">0</span> <span class="o">?</span> <span class="n">right</span> <span class="o">:</span> <span class="n">left</span><span class="p">;</span>
    <span class="n">smaller</span> <span class="o">=</span> <span class="n">larger</span> <span class="o">==</span> <span class="n">left</span> <span class="o">?</span> <span class="n">right</span> <span class="o">:</span> <span class="n">left</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="c1">// now "left" is always the index of the smaller element</span>
  <span class="c1">// and "right" is always the index of the larger element</span>

  <span class="c1">// in loser trees, the smaller element goes on, larger stays</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">values</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">larger</span><span class="p">;</span>
  <span class="k">return</span> <span class="n">smaller</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">LT_fillBin</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">int</span> <span class="n">bin</span><span class="p">,</span> <span class="kt">int</span> <span class="n">nelem</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">input</span><span class="p">){</span>
  <span class="c1">// fills a bin of the LT with some amount of data</span>
  <span class="c1">// input data should be preallocated, no memory copying will be done</span>
  <span class="k">if</span><span class="p">(</span><span class="n">bin</span> <span class="o">&gt;</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nbins</span><span class="p">)</span>
    <span class="n">error</span><span class="p">(</span><span class="s">"Attempted to fill out-of-bounds bin in LoserTree!"</span><span class="p">);</span>
  <span class="k">if</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span><span class="p">[</span><span class="n">bin</span><span class="p">]</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">&amp;&amp;</span> <span class="n">nelem</span><span class="p">)</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">full_bins</span><span class="o">++</span><span class="p">;</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span><span class="p">[</span><span class="n">bin</span><span class="p">]</span> <span class="o">=</span> <span class="n">nelem</span><span class="p">;</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">[</span><span class="n">bin</span><span class="p">]</span> <span class="o">=</span> <span class="n">nelem</span> <span class="o">?</span> <span class="n">input</span> <span class="o">:</span> <span class="nb">NULL</span><span class="p">;</span>
  <span class="k">if</span><span class="p">(</span><span class="n">nelem</span> <span class="o">&amp;&amp;</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span> <span class="o">==</span> <span class="n">bin</span><span class="p">)</span>
    <span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="k">return</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">LT_refillBin</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">int</span> <span class="n">bin</span><span class="p">,</span> <span class="kt">int</span> <span class="n">nelem</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">input</span><span class="p">){</span>
  <span class="c1">// should be called when the last popOutput() emptied a bin</span>
  <span class="c1">// then the top element will still be the (new) empty bin</span>
  <span class="k">if</span><span class="p">(</span><span class="n">nelem</span><span class="p">)</span> <span class="n">LT_fillBin</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="n">bin</span><span class="p">,</span> <span class="n">nelem</span><span class="p">,</span> <span class="n">input</span><span class="p">);</span>
  <span class="n">LT_updateTree</span><span class="p">(</span><span class="n">tree</span><span class="p">);</span>
  <span class="k">return</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">LT_initGame</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">){</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">values</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">LT_playRecursiveGameAtNodeI</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="mi">1</span><span class="p">);</span>
  <span class="k">return</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">LT_popOutput</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">){</span>
  <span class="k">if</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">output_size</span> <span class="o">&lt;=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span><span class="p">)</span>
    <span class="n">error</span><span class="p">(</span><span class="s">"Tried to pop output from LoserTree but buffer is full!"</span><span class="p">);</span>
  <span class="kt">size_t</span> <span class="n">size</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">e_size</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">cur_min</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">values</span><span class="p">[</span><span class="mi">0</span><span class="p">];</span>
  <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span><span class="p">[</span><span class="n">cur_min</span><span class="p">])</span>
    <span class="n">error</span><span class="p">(</span><span class="s">"Tried to pop LoserTree output from an empty bin!"</span><span class="p">);</span>

  <span class="c1">// void_deref(v, i, size) is equivalent to v[i] for a void*</span>
  <span class="kt">void</span> <span class="o">*</span><span class="n">to_write</span> <span class="o">=</span> <span class="n">void_deref</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">output</span><span class="p">,</span> <span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span><span class="p">)</span><span class="o">++</span><span class="p">,</span> <span class="n">size</span><span class="p">);</span>

  <span class="c1">// copy the top value into the output array</span>
  <span class="n">memcpy</span><span class="p">(</span><span class="n">to_write</span><span class="p">,</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">[</span><span class="n">cur_min</span><span class="p">],</span> <span class="n">size</span><span class="p">);</span>


  <span class="k">if</span><span class="p">(</span><span class="o">--</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span><span class="p">[</span><span class="n">cur_min</span><span class="p">])){</span>
    <span class="c1">// if there's still elements in the bin, advance the pointer by one</span>
    <span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">[</span><span class="n">cur_min</span><span class="p">]</span> <span class="o">=</span> <span class="n">void_deref</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">[</span><span class="n">cur_min</span><span class="p">],</span> <span class="mi">1</span><span class="p">,</span> <span class="n">size</span><span class="p">);</span>
    <span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// otherwise the bin is empty, mark the signal value so we can populate it</span>
    <span class="c1">// in the calling function</span>
    <span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span> <span class="o">=</span> <span class="n">cur_min</span><span class="p">;</span>
    <span class="n">tree</span><span class="o">-&gt;</span><span class="n">full_bins</span><span class="o">--</span><span class="p">;</span>
    <span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">[</span><span class="n">cur_min</span><span class="p">]</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="c1">// note that I'm not going to update the tree here</span>
  <span class="c1">// we'll do that in LT_updateTree</span>
  <span class="k">return</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">LT_updateTree</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">){</span>
  <span class="c1">// this function will update the tree with the next value in the bin</span>
  <span class="c1">// assume we've already called LT_popOutput</span>
  <span class="kt">int</span> <span class="n">last_popped</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">values</span><span class="p">[</span><span class="mi">0</span><span class="p">];</span>
  <span class="kt">int</span> <span class="n">cur_node</span> <span class="o">=</span> <span class="n">last_popped</span> <span class="o">+</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nbins</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">v1</span> <span class="o">=</span> <span class="n">last_popped</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">v2</span><span class="p">;</span>

  <span class="k">while</span><span class="p">(</span><span class="n">cur_node</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">v2</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">values</span><span class="p">[</span><span class="n">cur_node</span><span class="p">];</span>
    <span class="n">LT_playgame</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">v1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">v2</span><span class="p">);</span>
    <span class="n">tree</span><span class="o">-&gt;</span><span class="n">values</span><span class="p">[</span><span class="n">cur_node</span><span class="p">]</span> <span class="o">=</span> <span class="n">v2</span><span class="p">;</span>
    <span class="n">cur_node</span> <span class="o">/=</span> <span class="mi">2</span><span class="p">;</span> <span class="c1">// this moves to parent node</span>
  <span class="p">};</span>

  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">values</span><span class="p">[</span><span class="n">cur_node</span><span class="p">]</span> <span class="o">=</span> <span class="n">v1</span><span class="p">;</span>

  <span class="k">return</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">int</span> <span class="nf">LT_runFileGame</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">FILE</span> <span class="o">*</span><span class="n">f</span><span class="p">){</span>
  <span class="cm">/*
   * this function will run games until a bin is emptied
   * when this happens, control returns to the caller to
   * allow the bin to be refilled
   */</span>
  <span class="kt">int</span> <span class="n">retval</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="k">while</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">full_bins</span><span class="p">){</span>
    <span class="n">LT_popOutput</span><span class="p">(</span><span class="n">tree</span><span class="p">);</span>
    <span class="k">if</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span> <span class="o">==</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">output_size</span><span class="p">)</span>
      <span class="n">LT_fdumpOutput</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="n">f</span><span class="p">);</span>
    <span class="k">if</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span><span class="p">){</span>
      <span class="n">retval</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span><span class="p">;</span>
      <span class="n">tree</span><span class="o">-&gt;</span><span class="n">empty_bin</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
      <span class="k">return</span> <span class="n">retval</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">LT_updateTree</span><span class="p">(</span><span class="n">tree</span><span class="p">);</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">size_t</span> <span class="nf">LT_dumpOutput</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">output_buffer</span><span class="p">){</span>
  <span class="kt">size_t</span> <span class="n">nbytes</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">e_size</span> <span class="o">*</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span><span class="p">;</span>
  <span class="n">memcpy</span><span class="p">(</span><span class="n">output_buffer</span><span class="p">,</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">output</span><span class="p">,</span> <span class="n">nbytes</span><span class="p">);</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">return</span> <span class="n">nbytes</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">size_t</span> <span class="nf">LT_fdumpOutput</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">,</span> <span class="kt">FILE</span> <span class="o">*</span><span class="n">f</span><span class="p">){</span>
  <span class="c1">// assume f is a valid file</span>
  <span class="c1">//printf("\n\tWriting %d values\n", tree-&gt;cur_output_i);</span>
  <span class="kt">size_t</span> <span class="n">nbytes</span> <span class="o">=</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">e_size</span> <span class="o">*</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">nbytes</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="kt">size_t</span> <span class="n">nwrote</span> <span class="o">=</span> <span class="n">fwrite</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">output</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">nbytes</span><span class="p">,</span> <span class="n">f</span><span class="p">);</span>
  <span class="k">if</span><span class="p">(</span><span class="n">nwrote</span> <span class="o">!=</span> <span class="n">nbytes</span><span class="p">)</span>
    <span class="n">error</span><span class="p">(</span><span class="s">"Failed to write to file! (tried to write %zu bytes, wrote %zu bytes)"</span><span class="p">,</span>
      <span class="n">nbytes</span><span class="p">,</span> <span class="n">nwrote</span><span class="p">);</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">cur_output_i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="n">tree</span><span class="o">-&gt;</span><span class="n">nwritten</span> <span class="o">+=</span> <span class="n">nwrote</span> <span class="o">/</span> <span class="n">tree</span><span class="o">-&gt;</span><span class="n">e_size</span><span class="p">;</span>
  <span class="k">return</span> <span class="n">nwrote</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">LT_free</span><span class="p">(</span><span class="n">LoserTree</span> <span class="o">*</span><span class="n">tree</span><span class="p">){</span>
  <span class="n">free</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">bins</span><span class="p">);</span>
  <span class="n">free</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">binsize</span><span class="p">);</span>
  <span class="n">free</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">output</span><span class="p">);</span>
  <span class="n">free</span><span class="p">(</span><span class="n">tree</span><span class="o">-&gt;</span><span class="n">values</span><span class="p">);</span>
  <span class="n">free</span><span class="p">(</span><span class="n">tree</span><span class="p">);</span>
  <span class="k">return</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>  </div>
</details>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><category term="C" /><summary type="html"><![CDATA[In my last post, I talked about ways to improve the efficiency of fwrite calls. Essentially, it boils down to prioritizing sequential read/writes. At the end of that post, I mentioned that I need a way to sort a file on disk. These are called external sorting algorithms. While they’re not used very often today, they were incredibly important in the past. Back in the days of tape drives, computers rarely had enough RAM to load a dataset into memory for sorting, and so external sorts were used instead.]]></summary></entry><entry><title type="html">Efficient File I/O, Part 2: Why is `fwrite` so slow?</title><link href="https://www.ahl27.com/posts/2024/12/fwrite-io/" rel="alternate" type="text/html" title="Efficient File I/O, Part 2: Why is `fwrite` so slow?" /><published>2024-12-07T00:00:00-05:00</published><updated>2024-12-07T00:00:00-05:00</updated><id>https://www.ahl27.com/posts/2024/12/fileio2</id><content type="html" xml:base="https://www.ahl27.com/posts/2024/12/fwrite-io/"><![CDATA[<p><a href="https://www.ahl27.com/posts/2024/10/fseek/">My last post</a> talked about some of the things I discovered when looking into how to optimize my current research project, <a href="https://www.ahl27.com/posts/2024/03/oomcluster/">ExoLabel</a>. Since then, I’ve made some big progress improvements in terms of speed, and I thought it would be worth it to break them down. Building efficient external memory algorithms is a really cool process; every potential inefficiency mattters a lot more than with RAM-based algorithms, so you start to understand how the computer works at a deeper level.</p>

<p>The previous version of ExoLabel successfully clustered a network with around 10 million nodes and 20 billion edges in roughly 24 hours. ExoLabel takes as input a tsv file containing edges specified as <code class="language-plaintext highlighter-rouge">A B W</code>, where <code class="language-plaintext highlighter-rouge">A</code> and <code class="language-plaintext highlighter-rouge">B</code> are node names, and <code class="language-plaintext highlighter-rouge">W</code> is the weight of the edge that connects them. The core algorithm has three main steps:</p>

<ol>
  <li>Read over the edgelist file once to reindex node names. Characters are hard to work with, so we convert them to 0-indexed values and also set up some files for later.</li>
  <li>Read over the edgelist file again to add the edges to a CSR-compressed format. This step is covered in my <a href="https://www.ahl27.com/posts/2024/03/oomcluster/">original post</a> on ExoLabel.</li>
  <li>Cluster the network.</li>
  <li>Write the results to a file.</li>
</ol>

<p>On that network of 10M/20B nodes/edges, the timing breakdown looked like this:</p>

<ul>
  <li>Step 1 took 6 hours</li>
  <li>Step 2 took 18 hours</li>
  <li>Step 3 took…30 minutes!</li>
</ul>

<p>Not exactly what I was expecting to see, if I’m being honest. My obvious next question was: “why is step 2 taking so long??”. Let’s find out.</p>

<h2 id="where-is-the-slowdown">Where is the slowdown?</h2>

<p>I’ve broken down the inner processes of this step before, but I’ll briefly review it here. The purpose of this step is to transform an edgelist file into something that’s easier to work with. The format we transform it into is called compressed sparse-row (CSR) format. This looks like the following:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Edgelist (no weights):
0 1
1 2
1 3
2 3

CSR:
0 1 3 4
1 2 3 3
</code></pre></div></div>

<p>The first <code class="language-plaintext highlighter-rouge">n+1</code> values store offsets for each node, and the following numbers store the edges. For node <code class="language-plaintext highlighter-rouge">i</code>, we first look at value <code class="language-plaintext highlighter-rouge">i</code> and <code class="language-plaintext highlighter-rouge">i+1</code> from the CSR file. If we were looking at node 1, we’d find the values <code class="language-plaintext highlighter-rouge">1</code> and <code class="language-plaintext highlighter-rouge">3</code>. This means that the edges from node 1 are edges 1-2 in the file (0-indexed, and not including the final index). Skipping past the offsets, we see that the two edges from node 1 are <code class="language-plaintext highlighter-rouge">2,3</code>. This is better for later processing because the neighbors of each node are stored in a contiguous block that we can easily access.</p>

<p>The slowest part of this algorithm is building this file. We set up the scaffold of the CSR file in Step 1 by recording the node degree for each node (which gives us the offsets), and then in Step 2 we populate the edges themselves (the values after the offsets). The pseudocode basically looks like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>f = edgelist_file
csr = csr_file
n = num_nodes

for edge in f:
  edge_start = edge[0]
  edge_end = edge[1]

  // get the offset
  fseek(f, edge_start, SEEK_SET)
  fread(offset, ..., f)

  // write the edge
  fseek(f, num_nodes + offset + 1, SEEK_SET)
  fwrite(edge_end, ..., f)
</code></pre></div></div>

<p>There’s some additional logic that goes into determining where in the block of values allocated for each node to write to, but it doesn’t really matter for this use-case. This code is pretty simple, and I wasn’t really sure how to improve it further.</p>

<p>After talking with my advisor, we decided the best route is to try just benchmarking how long it takes to copy the entire file without doing any of the extra stuff. In other words, if we just had to write the same amount raw amount of data but without doing any other processing, how long does it take? If my implementation is close in speed to this version, we’d know that the implementation is pretty close to optimal (and that the slowdown is really just due to inherent limitations with data I/O).</p>

<p>I used a file with 74 million edges so I wouldn’t have to wait an entire day for each run. My code took 630 seconds to build the CSR list. Just writing the file without any other processing took…<strong>25 seconds</strong>. The bad news is that that’s a huge difference, so my code probably isn’t optimal. The good news is that there’s a lot of room to improve!</p>

<p>So, what’s causing this, and why didn’t this show up in my initial timing benchmarks? In short, I was too focused on speeding up <code class="language-plaintext highlighter-rouge">fwrite</code> specifically that I forgot to check how <code class="language-plaintext highlighter-rouge">fwrite</code> interacts with <code class="language-plaintext highlighter-rouge">fread</code> and <code class="language-plaintext highlighter-rouge">fseek</code>. The conceptual reason for the slowdown is that hard drives <strong>really</strong> do not enjoy random access, even on SSDs. Yes, an SSD will have much faster random access than an HDD, but all these devices will prefetch data past the read point to improve future lookups. If you’re reading/writing in sequential order, the hardware can operate at its maximum efficiency (since that’s its most common use-case, and thus what it’s designed to do). If you’re reading/writing in random order, that extra data fetching won’t give you any benefit, essentially putting a huge performance penalty on all your data accesses.</p>

<p>This means that my observed slowdown isn’t because of a particular <code class="language-plaintext highlighter-rouge">fwrite</code> or <code class="language-plaintext highlighter-rouge">fseek</code> call, but rather the <em>combination</em> of an <code class="language-plaintext highlighter-rouge">fseek</code> followed by an <code class="language-plaintext highlighter-rouge">fwrite</code>. This slowdown even occurs when the <code class="language-plaintext highlighter-rouge">fseek</code> calls traverse the file linearly rather than randomly – presorting the output buffer so that each <code class="language-plaintext highlighter-rouge">fseek</code> call strictly moves the file pointer forward reduced the runtime from 630 seconds to 610 seconds. The solution, then, is to find a way to build the CSR compressed file while only reading/writing sequentially.</p>

<h2 id="conclusion-and-next-steps">Conclusion and Next Steps</h2>

<p>The broad takeaway here is that you get massive performance gains by sticking to sequential read/writes, even on an SSD. Hard drives are like really terrible caches – you’ll get better performance by reducing the number of hard drive cache flush/refills just like you would for RAM-based solutions by improving cache locality. The catch is that every inefficiency is magnified when working with external storage due to how slow I/O is compared to internal memory. Optimizing your <code class="language-plaintext highlighter-rouge">fseek</code> calls can definitely improve speed, but the optimal solution will likely be one that doesn’t ever call <code class="language-plaintext highlighter-rouge">fseek</code>.</p>

<p>As for this project, there is a way to improve it. Note that the edges in the CSR format are just the second vertices sorted in order of their first vertex. In R, that would look something like:</p>

<div class="language-r highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">offsets</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">cumsum</span><span class="p">(</span><span class="n">table</span><span class="p">(</span><span class="n">edgelist</span><span class="p">[,</span><span class="m">1</span><span class="p">]))</span><span class="w">
</span><span class="n">csr_verts</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">edgelist</span><span class="p">[</span><span class="n">order</span><span class="p">(</span><span class="n">edgelist</span><span class="p">[,</span><span class="m">1</span><span class="p">]),</span><span class="m">2</span><span class="p">]</span><span class="w">
</span><span class="n">csr_weights</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">edgelist</span><span class="p">[</span><span class="n">order</span><span class="p">(</span><span class="n">edgelist</span><span class="p">[,</span><span class="m">1</span><span class="p">]),</span><span class="m">3</span><span class="p">]</span><span class="w">
</span></code></pre></div></div>

<p>Sadly, it’s not possible to load entire edgelists into an R session because of RAM requirements. However, what we can do is build an intermediate array and then sort it with external memory. The new algorithm will look something like this (c pseudocode):</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="n">edge_holder</span> <span class="p">{</span>
  <span class="kt">int</span> <span class="n">v1</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">v2</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">weight</span><span class="p">;</span>
<span class="p">}</span> <span class="n">edge_t</span><span class="p">;</span>

<span class="c1">// comparison function</span>
<span class="kt">int</span> <span class="nf">cmp</span><span class="p">(</span><span class="k">const</span> <span class="kt">void</span> <span class="o">*</span><span class="n">a</span><span class="p">,</span> <span class="k">const</span> <span class="kt">void</span> <span class="o">*</span><span class="n">b</span><span class="p">){</span>
  <span class="k">return</span> <span class="o">*</span><span class="p">(</span><span class="k">const</span> <span class="n">edge</span> <span class="o">*</span><span class="p">)</span><span class="n">b</span><span class="p">.</span><span class="n">v1</span> <span class="o">-</span> <span class="o">*</span><span class="p">(</span><span class="k">const</span> <span class="n">edge</span> <span class="o">*</span><span class="p">)</span><span class="n">a</span><span class="p">.</span><span class="n">v2</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">edge_t</span> <span class="n">e</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="n">edge</span> <span class="n">in</span> <span class="n">file</span><span class="p">){</span>
  <span class="n">e</span><span class="p">.</span><span class="n">v1</span> <span class="o">=</span> <span class="n">edge</span><span class="p">[</span><span class="mi">0</span><span class="p">];</span>
  <span class="n">e</span><span class="p">.</span><span class="n">v2</span> <span class="o">=</span> <span class="n">edge</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
  <span class="n">e</span><span class="p">.</span><span class="n">weight</span> <span class="o">=</span> <span class="n">edge</span><span class="p">[</span><span class="mi">2</span><span class="p">];</span>
  <span class="n">fwrite</span><span class="p">(</span><span class="n">e</span><span class="p">,</span> <span class="p">...,</span> <span class="n">output_file</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">// some way to sort this file using disk space</span>
<span class="n">external_sort</span><span class="p">(</span><span class="n">output_file</span><span class="p">,</span> <span class="n">cmp</span><span class="p">);</span>
</code></pre></div></div>

<p>This method guarantees we only use sequential access – reads from <code class="language-plaintext highlighter-rouge">file</code> are sequential, and writes to <code class="language-plaintext highlighter-rouge">output_file</code> are sequential. The above method isn’t exactly what I implemented; the real code includes things like buffering to reduce the number of <code class="language-plaintext highlighter-rouge">fwrite</code> calls as well as some compression methods to reduce the size of the <code class="language-plaintext highlighter-rouge">edge_t</code> type.</p>

<p>The elephant in the room is the last step: sorting with external memory. I’m going to leave the details on that to the next blog post…but if you can’t wait, it uses a k-way mergesort with a tournament tree. And it’s really, really fast.</p>

<p>Thanks for reading – check out the next post in this series <a href="https://www.ahl27.com/posts/2024/12/loser-trees-io/">here</a>!</p>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><category term="C" /><summary type="html"><![CDATA[My last post talked about some of the things I discovered when looking into how to optimize my current research project, ExoLabel. Since then, I’ve made some big progress improvements in terms of speed, and I thought it would be worth it to break them down. Building efficient external memory algorithms is a really cool process; every potential inefficiency mattters a lot more than with RAM-based algorithms, so you start to understand how the computer works at a deeper level.]]></summary></entry><entry><title type="html">Efficient File I/O, Part 1: Some (somewhat) surprising findings on C’s `fseek`</title><link href="https://www.ahl27.com/posts/2024/10/fseek/" rel="alternate" type="text/html" title="Efficient File I/O, Part 1: Some (somewhat) surprising findings on C’s `fseek`" /><published>2024-10-10T00:00:00-04:00</published><updated>2024-10-10T00:00:00-04:00</updated><id>https://www.ahl27.com/posts/2024/10/fseek</id><content type="html" xml:base="https://www.ahl27.com/posts/2024/10/fseek/"><![CDATA[<p>I’m working a lot with files for my latest research project, <a href="https://www.ahl27.com/posts/2024/03/oomcluster/">ExoLabel</a>. I’ve (mostly) finished ensuring that the algorithm itself is accurate, so lately I’ve been turning my attention to optimizing its speed. Unsurprisingly, most of the slowest operations are working with files, since accessing files is orders of magnitude slower than accessing RAM.</p>

<p>This led me to ask–what, specifically, is the slowest operation when writing to or reading from a file? I’m specifically looking at the following operations that are pretty common throughout my code:</p>

<p>Update a random value in a file:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fseek to position
fread value
update value
fseek to position
fwrite value
</code></pre></div></div>

<p>Read a bunch of values at random positions:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fseek to position
fread value(s)
</code></pre></div></div>

<p>Now, there are a couple “dials” we can turn for optimization:</p>
<ul>
  <li>sorting locations vs. not sorting</li>
  <li>buffered vs. unbuffered files</li>
  <li>absolute vs. relative positioning for <code class="language-plaintext highlighter-rouge">fseek</code></li>
  <li>opening in <code class="language-plaintext highlighter-rouge">rb</code> vs. <code class="language-plaintext highlighter-rouge">rb+</code> for reads</li>
  <li>HDDs vs SSDs (can’t control this, but should know how it affects results)</li>
</ul>

<p>Finally, there is always the option of using portable C vs. POSIX/Windows-specific instructions. I’m not going to test this because we’re specifically interested in the performance of 100% portable C code. You could probably improve performance further by using <code class="language-plaintext highlighter-rouge">mmap</code> (or <code class="language-plaintext highlighter-rouge">MapViewOfFile</code>), but controlling for those scenarios adds a ton of code complexity given that my algorithm has to work on both POSIX and Windows.</p>

<h2 id="benchmarks">Benchmarks</h2>

<p>Let’s start with the data, then we can break it down. If you’re just interested in the conclusions, skip to the bottom.</p>

<p>All of these tests used the following setup:</p>

<ul>
  <li>M1 MacBook Pro with 32GB of RAM</li>
  <li>SSD testing used the MacBook internal drive (unclear specifications)</li>
  <li>HDD testing used a LaCie Rugged Mini 2TB external hard drive (<a href="https://a.co/d/jfvXofR">link</a>) connected via USB-C (5120 Mbit/sec transfer speed)</li>
  <li>Tests preinitialized a 4.29GB file (2^30 random integer values, nonzero to prevent sparse files)</li>
  <li>Each test did 100,000 reads or updates at random locations (locations were consistent across tests)</li>
  <li>Timing was measured using <code class="language-plaintext highlighter-rouge">clock()</code> from <code class="language-plaintext highlighter-rouge">time.h</code>, and reported in clock cycles (timing was only for each operation, excluding other things like file initialization or results reporting)</li>
  <li>Tests marked as <code class="language-plaintext highlighter-rouge">w/ sort</code> would sort the indices to analyze prior to going through the file; this makes reads more sequential than random access</li>
  <li>Tests marked as <code class="language-plaintext highlighter-rouge">(b)uffered</code> used the standard file buffer; those marked <code class="language-plaintext highlighter-rouge">unbuffered (ub)</code> called <code class="language-plaintext highlighter-rouge">setvbuf(f, NULL, _IONBF, 0)</code> to prevent buffering</li>
  <li><code class="language-plaintext highlighter-rouge">SEEK_SET</code> and <code class="language-plaintext highlighter-rouge">SEEK_CUR</code> are <code class="language-plaintext highlighter-rouge">whence</code> parameters for <code class="language-plaintext highlighter-rouge">fseek</code>, either calculating the position to move to as absolute (<code class="language-plaintext highlighter-rouge">SEEK_SET</code>) or relative to the current position (<code class="language-plaintext highlighter-rouge">SEEK_CUR</code>)</li>
  <li>Sorting the array of indicies used <code class="language-plaintext highlighter-rouge">qsort</code> and took around 7,000 clock cycles, which was negligible relative to the overall time consumed for each test</li>
  <li>Average times are calculated using the middle 90% range of times reported (the 5%-95% range of results) to reduce impact of huge outliers</li>
</ul>

<h3 id="benchmark-1-random-reads">Benchmark 1: Random Reads</h3>

<p>This benchmark analyzed the average time per read to read 100,000 <code class="language-plaintext highlighter-rouge">int</code> values from random locations in a large file.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>| drive | mode | sorted? |  buffered? |  whence  |  mean  | median |  max  |
|-------|------|---------|------------|----------|--------|--------|-------|
|  SSD  |  rb  | no sort |   buffered | SEEK_SET |   9.15 |      9 |  516  |
|  SSD  |  rb  | no sort |   buffered | SEEK_CUR |   8.61 |      9 |  226  |
|  SSD  |  rb  | no sort | unbuffered | SEEK_SET |   8.53 |      9 |  224  |
|  SSD  |  rb  | no sort | unbuffered | SEEK_CUR |  10.55 |     10 |  244  |
|  SSD  |  rb+ | no sort |   buffered | SEEK_SET |   9.22 |     10 |  409  |
|  SSD  |  rb+ | no sort |   buffered | SEEK_CUR |   9.16 |     10 |  207  |
|  SSD  |  rb+ | no sort | unbuffered | SEEK_SET |   8.16 |      9 |  436  |
|  SSD  |  rb+ | no sort | unbuffered | SEEK_CUR |   8.39 |      9 |  310  |
|-------|------|---------|------------|----------|--------|--------|-------|
|  SSD  |  rb  |  sorted |   buffered | SEEK_SET |   8.75 |      9 |  539  |
|  SSD  |  rb  |  sorted |   buffered | SEEK_CUR |   8.91 |      9 |  382  |
|  SSD  |  rb  |  sorted | unbuffered | SEEK_SET |   8.77 |      9 |  314  |
|  SSD  |  rb  |  sorted | unbuffered | SEEK_CUR |   8.49 |      9 |  259  |
|  SSD  |  rb+ |  sorted |   buffered | SEEK_SET |   9.47 |     10 |  563  |
|  SSD  |  rb+ |  sorted |   buffered | SEEK_CUR |   9.13 |     10 |  383  |
|  SSD  |  rb+ |  sorted | unbuffered | SEEK_SET |   8.39 |      9 |  267  |
|  SSD  |  rb+ |  sorted | unbuffered | SEEK_CUR |   8.65 |      9 |  338  |
|-------|------|---------|------------|----------|--------|--------|-------|
|  HDD  |  rb  | no sort |   buffered | SEEK_SET |  83.17 |     84 |  241  |
|  HDD  |  rb  | no sort |   buffered | SEEK_CUR |  95.34 |     96 |  301  |
|  HDD  |  rb  | no sort | unbuffered | SEEK_SET |  87.15 |     88 |  260  |
|  HDD  |  rb  | no sort | unbuffered | SEEK_CUR |  87.87 |     89 |  315  |
|  HDD  |  rb+ | no sort |   buffered | SEEK_SET | 107.93 |    107 |  329  |
|  HDD  |  rb+ | no sort |   buffered | SEEK_CUR | 105.47 |    105 |  293  |
|  HDD  |  rb+ | no sort | unbuffered | SEEK_SET |  80.47 |     81 |  269  |
|  HDD  |  rb+ | no sort | unbuffered | SEEK_CUR |  86.16 |     87 |  295  |
|-------|------|---------|------------|----------|--------|--------|-------|
|  HDD  |  rb  |  sorted |   buffered | SEEK_SET |  28.58 |     31 |  541  |
|  HDD  |  rb  |  sorted |   buffered | SEEK_CUR |  30.47 |     33 |  329  |
|  HDD  |  rb  |  sorted | unbuffered | SEEK_SET |  28.40 |     31 |  377  |
|  HDD  |  rb  |  sorted | unbuffered | SEEK_CUR |  27.45 |     30 |  320  |
|  HDD  |  rb+ |  sorted |   buffered | SEEK_SET |  22.17 |     21 |  446  |
|  HDD  |  rb+ |  sorted |   buffered | SEEK_CUR |  22.33 |     21 |  690  |
|  HDD  |  rb+ |  sorted | unbuffered | SEEK_SET |  20.34 |     19 |  388  |
|  HDD  |  rb+ |  sorted | unbuffered | SEEK_CUR |  21.00 |     20 |  314  |
</code></pre></div></div>

<p>The best performing results for HDDs and SSDs were:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>|-------|------|---------|------------|----------|--------|--------|-------|
|  SSD  |  rb+ | no sort | unbuffered | SEEK_SET |   8.16 |      9 |  436  |
|  SSD  |  rb+ | no sort | unbuffered | SEEK_CUR |   8.39 |      9 |  310  |
|  SSD  |  rb+ |  sorted | unbuffered | SEEK_SET |   8.39 |      9 |  267  |
|-------|------|---------|------------|----------|--------|--------|-------|
|  HDD  |  rb+ |  sorted | unbuffered | SEEK_SET |  20.34 |     19 |  388  |
|-------|------|---------|------------|----------|--------|--------|-------|
</code></pre></div></div>

<p>Broadly, opening as <code class="language-plaintext highlighter-rouge">rb</code> vs. <code class="language-plaintext highlighter-rouge">rb+</code> doesn’t make a difference. However, if you know in advance that you’re only going to be reading a single <code class="language-plaintext highlighter-rouge">int</code> from each position, eliminating buffering can improve runtimes. The largest improvement, however, was sorting the indices to traverse prior to analyzing for HDDs. HDDs benefit significantly from sequential over random access because of their internal hardware, so this finding makes sense. There’s also the difference between <code class="language-plaintext highlighter-rouge">SEEK_SET</code> and <code class="language-plaintext highlighter-rouge">SEEK_CUR</code>, which I’ll come back to later.</p>

<h3 id="benchmark-2-random-updates">Benchmark 2: Random Updates</h3>

<p>This benchmark analyzed the average time to find 100,000 values, increment each one, and then overwrite the initial value in the file. Running on an HDD without presorting the locations to access took prohibitively long, so those results are not included.</p>

<p>An additional <code class="language-plaintext highlighter-rouge">whence</code> argument is included here, which I’m calling <code class="language-plaintext highlighter-rouge">SEEK_BOTH</code>. There are two <code class="language-plaintext highlighter-rouge">fseek</code> calls required for each update: we <code class="language-plaintext highlighter-rouge">fseek</code> to the position, read it, and then have to again <code class="language-plaintext highlighter-rouge">fseek</code> to the position to write the new value (because <code class="language-plaintext highlighter-rouge">fread</code> increments the position in the file). We can either do two <code class="language-plaintext highlighter-rouge">fseek</code> calls from <code class="language-plaintext highlighter-rouge">SEEK_SET</code> (this is strategy <code class="language-plaintext highlighter-rouge">SEEK_SET</code>), do two relative calls with <code class="language-plaintext highlighter-rouge">SEEK_CUR</code>, or do one absolute call from <code class="language-plaintext highlighter-rouge">SEEK_SET</code> and then a call to <code class="language-plaintext highlighter-rouge">fseek(f, -1*sizeof(int), SEEK_CUR)</code>. This last case is strategy <code class="language-plaintext highlighter-rouge">SEEK_BOTH</code>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>| Drive |  sort?  |  Strategy | buff? |  min  |  mean  | median |  max  |
|-------|---------|-----------|-------|-------|--------|--------|-------|
|   SSD | no sort |  SEEK_SET |     b |     3 |  95.21 |     20 |   514 |
|   SSD | no sort | SEEK_BOTH |     b |     3 |  92.48 |     15 |   606 |
|   SSD | no sort |  SEEK_CUR |     b |     3 |  81.08 |     15 |   611 |
|   SSD | no sort |  SEEK_SET |    ub |     2 |  93.62 |     16 |   589 |
|   SSD | no sort | SEEK_BOTH |    ub |     3 |  79.33 |     15 |   629 |
|   SSD | no sort |  SEEK_CUR |    ub |     3 |  80.24 |     15 |   628 |
|-------|---------|-----------|-------|-------|--------|--------|-------|
|   SSD | w/ sort |  SEEK_SET |     b |     2 |  18.60 |     14 |  1569 |
|   SSD | w/ sort | SEEK_BOTH |     b |     2 |  16.11 |     13 |  1311 |
|   SSD | w/ sort |  SEEK_CUR |     b |     2 |  16.60 |     13 |  1411 |
|   SSD | w/ sort |  SEEK_SET |    ub |     2 |  12.59 |     10 |  1308 |
|   SSD | w/ sort | SEEK_BOTH |    ub |     2 |  11.76 |      7 |  1423 |
|   SSD | w/ sort |  SEEK_CUR |    ub |     2 |   9.52 |      5 |  1321 |
|-------|---------|-----------|-------|-------|--------|--------|-------|
|   HDD | w/ sort |  SEEK_SET |     b |     1 |  33.01 |     35 |   403 |
|   HDD | w/ sort | SEEK_BOTH |     b |     1 |  40.26 |     37 |   400 |
|   HDD | w/ sort |  SEEK_CUR |     b |     1 |  44.22 |     39 |   393 |
|   HDD | w/ sort |  SEEK_SET |    ub |     1 |  34.44 |     34 |   572 |
|   HDD | w/ sort | SEEK_BOTH |    ub |     1 |  40.87 |     36 |   377 |
|   HDD | w/ sort |  SEEK_CUR |    ub |     1 |  35.41 |     36 |   370 |
</code></pre></div></div>

<p>The best results for SSDs and HDDs are:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>|-------|---------|-----------|-------|-------|--------|--------|-------|
|   SSD | w/ sort |  SEEK_CUR |    ub |     2 |   9.52 |      5 |  1321 |
|   HDD | w/ sort |  SEEK_SET |     b |     1 |  33.01 |     35 |   403 |
|-------|---------|-----------|-------|-------|--------|--------|-------|
</code></pre></div></div>

<p>Once again, sorting the locations to visit prior to accessing them makes the largest difference. Once again, though, there is a performance improvement between <code class="language-plaintext highlighter-rouge">SEEK_SET</code> and <code class="language-plaintext highlighter-rouge">SEEK_CUR</code>, at least for HDDs.</p>

<h2 id="whats-going-on-with-seek_set-vs-seek_cur">What’s going on with SEEK_SET vs SEEK_CUR?</h2>

<p>When I started writing code, I assumed that using <code class="language-plaintext highlighter-rouge">SEEK_CUR</code> would give better performance. It takes a little more work to program, but I thought that it would require the OS to move around less in the file. If we’re at position 10 and want to get to position 9, <code class="language-plaintext highlighter-rouge">fseek(f, -1, SEEK_CUR)</code> would only move one space whereas <code class="language-plaintext highlighter-rouge">fseek(f, 9, SEEK_SET)</code> would rewind to the start and then move 9 positions. At least, that’s what I thought.</p>

<p>To accomplish this, I added a lot of complexity to my code. Assume we have a vector of positions <code class="language-plaintext highlighter-rouge">pos</code>. Using just <code class="language-plaintext highlighter-rouge">SEEK_SET</code> looks like this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// traversing just using SEEK_SET</span>
<span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span> <span class="n">i</span><span class="o">&lt;</span><span class="n">length_of_pos</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">){</span>
  <span class="n">fseek</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">pos</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="n">SEEK_SET</span><span class="p">);</span>
  <span class="c1">// do stuff</span>
<span class="p">}</span>
</code></pre></div></div>

<p>If we want to only use relative paths, it instead looks like this:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// traversing just using SEEK_CUR</span>
<span class="kt">int</span> <span class="n">cur_pos</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">to_move</span><span class="p">;</span>
<span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span> <span class="n">i</span><span class="o">&lt;</span><span class="n">length_of_pos</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">){</span>
  <span class="n">to_move</span> <span class="o">=</span> <span class="n">pos</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">-</span> <span class="n">cur_pos</span><span class="p">;</span>
  <span class="n">fseek</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">to_move</span><span class="p">,</span> <span class="n">SEEK_CUR</span><span class="p">);</span>
  <span class="c1">// do stuff, if we read we have to increment cur_pos too</span>
  <span class="n">cur_pos</span> <span class="o">+=</span> <span class="n">to_move</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This is a little more complicated, and it can get a lot more complex when read/writes are included.</p>

<p>It turns out, though, that this is a dumb thing to do…and also, my understanding of <code class="language-plaintext highlighter-rouge">fseek</code> was completely incorrect. Let’s take a look at the source code for <code class="language-plaintext highlighter-rouge">fseek</code> (sourced from <a href="https://opensource.apple.com/source/Libc/Libc-186/stdio.subproj/fseek.c.auto.html">here</a>, note I’m removing a lot of error checking to make this more digestible):</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/*
 * Seek the given file to the given offset.
 * `Whence' must be one of the three SEEK_* macros.
 * NOTE: fseek is essentially a wrapper for fseeko
 */</span>
<span class="kt">int</span>
<span class="n">fseeko</span><span class="p">(</span><span class="n">fp</span><span class="p">,</span> <span class="n">offset</span><span class="p">,</span> <span class="n">whence</span><span class="p">)</span>
  <span class="k">register</span> <span class="kt">FILE</span> <span class="o">*</span><span class="n">fp</span><span class="p">;</span>
  <span class="kt">off_t</span> <span class="n">offset</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">whence</span><span class="p">;</span>
<span class="p">{</span>
  <span class="k">register</span> <span class="kt">fpos_t</span> <span class="p">(</span><span class="o">*</span><span class="n">seekfn</span><span class="p">)</span> <span class="n">__P</span><span class="p">((</span><span class="kt">void</span> <span class="o">*</span><span class="p">,</span> <span class="kt">fpos_t</span><span class="p">,</span> <span class="kt">int</span><span class="p">));</span>
  <span class="kt">fpos_t</span> <span class="n">target</span><span class="p">,</span> <span class="n">curoff</span><span class="p">;</span>
  <span class="kt">size_t</span> <span class="n">n</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">stat</span> <span class="n">st</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">havepos</span><span class="p">;</span>

  <span class="cm">/*
   * Change any SEEK_CUR to SEEK_SET, and check `whence' argument.
   * After this, whence is either SEEK_SET or SEEK_END.
   */</span>
  <span class="k">switch</span> <span class="p">(</span><span class="n">whence</span><span class="p">)</span> <span class="p">{</span>

  <span class="k">case</span> <span class="n">SEEK_CUR</span><span class="p">:</span>
    <span class="cm">/*
     * In order to seek relative to the current stream offset,
     * we have to first find the current stream offset a la
     * ftell (see ftell for details).
     */</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">fp</span><span class="o">-&gt;</span><span class="n">_flags</span> <span class="o">&amp;</span> <span class="n">__SOFF</span><span class="p">)</span>
      <span class="n">curoff</span> <span class="o">=</span> <span class="n">fp</span><span class="o">-&gt;</span><span class="n">_offset</span><span class="p">;</span>
    <span class="k">else</span> <span class="p">{</span>
      <span class="n">curoff</span> <span class="o">=</span> <span class="p">(</span><span class="o">*</span><span class="n">seekfn</span><span class="p">)(</span><span class="n">fp</span><span class="o">-&gt;</span><span class="n">_cookie</span><span class="p">,</span> <span class="p">(</span><span class="kt">fpos_t</span><span class="p">)</span><span class="mi">0</span><span class="p">,</span> <span class="n">SEEK_CUR</span><span class="p">);</span>
      <span class="k">if</span> <span class="p">(</span><span class="n">curoff</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">return</span> <span class="p">(</span><span class="n">EOF</span><span class="p">);</span>
      <span class="p">}</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">fp</span><span class="o">-&gt;</span><span class="n">_flags</span> <span class="o">&amp;</span> <span class="n">__SRD</span><span class="p">)</span> <span class="p">{</span>
      <span class="n">curoff</span> <span class="o">-=</span> <span class="n">fp</span><span class="o">-&gt;</span><span class="n">_r</span><span class="p">;</span>
      <span class="k">if</span> <span class="p">(</span><span class="n">HASUB</span><span class="p">(</span><span class="n">fp</span><span class="p">))</span>
        <span class="n">curoff</span> <span class="o">-=</span> <span class="n">fp</span><span class="o">-&gt;</span><span class="n">_ur</span><span class="p">;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">fp</span><span class="o">-&gt;</span><span class="n">_flags</span> <span class="o">&amp;</span> <span class="n">__SWR</span> <span class="o">&amp;&amp;</span> <span class="n">fp</span><span class="o">-&gt;</span><span class="n">_p</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span>
      <span class="n">curoff</span> <span class="o">+=</span> <span class="n">fp</span><span class="o">-&gt;</span><span class="n">_p</span> <span class="o">-</span> <span class="n">fp</span><span class="o">-&gt;</span><span class="n">_bf</span><span class="p">.</span><span class="n">_base</span><span class="p">;</span>

    <span class="n">offset</span> <span class="o">+=</span> <span class="n">curoff</span><span class="p">;</span>
    <span class="n">whence</span> <span class="o">=</span> <span class="n">SEEK_SET</span><span class="p">;</span>
    <span class="n">havepos</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="k">break</span><span class="p">;</span>

  <span class="k">case</span> <span class="n">SEEK_SET</span><span class="p">:</span>
  <span class="k">case</span> <span class="n">SEEK_END</span><span class="p">:</span>
    <span class="n">curoff</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">havepos</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">break</span><span class="p">;</span>

  <span class="nl">default:</span>
    <span class="n">errno</span> <span class="o">=</span> <span class="n">EINVAL</span><span class="p">;</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">EOF</span><span class="p">);</span>
  <span class="p">}</span>

  <span class="c1">// ...other stuff happens here</span>
<span class="p">}</span>
</code></pre></div></div>

<p>It turns out that <code class="language-plaintext highlighter-rouge">fseek</code> is <em>always</em> using <code class="language-plaintext highlighter-rouge">SEEK_SET</code> (or <code class="language-plaintext highlighter-rouge">SEEK_END</code>). When <code class="language-plaintext highlighter-rouge">fseek</code> is called, it first has to figure out the absolute position in the file to go to. When <code class="language-plaintext highlighter-rouge">whence</code> is <code class="language-plaintext highlighter-rouge">SEEK_CUR</code>, it has to do some additional calculations to figure out where the pointer <em>currently</em> is to convert the relative position to absolute, which isn’t as simple as it sounds due to potential internal buffering. In fact, when buffering is disabled on the HDD, you can see that the difference between <code class="language-plaintext highlighter-rouge">SEEK_CUR</code> and <code class="language-plaintext highlighter-rouge">SEEK_SET</code> for the second benchmark is much smaller than when buffering is enabled.</p>

<p>Notably, this determination of the position to seek to is done <em>before</em> any checks for cached content. In other words, the program first finds where you want to go, then asks if it has any cached content from the destination you’re asking for.</p>

<p>The difference between these two argument values is not that big, but if you’re trying to eke out every bit of performance, you can typically improve results slightly by always using absolute positions rather than relative.</p>

<h2 id="conclusions">Conclusions</h2>

<p>Broadly, here are the results I found for my benchmarks:</p>

<p>Unsurprising Results:</p>

<ul>
  <li>Reading is faster than updating. If you can keep immutable values on disk and mutable values in RAM, you’ll get a big performance boost.</li>
  <li>SSDs are much faster than HDDs</li>
  <li>Batched read/writes are much faster than lots of individual writes (I didn’t show this benchmark, but it should be easy to believe)</li>
</ul>

<p>Useful Results:</p>

<ul>
  <li>SSDs have very good random access for reads. Regardless of parameterization, all my results in Benchmark 1 were essentially identical on SSDs.</li>
  <li>Doing everything you can to ensure sequential access is a <strong>huge</strong> improvement on HDDs. Sorting the indices to access means that the drive will always be seeking forward, and for fewer positions on average than not presorting the positions. Sorting the positions to access is typically negligible in the overall runtime, so whenever possible, do it.</li>
  <li>If you know exactly how many elements you’re going to be reading, using unbuffered access (or changing buffer size) can give a slight performance increase for HDDs. The increase is so minor that it’s not usually worth doing.</li>
  <li>Using absolute positions for <code class="language-plaintext highlighter-rouge">fseek</code> (from <code class="language-plaintext highlighter-rouge">SEEK_SET</code>) on HDDs is at worst identical to relative positioning (<code class="language-plaintext highlighter-rouge">SEEK_CUR</code>), and at best around 20-25% faster. On SSDs using <code class="language-plaintext highlighter-rouge">SEEK_CUR</code> can be slightly faster, but all access times are basically identical anyway.</li>
</ul>

<p>There are other ways you could further optimize–my next steps would probably be to ensure file pointers are always tagged as <code class="language-plaintext highlighter-rouge">restrict</code> unless absolutely necessary, and investigating platform-specific implementations. For ExoLabel, I’m going to move towards making files read-only and storing mutable data in RAM.</p>

<p>Thanks for reading. If you have further comments or suggestions on optimizing file read/writes using <code class="language-plaintext highlighter-rouge">stdio.h</code>, feel free to comment or email me–I’d love to hear your thoughts!</p>

<p>Check out the next part in this series <a href="https://www.ahl27.com/posts/2024/12/fwrite-io/">here</a>!</p>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><category term="C" /><summary type="html"><![CDATA[I’m working a lot with files for my latest research project, ExoLabel. I’ve (mostly) finished ensuring that the algorithm itself is accurate, so lately I’ve been turning my attention to optimizing its speed. Unsurprisingly, most of the slowest operations are working with files, since accessing files is orders of magnitude slower than accessing RAM.]]></summary></entry><entry><title type="html">Converting vectors to dendrograms in R</title><link href="https://www.ahl27.com/posts/2024/08/dend-bst/" rel="alternate" type="text/html" title="Converting vectors to dendrograms in R" /><published>2024-08-18T00:00:00-04:00</published><updated>2024-08-18T00:00:00-04:00</updated><id>https://www.ahl27.com/posts/2024/08/dendrogram_bst</id><content type="html" xml:base="https://www.ahl27.com/posts/2024/08/dend-bst/"><![CDATA[<p>I do really like R’s <code class="language-plaintext highlighter-rouge">dendrogram</code> object, but it can be really clunky to work with them. I recently implemented <a href="https://www.ahl27.com/posts/2024/01/randomforest/">random forests from scratch</a>, and the decision trees within were stored as two vectors. However, it would be really nice to be able to plot these decision trees to visualize their contents. This got me thinking–is it possible to convert vectors of values into <code class="language-plaintext highlighter-rouge">dendrogram</code> objects in R if we know the vectors are ordered in a known tree traversal? In other languages this would be fairly simple, but the nested list structure of <code class="language-plaintext highlighter-rouge">dendrogram</code> objects (and their other attributes) makes it a little trickier in R.</p>

<h2 id="setup">Setup</h2>

<p>Let me explain the problem a little more clearly. Our input is minimally an integer vector, with an optional second vector. The integer vector encodes nodes–positive values indicate internal nodes, whereas negative values indicate leaves. The second vector is paired with data we want to include at each node; this could be thresholds for a decision tree node, labels to print, or whatever. I’m assuming the input is ordered along a breadth-first traversal. Let’s see what that would look like for a small tree:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>       a
     /   \
    b     c
   / \
  d   e

 labels: a  b  c  d  e
indices: 1  1 -1 -1 -1
</code></pre></div></div>

<p>I’m also assuming that this tree is fully bifurcating, with no interior nodes having outdegree 1. In other words, all interior nodes have exactly two children. The output we’re expecting is a <code class="language-plaintext highlighter-rouge">dendrogram</code> object with the same structure as the tree implied by the <code class="language-plaintext highlighter-rouge">labels</code>/<code class="language-plaintext highlighter-rouge">indices</code> vectors.</p>

<h2 id="what-makes-a-dendrogram">What makes a dendrogram?</h2>

<p><code class="language-plaintext highlighter-rouge">dendrogram</code> objects are nested lists with a set of attributes. Each internal node of the dendrogram has the following attributes:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">members</code>: number of leaves below this node (1 for leaves)</li>
  <li><code class="language-plaintext highlighter-rouge">height</code>: height of the node</li>
  <li><code class="language-plaintext highlighter-rouge">midpoint</code>: (optional) x offset relative to the leftmost child for plotting</li>
</ul>

<p>Leaf nodes have a <code class="language-plaintext highlighter-rouge">members</code> attribute of 1, usually a <code class="language-plaintext highlighter-rouge">height</code> attribute of 0, and no <code class="language-plaintext highlighter-rouge">midpoint</code> attribute. They also have the following extra attributes:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">label</code>: label of the leaf</li>
  <li><code class="language-plaintext highlighter-rouge">leaf</code>: logical always set to <code class="language-plaintext highlighter-rouge">TRUE</code></li>
</ul>

<p>One important note is that these are largely nested list objects with a bunch of attributes. What happens at the leaves? Are they just empty lists?</p>

<p>The answer is no. In fact, if you call <code class="language-plaintext highlighter-rouge">unlist</code> on a <code class="language-plaintext highlighter-rouge">dendrogram</code>, you’ll get back a vector of integers. The leaf nodes are single integer values with additional attributes. In the previous example, the dendrogram object internally (without all its attributes) would be equivalent to:</p>

<div class="language-r highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">list</span><span class="p">(</span><span class="nf">list</span><span class="p">(</span><span class="m">1L</span><span class="p">,</span><span class="w"> </span><span class="m">2L</span><span class="p">),</span><span class="w"> </span><span class="m">3L</span><span class="p">)</span><span class="w">
</span></code></pre></div></div>

<p><strong>This is important</strong>. Lots of stuff breaks if you build a dendrogram object by hand that doesn’t have integers in the leaves.</p>

<p><code class="language-plaintext highlighter-rouge">dendrogram</code> objects have another nice property, although it isn’t specific to the <code class="language-plaintext highlighter-rouge">dendrogram</code> class. Sublists in any nested list structure can be accessed using either multiple <code class="language-plaintext highlighter-rouge">[[</code> calls, or vectors of indices. For example:</p>

<div class="language-r highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">x</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="nf">list</span><span class="p">(</span><span class="nf">list</span><span class="p">(</span><span class="m">1</span><span class="p">,</span><span class="m">2</span><span class="p">),</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="m">3</span><span class="p">,</span><span class="m">4</span><span class="p">)),</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="nf">list</span><span class="p">(</span><span class="m">5</span><span class="p">,</span><span class="m">6</span><span class="p">),</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="m">7</span><span class="p">,</span><span class="m">8</span><span class="p">)))</span><span class="w">

</span><span class="n">x</span><span class="p">[[</span><span class="m">1</span><span class="p">]][[</span><span class="m">2</span><span class="p">]][[</span><span class="m">1</span><span class="p">]]</span><span class="w">
</span><span class="c1"># 3</span><span class="w">

</span><span class="n">x</span><span class="p">[[</span><span class="nf">c</span><span class="p">(</span><span class="m">1</span><span class="p">,</span><span class="m">2</span><span class="p">,</span><span class="m">1</span><span class="p">)]]</span><span class="w">
</span><span class="c1"># 3</span><span class="w">
</span></code></pre></div></div>

<p>This latter accession mode is going to be extremely useful.</p>

<h2 id="building-the-nested-list-structure">Building the nested list structure</h2>

<p>Breadth-first searches are typically done using queues–for each node, we process it, then add its children to the end of the queue. This is what makes this operation difficult in R…we can’t store pointers to nodes like we could do in (for example) C. <em>However</em>, we can actually build a queue accessing the nodes of the tree by using vectors of accessors. We can start with the root and a vector of accessors <code class="language-plaintext highlighter-rouge">list(1,2)</code>. At any particular node <code class="language-plaintext highlighter-rouge">x</code>, its children are <code class="language-plaintext highlighter-rouge">x[[1]]</code> and <code class="language-plaintext highlighter-rouge">x[[2]]</code>. That means that, given an accessor <code class="language-plaintext highlighter-rouge">i</code>, if we append <code class="language-plaintext highlighter-rouge">list(c(i,1)</code> and <code class="language-plaintext highlighter-rouge">list(c(i,2))</code> to our vector of accessors, we now have “pointers” to the children of the node accessed at <code class="language-plaintext highlighter-rouge">root[[i]]</code>.</p>

<div class="language-r highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">f</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="k">function</span><span class="p">(</span><span class="n">node_indices</span><span class="p">,</span><span class="w"> </span><span class="n">node_data</span><span class="p">){</span><span class="w">
  </span><span class="c1">## initialize the root node</span><span class="w">
  </span><span class="n">root</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">vector</span><span class="p">(</span><span class="s1">'list'</span><span class="p">,</span><span class="w"> </span><span class="n">length</span><span class="o">=</span><span class="m">2L</span><span class="p">)</span><span class="w">
  </span><span class="nf">attr</span><span class="p">(</span><span class="n">root</span><span class="p">,</span><span class="w"> </span><span class="s2">"members"</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0L</span><span class="w">
  </span><span class="nf">attr</span><span class="p">(</span><span class="n">root</span><span class="p">,</span><span class="w"> </span><span class="s2">"height"</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0</span><span class="w">
  </span><span class="nf">attr</span><span class="p">(</span><span class="n">root</span><span class="p">,</span><span class="w"> </span><span class="s2">"midpoint"</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0</span><span class="w">
  </span><span class="nf">attr</span><span class="p">(</span><span class="n">root</span><span class="p">,</span><span class="w"> </span><span class="s2">"otherdata"</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">node_data</span><span class="p">[[</span><span class="m">1</span><span class="p">]]</span><span class="w">
  </span><span class="nf">class</span><span class="p">(</span><span class="n">root</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="s2">"dendrogram"</span><span class="w">

  </span><span class="c1">## set up a queue</span><span class="w">
  </span><span class="n">cur_q</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="m">1</span><span class="p">,</span><span class="m">2</span><span class="p">)</span><span class="w">
  </span><span class="n">ctr</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">2L</span><span class="w">
  </span><span class="n">leafctr</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">1L</span><span class="w">
  </span><span class="k">while</span><span class="p">(</span><span class="n">ctr</span><span class="w"> </span><span class="o">&lt;=</span><span class="w"> </span><span class="nf">length</span><span class="p">(</span><span class="n">node_indices</span><span class="p">)){</span><span class="w">
    </span><span class="n">accessor</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">cur_q</span><span class="p">[[</span><span class="n">ctr</span><span class="p">]]</span><span class="w">
    </span><span class="n">is_leaf</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">node_indices</span><span class="p">[</span><span class="n">ctr</span><span class="p">]</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="m">0</span><span class="w">
    </span><span class="n">otherdata</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">node_data</span><span class="p">[[</span><span class="n">ctr</span><span class="p">]]</span><span class="w">
    </span><span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">is_leaf</span><span class="p">){</span><span class="w">
      </span><span class="c1">## interior nodes are lists</span><span class="w">
      </span><span class="n">cur_node</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">vector</span><span class="p">(</span><span class="s1">'list'</span><span class="p">,</span><span class="w"> </span><span class="n">length</span><span class="o">=</span><span class="m">2L</span><span class="p">)</span><span class="w">
      </span><span class="nf">attr</span><span class="p">(</span><span class="n">cur_node</span><span class="p">,</span><span class="w"> </span><span class="s1">'midpoint'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0</span><span class="w">

      </span><span class="c1">## add children to the queue</span><span class="w">
      </span><span class="n">cur_q</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="n">cur_q</span><span class="p">,</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="nf">c</span><span class="p">(</span><span class="n">accessor</span><span class="p">,</span><span class="w"> </span><span class="m">1L</span><span class="p">),</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="n">accessor</span><span class="p">,</span><span class="w"> </span><span class="m">2L</span><span class="p">)))</span><span class="w">
    </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="c1">## leaves are integers</span><span class="w">
      </span><span class="n">cur_node</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">leafctr</span><span class="w">

      </span><span class="c1">## extra leaf attributes</span><span class="w">
      </span><span class="nf">attr</span><span class="p">(</span><span class="n">cur_node</span><span class="p">,</span><span class="w"> </span><span class="s1">'leaf'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kc">TRUE</span><span class="w">
      </span><span class="nf">attr</span><span class="p">(</span><span class="n">cur_node</span><span class="p">,</span><span class="w"> </span><span class="s1">'label'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">as.character</span><span class="p">(</span><span class="n">leafctr</span><span class="p">)</span><span class="w">

      </span><span class="n">leafctr</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">leafctr</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="m">1L</span><span class="w">
    </span><span class="p">}</span><span class="w">

    </span><span class="c1">## add attributes for all nodes</span><span class="w">
    </span><span class="nf">attr</span><span class="p">(</span><span class="n">cur_node</span><span class="p">,</span><span class="w"> </span><span class="s1">'height'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0</span><span class="w">
    </span><span class="nf">attr</span><span class="p">(</span><span class="n">cur_node</span><span class="p">,</span><span class="w"> </span><span class="s1">'members'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0L</span><span class="w">
    </span><span class="nf">attr</span><span class="p">(</span><span class="n">cur_node</span><span class="p">,</span><span class="w"> </span><span class="s1">'otherdata'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">otherdata</span><span class="w">
    </span><span class="nf">class</span><span class="p">(</span><span class="n">cur_node</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="s1">'dendrogram'</span><span class="w">

    </span><span class="c1">## assign as a child of the current node</span><span class="w">
    </span><span class="n">root</span><span class="p">[[</span><span class="n">accessor</span><span class="p">]]</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">cur_node</span><span class="w">
    </span><span class="n">ctr</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">ctr</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="m">1L</span><span class="w">
  </span><span class="p">}</span><span class="w">

  </span><span class="c1">## What are we missing here?</span><span class="w">

  </span><span class="n">root</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<h2 id="fixing-the-nodes">Fixing the nodes</h2>

<p>This is pretty close! There’s one small issue that you may have noticed in the prior function–all the attributes are wrong! We set <code class="language-plaintext highlighter-rouge">members</code> and <code class="language-plaintext highlighter-rouge">height</code> (and <code class="language-plaintext highlighter-rouge">midpoint</code>) to zero for every node, which isn’t really correct. If we try to plot the resulting object, it’ll be garbage.</p>

<p>The reason these are set to zero is because there isn’t a great way to determine what the correct values of these should be during the initial processing. It’s much easier to build the <code class="language-plaintext highlighter-rouge">dendrogram</code> object and then correct the values later. For this, I’m going to use <a href="https://www.ahl27.com/posts/2023/02/dendrapply/">my version of <code class="language-plaintext highlighter-rouge">dendrapply</code></a> (available in SynExtend) because it supports post-order traversals, which are important for this.</p>

<p>For each node <code class="language-plaintext highlighter-rouge">x</code>, we have to correct <code class="language-plaintext highlighter-rouge">members</code>, <code class="language-plaintext highlighter-rouge">height</code>, and <code class="language-plaintext highlighter-rouge">midpoint</code>. The <code class="language-plaintext highlighter-rouge">members</code> attribute is the number of leaves, which we can get with <code class="language-plaintext highlighter-rouge">length(unlist(x))</code>. The <code class="language-plaintext highlighter-rouge">height</code> attribute is relatively arbitrary, but each node has to be higher than its children for plotting. We’ll just set leaves to zero, and then interior nodes to <code class="language-plaintext highlighter-rouge">max(height(x[[1]]), height(x[[2]])) + 1L</code>.</p>

<p>The last attribute is <code class="language-plaintext highlighter-rouge">midpoint</code>, which can be relatively complicated. This attribute determines where the node is placed on the x-axis relative to its leftmost child. I’m not entirely sure why <code class="language-plaintext highlighter-rouge">dendrogram</code> objects plot using this parameter, but the relative referencing makes things complex. Each leaf is plotted with distance 1.0 from subsequent nodes. Thus, if the children of <code class="language-plaintext highlighter-rouge">x</code> are both leaves, the midpoint is 0.5–halfway between the leaves, since the leaves are distance 1.0 apart. The other cases are more complicated, but I’ll include the code below and leave the reasoning as an exercise for the reader.</p>

<div class="language-r highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">f</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="k">function</span><span class="p">(</span><span class="n">node_indices</span><span class="p">,</span><span class="w"> </span><span class="n">node_data</span><span class="p">){</span><span class="w">
  </span><span class="c1">## ... everything from before</span><span class="w">

  </span><span class="c1">## here's what we were missing:</span><span class="w">
  </span><span class="n">midpoint</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="err">\</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="w"> </span><span class="nf">attr</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="s1">'midpoint'</span><span class="p">)</span><span class="w">
  </span><span class="n">height</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="err">\</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="w"> </span><span class="nf">attr</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="s1">'height'</span><span class="p">)</span><span class="w">
  </span><span class="n">root</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">dendrapply</span><span class="p">(</span><span class="n">root</span><span class="p">,</span><span class="w"> </span><span class="err">\</span><span class="p">(</span><span class="n">x</span><span class="p">){</span><span class="w">
    </span><span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">is.leaf</span><span class="p">(</span><span class="n">x</span><span class="p">)){</span><span class="w">
      </span><span class="c1">## internal nodes</span><span class="w">
      </span><span class="nf">attr</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="s1">'members'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">length</span><span class="p">(</span><span class="n">unlist</span><span class="p">(</span><span class="n">x</span><span class="p">))</span><span class="w">
      </span><span class="nf">attr</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="s1">'height'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">max</span><span class="p">(</span><span class="n">height</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">1</span><span class="p">]]),</span><span class="w"> </span><span class="n">height</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">2</span><span class="p">]]))</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="m">1L</span><span class="w">

      </span><span class="c1">## midpoint calculation</span><span class="w">
      </span><span class="n">mp</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0</span><span class="w">
      </span><span class="n">child_is_leaf</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="n">is.leaf</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">1</span><span class="p">]]),</span><span class="w"> </span><span class="n">is.leaf</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">2</span><span class="p">]]))</span><span class="w">
      </span><span class="k">if</span><span class="p">(</span><span class="n">child_is_leaf</span><span class="p">[</span><span class="m">1</span><span class="p">]</span><span class="w"> </span><span class="o">&amp;&amp;</span><span class="w"> </span><span class="n">child_is_leaf</span><span class="p">[</span><span class="m">2</span><span class="p">]){</span><span class="w">
        </span><span class="c1">## both children leaves</span><span class="w">
        </span><span class="n">mp</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0.5</span><span class="w">
      </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="p">(</span><span class="n">child_is_leaf</span><span class="p">[</span><span class="m">1</span><span class="p">]){</span><span class="w">
        </span><span class="c1">## only left child a leaf</span><span class="w">
        </span><span class="n">mp</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="p">((</span><span class="n">midpoint</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">2</span><span class="p">]])</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="m">1L</span><span class="p">)</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="m">2</span><span class="p">)</span><span class="w">
      </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="p">(</span><span class="n">child_is_leaf</span><span class="p">[</span><span class="m">2</span><span class="p">]){</span><span class="w">
        </span><span class="c1">## only right child is a leaf</span><span class="w">
        </span><span class="n">mp</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="p">((</span><span class="n">midpoint</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">1</span><span class="p">]])</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="m">1L</span><span class="p">)</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="m">2</span><span class="p">)</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">midpoint</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">1</span><span class="p">]])</span><span class="w">
      </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="c1">## both children non-leaves</span><span class="w">
        </span><span class="n">mp</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="p">(</span><span class="nf">attr</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">1</span><span class="p">]],</span><span class="w"> </span><span class="s1">'members'</span><span class="p">)</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">midpoint</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">1</span><span class="p">]])</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">midpoint</span><span class="p">(</span><span class="n">x</span><span class="p">[[</span><span class="m">2</span><span class="p">]]))</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="m">2</span><span class="w">
      </span><span class="p">}</span><span class="w">
      </span><span class="nf">attr</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="s1">'midpoint'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">mp</span><span class="w">
    </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="c1">## leaves</span><span class="w">
      </span><span class="nf">attr</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="s1">'members'</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">1L</span><span class="w">
    </span><span class="p">}</span><span class="w">

    </span><span class="n">x</span><span class="w">
  </span><span class="p">},</span><span class="w"> </span><span class="n">how</span><span class="o">=</span><span class="s1">'post.order'</span><span class="p">)</span><span class="w">

  </span><span class="n">root</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<h2 id="conclusion">Conclusion</h2>

<p>This doesn’t put together the entire function–if you’re interested in the complete thing, you can check out the source code <a href="https://github.com/ahl27/machineRy/blob/e5c1c0948f9e4d8a604a493dd222c3a7e905f49b/R/randomforest.R#L240">on GitHub</a>. Thanks for reading!</p>]]></content><author><name>Aidan Lakshman</name></author><category term="blog posts" /><category term="R" /><summary type="html"><![CDATA[I do really like R’s dendrogram object, but it can be really clunky to work with them. I recently implemented random forests from scratch, and the decision trees within were stored as two vectors. However, it would be really nice to be able to plot these decision trees to visualize their contents. This got me thinking–is it possible to convert vectors of values into dendrogram objects in R if we know the vectors are ordered in a known tree traversal? In other languages this would be fairly simple, but the nested list structure of dendrogram objects (and their other attributes) makes it a little trickier in R.]]></summary></entry></feed>