<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
    <title>ktnlvr</title>
    <link rel="self" type="application/atom+xml" href="https://ktnlvr.dev/atom.xml"/>
    <link rel="alternate" type="text/html" href="https://ktnlvr.dev/"/>
    <generator uri="https://gohugo.io/">Hugo</generator>
    <updated>2026-11-20T00:00:00+00:00</updated>
    <id>https://ktnlvr.dev/atom.xml</id>
    <entry xml:lang="en">
        <title>Reconvergence: Demystified</title>
        <published>2026-11-20T00:00:00+00:00</published>
        <updated>2026-11-20T00:00:00+00:00</updated>
        <link rel="alternate" type="text/html" href="https://ktnlvr.dev/computing/reconvergence-demystified/"/>
        <id>https://ktnlvr.dev/computing/reconvergence-demystified/</id>
        <content type="html" xml:base="https://ktnlvr.dev/computing/reconvergence-demystified/">&lt;p&gt;For parallel execution, the homogeneity of the workflow is an important factor for efficient parallelism.&lt;/p&gt;&#xA;&lt;p&gt;At the same time, some degree of difference is unavoidable. At minimum, you want your program to at least work on different input. If the input is the same&lt;/p&gt;&#xA;&lt;p&gt;The phenomenon of a single workflow branching into multiple stable execution paths is called &lt;em&gt;divergence&lt;/em&gt; and, if nto accounted for, can put good performance in a coffin. This article intends to educate you on &lt;em&gt;control flow divergence&lt;/em&gt; and how GPUs handle it in a performant way - the &lt;em&gt;reconvergence&lt;/em&gt;.&lt;/p&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;&lt;strong&gt;N.B.&lt;/strong&gt; This article focuses mostly on what I learned about the NVidia GPU and corresponds roughly to the first CUDA-capable architecture: Tesla (G80, GeForce 8800 circa 2006). Slightly dated, but I figured people might benefit from more publicly available information about this.&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&#xA;&lt;h2 id=&#34;the-execution-model&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#the-execution-model&#34; aria-label=&#34;the-execution-model&#34;&gt;❦ &lt;/a&gt;The Execution Model&lt;/h2&gt;&#xA;&lt;p&gt;The GPU work is scheduled in kernels, each kernel is a piece of code that all parallel executors runs. In software, the programmer is able to specify the amount of threads, each with their own numeric id.&lt;/p&gt;&#xA;&lt;p&gt;In hardware there are warps. Each warp has 32 lanes, each able to accomodate one thread. The warp executes code in lockstep across all the lanes, the program counter is shared across them. We can, of course, request more than just 32 threads. We group warps into Streaming Multiprocessors (SMs). The SM issues an instruction every single to a warp, that then makes all its resident threads execute it.&lt;/p&gt;&#xA;&lt;p&gt;Warps do not have branch prediction or out-of-order execution, the instructions are scheduled statically. Now, given that warps force all threads to do the same thing, what happens when an &lt;code&gt;if&lt;/code&gt; takes two different paths within a single warp?&lt;/p&gt;&#xA;&lt;p&gt;This split is exactly &lt;em&gt;divergence&lt;/em&gt;.&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;minor-divergence&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#minor-divergence&#34; aria-label=&#34;minor-divergence&#34;&gt;❦ &lt;/a&gt;Minor Divergence&lt;/h2&gt;&#xA;&lt;p&gt;To resolve simple divergences of a few instructions, the GPU allows predication. Each thread is equipped with 7 boolean registers &lt;code&gt;P0&lt;/code&gt; to &lt;code&gt;P6&lt;/code&gt; and a constant register &lt;code&gt;PT&lt;/code&gt; that always reads &lt;code&gt;true&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;Every opcode is prefixed with a 4 bit field: 3 bits to index into the boolean registers and one for negating it, usually written as &lt;code&gt;@Pk&lt;/code&gt; and &lt;code&gt;@!Pk&lt;/code&gt; for negation. The warp issues the instruction to every thread, but its results are only written if the predicated is true for that specific lane.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;// -- snip --&#xA;LOP3.LUT P0, RZ, R2, 0x1, RZ, 0xc0, !PT&#xA;@P0  IMAD R2, R2, 0x3, 0x1         // only lanes with P0 true&#xA;@!P0 SHF.R.S32.HI R2, ...          // only lanes with P0 false&#xA;// -- snip --&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Notice that the work is still done by all threads, so some compute is wasted. This mechanism is best for small divergences where the chance of each short path being taken is roughly 50%. Consequently, it demonstrates worse performance on highly skewed workloads, since every lane has to calculate the rare path and throw the result away.&lt;/p&gt;&#xA;&lt;p&gt;GPUs also do not have branch prediction, so this avoids having to pay the expensive cost of an instruction fetch for a jump. The execution is optimised in such a way that no memory operations are actually issued if the predicate is not met. Notice how that does not require any additional handling of the program counter, it just keeps ticking forward.&lt;/p&gt;&#xA;&lt;p&gt;At the same time, the instructions are guaranteed to be executed in disjoint lanes, so they must not depend on each other. We can consider two instruction paths $a$ and $b$, then each of them has a dependency latency of $D_a$ and $D_b$. A scheduler issues at most one warp instruction per cycle,that&#39;s also the minimum number of cycles a predicated region can take, so for two instructions the issue latency is at least $L_a$ and $L_b$. The instruction &lt;code&gt;ISETP&lt;/code&gt; that sets the predicate has its own latency, so together the latency of any region $L$ is approximately...&lt;/p&gt;&#xA;&lt;p&gt;$$L_\text{predicated} \approx L_\text{ISETP} + \max(L_a + L_b, D_a, D_b)$$&lt;/p&gt;&#xA;&lt;p&gt;This mechanism is also why branchless programming often does not produce the expected performance improvements, it gets optimised into a relatively inexpensive predicate anyway. If it were computed as &lt;code&gt;!cond * a + cond * b&lt;/code&gt;, that would require computing both paths still, and then also paying for the cost of both negation and the final addition. This gets reduced to a &lt;code&gt;SEL&lt;/code&gt; instruction that picks between two values based on a predicate.&lt;/p&gt;&#xA;&lt;p&gt;Despite its benefits, the approach described above generalises to loops quite poorly.&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;major-divergence&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#major-divergence&#34; aria-label=&#34;major-divergence&#34;&gt;❦ &lt;/a&gt;Major Divergence&lt;/h2&gt;&#xA;&lt;p&gt;For convenience we will be looking at the numerical calculation of the Collatz function:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Take a natural number.&lt;/li&gt;&#xA;&lt;li&gt;If the number is even, halve it.&lt;/li&gt;&#xA;&lt;li&gt;If the number is odd, multiply by 3 and add 1.&lt;/li&gt;&#xA;&lt;li&gt;Repeat until the number reaches 1. The amount of steps is the value of the function.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;Consider the snippet of code below. The code performs computes the Collatz function on the index of the thread. When dispatched on a group of &lt;code&gt;1024&lt;/code&gt; threads, the function will run across &lt;code&gt;32&lt;/code&gt; warps.&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;background-color:#f7f7f7;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-cpp&#34; data-lang=&#34;cpp&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;__global__ &lt;span style=&#34;color:#cf222e&#34;&gt;void&lt;/span&gt; &lt;span style=&#34;color:#6639ba&#34;&gt;collatz&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;(&lt;/span&gt;&lt;span style=&#34;color:#cf222e&#34;&gt;const&lt;/span&gt; &lt;span style=&#34;color:#cf222e&#34;&gt;int&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;*&lt;/span&gt;in&lt;span style=&#34;color:#1f2328&#34;&gt;,&lt;/span&gt; &lt;span style=&#34;color:#cf222e&#34;&gt;int&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;*&lt;/span&gt;r&lt;span style=&#34;color:#1f2328&#34;&gt;)&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;{&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#57606a&#34;&gt;// n = 0 never terminates, so we process 1 to 1024&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#cf222e&#34;&gt;int&lt;/span&gt; n &lt;span style=&#34;color:#0550ae&#34;&gt;=&lt;/span&gt; in&lt;span style=&#34;color:#1f2328&#34;&gt;[&lt;/span&gt;threadIdx&lt;span style=&#34;color:#1f2328&#34;&gt;.&lt;/span&gt;x&lt;span style=&#34;color:#1f2328&#34;&gt;]&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;1&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;,&lt;/span&gt; i &lt;span style=&#34;color:#0550ae&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;0&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#cf222e&#34;&gt;while&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;(&lt;/span&gt;n &lt;span style=&#34;color:#0550ae&#34;&gt;!=&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;1&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;)&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;{&lt;/span&gt;        &lt;span style=&#34;color:#57606a&#34;&gt;// A---+&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#cf222e&#34;&gt;if&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;(&lt;/span&gt;n &lt;span style=&#34;color:#0550ae&#34;&gt;&amp;amp;&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;1&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;)&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;{&lt;/span&gt;        &lt;span style=&#34;color:#57606a&#34;&gt;//     |&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            n &lt;span style=&#34;color:#0550ae&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;3&lt;/span&gt;&lt;span style=&#34;color:#0550ae&#34;&gt;*&lt;/span&gt;n &lt;span style=&#34;color:#0550ae&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;1&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;;&lt;/span&gt;    &lt;span style=&#34;color:#57606a&#34;&gt;// B-+ |&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#1f2328&#34;&gt;}&lt;/span&gt; &lt;span style=&#34;color:#cf222e&#34;&gt;else&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;{&lt;/span&gt;            &lt;span style=&#34;color:#57606a&#34;&gt;//   | |&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            n &lt;span style=&#34;color:#0550ae&#34;&gt;/=&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;2&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;;&lt;/span&gt;         &lt;span style=&#34;color:#57606a&#34;&gt;// C-+ |&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#1f2328&#34;&gt;}&lt;/span&gt;                   &lt;span style=&#34;color:#57606a&#34;&gt;//   | |&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                            &lt;span style=&#34;color:#57606a&#34;&gt;//   | |&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        i&lt;span style=&#34;color:#0550ae&#34;&gt;++&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;;&lt;/span&gt;                &lt;span style=&#34;color:#57606a&#34;&gt;// D-/ |&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#1f2328&#34;&gt;}&lt;/span&gt;                       &lt;span style=&#34;color:#57606a&#34;&gt;//     |&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                            &lt;span style=&#34;color:#57606a&#34;&gt;//     |&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    r&lt;span style=&#34;color:#1f2328&#34;&gt;[&lt;/span&gt;threadIdx&lt;span style=&#34;color:#1f2328&#34;&gt;.&lt;/span&gt;x&lt;span style=&#34;color:#1f2328&#34;&gt;]&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;=&lt;/span&gt; i&lt;span style=&#34;color:#1f2328&#34;&gt;;&lt;/span&gt;     &lt;span style=&#34;color:#57606a&#34;&gt;// E---/&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#xA;&lt;p&gt;In this code we have several sections that require conditional execution.&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;code&gt;A&lt;/code&gt; runs until the termination condition is met.&lt;/li&gt;&#xA;&lt;li&gt;&lt;code&gt;B&lt;/code&gt; runs when &lt;code&gt;n &amp;amp; 1&lt;/code&gt; and only if already in &lt;code&gt;A&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;li&gt;&lt;code&gt;C&lt;/code&gt; runs if &lt;code&gt;B&lt;/code&gt; doesn&#39;t, so when not &lt;code&gt;n &amp;amp; 1&lt;/code&gt;, but still only in &lt;code&gt;A&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;li&gt;&lt;code&gt;D&lt;/code&gt; runs after &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt;, only if &lt;code&gt;A&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;li&gt;&lt;code&gt;E&lt;/code&gt; runs for every thread, but only after the termination condition is met.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;With predication the section would look something like the following:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;background-color:#f7f7f7;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-cpp&#34; data-lang=&#34;cpp&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#cf222e&#34;&gt;while&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;(&lt;/span&gt;n &lt;span style=&#34;color:#0550ae&#34;&gt;!=&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;1&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;)&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;{&lt;/span&gt;      &lt;span style=&#34;color:#57606a&#34;&gt;// .loop     P0 := n != 1&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#cf222e&#34;&gt;if&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;(&lt;/span&gt;n &lt;span style=&#34;color:#0550ae&#34;&gt;&amp;amp;&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;1&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;)&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;{&lt;/span&gt;      &lt;span style=&#34;color:#57606a&#34;&gt;// @P0       P1 := n &amp;amp; 1&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        n &lt;span style=&#34;color:#0550ae&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;3&lt;/span&gt;&lt;span style=&#34;color:#0550ae&#34;&gt;*&lt;/span&gt;n &lt;span style=&#34;color:#0550ae&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;1&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;;&lt;/span&gt;  &lt;span style=&#34;color:#57606a&#34;&gt;// @P0  @P1  n  := 3*n + 1&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#1f2328&#34;&gt;}&lt;/span&gt; &lt;span style=&#34;color:#cf222e&#34;&gt;else&lt;/span&gt; &lt;span style=&#34;color:#1f2328&#34;&gt;{&lt;/span&gt;          &lt;span style=&#34;color:#57606a&#34;&gt;// &#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        n &lt;span style=&#34;color:#0550ae&#34;&gt;/=&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;2&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;;&lt;/span&gt;       &lt;span style=&#34;color:#57606a&#34;&gt;// @P0 @!P1  n  := n / 2 &#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#1f2328&#34;&gt;}&lt;/span&gt;                 &lt;span style=&#34;color:#57606a&#34;&gt;// &#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    i&lt;span style=&#34;color:#0550ae&#34;&gt;++&lt;/span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;;&lt;/span&gt;              &lt;span style=&#34;color:#57606a&#34;&gt;// @P0       i  := i + 1&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#1f2328&#34;&gt;}&lt;/span&gt;                     &lt;span style=&#34;color:#57606a&#34;&gt;// @P0       goto .loop &#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                      &lt;span style=&#34;color:#57606a&#34;&gt;// &#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;r&lt;span style=&#34;color:#1f2328&#34;&gt;[&lt;/span&gt;threadIdx&lt;span style=&#34;color:#1f2328&#34;&gt;.&lt;/span&gt;x&lt;span style=&#34;color:#1f2328&#34;&gt;]&lt;/span&gt; &lt;span style=&#34;color:#0550ae&#34;&gt;=&lt;/span&gt; i&lt;span style=&#34;color:#1f2328&#34;&gt;;&lt;/span&gt;   &lt;span style=&#34;color:#57606a&#34;&gt;//           r  := i&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#xA;&lt;p&gt;Messy. Obviously, the code will not work, since any opcode can only ever reference a single predicate, and the nested computations in the &lt;code&gt;if&lt;/code&gt; require two conditions: evenness and being inside the loop body. What&#39;s worse, is that in &lt;code&gt;@P0 goto .loop&lt;/code&gt;, the program counter needs to be different for different threads depending on the value of &lt;code&gt;P0&lt;/code&gt;, but the program counter is fixed across all the threads in a warp! We need something better.&lt;/p&gt;&#xA;&lt;p&gt;We may notice how the predication to the left of the instructions grows, almost like a stack. For resolving these kinds of divergence we have the &lt;em&gt;reconvergence stack&lt;/em&gt;.&lt;/p&gt;&#xA;&lt;p&gt;Looking at the first snippet, may notice that at some point the branches will meet: &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; meet at &lt;code&gt;D&lt;/code&gt;, &lt;code&gt;A&lt;/code&gt;s meet at &lt;code&gt;E&lt;/code&gt;. In that case we can maintain a stack of possible branches, executes the lanes relevant to a specific branch, and then pop it.&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;deadlocks--forward-progress-guarantees&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#deadlocks--forward-progress-guarantees&#34; aria-label=&#34;deadlocks--forward-progress-guarantees&#34;&gt;❦ &lt;/a&gt;Deadlocks &amp;amp; Forward Progress Guarantees&lt;/h2&gt;&#xA;</content>
    </entry>
    <entry xml:lang="en">
        <title>When to do Contrapositive Proofs</title>
        <published>2026-08-01T00:00:00+00:00</published>
        <updated>2026-08-01T00:00:00+00:00</updated>
        <link rel="alternate" type="text/html" href="https://ktnlvr.dev/maths/when-to-do-contrapositive-proofs/"/>
        <id>https://ktnlvr.dev/maths/when-to-do-contrapositive-proofs/</id>
        <content type="html" xml:base="https://ktnlvr.dev/maths/when-to-do-contrapositive-proofs/">&lt;p&gt;A contrapositive proof is based on the fact that expressions $A \Rightarrow B$ and $\neg{B} \Rightarrow \neg{A}$ are equivalent. The statement &amp;quot;it&#39;s raining, so it&#39;s wet outside&amp;quot; is the same as saying &amp;quot;it&#39;s not wet outside, so it&#39;s not raining.&amp;quot; Hence, when doing proofs you can freely swap one for the other.&lt;/p&gt;&#xA;&lt;p&gt;This is similar, but distinct, from proofs by contradiction. You are not showing the opposite leads to absurd results, you are just talking about the same facts within a different logical frame, much like double negation yields back the same proposition.&lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;&#xA;&lt;p&gt;So, what kinds of problems is it convenient for?&lt;/p&gt;&#xA;&lt;hr&gt;&#xA;&lt;p&gt;This question came to me while reading in &lt;a href=&#34;/books/book-of-proof&#34;&gt;Richard Hammack&#39;s Book of Proof&lt;/a&gt;. You should use contrapositives when the consequent $B$ is significantly simpler than the antecedent $A$. For instance, if $B$ states that something is prime, working in a contrapositive proof just requires assuming that it&#39;s composite. If $A$ is an algebraic expression of some sort, the proof will likely just naturally fall out of it.&lt;/p&gt;&#xA;&lt;p&gt;For example, consider the following problem:&lt;/p&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;&lt;strong&gt;A.5&lt;/strong&gt; Show that&#xA;$$x^2 + 5x &amp;lt; 0 \Rightarrow x &amp;lt; 0$$&lt;/p&gt;&#xA;&lt;p&gt;&lt;em&gt;Hammack. Book of Proof, Chapter 5&lt;/em&gt;&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;p&gt;A very simple question! Working through it with a direct proof, however, is not quite trivial. Consider the following direct proofs:&lt;/p&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;&lt;strong&gt;A.5&lt;/strong&gt; &lt;em&gt;Direct Proof 1.&lt;/em&gt;&lt;/p&gt;&#xA;&lt;p&gt;We can factor $x^2 + 5x$ as $x(x+5)$. We know it&#39;s a parabola concave up because the factor before $x^2$ is positive, so it is positive in both $x \rightarrow -\infty$ and $x \rightarrow \infty$.&lt;/p&gt;&#xA;&lt;p&gt;Roots $x = 0$ and $x = -5$ will mean change of sign, so it has to change the sign twice, so it will go to negative across $x = -5$ and then back to positive across $x = 0$. Thus, it will be negative for all $x \in (-5, 0)$. $\blacksquare$&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;&lt;strong&gt;A.5&lt;/strong&gt; &lt;em&gt;Direct Proof 2.&lt;/em&gt;&lt;/p&gt;&#xA;&lt;p&gt;We know that $-x^2 \leq 0$ is always true, so we can add it to our original $x^2 + 5x &amp;lt; 0$, obtaining $x^2 + 5x + (-x^2) &amp;lt; 0 + 0$. We can trivially merge the &amp;quot;$\leq$&amp;quot; and &amp;quot;$&amp;lt;$&amp;quot; into a single less-than.&lt;/p&gt;&#xA;&lt;p&gt;Computing the expression, we obtain $5x &amp;lt; 0$, from which we can divide the $5$ out, arriving at $x &amp;lt; 0$. $\blacksquare$&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;p&gt;Those are all quite concise. Now let&#39;s look at a contrapositive proof:&lt;/p&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;&lt;strong&gt;A.5&lt;/strong&gt; &lt;em&gt;Contrapositive Proof.&lt;/em&gt;&lt;/p&gt;&#xA;&lt;p&gt;Assume $x \geq 0$. It follows that $x^2 \geq 0$ and $5x \geq 0$. The sum of two non-negative numbers is also non-negative, so $x^2 + 5x \geq 0$. $\blacksquare$&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;p&gt;Notice the contrast. To do the direct proof we had to apply quite heavy machinery. In the first proof we had to consider the behaviour of the intervals and consider the sign changing. For the second one we had to conjure the $-x^2 \leq 0$ out of thin air. Both methods are not simple or intuitive.&lt;/p&gt;&#xA;&lt;p&gt;More problematically, they are not easily generalisable. We had to make statements about the specifics of the expression rather than using simpler constructs. The problem &lt;strong&gt;A.8&lt;/strong&gt; from the same chapter asks to show that $x^5 - 4x^4 + 3x^3 - x^2 + 3x - 4 \geq 0$ implies $x \geq 0$. The same term-by-term negativity proof works for it. The direct ones don&#39;t.&lt;/p&gt;&#xA;&lt;p&gt;The examples might seem a little bit simplistic, but I assure the method is more broadly applicable! This method is very applicable to problems that are significantly more complex. Consider the following:&lt;/p&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;&lt;strong&gt;Ω.ω&lt;/strong&gt; Show that for all positive reals $x, y \in \mathbb{R}^+$ the following holds...&lt;/p&gt;&#xA;&lt;p&gt;$$x^{x+y(x+y)} y^{y+x(y+x)} &amp;gt; 9765625^{11} \Rightarrow x &amp;gt; 5 \text{ or } y &amp;gt; 5$$&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;p&gt;The problem above is of my own construction and while, yes, it was manufactured to prove me right, but you can probably imagine that kind of problem appearing on a entry-level Olympiad. This is your call to stop and try solving it for yourself, both with and without the contrapositive trick.&lt;/p&gt;&#xA;&lt;hr&gt;&#xA;&lt;p&gt;Gave it a try? Great, keep reading!&lt;/p&gt;&#xA;&lt;p&gt;Laying some ground work, notice that $9765625$ is $5^{10}$, so $9765625^{11} = (5^{10})^{11} = 5^{110}$. Also, for brevity, let us denote the expression on the left as $f(x, y)$.&lt;/p&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;&lt;strong&gt;Ω.ω&lt;/strong&gt; &lt;em&gt;Direct Proof.&lt;/em&gt;&lt;/p&gt;&#xA;&lt;p&gt;We can see that $f(x, y)$ is symmetric. Then, without loss of generality consider that $x \geq y &amp;gt; 0$. Consider the following expression, a direct statement of our assumed antecedent:&lt;/p&gt;&#xA;&lt;p&gt;$$x^{x+y(x+y)}y^{y+x(y+x)} &amp;gt; 5^{110}$$&lt;/p&gt;&#xA;&lt;p&gt;Notice how because of our relative bound $x \geq y$, it is also true that...&lt;/p&gt;&#xA;&lt;p&gt;$$x^{[x+y(x+y)] + [y+x(y+x)]} \geq x^{x+y(x+y)}y^{y+x(y+x)}$$&lt;/p&gt;&#xA;&lt;p&gt;Through some algebraic manipulation, the left term can be simplified to the following with a new term $u$...&lt;/p&gt;&#xA;&lt;p&gt;$$x^{(x+y)^2 + x + y} = x^{u^2 + u} = x^{u(u + 1)}$$&lt;/p&gt;&#xA;&lt;p&gt;Now consider the following mutation of the original statement...&lt;/p&gt;&#xA;&lt;p&gt;$$x^{u(u + 1)} &amp;gt; 5^{110}$$&lt;/p&gt;&#xA;&lt;p&gt;We can look at the relationship between the two exponents. Since $x^{u(u+1)} &amp;gt; 5^{110} &amp;gt; 1$, the base must be $x &amp;gt; 1$, so a bigger exponent only makes the power bigger. From $y \leq x$ we get $u \leq 2x$, hence $u(u+1) \leq 2x(2x+1)$ and...&lt;/p&gt;&#xA;&lt;p&gt;$$x^{2x(2x+1)} \geq x^{u(u+1)} &amp;gt; 5^{110} = 5^{2 \cdot 5(2 \cdot 5 + 1)}$$&lt;/p&gt;&#xA;&lt;p&gt;The function $g(t) = t^{2t(2t+1)}$ is strictly increasing for $t &amp;gt; 1$, since both its base and its exponent grow. So $g(x) &amp;gt; g(5)$ forces $x &amp;gt; 5$. $\blacksquare$&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;&lt;strong&gt;Ω.ω&lt;/strong&gt; &lt;em&gt;Contrapositive Proof.&lt;/em&gt;&lt;/p&gt;&#xA;&lt;p&gt;Assume $x \leq 5$ and $y \leq 5$. Our goal is to show that $x^{x+y(x+y)} y^{y+x(y+x)} \leq 9765625^{11}$.&lt;/p&gt;&#xA;&lt;p&gt;Both exponents are positive, and a positive power of a smaller base is smaller, so we can swap each base for $5$...&lt;/p&gt;&#xA;&lt;p&gt;$$x^{x+y(x+y)} y^{y+x(y+x)} \leq 5^{x+y(x+y)} 5^{y+x(y+x)} = 5^{(x+y)^2 + (x+y)}$$&lt;/p&gt;&#xA;&lt;p&gt;With $x + y \leq 10$ the exponent is at most $10^2 + 10 = 110$, so the whole thing is at most $5^{110} = 9765625^{11}$. $\blacksquare$&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;p&gt;The direct proof needs more work, evidently. Of course, one could probably engineer a simpler version of the proof and I don&#39;t have a systematic way to verify that a contrapositive proof is &lt;em&gt;always&lt;/em&gt; shorter. The next time you are dealing with a messy antecedant, think of the contrapositive.&lt;/p&gt;&#xA;&lt;hr&gt;&#xA;&lt;div class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;&#xA;&lt;hr&gt;&#xA;&lt;ol&gt;&#xA;&lt;li id=&#34;fn:1&#34;&gt;&#xA;&lt;p&gt;This blogpost assumes excluded middle. However, you can also notice how the direct proof for Ω.ω is actually constructive. You can choose $\mathbb{Q}^+$ in place of $\mathbb{R}^+$ and the proof should read identically.&amp;#160;&lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;/div&gt;&#xA;</content>
    </entry>
    <entry xml:lang="en">
        <title>Why &#34;AI&#34; feels exhausting</title>
        <published>2026-07-19T00:00:00+00:00</published>
        <updated>2026-07-19T00:00:00+00:00</updated>
        <link rel="alternate" type="text/html" href="https://ktnlvr.dev/philosophy/why-ai-feels-so-exhausting/"/>
        <id>https://ktnlvr.dev/philosophy/why-ai-feels-so-exhausting/</id>
        <content type="html" xml:base="https://ktnlvr.dev/philosophy/why-ai-feels-so-exhausting/">&lt;p&gt;In 1984 Ken Thompson wrote a seminal 3-pager, detailing how an undetectable backdoor can be injected into programs, the first &amp;quot;Trojan horse.&amp;quot; He demonstrated a method that undermined the security of the existing and future computer infrastructure, by injecting information into the binary of a bootstrapping compiler, resulting in a program that does not express a potentially malicious behavior in its source code.&lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt; And mostly, not a single engineer gave a flying fuck.&lt;/p&gt;&#xA;&lt;p&gt;Why? Because the only complete solution eliminating doubt would be rewriting the entire technological stack from scratch. It is very possible that a vulnerability exists at a lower level than your &amp;quot;rewriting frontier.&amp;quot; Doubting every single layer, from the source code that you yourself typed in, to a specific AND-gate in the HDMI video controller of your display is just too damn exhausting to really care. Sustaining the doubt is too taxing for ordinary life.&lt;/p&gt;&#xA;&lt;p&gt;Now, with &amp;quot;AI&amp;quot; we have a method capable of swiftly producing outputs that might have taken a competent engineering team a week of effort and generating functioning code at record speed. You work with it, review the result and verify that the result is reasonable. Oftentimes it is not. Be it an issue of training, or architecture, or the number of weights, or Mercury&#39;s retrograde, the outcome is wrong and it is your problem – you lose sleep, money, reputation and bear the cost of the model&#39;s error. The error can also be villainously subtle, buried as a highly non-local action at a distance side effect somewhere halfway across the product. As the mistakes become more elegantly obscured, the final outcome demands more and more scrutiny.&lt;/p&gt;&#xA;&lt;p&gt;When you last made a small script for your class, it is very possible that you only scrutinized your own ability to write code and the understanding of the subject matter. Sometimes, there is a compiler bug. The experience of finding one is similar to running full speed into a perfectly clear glass door. Like with Thompson&#39;s backdoor, you still need to draw the line of trust somewhere. When the trust is violated it can induce an almost psychotic experience, as the person is exposed to the magnitude of trust they were expending. The only protection from this shock is placing the trust in the hands of the compiler developers – not reading the final binary, not engaging with the possibility unless no other options remain. With &amp;quot;AI&amp;quot; we can&#39;t help but see the constant failure demanding attention. Every success becomes a potential glass wall.&lt;/p&gt;&#xA;&lt;p&gt;As this kind of work becomes more prevalent, skepticism becomes the value you deliver as an engineer. For tasks where sufficient training data is available technology has reached a state where a final value can be delivered autonomously. However, as expectations rise the to-be-verified output demands outrageous amounts of humility and reflection. The job of an engineer in the AI age becomes glass wall testing. You move through probably empty space with possibly see through obstacles and make sure it is actually empty. That does not sound great at all.&lt;/p&gt;&#xA;&lt;p&gt;This is probably not a phase. Compilers stopped needing supervision because they became consistent, standardized and deterministic. They got boring, in a good way. A compiler bug gets patched and stays patched; a model gets replaced by a different one and this is how they get improved. The ground keeps shifting under whatever trust would have otherwise built. Being a glass wall hunter isn&#39;t an additional responsibility, it has become the job. It has become your job.&lt;/p&gt;&#xA;&lt;div class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;&#xA;&lt;hr&gt;&#xA;&lt;ol&gt;&#xA;&lt;li id=&#34;fn:1&#34;&gt;&#xA;&lt;p&gt;&lt;a href=&#34;https://www.cs.cmu.edu/~rdriley/487/papers/Thompson_1984_ReflectionsonTrustingTrust.pdf&#34;&gt;Thompson 1984, &amp;quot;Reflections on Trusting Trust&amp;quot;&lt;/a&gt;&amp;#160;&lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;/div&gt;&#xA;</content>
    </entry>
    <entry xml:lang="en">
        <title>Random Matrices with Determinant 1</title>
        <published>2026-05-25T00:00:00+00:00</published>
        <updated>2026-05-25T00:00:00+00:00</updated>
        <link rel="alternate" type="text/html" href="https://ktnlvr.dev/maths/random-matrices-with-determinant-1/"/>
        <id>https://ktnlvr.dev/maths/random-matrices-with-determinant-1/</id>
        <content type="html" xml:base="https://ktnlvr.dev/maths/random-matrices-with-determinant-1/">&lt;p&gt;I was through Stinson&#39;s Cryptography when I saw this. A matrix $A \in \mathbb{Z}^{n\times n}$ is invertible in $\mathbb{Z}_m$ iff $\gcd{(\det A, m)} = 1 \text{ mod } m$. That&#39;s a really cool fact! I wanted to generate some matrices that are invertible in $\mathbb{Z}_m$. How?&lt;/p&gt;&#xA;&lt;p&gt;There is always the trivial solution. We can just do $1_{n \times n}$, but that&#39;s boring.&lt;/p&gt;&#xA;&lt;p&gt;$$&#xA;\det \begin{bmatrix}&#xA;1 &amp;amp; 0 &amp;amp; \cdots &amp;amp; 0 \\&#xA;0 &amp;amp; 1 &amp;amp; \cdots &amp;amp; 0 \\&#xA;\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\&#xA;0 &amp;amp; 0 &amp;amp; \cdots &amp;amp; 1&#xA;\end{bmatrix}&#xA;= \det (1_{n \times n}) = 1&#xA;$$&lt;/p&gt;&#xA;&lt;p&gt;A common approach is generating a random matrix and then checking it for invertibility. Napkin math shows that if the determinant is uniformly distributed the chance of getting an invertible matrix is $\frac{1}{m}$. That&#39;s unfortunate.&lt;/p&gt;&#xA;&lt;p&gt;In the rest of this blogpost I describe my approach that tries to generate the matrices sufficiently-uniformly in a deterministic way.&lt;/p&gt;&#xA;&lt;p&gt;As the goal we will assume an adversarial model of the determinant calculator: we must not leave behind any obvious traces of the method used that will allow checking if the $\det(A) = 1$ any faster than for an arbitrary matrix.&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;diagonal-entries&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#diagonal-entries&#34; aria-label=&#34;diagonal-entries&#34;&gt;❦ &lt;/a&gt;Diagonal Entries&lt;/h2&gt;&#xA;&lt;p&gt;First, let&#39;s try to modify the trivial solution to be more random. For that we require that $\text{tr}(A) = a_{1,1} \times a_{2,2} \times \cdots \times a_{n,n} = 1 \text{ mod } m$. That&#39;s relatively trivial.&lt;/p&gt;&#xA;&lt;p&gt;In the case for $n = 1$ we only have one choice: $a_{1,1} = 1 \text{ mod } m$. Notice that we can&#39;t do a greedy algorithm from here. That would fill the diagonal with zeros, so we must be clever.&lt;/p&gt;&#xA;&lt;p&gt;The only way to produce $1$ by multiplication is through $aa^{-1} \equiv 1$. Thus, we can split the diagonal product into two values: $a^{-1}$ and $a$. The choice of $a^{-1}$ is uniquely defined by $a$, so we need to allocate at least one entry on the diagonal to be $a^{-1}$. The rest can be random.&lt;/p&gt;&#xA;&lt;p&gt;$$&#xA;\det \begin{bmatrix}&#xA;\ast &amp;amp; 0 &amp;amp; \cdots &amp;amp; 0 \\&#xA;0 &amp;amp; a^{-1} &amp;amp; \cdots &amp;amp; 0 \\&#xA;\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\&#xA;0 &amp;amp; 0 &amp;amp; \cdots &amp;amp; \ast&#xA;\end{bmatrix}&#xA;= \det (aa^{-1}) = 1&#xA;$$&lt;/p&gt;&#xA;&lt;p&gt;Now let&#39;s consider $a$, the product of the other diagonal values. To compute $a$ we must make sure that it&#39;s not divisible by $m$. If it was, then $a\text{ mod } m = 0$, so $a^{-1}$ does not exist. To avoid that, none of the terms in the product must be multiples of $m$. That is already given, since $m \notin \mathbb{Z}_m$.&lt;/p&gt;&#xA;&lt;p&gt;At the same time, for $a^{-1}$ to exist we require $\gcd(a, m) = 1$. That is easy to check for: we just factorize $m = p_1^{q_1} p_2^{q_2}\cdots p_k^{q_k}$ and for every generated $a$ we check that $a \text{ mod } p \neq 0$. We can ignore the $q$s entirely, since if $a \text{ mod } p^q = 0$, then $a \text{ mod } p = 0$.&lt;/p&gt;&#xA;&lt;p&gt;By using all of the above we produce a diagonal that has determinant $1$. Similar approach can be applied to find a diagonal with an arbitrary determinant $d$.&lt;/p&gt;&#xA;&lt;p&gt;$$&#xA;\det \begin{bmatrix}&#xA;25 &amp;amp; 0 &amp;amp; 0 &amp;amp; 0 \\&#xA;0 &amp;amp; 7 &amp;amp; 0 &amp;amp; 0 \\&#xA;0 &amp;amp; 0 &amp;amp; 17 &amp;amp; 0 \\&#xA;0 &amp;amp; 0 &amp;amp; 0 &amp;amp; 19 \\&#xA;\end{bmatrix}&#xA;\text{mod } 26 = 25 \times 7 \times 17 \times 19\text{ mod } 26 = 56525 \text{ mod } {26} = 1 \text{  } \blacksquare&#xA;$$&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;off-diagonal-entries&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#off-diagonal-entries&#34; aria-label=&#34;off-diagonal-entries&#34;&gt;❦ &lt;/a&gt;Off-Diagonal Entries&lt;/h2&gt;&#xA;&lt;p&gt;Now, being able to produce a diagonal is lovely, but we want a full matrix. For that we may extend it in a way that preserves our original determinant. Luckily, determinants are distributive over addition, so starting with our diagonal matrix $A$, we can extend it as $\det(A) = 1 \cdot \det(A) \cdot 1 = \det(\ast)\det(A)\det(\ast)$.&lt;/p&gt;&#xA;&lt;p&gt;A reasonable candidate is any unitriangular matrix. A unitriangular matrix is triangular, but also the diagonal is all $1$s. If the diagonal is composed of $1$ and the other entries will be multiplied awsay by $0$s, the determinant is $1$. This is true of both lower and upper unitriangular matrices.&lt;/p&gt;&#xA;&lt;p&gt;$$&#xA;\det(L) = \det \begin{bmatrix}&#xA;1 &amp;amp; 0 &amp;amp; \cdots &amp;amp; 0 \\&#xA;\ast &amp;amp; 1 &amp;amp; \cdots &amp;amp; 0 \\&#xA;\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\&#xA;\ast &amp;amp; \ast &amp;amp; \cdots &amp;amp; 1&#xA;\end{bmatrix} = \begin{aligned}&#xA;&amp;amp; (1 \times \cdots \times 1) +\\&#xA;&amp;amp; + (0 \times \cdots) +\\&#xA;&amp;amp; + \cdots\end{aligned} = 1&#xA;$$&lt;/p&gt;&#xA;&lt;p&gt;$$&#xA;\det(U) = \det \begin{bmatrix}&#xA;1 &amp;amp; \ast &amp;amp; \cdots &amp;amp; \ast \\&#xA;0 &amp;amp; 1 &amp;amp; \cdots &amp;amp; \ast \\&#xA;\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\&#xA;0 &amp;amp; 0 &amp;amp; \cdots &amp;amp; 1&#xA;\end{bmatrix} = \cdots = 1&#xA;$$&lt;/p&gt;&#xA;&lt;p&gt;We can fill the $\ast$ entries using any random number generator, they do not influence the determinant at all. This procedure can be repeated to generate both the lower and upper-triangular matrices that when combined with the diagonal $A$ still produces the correct value:&lt;/p&gt;&#xA;&lt;p&gt;$$\det(LAU) = \det(L)\det(A)\det(U) = 1 \times \det(A) \times 1 = \det(A) = 1 \text{ mod } m$$&lt;/p&gt;&#xA;&lt;p&gt;Problematically, with this approach the final value is still determined by the diagonal product of the final matrix. To fix that we can apply the same principle as we did in $A$, so we keep the determinant $1 \text{ mod } m$ while the diagonal is only ones!&lt;/p&gt;&#xA;&lt;p&gt;To remedy this, we can avoid using the intermediate $A$ matrix entirely! We can replace the diagonals of the unitriangular matrices with the same algorithm that we used to generate the diagonal for $A$.&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;conclusion&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#conclusion&#34; aria-label=&#34;conclusion&#34;&gt;❦ &lt;/a&gt;Conclusion&lt;/h2&gt;&#xA;&lt;p&gt;We intended to generate a random matrix in $\mathbb{Z}_n$ and we did it! Yay! 🎉&lt;/p&gt;&#xA;&lt;p&gt;Interestingly, while the algorithm is functional and quite effective, there is a better way of doing it, presented in the followup: &lt;a href=&#34;/rmwd1u&#34;&gt;Random Matrix with Determinant 1, Uniformly&lt;/a&gt;.&lt;/p&gt;&#xA;</content>
    </entry>
    <entry xml:lang="en">
        <title>Quantifier Order Matters</title>
        <published>2026-01-18T00:00:00+00:00</published>
        <updated>2026-01-18T00:00:00+00:00</updated>
        <link rel="alternate" type="text/html" href="https://ktnlvr.dev/maths/quantifier-order-matters/"/>
        <id>https://ktnlvr.dev/maths/quantifier-order-matters/</id>
        <content type="html" xml:base="https://ktnlvr.dev/maths/quantifier-order-matters/">&lt;p&gt;This is more of an aside than a proper thoughtpiece, but I never noticed that the relative order of quantifiers can matter. Consider the two definitions below:&lt;/p&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;We say that a function $f$ is &lt;strong&gt;continous&lt;/strong&gt; on $A$ when...&#xA;$$\forall x\in A\;\forall \epsilon &amp;gt; 0 \; \exists \delta &amp;gt; 0 : \forall z \in A\; |x - z| &amp;lt; \delta \Rightarrow |f(x) - f(z)|&amp;lt; \epsilon$$&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;We say that a function $f$ is &lt;strong&gt;uniformly continous&lt;/strong&gt; on $A$ when...&#xA;$$\forall \epsilon &amp;gt; 0 \; \exists \delta &amp;gt; 0 \; : \forall x,z \in A \; |x - z| &amp;lt; \delta \Rightarrow |f(x) - f(z)| &amp;lt; \epsilon$$&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;p&gt;They are remarkably similar! The only real difference is that in &lt;em&gt;continous&lt;/em&gt; functions $x \in A$ is quantified before the $\delta$ is. Nonetheless, the two definitions mean different things. Why?&lt;/p&gt;&#xA;&lt;p&gt;Well, the order of existential quantifiers defines how they can depend on eachother. Since for &lt;em&gt;continous&lt;/em&gt; functions we quantify $\forall x, \forall \epsilon$ before we quantify $\exists \delta$, it is possible and expected that $\delta(x, \epsilon)$, while for &lt;em&gt;uniformly continous&lt;/em&gt; functions only $\forall \epsilon$ is quantified and so $\delta(\epsilon)$.&lt;/p&gt;&#xA;&lt;p&gt;In turn, this gives a stronger notion of &lt;em&gt;continuity&lt;/em&gt;, since any &lt;em&gt;uniformly continous&lt;/em&gt; function is also continous with $\delta(x, \epsilon) = \delta(\epsilon)$.&lt;/p&gt;&#xA;&lt;p&gt;To give a specific example, $\frac{1}{x}$ is &lt;em&gt;continous&lt;/em&gt; but not &lt;em&gt;uniformly continous&lt;/em&gt; on $(0, 1)$.&lt;/p&gt;&#xA;&lt;hr&gt;&#xA;&lt;p&gt;In some logical systems you have an analogous property - &lt;em&gt;restricted exchange&lt;/em&gt;. In a logic with a restricted exchange you can&#39;t change the order of the premises, so $A \rightarrow B \rightarrow C$ is not the same as $B \rightarrow A \rightarrow C$.&lt;/p&gt;&#xA;&lt;p&gt;We can see an example of that using &lt;em&gt;Linear Logic&lt;/em&gt; and Rust&#39;s borrow-checker semantics. We can introduce a $\multimap$ symbol. It means a &lt;em&gt;temporal entailment&lt;/em&gt;, so if the thing on the left is true, we can also have the thing on the right by giving up the thing on the left.&lt;/p&gt;&#xA;&lt;p&gt;Consider the following piece of Rust code relative to &lt;code&gt;x&lt;/code&gt;:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;let mut x = 5;    // O: own x&#xA;let y = &amp;amp;mut x;   // B: borrow x mutably&#xA;*y &amp;#43;= 1;&#xA;drop(y);          // E: end borrow, regain ownership of x&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;In linear logic, this can be written as $\text O \multimap (\text B \multimap \text E)$. Notice how because of the temporal dependence between &lt;em&gt;owning an object&lt;/em&gt; and &lt;em&gt;borrowing it&lt;/em&gt; we lose the ability to exchange the order of the first two premises. We can&#39;t borrow an object &lt;em&gt;and then&lt;/em&gt; own it!&lt;/p&gt;&#xA;&lt;p&gt;However, this is clearly not the case in the following snippet:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;let mut p = 0;    // O(p): own p&#xA;let mut q = 1;    // O(q): own q&#xA;let p_m = &amp;amp;mut p; // B(p): borrow p mutably&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;This can again be formalised as $\text O(p) \multimap \text O (q) \multimap \text B (p)$. Here the relative order of $\text O(p)$ and $\text O(q)$ can be exchanged since they are somehow independent, they do not commute.&lt;/p&gt;&#xA;&lt;p&gt;The voices in my head tell me that this is &lt;a href=&#34;https://ncatlab.org/nlab/show/effect+algebra&#34;&gt;&lt;em&gt;effect algebras&lt;/em&gt; and &lt;em&gt;partial commutative monoids&lt;/em&gt;&lt;/a&gt;, but that&#39;s just the voices.&lt;/p&gt;&#xA;&lt;hr&gt;&#xA;&lt;p&gt;How is this relevant? Well, consider what is being done when actually proving. You are being asked to give a specific $\epsilon$ and $\delta$ such that the conditions are satisfied.&lt;/p&gt;&#xA;&lt;p&gt;Much like in the Rust examples you are creating some temporary &lt;em&gt;resource&lt;/em&gt;, the value of the quantified variable, that might be dependent on the variables previously quantified.&lt;/p&gt;&#xA;&lt;p&gt;Naturally, because of the dependence on the previous result this is similar to computation. We can weaken the strict requirements of the linear logic system and use &lt;em&gt;Intuitionistic Logic&lt;/em&gt; instead. That logic allows continued reuse of the assumption on the left, much like once a value for the first existing variable is set we may reuse it any amount of times.&lt;/p&gt;&#xA;&lt;p&gt;Are existential and universal quantifiers isomorphic to Intuitionistic Logic? I don&#39;t know! Open question.&lt;/p&gt;&#xA;&lt;p&gt;To some extent I can say that the isomorphism wouldn&#39;t always go the other way around. In the case of &lt;em&gt;continous&lt;/em&gt; and &lt;em&gt;uniformly continous&lt;/em&gt; functions we use a values of $\epsilon$ and $\delta$ in the expression directly. The advantage of classical logic is that you can prove that things exist without actually showing how they are obtained.&lt;/p&gt;&#xA;&lt;p&gt;Overall I think this is a nice piece of maths that deserves a little more love and attention.&lt;/p&gt;&#xA;</content>
    </entry>
    <entry xml:lang="en">
        <title>Operator Overloading Bad</title>
        <published>2025-05-04T00:00:00+00:00</published>
        <updated>2025-05-04T00:00:00+00:00</updated>
        <link rel="alternate" type="text/html" href="https://ktnlvr.dev/computing/operator-overloading-bad/"/>
        <id>https://ktnlvr.dev/computing/operator-overloading-bad/</id>
        <content type="html" xml:base="https://ktnlvr.dev/computing/operator-overloading-bad/">&lt;p&gt;&lt;a href=&#34;https://odin-lang.org/docs/faq/#why-does-odin-not-have-operator-overloading&#34;&gt;Enough&lt;/a&gt; &lt;a href=&#34;https://cafe.elharo.com/programming/operator-overloading-considered-harmful/&#34;&gt;has been&lt;/a&gt; &lt;a href=&#34;https://pages.cs.wisc.edu/~fischer/cs538.s08/lectures/Lecture08.4up.pdf&#34;&gt;said&lt;/a&gt; about how bad Operator Overloading is. This is the specific case that turned me into its hater.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# timestamp = &amp;#34;2025-05-04T20:12:14,000&amp;#43;03:00&amp;#34;&#xA;date, time = timestamp.split(&amp;#39;T&amp;#39;)&#xA;&#xA;Y, M, D = date.split(&amp;#34;-&amp;#34;)&#xA;h, m, *_ = time.split(&amp;#34;:&amp;#34;)&#xA;Y %= 2000&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Ignore how bad of an idea it is to do this little error handling. Granted, the error is partially faciliated by Python&#39;s lack of static typing. Cudos to one who have already spotted the mistake. For those who haven&#39;t, here&#39;s the error message:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;TypeError: format string didn&amp;#39;t convert all arguments&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;This should raise some eyebrows. It is honest and it being a &lt;code&gt;TypeError&lt;/code&gt; is expected, after all the variables are strings. Anyone who used Python before 3.6 should already know whats up&lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;&#xA;&lt;p&gt;Before syntax like &lt;code&gt;f&amp;quot;{Y}-{M}-{D}&amp;quot;&lt;/code&gt; was possible, you would have to write something like &lt;code&gt;&amp;quot;%d-%02d-%02d&amp;quot; % (Y, M, D)&lt;/code&gt;. This syntax has lingered on from &lt;strong&gt;Python 1&lt;/strong&gt;, released in &lt;strong&gt;1991&lt;/strong&gt;. I guess the percentage symbol for the formatting operator is in reference to the percentage symbol prepending the value placeholders, which are in turn a holdover from C, from &lt;strong&gt;1973&lt;/strong&gt;.&lt;/p&gt;&#xA;&lt;p&gt;Knowing that a feature from &lt;em&gt;50 years ago&lt;/em&gt; caused a bug in my code instills in me some sort of primordial honor.&lt;/p&gt;&#xA;&lt;p&gt;In the snippet from above the &lt;code&gt;%&lt;/code&gt; is actually trying to do an in-place formatting of the string, trying to find a value placeholder to insert the &lt;code&gt;2000&lt;/code&gt; into. This could have been prevented if a simple &lt;code&gt;.format&lt;/code&gt; was preferred.&lt;/p&gt;&#xA;&lt;p&gt;Please, unless you are doing math, collections or Haskell, don&#39;t use operator overloading.&lt;/p&gt;&#xA;&lt;div class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;&#xA;&lt;hr&gt;&#xA;&lt;ol&gt;&#xA;&lt;li id=&#34;fn:1&#34;&gt;&#xA;&lt;p&gt;Bit of a spoiler, but f-strings were introduced in &lt;a href=&#34;https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals&#34;&gt;Python 3.6&lt;/a&gt;.&amp;#160;&lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;/div&gt;&#xA;</content>
    </entry>
    <entry xml:lang="en">
        <title>Random List Sampling is Hard</title>
        <published>2025-04-23T00:00:00+00:00</published>
        <updated>2025-04-23T00:00:00+00:00</updated>
        <link rel="alternate" type="text/html" href="https://ktnlvr.dev/computing/random-list-sampling-is-hard/"/>
        <id>https://ktnlvr.dev/computing/random-list-sampling-is-hard/</id>
        <content type="html" xml:base="https://ktnlvr.dev/computing/random-list-sampling-is-hard/">&lt;p&gt;Non-trivial probabilities aren&#39;t that difficult compared to other computer science concepts, especially if you are an experienced programmer and/or probabilist.&lt;/p&gt;&#xA;&lt;p&gt;However, that doesn&#39;t mean that rookie programmers fresh out of a bootcamp have same easy time as you, the Nutella-titled codeforces enjoyer. This is a case of one of my students who shall remain undisclosed.&lt;/p&gt;&#xA;&lt;p&gt;It happened when as an exercise I suggested rewriting Python&#39;s &lt;code&gt;random&lt;/code&gt; builtin module entirely from scratch. Said student had to learn about pseudo-randomness in computers and I assumed they would have a great time with it.&lt;/p&gt;&#xA;&lt;p&gt;All was good and dandy until the deal came to implementing &lt;code&gt;random.choices&lt;/code&gt;&lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;. The function takes in a list of items, a list of weights and some integer &lt;code&gt;k&lt;/code&gt;. The original definition also includes optional cumulative weights, but they can be derived from weights if/when necessary.&lt;/p&gt;&#xA;&lt;p&gt;The function itself samples the item list with replacement &lt;code&gt;k&lt;/code&gt; times, such that likelyhood of each element being drawn is determined by its respective weight: the higher the weight, the higher the probability. In the end you get a list of length &lt;code&gt;k&lt;/code&gt; with elements randomly chosen from the supplied list, where elements with higher weights were more likely to get picked.&lt;/p&gt;&#xA;&lt;p&gt;Imagine a familiar situation from your probabilities class: you are given a magical bag, such that it contains balls: 3 blue, 1 brown and none of other colour. In this case, the amount of balls in the bag is their weights. The magical property of said bag is that it manifests a same-coloured ball when one is taken out, so were you to pull out a blue one, another blue one would appear. Notice how this property of the bag maintains the probabilities of each type of ball to get pulled out &lt;em&gt;no matter how many times we pull&lt;/em&gt; (sample the bag). We can imagine pulling 4 balls out of the bag in code:&lt;/p&gt;&#xA;&lt;p&gt;We use weights instead of probabilities because they are more universal. Besides, probabilities can be derived from weights: if we sum up all the weights and divide each individual weight by the total, we get a probability out! Beyond that, probabilities are weights themselves, with an imposed requirement of summing up to 1. Why use something more restrictive if the maths works just fine in the general case?&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;from random import choices&#xA;&#xA;k = 4&#xA;chosen: list[str] = choices([&amp;#39;blue&amp;#39;, &amp;#39;brown&amp;#39;, &amp;#39;other&amp;#39;], [3, 1, 0], k=k)&#xA;assert len(chosen) == k&#xA;&#xA;(first, *_) = ls&#xA;&#xA;print(first) # P(first=&amp;#39;blue&amp;#39;)  = 3 / (3 &amp;#43; 1 &amp;#43; 0) = 3/4&#xA;             # P(first=&amp;#39;brown&amp;#39;) = 1 / (3 &amp;#43; 1 &amp;#43; 0) = 1/4&#xA;             # P(first=&amp;#39;other&amp;#39;) = 0 / (3 &amp;#43; 1 &amp;#43; 0) = 0&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;You can already figure out that drawing with replacement simplifies the task to repeating calls of the &amp;quot;weighted draw&amp;quot; function &lt;code&gt;k&lt;/code&gt; times, so let us focus our attention on that. We will take for granted a function &lt;code&gt;randint(a, b)&lt;/code&gt; that returns a perfect uniformly distributed random number in range &lt;code&gt;[a; b)&lt;/code&gt; or &lt;code&gt;[a; b[&lt;/code&gt;. Also drop all error handling, since it will only clutter the code and it doesn&#39;t change the algorithm much. Based on what was said before, the &lt;code&gt;choices&lt;/code&gt; function may look like this:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;def choices(population: list, weights: list, k: int) -&amp;gt; list:&#xA;    return [weighted_draw(population, weights) for _ in range(k)]&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;The most naive implementation of &lt;code&gt;weighted_draw&lt;/code&gt; would look something like the following:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;def naive_weighted_draw(population: list, weights: list):&#xA;    weighted_population = []&#xA;    for p, w in zip(population, weights):&#xA;        weighted_population.extend([p] * int(round(w)))&#xA;    return weighted_population[randint(0, len(weighted_population) - 1)]&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;This approach is very direct and clearly didn&#39;t take much effort. We can assume that the implementation is drawn from the previous experience of implementing a function that samples a random element uniformly. It... works. Not in the nearly best way, not in all cases (e.g. fractional weights), the memory usage can be through the roof in some edgecases, but it limps. Not remotely good enough for production. There is a better candidate.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;def random_01():&#xA;    return randint(0, 2**32) / 2**32&#xA;&#xA;def repeated_sampling_weighted_draw(population: list, weights: list):&#xA;    total_w = sum(weights)&#xA;    probabilities = list(map(lambda w: w / total_w, weights))&#xA;    while True:&#xA;        for e, p in zip(population, probabilities):&#xA;            if random_01() &amp;lt;= p:&#xA;                return e&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;In this case we keep sampling the population elements one by one with their respective probabilities. If none of the elements matched first time we just keep sampling. Potentially forever.&lt;/p&gt;&#xA;&lt;p&gt;The &amp;quot;pathological case&amp;quot; comes to haunt us when there is a lot of different items, since then the probability of one specific item to be drawn becomes minuscule, which in turn increases the runtimes dramatically, making the average runtime &lt;em&gt;O(1 / P)&lt;/em&gt;, where &lt;em&gt;P&lt;/em&gt; is the average probability of an item to be picked.&lt;/p&gt;&#xA;&lt;p&gt;This is known in the biz as &amp;quot;rejection sampling&amp;quot; and there is no shortage of articles discussing all the troubles with it.&lt;/p&gt;&#xA;&lt;p&gt;Despite the &lt;em&gt;exceptionally poor&lt;/em&gt; theoretical worst-case runtime of &lt;em&gt;O(∞)&lt;/em&gt;&lt;sup id=&#34;fnref:2&#34;&gt;&lt;a href=&#34;#fn:2&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;2&lt;/a&gt;&lt;/sup&gt; this implementation might seem more sensible, though it raises an interesting question: are the earlier elements in the list more likely to occur when sampling?&lt;/p&gt;&#xA;&lt;p&gt;An answer might be intuitive, yet it&#39;s not the same to everyone. The probability doesn&#39;t gets skewed, shame. The probability for any noninitial element to occur is exactly the probability of it to occur on its own &lt;em&gt;given that&lt;/em&gt; none of the previous elements were chosen.&lt;/p&gt;&#xA;&lt;p&gt;If you expand it according to Bayes&#39; Theorem&lt;sup id=&#34;fnref:3&#34;&gt;&lt;a href=&#34;#fn:3&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;3&lt;/a&gt;&lt;/sup&gt; we get that the probability is in fact independent, so this algorithm is nontheless sound. Anyhow, what gives? This didn&#39;t save us from &lt;em&gt;O(∞)&lt;/em&gt;, so we are safe to forget this solution.&lt;/p&gt;&#xA;&lt;p&gt;The following implementation employs cumulative weights and is most certainly the reason why this function in Python&#39;s standard library accepts them (cumulative weights) in the first place.&lt;/p&gt;&#xA;&lt;p&gt;For those unfamiliar with the concept, they are a prefix sum of the weights by definition, so some weight + all the weights preceding it. The cumulative weights are monotonously increasing which makes them a perfect subject for bisection.&lt;/p&gt;&#xA;&lt;p&gt;Now we pick a random number from 0 to the maximum cumulative weight and search for its respective population element using the cumulative weights, bingo! With all knowledge gathered, final implementation is as follows:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;from itertools import accumulate&#xA;from bisect import bisect&#xA;&#xA;def choices(population: list, weights: list, k: int) -&amp;gt; list:&#xA;    return [weighted_draw(population, weights) for _ in range(k)]&#xA;&#xA;def cumulative_weighted_draw(population: list, weights: list):&#xA;    cum_weights = list(accumulate(weights))&#xA;    max_cum_weight = cum_weights[-1]&#xA;    index = bisect(cum_weights, random_01() * cum_weights[-1])&#xA;    return population[index]&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Funnily enough, this is the exact solution CPython went with &lt;sup id=&#34;fnref:4&#34;&gt;&lt;a href=&#34;#fn:4&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;4&lt;/a&gt;&lt;/sup&gt;. That makes me happy.&lt;/p&gt;&#xA;&lt;p&gt;Of course this implementation can be unfolded without using any of the standard functions.&lt;/p&gt;&#xA;&lt;p&gt;The overall runtime is &lt;em&gt;O(k logN)&lt;/em&gt;, which is rather good: &lt;em&gt;k&lt;/em&gt; for each choice and &lt;em&gt;logN&lt;/em&gt; for bisecting a list of &lt;em&gt;N&lt;/em&gt; elements. If you don&#39;t trust the handwavy maths consider the chart below. The functions were ran 1M times, with numbers 0 to 24 each having the weight of itself, so the larger numbers are more likely to occur. As expected, the correlation coefficient is almost 1 with number 0 never appearing due to it&#39;s weight being, well, zero.&lt;/p&gt;&#xA;&lt;p&gt;&lt;img src=&#34;/random-list-sampling-is-hard.png&#34; alt=&#34;The chart generated by Matplotlib showing almost statistically-significant correlation of all the implementations&#34;&gt;&#xA;&lt;/p&gt;&#xA;&lt;p&gt;Weighted random sampling is tricky. It tempts you to write an intuitive implementation that hides inefficiencies or subtle bias. But with a little probability theory and the clever use of cumulative weights, we can achieve both correctness and performance.&lt;/p&gt;&#xA;&lt;div class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;&#xA;&lt;hr&gt;&#xA;&lt;ol&gt;&#xA;&lt;li id=&#34;fn:1&#34;&gt;&#xA;&lt;p&gt;&lt;a href=&#34;https://docs.python.org/3/library/random.html#random.choices&#34;&gt;&lt;code&gt;random.choices&lt;/code&gt;&lt;/a&gt; in Python&#39;s official documentation.&amp;#160;&lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li id=&#34;fn:2&#34;&gt;&#xA;&lt;p&gt;Actually, using Big-O to talk about probabilistic algorithms in general is a bad idea. They might just not terminate.&amp;#160;&lt;a href=&#34;#fnref:2&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li id=&#34;fn:3&#34;&gt;&#xA;&lt;p&gt;&lt;a href=&#34;https://www.youtube.com/watch?v=HZGCoVF3YvM&#34;&gt;Here&lt;/a&gt; is wonderful explanation of the Bayes&#39; Theorem by 3b1b.&amp;#160;&lt;a href=&#34;#fnref:3&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li id=&#34;fn:4&#34;&gt;&#xA;&lt;p&gt;&lt;a href=&#34;https://github.com/python/cpython/blob/46957091433bfa097d7ea19b177bf42a52412f2d/Lib/random.py#L454-L489&#34;&gt;Link&lt;/a&gt; to CPython&#39;s implementation of &lt;code&gt;random.choices&lt;/code&gt; as of writing this post.&amp;#160;&lt;a href=&#34;#fnref:4&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;/div&gt;&#xA;</content>
    </entry>
    <entry xml:lang="en">
        <title>Turing-Complete Module Exports</title>
        <published>2024-09-13T00:00:00+00:00</published>
        <updated>2024-09-13T00:00:00+00:00</updated>
        <link rel="alternate" type="text/html" href="https://ktnlvr.dev/computing/turing-complete-module-exports/"/>
        <id>https://ktnlvr.dev/computing/turing-complete-module-exports/</id>
        <content type="html" xml:base="https://ktnlvr.dev/computing/turing-complete-module-exports/">&lt;p&gt;&lt;img src=&#34;/computing/turing-complete-module-exports.png&#34; alt=&#34;&#34; title=&#34;John La Farge. Sheep Porcupine Island.&#34;&gt;&#xA;&lt;/p&gt;&#xA;&lt;p&gt;Everything good in dynamically typed programming languages are things, not yet well expressed by the statically typed ones. I will die fighting on that hill. Here I examine a particular case of behaviour, that is only allowed in dynamic languages&lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;. In allows you express a quirky nature of how imports can work in language.&lt;/p&gt;&#xA;&lt;p&gt;By the end of this article you will understand why dunder methods are my favourite small feature in Python and how you can use them in your projects to make your APIs more verbose.&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;introduction&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#introduction&#34; aria-label=&#34;introduction&#34;&gt;❦ &lt;/a&gt;Introduction&lt;/h2&gt;&#xA;&lt;p&gt;All the examples below will be in Python&lt;sup id=&#34;fnref:2&#34;&gt;&lt;a href=&#34;#fn:2&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;. I did my best to avoid verbose syntax and Python-specific semantics. One rule to keep in mind: &lt;em&gt;everything is an object&lt;/em&gt;. This principle means that everything has members: methods and fields.&lt;/p&gt;&#xA;&lt;p&gt;This includes everything that would be a primitive in other languages: &lt;code&gt;int&lt;/code&gt;, &lt;code&gt;bool&lt;/code&gt;, no one is safe!&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# `.bit_count()` is a method on integers&#xA;# that counts the 1s in the binary&#xA;# representation of the number&#xA;# 13 is 0b1101&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; (13).bit_count()&#xA;3&lt;/code&gt;&lt;/pre&gt;&#xA;&#xA;&lt;h3 id=&#34;dunder-methods&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#dunder-methods&#34; aria-label=&#34;dunder-methods&#34;&gt;❦ &lt;/a&gt;Dunder Methods&lt;/h3&gt;&#xA;&lt;p&gt;If a method starts and ends with two underscores, it is called a dunder (&lt;strong&gt;d&lt;/strong&gt;ouble &lt;strong&gt;under&lt;/strong&gt;score) method. Dunder methods are reserved by the language to implement operator overloading&lt;sup id=&#34;fnref:3&#34;&gt;&lt;a href=&#34;#fn:3&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;, constructors and type coercion and other semantic-level fluff.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;class Vec2:&#xA;    # Python requires an explicit &amp;#39;this&amp;#39;&#xA;    # usually denoted `self` for all&#xA;    # member functions&#xA;&#xA;    def __init__(self, x, y):&#xA;        self.x = x&#xA;        self.y = y&#xA;&#xA;    def __add__(lhs, rhs):&#xA;        return Vec2(lhs.x &amp;#43; rhs.x, lhs.y &amp;#43; rhs.y)&#xA;&#xA;a = Vec2(2, 3)&#xA;b = Vec2(8, 9)&#xA;c = a &amp;#43; b&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; c.x&#xA;10&#xA;&amp;gt;&amp;gt;&amp;gt; c.y&#xA;12&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;One of the things that can be overloaded is member access. If the method &lt;code&gt;__getattr__&lt;/code&gt; (get attribute) is defined, it will be called whenever an &lt;em&gt;unset&lt;/em&gt; member is accessed. For instance, &lt;code&gt;x.y&lt;/code&gt; is equivalent to using &lt;code&gt;x.__getattr__(y)&lt;/code&gt; if no member &lt;code&gt;y&lt;/code&gt; exists on the object &lt;code&gt;x&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;class DictionaryObject:&#xA;    # supply the dictionary in the constructor&#xA;    def __init__(self, dictionary: dict):&#xA;        self.dictionary = dictionary&#xA;&#xA;    # called when a member is accessed&#xA;    def __getattr__(self, value: str) -&amp;gt; str:&#xA;        return self.dictionary[value]&#xA;&#xA;dictionary = {&amp;#39;foo&amp;#39;: &amp;#39;bar&amp;#39;}&#xA;do = DictionaryObject(dictionary)&#xA;&#xA;# accessing a set property&#xA;&amp;gt;&amp;gt;&amp;gt; do.dictionary is dictionary&#xA;True&#xA;&#xA;# accessing the value for &amp;#39;foo&amp;#39;&#xA;# directly with a method call&#xA;&amp;gt;&amp;gt;&amp;gt; do.__getattr__(&amp;#39;foo&amp;#39;)&#xA;&amp;#39;bar&amp;#39;&#xA;&#xA;# `.foo` is unset&#xA;# falling back to __getattr__&#xA;# key &amp;#39;foo&amp;#39; resolved from the dictionary&#xA;&amp;gt;&amp;gt;&amp;gt; do.foo&#xA;&amp;#39;bar&amp;#39;&#xA;&#xA;# `.qua` is unset&#xA;# falling back to __getattr__&#xA;# key &amp;#39;qua&amp;#39; is not in the dictionary&#xA;&amp;gt;&amp;gt;&amp;gt; do.qua&#xA;KeyError: &amp;#39;qua&amp;#39;&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Make sure to understand what exactly is happening at every step in the snippet above. Since &lt;em&gt;everything is an object&lt;/em&gt;, this method can be attached to anything! Notice, how the call to &lt;code&gt;self.dictionary&lt;/code&gt; does not go through &lt;code&gt;__getattr__&lt;/code&gt;, because the field is defined on the object in the constructor.&lt;/p&gt;&#xA;&lt;p&gt;This might seem like an awful idea. Usually, property access is an operation that doesn&#39;t mutate anything. It might feel like nothing is sacred anymore and you can&#39;t trust a single line of code. That is to some extent true, you can realistically even hide a full-on database call behind the &lt;code&gt;__getattr__&lt;/code&gt;. However, being horryfing doesn&#39;t stop it from being useful.&lt;/p&gt;&#xA;&lt;p&gt;Firstly, you can imagine the example above to be a good tool when dealing with JSON data. Sure, a typed model class is better, but it just always is. If that&#39;s your only point, go use a type-checked language. For everyone who stayed,&#xA;the class above was deemed useful enough to &lt;a href=&#34;https://docs.python.org/3/library/types.html#types.SimpleNamespace&#34;&gt;be in the standard library&lt;/a&gt;!&lt;/p&gt;&#xA;&lt;p&gt;Secondly, notice how higher this function is to all of the other code. Programming is defining functions, metaprogramming is defining functions that define functions, what is this? This is where the dynamism really shines, we unlocked &lt;em&gt;hyperprogramming&lt;/em&gt; potential through simple language semantics and a first-order function.&lt;/p&gt;&#xA;&lt;p&gt;Thirdly, keep reading, let me cook.&lt;/p&gt;&#xA;&#xA;&lt;h3 id=&#34;pythonic-modules&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#pythonic-modules&#34; aria-label=&#34;pythonic-modules&#34;&gt;❦ &lt;/a&gt;Pythonic Modules&lt;/h3&gt;&#xA;&lt;p&gt;A Python module is a file containing definitions. All defined objects inside a module are given to it as methods. It&#39;s an object too after all!&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; import math&#xA;&amp;gt;&amp;gt;&amp;gt; type(math)&#xA;&amp;lt;class &amp;#39;module&amp;#39;&amp;gt;&#xA;&amp;gt;&amp;gt;&amp;gt; math.sin(0)&#xA;0.0&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;When something is defined at module-level, it is attached to the module as a member. This is the main tool of code reuse.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# example.py&#xA;def sqr(x):&#xA;    return x * x&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; import example&#xA;&amp;gt;&amp;gt;&amp;gt; maths.sqr(4)&#xA;16&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Module definitions can also be imported in two ways with basically the same underlying implementation.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# crude, but valid&#xA;import math&#xA;sin = math.sin&#xA;cos = math.cos&#xA;&#xA;# idiomatic&#xA;from math import sin, cos&#xA;from example import sqr&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Since this syntax counts as member access, it can be overriden with the dunder method like in any other object. This is where the magic lies.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# counter.py&#xA;i = 0&#xA;def __iadd__(self, rhs):&#xA;    global i&#xA;    i &amp;#43;= rhs&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; import counter&#xA;&amp;gt;&amp;gt;&amp;gt; counter.__iadd__(2)&#xA;&amp;gt;&amp;gt;&amp;gt; counter &amp;#43;= 4&#xA;&amp;gt;&amp;gt;&amp;gt; counter.i&#xA;6&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Notice how &lt;code&gt;counter&lt;/code&gt; is not imported from anywhere in particular, instead the import brings the &lt;code&gt;counter&lt;/code&gt; object itself into the scope and calls the &lt;code&gt;__iadd__&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;When &lt;code&gt;__getattr__(...)&lt;/code&gt; is defined at module level, it gets attached to the module as a method upon import. Hence, it is possible to overwrite the attribute access in a module.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# attrprinter.py&#xA;&#xA;def __getattr__(self, value):&#xA;    print(f&amp;#34;Access to {value}!&amp;#34;)&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; from attrprinter import LionKing, alphabet, _&#xA;Access to LionKing!&#xA;Access to alphabet!&#xA;Access to _!&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;The &lt;code&gt;__getattr__&lt;/code&gt; is called for each item imported from the module, that&#39;s wonderful!&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;use-cases&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#use-cases&#34; aria-label=&#34;use-cases&#34;&gt;❦ &lt;/a&gt;Use Cases&lt;/h2&gt;&#xA;&lt;p&gt;It makes sense to see how that would work on a practical example. Luckily, a wild occurance of that is in a crate that inspired me to write about this in the first place.&lt;/p&gt;&#xA;&#xA;&lt;h3 id=&#34;htbuilder&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#htbuilder&#34; aria-label=&#34;htbuilder&#34;&gt;❦ &lt;/a&gt;HTBuilder&lt;/h3&gt;&#xA;&lt;p&gt;&lt;a href=&#34;https://github.com/tvst/htbuilder&#34;&gt;HTBuilder&lt;/a&gt; (&amp;quot;HT&amp;quot; for &amp;quot;Hyper Text&amp;quot;) is a library of functions for declaratively constructing a string representation of an HTML DOM. You can already imagine how this will go.Instead of listing all the possible tags, it just exports a factory function:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;def __getattr__(tag):&#xA;    return HtmlTag(tag)&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;This allows using the library as follows:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; from htbuilder import b, i&#xA;&amp;gt;&amp;gt;&amp;gt; hello = b(i(&amp;#34;Hello, world!&amp;#34;))&#xA;&amp;lt;htbuilder.HtmlElement object at 0x7ffb63da9650&amp;gt;&#xA;&amp;gt;&amp;gt;&amp;gt; str(hello)&#xA;&amp;#39;&amp;lt;b&amp;gt;&amp;lt;i&amp;gt;Hello, world!&amp;lt;/i&amp;gt;&amp;lt;/b&amp;gt;&amp;#39;&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;The tags don&#39;t have to be listed in the file&lt;sup id=&#34;fnref:4&#34;&gt;&lt;a href=&#34;#fn:4&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;4&lt;/a&gt;&lt;/sup&gt;, hence it comes with builtin support for all the HTML tags you could want.&lt;/p&gt;&#xA;&lt;p&gt;Going further, this type of usage in no way restricts&lt;/p&gt;&#xA;&lt;p&gt;This type of trick is &lt;em&gt;impossible&lt;/em&gt; to encode in any modern statically typed language known to me. The semantics themselves are not too complicated, but treating modules as &lt;em&gt;first class values&lt;/em&gt; is not very popular.&lt;/p&gt;&#xA;&#xA;&lt;h3 id=&#34;sympy&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#sympy&#34; aria-label=&#34;sympy&#34;&gt;❦ &lt;/a&gt;SymPy&lt;/h3&gt;&#xA;&lt;p&gt;&lt;a href=&#34;https://sympy.org&#34;&gt;SymPy&lt;/a&gt; is a symbolic mathematics library written entirely in Python. it supports everything from basic algebra to calculus and linear algebra, as well as (with some extension) a plethora of &lt;a href=&#34;https://github.com/bjodah/chempy&#34; title=&#34;Chemistry&#34;&gt;other&lt;/a&gt; &lt;a href=&#34;https://galgebra.readthedocs.io&#34; title=&#34;Geometric Algebra&#34;&gt;research&lt;/a&gt; &lt;a href=&#34;https://lcapy.readthedocs.io/&#34; title=&#34;Linear... circuit analysis? I&#39;m not even sure what that is&#34;&gt;areas&lt;/a&gt;.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; from sympy import symbols, sin, cos, pi&#xA;&amp;gt;&amp;gt;&amp;gt; x, y, z = symbols(&amp;#34;x, y, z&amp;#34;)&#xA;&amp;gt;&amp;gt;&amp;gt; expr = cos(x) &amp;#43; sin(y)&#xA;&amp;gt;&amp;gt;&amp;gt; expr.subs(cos(x), y)&#xA;z &amp;#43; sin(y)&#xA;&amp;gt;&amp;gt;&amp;gt; expr.subs(x, 0).subs(y, pi / 2)&#xA;2&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Wonderful stuff. However, pay close attention to the &lt;code&gt;symbols(...)&lt;/code&gt; call. Doesn&#39;t it seem cumbersome to you? Wouldn&#39;t it be wonderful to do something like...&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; from sympy.abc import x, y, z&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Well, behold! You can already do that, the &lt;a href=&#34;https://docs.sympy.org/latest/modules/abc.html&#34;&gt;&lt;code&gt;abc&lt;/code&gt;&lt;/a&gt; module is specifically designed to do that, it houses all the usual variables you could need.&lt;/p&gt;&#xA;&lt;p&gt;One possible issue is that variables under the same name might get mixed up. For instance, if we have a parabola and hooke&#39;s law meet in the same expression we got problems:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# hooke.py&#xA;from sympy.abc import x, k&#xA;F = -k * x&#xA;&#xA;# parabola.py&#xA;from sympy.abc import x&#xA;y = x**2 - x - 1&#xA;&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; from hooke import F, x as hookes_x, k&#xA;&amp;gt;&amp;gt;&amp;gt; from parabola import y, x as pararbola_x&#xA;&#xA;# different x refer to the same object&#xA;# that can&amp;#39;t be good&#xA;&amp;gt;&amp;gt;&amp;gt; hookes_x is parabola_x&#xA;True&#xA;&#xA;# J will be our placeholder to see all the substituted locations&#xA;&amp;gt;&amp;gt; from sympy.abc import J&#xA;&#xA;# work = force * displacement&#xA;&amp;gt;&amp;gt;&amp;gt; W = F * y&#xA;&amp;gt;&amp;gt;&amp;gt; W&#xA;(-k*x) * (x**2 - x - 1)&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; W.subs(hookes_x, J)&#xA;(-J*k) * (J**2 - J - 1)&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Oh no! Two variables that were irrelevant got mixed up! Notice how importing them from appropriate modules didn&#39;t change anything. To be fair, the same issue could arise on sheet of paper. After all, you are using the same symbol to mean two different things.&lt;/p&gt;&#xA;&lt;p&gt;In their &amp;quot;&lt;a href=&#34;https://docs.sympy.org/latest/explanation/best-practices.html&#34;&gt;Best Practices&lt;/a&gt;&amp;quot; section SymPy themselves recommend using the aforementioned &lt;code&gt;symbols&lt;/code&gt; function to define symbols:&lt;/p&gt;&#xA;&lt;blockquote&gt;&#xA;&lt;p&gt;Define symbols with &lt;a href=&#34;https://docs.sympy.org/latest/modules/core.html#sympy.core.symbol.symbols&#34;&gt;&lt;code&gt;symbols()&lt;/code&gt;&lt;/a&gt; or &lt;a href=&#34;https://docs.sympy.org/latest/modules/core.html#sympy.core.symbol.Symbol&#34;&gt;&lt;code&gt;Symbol()&lt;/code&gt;&lt;/a&gt;. The &lt;code&gt;symbols()&lt;/code&gt; function is the most convenient way to create symbols. It supports creating one or more symbols at once. (&lt;a href=&#34;https://docs.sympy.org/latest/explanation/best-practices.html#defining-symbols&#34;&gt;source&lt;/a&gt;)&lt;/p&gt;&#xA;&lt;/blockquote&gt;&#xA;&lt;p&gt;As of writing this, the implementation defines all the symbols inside &lt;code&gt;abc&lt;/code&gt; &lt;a href=&#34;https://github.com/sympy/sympy/blob/9f8a5d50c675a9a677f873180b1b067cff7ce4ba/sympy/abc.py#L64-L80&#34;&gt;manually&lt;/a&gt;. Beyond that, it also contains a note describing the easiest way &lt;em&gt;to avoid typos&lt;/em&gt; in the variable names! I wish there was a way of avoiding that.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;def __getattr__(self, var: str):&#xA;    return Symbol(var)&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;The snippet above effectively cuts out circa 30% of the code in the file without breaking compatibility. Lovely, isn&#39;t it?&lt;/p&gt;&#xA;&#xA;&lt;h3 id=&#34;opengl-loaders&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#opengl-loaders&#34; aria-label=&#34;opengl-loaders&#34;&gt;❦ &lt;/a&gt;OpenGL Loaders&lt;/h3&gt;&#xA;&lt;p&gt;I&#39;m sorry C, you never had real imports anyway&lt;sup id=&#34;fnref:5&#34;&gt;&lt;a href=&#34;#fn:5&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;5&lt;/a&gt;&lt;/sup&gt;. Let&#39;s hope we can &lt;del&gt;macro&lt;/del&gt; template this one away.&lt;/p&gt;&#xA;&#xA;&lt;h3 id=&#34;pint&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#pint&#34; aria-label=&#34;pint&#34;&gt;❦ &lt;/a&gt;Pint&lt;/h3&gt;&#xA;&lt;p&gt;&lt;a href=&#34;https://pint.readthedocs.io/&#34;&gt;Pint&lt;/a&gt; brings units to Python. Meters, newtons, gigaparsecs per hertz - you can have them all! The definitions are loaded from a text file, which serves as a single source of truth for the unit conversion. It allows you to make all your computations unitful:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; import pint&#xA;&amp;gt;&amp;gt;&amp;gt; ureg = pint.UnitRegistry()&#xA;&amp;gt;&amp;gt;&amp;gt; 3 * ureg.meter &amp;#43; 4 * ureg.cm&#xA;&amp;lt;Quantity(3.04, &amp;#39;meter&amp;#39;)&amp;gt;&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Much like the aforementioned text file, the &lt;code&gt;UnitRegistry&lt;/code&gt; is supposed to function as a single source of truth across the system. Unlike in the case with SymPy, we want all the exports of the same name to refer to the same value and the solution is basically already there.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# pint.py&#xA;GLOBAL_REGISTRY = UnitRegistry()&#xA;&#xA;def __getattr__(self, unit):&#xA;    if unit in GLOBAL_REGISTRY:&#xA;        return getattr(GLOBAL_REGISTRY, unit)&#xA;    else:&#xA;        raise KeyError(...)&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; from pint import m, cm&#xA;&amp;gt;&amp;gt;&amp;gt; 3 * m &amp;#43; 4 * cm&#xA;&amp;lt;Quantity(3.04, &amp;#39;meter&amp;#39;)&amp;gt;&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Hence the source of truth is shared across all possible imports of the module, including all the libraries. A global registry surely would&#39;ve saved the &lt;a href=&#34;https://science.nasa.gov/mission/mars-climate-orbiter/&#34;&gt;Mars Climate Orbiter&lt;/a&gt;.&lt;/p&gt;&#xA;&lt;p&gt;We can go even further. Since the main feature of the SI prefixes is that they can be prepended to anything, we can automatically resolve them for any possible unit that we might invent.&lt;/p&gt;&#xA;&lt;p&gt;This is where problems begin: &lt;code&gt;from pint import meter&lt;/code&gt; means that we are importing &lt;code&gt;meter&lt;/code&gt; the unit or a &amp;quot;mega&amp;quot; &lt;code&gt;eter&lt;/code&gt;, whatever that is? Luckily, since all the conversions are defined in a file they are fetched from there whenever needed.&lt;/p&gt;&#xA;&lt;p&gt;All in all, hopefully this one is rather obvious. Although, the next one is more curious.&lt;/p&gt;&#xA;&#xA;&lt;h3 id=&#34;expressjs&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#expressjs&#34; aria-label=&#34;expressjs&#34;&gt;❦ &lt;/a&gt;Express.js&lt;/h3&gt;&#xA;&lt;p&gt;JS? I thought this post only uses Python.&lt;/p&gt;&#xA;&lt;p&gt;This example is a bit unusual compared to the previous ones, mainly because it uses a different dunder method.&#xA;While I&#39;m sure that this specific mechanism appears in some Python packages too, I don&#39;t know any specific examples of that. Besides, the syntax is rather transparent.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;import express from &amp;#39;express&amp;#39;;&#xA;import { createClient } from &amp;#39;redis&amp;#39;;&#xA;&#xA;let app = express();&#xA;let db = createClient();&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Woah! Or not, it may not jump at you the first time you look at this. Let me rewrite this one in Python.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;import express&#xA;from redis import create_client&#xA;&#xA;app = express()&#xA;db = create_client()&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Woah indeed! For &lt;code&gt;express&lt;/code&gt; we are calling the module itself, instead of importing functions from it like for &lt;code&gt;redis&lt;/code&gt;. Queer. This is a bit different from overriding the attribute getter, but the magic words are almost the same. The Pythonic version would use the &lt;code&gt;__call__&lt;/code&gt; dunder method. It defines the semantics of calling the object. &lt;em&gt;Everything is an object&lt;/em&gt;, remember? Even functions.&lt;/p&gt;&#xA;&lt;p&gt;We can replicate this in terms of a classic web framework &lt;code&gt;Flask&lt;/code&gt;. The code below simply proxies all the arguments to the module to&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# flask.py&#xA;__call__ = Flask&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; import flask&#xA;&amp;gt;&amp;gt;&amp;gt; app = flask()&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;This approach could be cool for libraries that export a single obvious function. Even though they are rare, maybe someone still makes those&lt;sup id=&#34;fnref:6&#34;&gt;&lt;a href=&#34;#fn:6&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;6&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;import leftpad&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; leftpad(&amp;#34;123&amp;#34;, 5, &amp;#34;0&amp;#34;)&#xA;&amp;#34;00123&amp;#34;&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;The main counterpoint to this approach is that it&#39;s not very verbose. It&#39;s not immediately evident where one could go to check how &lt;code&gt;leftpad&lt;/code&gt; works. This example is on the worse side, since it will leave all the developers unfamiliar with this feature very stumped.&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;import-all&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#import-all&#34; aria-label=&#34;import-all&#34;&gt;❦ &lt;/a&gt;Import All&lt;/h2&gt;&#xA;&lt;p&gt;There is one aspect of this feature that is important to note: importing everything from the module. Python has a syntax for importing all items from a module. Most languages contain something similar. You can imagine how that is useful.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# dump all functions into the global scope&#xA;from math import *&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Understandably, using &lt;code&gt;__getattr__&lt;/code&gt; primes an invisible footgun. How will it behave when importing everything? Surely the function itself will be re-exported and cause trouble. Luckily, this behaviour is far smarter than it looks.&lt;/p&gt;&#xA;&lt;p&gt;Since importing stuff from a module brings it into the scope, the imports of the imported module are brought along with it. As a result, using &lt;code&gt;import *&lt;/code&gt; all over the place clutters the scope, hence it is discouraged.&#xA;However, &lt;code&gt;__all__&lt;/code&gt; is a variable that can hold the list of all items that should be actually imported when a wildcard is used.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# mega.py&#xA;public = 1&#xA;private = 2&#xA;&#xA;__all__ = [&amp;#39;public&amp;#39;]&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; from mega import *&#xA;&amp;gt;&amp;gt;&amp;gt; public&#xA;1&#xA;&amp;gt;&amp;gt;&amp;gt; private&#xA;NameError: name &amp;#39;private&amp;#39; is not defined&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;How do you think &lt;code&gt;__all__&lt;/code&gt; is accessed? Using all the same &lt;code&gt;__getattr__&lt;/code&gt;. If &lt;code&gt;__all__&lt;/code&gt; is explicitly defined, &lt;code&gt;__getatrr__&lt;/code&gt; will not be called for it. In the other case, the &lt;code&gt;__all__&lt;/code&gt; will have to be returned by the &lt;code&gt;__getattr__&lt;/code&gt;. For libraries like HTBuilder it is sensible to export common values like &lt;code&gt;span&lt;/code&gt; and &lt;code&gt;div&lt;/code&gt; respectively.&lt;/p&gt;&#xA;&lt;pre&gt;&lt;code&gt;# htbuilder.py&#xA;def __getattr__(self, tag):&#xA;    return HtmlTag(tag)&#xA;&#xA;__all__ = [&amp;#39;span&amp;#39;, &amp;#39;div&amp;#39;]&#xA;&#xA;&amp;gt;&amp;gt;&amp;gt; from htbuilder import *&#xA;&amp;gt;&amp;gt;&amp;gt; hello = div(span(&amp;#34;Hello, world!&amp;#34;))&#xA;&amp;lt;htbuilder.HtmlElement object at 0x9ffb69420fadb0&amp;gt;&#xA;&amp;gt;&amp;gt;&amp;gt; str(hello)&#xA;&amp;#39;&amp;lt;div&amp;gt;&amp;lt;span&amp;gt;Hello, world!&amp;lt;/span&amp;gt;&amp;lt;/div&amp;gt;&amp;#39;&#xA;&amp;gt;&amp;gt;&amp;gt; b(hello)&#xA;NameError: name &amp;#39;b&amp;#39; is not defined&lt;/code&gt;&lt;/pre&gt;&#xA;&lt;p&gt;Like all dunder methods, &lt;code&gt;__all__&lt;/code&gt; should be used with consideration.&lt;/p&gt;&#xA;&#xA;&lt;h2 id=&#34;conclusion&#34;&gt;&lt;a class=&#34;anchor&#34; href=&#34;#conclusion&#34; aria-label=&#34;conclusion&#34;&gt;❦ &lt;/a&gt;Conclusion&lt;/h2&gt;&#xA;&lt;p&gt;One aspect I deliberetly left untouched is typing and compilation. I am not qualified to try and express that concept in any type system. Hopefully, someone can expand on this in the future. Hopefully, that can be a more educated me.&lt;/p&gt;&#xA;&lt;p&gt;All in all, this feature is useful in very niche circumstances, but there are 2 general usecases for it:&lt;/p&gt;&#xA;&lt;ol&gt;&#xA;&lt;li&gt;You are exporting named things, like the variables in SymPy or the units in Pint.&lt;/li&gt;&#xA;&lt;li&gt;You have a singleton object that should be the same everywhere, like a function or the units in Pint.&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;p&gt;For everything else, use something else.&lt;/p&gt;&#xA;&lt;p&gt;&lt;em&gt;P.S. If you are a Python developer and happen to have applied that in your own projects, feel free to share.&lt;/em&gt;&lt;/p&gt;&#xA;&lt;hr&gt;&#xA;&lt;div class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;&#xA;&lt;hr&gt;&#xA;&lt;ol&gt;&#xA;&lt;li id=&#34;fn:1&#34;&gt;&#xA;&lt;p&gt;The line between interpreted and compiled languages is virtually non-existent. When talking about dynamic languages I mean JavaScript, Python, Lisp. They allow encoding language sematics during program&#39;s runtime. This is facilitated by JavaScript&#39;s flexible notion of an object, Python&#39;s dunder methods and the entirety of Lisp.&amp;#160;&lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li id=&#34;fn:2&#34;&gt;&#xA;&lt;p&gt;The specific version used is Python ≥ 3.7, since it is the earliest version that allows the sourcery that I&#39;ll be demonstrating.&amp;#160;&lt;a href=&#34;#fnref:2&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li id=&#34;fn:3&#34;&gt;&#xA;&lt;p&gt;This type of overloading is very useful when it comes to representing mathematical objects. It can be argued that it&#39;s bad practice, since you never know how the underyling operation is used, but that is really only noticeable in severe cases like the &lt;a href=&#34;https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt&#34;&gt;&lt;code&gt;std::ostream::operator&amp;lt;&amp;lt;&lt;/code&gt;&lt;/a&gt; in C++.&amp;#160;&lt;a href=&#34;#fnref:3&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li id=&#34;fn:4&#34;&gt;&#xA;&lt;p&gt;Well, it defines a list of &lt;code&gt;EMPTY_ELEMENTS&lt;/code&gt; for self-closing elements like &lt;code&gt;&amp;lt;br&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;img&amp;gt;&lt;/code&gt;, but they are basically exceptional.&amp;#160;&lt;a href=&#34;#fnref:4&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li id=&#34;fn:5&#34;&gt;&#xA;&lt;p&gt;&lt;a href=&#34;https://en.cppreference.com/w/cpp/identifier_with_special_meaning/import&#34; title=&#34;import keyword in the C++ standard&#34;&gt;no way.&lt;/a&gt;&amp;#160;&lt;a href=&#34;#fnref:5&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li id=&#34;fn:6&#34;&gt;&#xA;&lt;p&gt;One JavaScript package containing only 11 lines of code once brought down a good chunk of the ecosystem for a short period of time. More on &lt;a href=&#34;https://en.wikipedia.org/wiki/Npm_left-pad_incident&#34;&gt;Wikipedia&lt;/a&gt;.&amp;#160;&lt;a href=&#34;#fnref:6&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;/div&gt;&#xA;</content>
    </entry>
</feed>
