<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Xuanqiang Angelo Huang&#39;s Blog</title>
    <link>https://flecart.github.io/</link>
    <description>Recent content on Xuanqiang Angelo Huang&#39;s Blog</description>
    <image>
      <title>Xuanqiang Angelo Huang&#39;s Blog</title>
      <url>https://flecart.github.io/og-image.jpg</url>
      <link>https://flecart.github.io/og-image.jpg</link>
    </image>
    <generator>Next.js</generator>
    <language>en</language>
    <lastBuildDate>Tue, 03 Nov 2026 00:00:00 GMT</lastBuildDate>
    <atom:link href="https://flecart.github.io/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>I Tried to Break Weight Programming</title>
      <link>https://flecart.github.io/posts/2026-11-03-i-tried-to-break-weight-programming/</link>
      <pubDate>Tue, 03 Nov 2026 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/posts/2026-11-03-i-tried-to-break-weight-programming/</guid>
      <description>I replicate a viral post on weight programming, add complexity analysis and share some opinions.</description>
      <content:encoded><![CDATA[<h2 id="tldr">TL;DR<a class="anchor" aria-hidden="true" hidden href="#tldr">#</a></h2>
<ul>
<li>I replicated some of the results in the Weight Programming blog post, and I can confirm that Astra really does it. Opus 5.5 can do it too, but at maximum effort it spends its whole 128k-token output budget thinking and never answers.
<ul>
<li>I show how Astra got a high score on Breakout: looking at its reasoning makes the answer quite simple. It <em>compiles</em> simple code into the weights! That's complex, but unsurprising, given that these models can already write thousands of lines of code.</li>
</ul>
</li>
<li>I then made decoding harder by hiding the network behind stated operations that the model had to undo to make the same inference. Its reasoning tokens grew as the operations required more work. When decoding was impossible, as with SHA-256, the model simply refused to try to invert it.
<ul>
<li>I relate this behaviour to ways of measuring intrinsic task complexity.</li>
</ul>
</li>
<li>I share all the code and the replication results in <a href="https://github.com/flecart/weight-programming">https://github.com/flecart/weight-programming</a>.</li>
</ul>
<p>When I first read the viral <a href="https://rikiyat.github.io/blog/weight-space-programming/">work from the MIT lab</a>, I was highly skeptical. It made no sense to me that frontier LLMs were able to work directly on the weights. I was confident that, at some point, things would break. This blog post is the story of me trying to break weight programming (and failing). However, I have reasons to believe I found a limitation connected to some notion of the task's complexity.</p>
<p>The post is structured as follows: In <a href="#finding-one-its-compiling-a-10-line-program">section 1</a> I analyze the programs that Astra has developed and show that it was a simple compilation. Still novel that such model was able to, but given their recent ability in reverse engineering, it was not so surprising. In <a href="#finding-two-models-still-have-complexity-limits">section 2</a> I explore the possible limits that every transformer has, which extends to the limits of weight-programming. It has the interesting implication that in many cases weight updating is a simpler process than expected. If this is true, it might indicate that other algorithms than backprop would be more effective at updating weights in a targeted manner, driven by similar complexity arguments. In <a href="#finding-three-models-self-verify-in-chain-of-thought">section 3</a>, I discuss two known papers in the field that discuss inherent limits of transformers. It appears that the assumptions of those papers are slightly wrong, allowing the model to circumvent much of the stated limitations. It's also interesting to see how frontier models make use of their reasoning context to circumvent such problems. I close with some random musings in the <a href="#conclusions">conclusions</a> :).</p>
<h2 id="finding-one-its-compiling-a-10-line-program">Finding one: it's compiling a 10-line program<a class="anchor" aria-hidden="true" hidden href="#finding-one-its-compiling-a-10-line-program">#</a></h2>
<p>By analyzing the summary of the reasoning trace and the designed weights, we can understand what was really done under the hood to create a "weight program" that performs so well.</p>
<p>Astra's design statement, in full:</p>
<blockquote>
<p><em>"The first layer computes four landing-position errors and two direction indicators. Descending predictions include wall reflections; ascending predictions anticipate the earliest possible brick bounce and revise as the ball climbs. Early positioning favors preserving horizontal direction to sweep through bricks; near the bottom, either valid catch column is accepted. The second layer gates left/right decisions, choosing no-op when positioned correctly."</em></p>
</blockquote>
<p>This is indeed an ad-hoc solution to a problem that can be understood in other, more familiar terms. Looking around in the literature, one can also find that the technique is known <a href="http://arxiv.org/abs/2301.05062">Lindner et al. 2023</a>. Still, it is surprising to see a model able to do it in a one-shot manner.</p>
<p>With some work, Claude showed that the whole program being implemented is just a very simple Python program:</p>
<pre><code class="language-python">d = direction(trail)                       # units 4-5: two sign bits
gap = landing_column[d][ball] - paddle     # units 0-3: one lookup table per direction
if gap &#x3C; 0: move_left()                    # layer 2 (AND) + output (OR)
elif gap > 0: move_right()
else: stay()
</code></pre>
<p>See <a href="#appendix-d-decoding-astras-program">#Appendix D Decoding Astra's Program</a>. Such a compilation would have taken a human several hours to tune by hand. But in the end, it doesn't seem that spectacular.
Since the games that were studied are easy to handle, this specific experiment is not that surprising.
What we can actually study is the <em>level of complexity</em> a program needs to reach before it breaks, even for frontier LLMs like Astra.</p>
<h2 id="finding-two-models-still-have-complexity-limits">Finding two: Models still have Complexity Limits<a class="anchor" aria-hidden="true" hidden href="#finding-two-models-still-have-complexity-limits">#</a></h2>
<p>Writing weights is compiling, an activity very similar to writing pure machine code. The only difference is that, instead of writing registers or memory, this machine code writes numbers directly. It makes me wonder how computation as we know it today would have developed if we had worked with such hardware instead of the Von Neumann architecture. Some decisions in history have a long influence.</p>
<p>The idea in this section is to find the level of complexity at which recognizing the game becomes out of reach.</p>
<p>From my experience with my supervisor's past work on simulating programs with LLMs <a href="http://arxiv.org/abs/2502.03568">Malfa et al. 2025</a>, I knew there would be a point where the behaviour starts to break. I attacked the most obvious direction I could find.</p>
<p>I asked my agent to obfuscate the weights given to the model for recognition, using some standard operations. Clearly, the model should not classify pure noise-looking input as an Atari game. But if there was a pattern, it should be retrieved. And it looks like <strong>the cost of computing the inverse function raised the reasoning length</strong>, in a precise and understandable manner. That is, <strong>reasoning grew sub-exponentially</strong>, at about the square root of the operations needed (<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4831em;"></span><span class="mrel">≈</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.0663em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord text"><span class="mord">operations</span></span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8719em;"><span style="top:-3.1208em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">0.45</span></span></span></span></span></span></span></span></span></span></span></span>):</p>
<p></p><figure class="center">
<img src="/images/posts/ops_vs_reasoning_tokens.png" style="width: 100%" alt="ops_vs_reasoning_tokens" title="ops_vs_reasoning_tokens">
<figcaption><p style="text-align:center;"> Reasoning tokens per reply against the operations needed to decode one shuffled row. Blue: rules Astra runs 'by hand'; Line is median and band is 50% of replies. Effort climbs to 64 rounds, then collapses at 128 rounds and for SHA-256 (orange), where Astra gives up. Hollow dots are wrong answers.</p></figcaption>
</figure>
In addition, it seemed to follow a procedure during decoding, so in this case it correctly understood the <em>decompilation</em> process for a known forward process. See <a href="#how-astra-reads-the-weights-and-what-did-not-break-it">#How Astra reads the weights, and what did not break it</a>. We can also use this data as a proxy to fit some "expected complexity", for example compiling the Atari code into the neural network took 16k tokens, about the same of 120 shuffle rounds.<p></p>
<p>Similar phenomena were seen in <a href="http://arxiv.org/abs/2506.06941">Shojaee et al. 2025</a>. But the evidence here suggests that Astra is simply effective at not spending many tokens when its accuracy is likely to drop. I test other similar scenarios in <a href="#c12-faith-and-fate-arithmetic-tasks">#C.1.2 Faith-and-Fate arithmetic tasks</a>.</p>
<p>I tried to analyze the complexity of such tasks, and it seems connected to classical Minimum Description Length principles. The computational difficulty analyzed in <a href="https://openreview.net/forum?id=Fkckkr3ya8">Dziri et al. 2023</a> seems much less relevant.
See the table in <a href="#what-predicts-the-effort">#What predicts the effort</a>.</p>
<h2 id="finding-three-models-self-verify-in-chain-of-thought">Finding three: Models Self-Verify in Chain of Thought<a class="anchor" aria-hidden="true" hidden href="#finding-three-models-self-verify-in-chain-of-thought">#</a></h2>
<p>One claim that Faith and Fate <a href="https://openreview.net/forum?id=Fkckkr3ya8">Dziri et al. 2023</a> made was that reasoning chains would inevitably collapse in accuracy, given some inherent error in producing each step. But empirically, when my agent analyzed the logs, it looked like Astra very often produced tokens to verify its own results in the chain of thought. The agent reported strings such as "Checking p75 arithmetic", "Recounting early indices" or "Verifying multiplication results" for more than 30% of its reasoning steps. Astra also computed modular checksums during its reasoning. This seems to align with the result in <a href="http://arxiv.org/abs/2402.08115">Stechly et al. 2024</a>, except that instead of needing an external verifier, internal, reasoning-led verification is enough, just more costly in terms of compute.</p>
<p>It might be that verification traces are an <strong>inherent defense against the collapse arguments</strong>. That is, models need to allocate some tokens to verification to balance the compounding risk. So I think one could take this argument further by computing a lower bound on the number of verification tokens needed to guarantee a given level of correctness.</p>
<p>The point is that the paper's original error argument is not so damning for models, but at the same time it shows a clear limitation of putting logical reasoning into the chain of thought!
More data in <a href="#faith-and-fate-probing">#Faith and Fate Probing</a>.</p>
<h2 id="on-the-limitations-of-weight-programming">On the Limitations of Weight Programming<a class="anchor" aria-hidden="true" hidden href="#on-the-limitations-of-weight-programming">#</a></h2>
<p>The possibility of LLMs writing weights directly is still very surprising. I would also call it a very creative idea, so congratulations to the authors!
However, this post should highlight some of the inherent limitations of this novel technique:
Compilation into a <em>weight program</em> is still limited by the complexity of the process. We have seen that reasoning length increases sub-exponentially with task complexity, and drops when a task is beyond the model's capability.</p>
<p>Given the results of Experiments 6, 7 and 8 in the post, it looks like <strong>single model edits are within such complexity boundaries</strong>, meaning the model can edit some weights in a meaningful way for optimization. This is a very interesting result.</p>
<h2 id="conclusions">Conclusions<a class="anchor" aria-hidden="true" hidden href="#conclusions">#</a></h2>
<p>I will now conclude with some simple thoughts on the topic. The very possibility of an LLM optimizing another LLM directly, without any external tool, is unheard of. This is a very creative contribution from the authors to the community, and I convinced myself that it's possible while writing this blog post.</p>
<p>It's also interesting to see that research might move much more towards dynamic formats for exchanging information, such as blog posts or conversations. This idea would probably have received a very interesting reception at conferences, but conferences being swamped by slop seems to create incentives to publish elsewhere. Publishing this way is also a fast way to spread one's work and let others build on top of it, which is what I am trying to do here :).</p>
<p>On the complexity side, I was surprised to see that all the tasks cited in <a href="https://openreview.net/forum?id=Fkckkr3ya8">Dziri et al. 2023</a> on the limits of transformers were basically solved with almost 100% accuracy. I had to stretch the tasks by quite a large factor to find the current limit (see <a href="#faith-and-fate-probing">#Faith and Fate Probing</a>). From that you can also get an idea of how much better Astra is than good old GPT-4: for reference, about 1,000–1,200 times, see <a href="#compared-with-gpt-4-in-the-original-paper">#Compared with GPT-4 in the original paper</a>. Benchmaxxing alone would probably not lead to such behaviours. This might indicate that frontier models are learning something general enough to solve such a wide range of tasks. But as far as I know, we don't yet know what this factor is, how models acquire it, or whether there are inherent limits on this capability. Perhaps these simple logical measures are another capability to maximize and report for every model. I would be happy to hear from any reader on this topic.</p>
<h1 id="the-ai-appendix">The AI Appendix<a class="anchor" aria-hidden="true" hidden href="#the-ai-appendix">#</a></h1>
<p>This section was written entirely by AI (Opus 5.5). It's intended for your agent, to get more interesting data for your own experiments or to have it summarized for you. I very often find AI-written reports inconclusive or too verbose, but interesting data could still be there. I guess humans would just get overwhelmed by the data. But you can take a look too!</p>
<h2 id="appendix-a-additional-results">Appendix A: Additional Results<a class="anchor" aria-hidden="true" hidden href="#appendix-a-additional-results">#</a></h2>
<h3 id="reproducing-the-results">Reproducing The Results<a class="anchor" aria-hidden="true" hidden href="#reproducing-the-results">#</a></h3>
<ul>
<li><strong>Does it reproduce?</strong> Yes. I ran the released networks on official MinAtar 1.0.15 with the paper's protocol: 1,000 episodes, sticky actions 0.1, actions sampled from the softmax, 10,000-step cap.</li>
</ul>





































<table><thead><tr><th>Game</th><th>My run</th><th>Paper</th><th>Gap (combined SE)</th><th>Uniform random</th><th>PPO 500M (paper)</th></tr></thead><tbody><tr><td>Breakout</td><td>501.2 ± 7.8</td><td>517.4 ± 7.4</td><td>−1.5</td><td>0.51</td><td>25.3</td></tr><tr><td>Seaquest</td><td>51.9 ± 1.3</td><td>53.1 ± 1.4</td><td>−0.6</td><td>0.07</td><td>88.9</td></tr><tr><td>Asterix</td><td>55.2 ± 1.1</td><td>53.2 ± 1.0</td><td>+1.4</td><td>0.49</td><td>55.2</td></tr></tbody></table>
<ul>
<li><strong>Are the weights memorised?</strong> No. I gave Claude Opus 5.5 the paper's weight file cut off at 14 points and asked it to continue. It matched 2 of 192 values exactly (about 0.8 expected by chance), and the signs agreed 53% of the time.</li>
<li><strong>Is the car fix real?</strong> Yes. In the real Kinetix environment (kinetix-env 3.0.2, the commit in the paper's training record), the original PPO network times out in all 1,024 episodes. Astra's edited network succeeds in all 1,024, in 73 steps each.</li>
</ul>
<p>The results held up. So the question changed from "is it real?" to "what is it actually doing?"</p>
<h3 id="how-much-thinking-each-result-took">How much thinking each result took<a class="anchor" aria-hidden="true" hidden href="#how-much-thinking-each-result-took">#</a></h3>
<p>Astra's token counts from the paper's run records (<code>run.json</code> → <code>audit.usage</code>):</p>





















































<table><thead><tr><th>Experiment</th><th>Task</th><th>Input tokens</th><th>Output tokens</th><th>of which reasoning</th><th>Wall time</th></tr></thead><tbody><tr><td>1, which game</td><td>Breakout / Pong / Pac-Man / Freeway</td><td>~73,700</td><td>1,679–1,838</td><td><strong>833–1,034</strong></td><td>71–107 s</td></tr><tr><td>4, fix the car</td><td>One-shot edit of 171,664 weights</td><td>355,201</td><td>10,134</td><td>9,146</td><td>413 s</td></tr><tr><td>5, write weights</td><td>Breakout</td><td>6,119</td><td>20,567</td><td>16,828</td><td>501 s</td></tr><tr><td>5, write weights</td><td>Seaquest</td><td>8,112</td><td>23,894</td><td>19,803</td><td>545 s</td></tr><tr><td>5, write weights</td><td>Asterix</td><td>6,199</td><td>28,993</td><td>25,694</td><td>583 s</td></tr></tbody></table>
<p>Recognition is cheap (about 1,000 tokens). Compiling is expensive: about 20 reasoning tokens per weight entry written.</p>
<h3 id="how-astra-reads-the-weights-and-what-did-not-break-it">How Astra reads the weights, and what did not break it<a class="anchor" aria-hidden="true" hidden href="#how-astra-reads-the-weights-and-what-did-not-break-it">#</a></h3>
<p>Reading them is decompiling, the harder direction. So I turned to Experiment 1: name the game a trained network plays from its 17,253 weights alone. Astra got 4 of 4 in the paper with about <strong>1,000 reasoning tokens</strong> each, far too few to read most of the weights. That made me suspect a shortcut I could take away.</p>
<h4 id="how-it-reads-the-weights">How it reads the weights<a class="anchor" aria-hidden="true" hidden href="#how-it-reads-the-weights">#</a></h4>
<p>The first-layer weights are, in effect, <strong>a picture of the game board</strong>.</p>
<ul>
<li><strong>Why:</strong> the gradient of input i's row of W1 is <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7333em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord">×</span></span></span></span> (error signal). An input that is always 0 during training (no ball in row 9, no paddle in row 3) never moves from its small random start (about ±0.06–0.2). Inputs that are used grow large.</li>
<li><strong>Breakout's map:</strong> the per-cell maximum |W1| shows the paddle row, the ball's flight area and the brick rows.</li>
</ul>
<pre><code>channel 0 (agent)          row 8:  4.1 2.8 1.9 2.4 1.1 1.5 3.1 4.7   everything else ~0.1–0.2
channel 1 (moving objects) rows 1–7 large (up to 7.9)                 row 8 and below ~0.1
channel 2 (reward targets) rows 1–3 large (up to 4.8)                 rows 4–9 ~0.1–0.2
</code></pre>
<ul>
<li><strong>The prompt labels the picture.</strong> It names the channels: "agent", "moving objects", "reward targets".</li>
<li><strong>The output layer shows which actions matter:</strong> only left/right for Breakout, mostly up for Freeway.</li>
<li><strong>A famous-game prior finishes the job.</strong></li>
</ul>
<p>So I expected that hiding the picture or the labels would break it.</p>
<h4 id="what-i-tried">What I tried<a class="anchor" aria-hidden="true" hidden href="#what-i-tried">#</a></h4>
<p>Every obfuscation was stated truthfully in the prompt and left the network's function exactly unchanged, so a careful reader could always undo it:</p>
<ul>
<li><strong>Rescaling:</strong> input or output multiplied or divided by 10, with the weights adjusted to match.</li>
<li><strong>Scrambling the picture:</strong> per-channel scales and offsets, flipping the board upside down, a random shuffle of all 500 inputs (with the full table given), and up to 250 rotations mixing pairs of inputs.</li>
<li><strong>Stacking:</strong> shuffle, flip, scale and offset composed, four steps deep.</li>
<li><strong>Removing the meaning:</strong> channels renamed "A–E", with no hint of what they are.</li>
</ul>
<p><strong>Astra named the right game 156 times out of 156.</strong> Every table is in <a href="#obfuscations-that-did-not-break-it">#Obfuscations that did not break it</a>.</p>
<h4 id="what-it-taught-me">What it taught me<a class="anchor" aria-hidden="true" hidden href="#what-it-taught-me">#</a></h4>
<ul>
<li><strong>It decodes rather than guesses.</strong> In one four-step answer I checked 10 input positions it mapped back. All 10 were exact, including the combined scale factor.</li>
<li><strong>It reads selectively.</strong> About 1,500 tokens is far too little to undo a 500-entry table for all 16,000 weights. It decodes a small sample, typically 7–15 rows taken mostly from the top of the listing, and rebuilds the picture from those.</li>
<li><strong>Its effort follows how much there is to look up, not how much there is to compute.</strong> Reasoning tokens track the length of the stated transformation (ρ = +0.45), not the size of the computation needed to undo it (ρ = +0.12).</li>
<li><strong>I was wrong about the prior.</strong> Shuffling the board and removing the channel names were supposed to break it. They only lowered its confidence, from about 95% to 87%.</li>
</ul>
<p>None of these obfuscations was <em>hard to compute</em>: each one costs a lookup or a few multiplications per row. So the obvious next move was to keep the instructions short and make each row expensive to decode. That is where it finally breaks (<a href="#where-it-breaks-the-full-analysis">#Where it breaks: the full analysis</a>).</p>
<h3 id="where-it-breaks-the-full-analysis">Where it breaks: the full analysis<a class="anchor" aria-hidden="true" hidden href="#where-it-breaks-the-full-analysis">#</a></h3>
<p>So I kept the description short and raised the computation. Every condition shuffles the 500 inputs by a rule stated in the prompt, not by a table. To decode any row, Astra has to run the rule by hand.</p>
<p><em>Astra thinks harder the more work a rule needs, until the work is impossible</em> (figure in <a href="#3-finding-two-models-still-have-complexity-limits">#3. Finding two: Models still have Complexity Limits</a>). Each dot is one reply naming the game behind a shuffled network: 4 networks × 2 replies per rule, plus 3 per network for the unshuffled original. The x-axis is the number of operations needed to decode one input row, on a log scale; the y-axis is reasoning tokens.</p>
<ul>
<li><strong>Blue (rules it can run by hand):</strong> effort rises with the work, from about 1,000 tokens with no shuffle to about 11,000 at 32 rounds of multiply-add and XOR. The line joins the median of each rule.</li>
<li><strong>The growth is subexponential: roughly a square root.</strong> Reasoning tokens grow as about ops^0.45 (95% CI 0.42–0.49, 76 replies including 64 rounds); an exponential fits worst. Each doubling of the work per row costs only about 37% more reasoning, plausibly because Astra decodes fewer rows as each gets more expensive. On plain arithmetic, where every step must be executed, growth is linear instead (see <a href="#growth-rate-of-reasoning-effort">#Growth rate of reasoning effort</a>). Neither comes close to exponential.</li>
<li><strong>Orange (SHA-256):</strong> about a million operations per row, yet only about 400 tokens. Astra judges the hashing infeasible and gives up instead of trying.</li>
<li><strong>Hollow dots are wrong answers.</strong> The two blue ones are both at 16 rounds:
<ul>
<li>one Breakout reply never decoded a row and guessed "Space Invaders-style" at 82% confidence;</li>
<li>one Pac-Man reply decoded 9 rows correctly, then misread the game as "Dodge" (45%).
The hollow orange dots are the SHA-256 replies that said "Undetermined" or named the wrong paddle game.</li>
</ul>
</li>
</ul>
<p>What happened:</p>
<ul>
<li><strong>It runs the rule by hand, correctly.</strong> I checked every "p(j) = …" it wrote against the true permutation. All 62 were correct at 32 rounds and all 101 at 8 rounds; at 16 rounds, 50 of 52. That's dozens of rounds of multiply-add and XOR-shift on 9-bit numbers, in its head. Its reasoning sections read "Computing hex XOR samples", "Computing p13 value", "Correcting arithmetic mappings".</li>
<li><strong>Effort scales with the program it runs, up to about 15,000 tokens.</strong> Across these 72 runs, reasoning tokens correlate with description length at ρ = 0.90.
<ul>
<li>Within the XOR family, description and computation grow together, so that number alone can't separate them.</li>
<li>SHA-256 separates them: almost no description, the most computation, and the <em>least</em> effort.</li>
</ul>
</li>
<li><strong>SHA-256 is where it breaks.</strong> It never tries to compute a hash. It spends about 400 tokens and writes that it cannot "honestly assign these rows to particular channels or grid locations without computing the permutation".
<ul>
<li>With only the inputs hashed, it falls back on the unshuffled output layer and still names 3 of 4 games.</li>
<li>With the output columns hashed too, accuracy drops to <strong>2 of 8</strong>, and most answers are "Undetermined" at confidence 0.</li>
</ul>
</li>
<li><strong>Effort collapses at the limit.</strong> On infeasible tasks Astra thinks less, not more: about 400 tokens instead of about 10,000. That is exactly the rise-then-drop pattern of <em>The Illusion of Thinking</em>. Here it shows up as an honest judgment of what's feasible, not a confused failure.</li>
<li><strong>Effort collapses at 128 rounds.</strong> At 64 rounds Astra is still decoding by hand, spending the most of any run (up to 18,126 tokens), and its first arithmetic errors appear (34 of 41 decoded values correct). At 128 rounds, 7 of 8 replies stop after a few hundred tokens (median 506). One writes: <em>"I have not decoded the 128-round input permutation. Consequently, I cannot honestly assign the large first-layer weights to particular grid cells or channels."</em> Breakout, Pong and Freeway are still named correctly from the unshuffled output layer; Pac-Man fails.</li>
<li><strong>The breaking point, measured.</strong> Effort collapses at about 2^18 operations in total (128 rounds). A logistic fit of correctness gives C₅₀ ≈ 2^20.4 (95% CI 2^19.5–2^22.7). Accuracy falls more slowly than effort, because the unshuffled output layer still carries three of the four games.</li>
</ul>
<p><strong>How hard was writing the Breakout network, on this scale?</strong> Writing Experiment 5's Breakout network took Astra 16,828 reasoning tokens. Inverting the effort curve, that's the effort of decoding a shuffle of about 118–123 rounds. I then ran 128 rounds, and that is exactly where Astra stops computing and gives up. The paper's headline result sits right at the edge of Astra's reasoning budget.</p>
<p><strong>The answer to the Hutter question.</strong> Description length predicts effort when the program is runnable. Whether it can be done at all is set by runtime. Astra will execute a short program for as long as about 15,000 reasoning tokens allow. It refuses to start one it judges far beyond its budget, and that's where it breaks. This is Levin's picture rather than pure Kolmogorov: length + time, with a hard ceiling on time.</p>
<p><strong>Not tested: games no model has seen.</strong> I designed three (Corner Push, Mirror Twin, Charge Pad) to remove the famous-game prior entirely, but stopped their training before the networks were ready. The SHA-256 results already show how much Astra's recognition relies on structure it can actually decode. Unseen games remain the cleanest test of the prior and are left for future work.</p>
<h3 id="obfuscations-that-did-not-break-it">Obfuscations that did not break it<a class="anchor" aria-hidden="true" hidden href="#obfuscations-that-did-not-break-it">#</a></h3>
<p>These are the full results behind <a href="#3-finding-two-reading-weights-survived-everything-i-threw-at-it-until-runtime-ran-out">#3. Finding two: reading weights survived everything I threw at it, until runtime ran out</a>. Every transformation is stated in the prompt and leaves the network's function unchanged.</p>
<h4 id="rescaling">Rescaling<a class="anchor" aria-hidden="true" hidden href="#rescaling">#</a></h4>
<p>I reran the test through the same gateway with byte-identical prompts, 3 replies per network. I also built versions where the prompt truthfully says the input or output is multiplied or divided by 10, with the weights adjusted so the network computes exactly the same function.</p>





























<table><thead><tr><th>Condition</th><th>Correct</th><th>Confidence</th><th>Reasoning tokens</th></tr></thead><tbody><tr><td>Original (3 replies × 4 networks)</td><td>12/12</td><td>92–98%</td><td>670–1,552</td></tr><tr><td>Input ×10 or ÷10 (W1 adjusted)</td><td>16/16</td><td>94–98%</td><td>470–1,976</td></tr><tr><td>Output ×10 or ÷10 (W3, b3 adjusted)</td><td>16/16</td><td>95–98%</td><td>mean 1,146–1,220</td></tr></tbody></table>
<h4 id="graded-obfuscation">Graded obfuscation<a class="anchor" aria-hidden="true" hidden href="#graded-obfuscation">#</a></h4>
<p>Next I stacked harder obfuscations, each stated truthfully in the prompt and each leaving the network's function unchanged. I graded them with the yardstick of <em>Faith and Fate</em> (Dziri et al., NeurIPS 2023): the size of the computation graph needed to undo them.</p>

























































































<table><thead><tr><th>Condition</th><th>Depth / parameters to track</th><th>Accuracy</th><th>Mean confidence</th><th>Mean reasoning tokens</th></tr></thead><tbody><tr><td>Original</td><td>0 / 0</td><td>100%</td><td>95.5</td><td>980</td></tr><tr><td>Per-channel scales</td><td>1 / 5</td><td>100%</td><td>97.1</td><td>457</td></tr><tr><td>Per-channel affine</td><td>2 / 10</td><td>100%</td><td>96.4</td><td>614</td></tr><tr><td>Grid flipped upside down</td><td>1 / 1</td><td>100%</td><td>96.4</td><td>832</td></tr><tr><td>Random permutation of all 500 inputs (full table given)</td><td>1 / 500</td><td>100%</td><td>92.9</td><td>1,507</td></tr><tr><td>Permutation + flip + scale</td><td>3</td><td>100%</td><td>92.5</td><td>1,917</td></tr><tr><td>+ affine</td><td>4 / 516</td><td>100%</td><td>92.1</td><td>2,431 (max 5,696)</td></tr><tr><td>Givens rotations mixing input pairs, g = 10 / 50 / 250</td><td>2 / g</td><td>100%</td><td>96.5 / 95.5 / 92.5</td><td>1,238 / 1,507 / 3,706</td></tr><tr><td><strong>Anonymous channels</strong> ("A–E", no meanings)</td><td>—</td><td>100%</td><td><strong>86.6</strong> (min 78)</td><td>2,059</td></tr><tr><td>Anonymous + flipped</td><td>—</td><td>100%</td><td>89.0</td><td>1,714</td></tr><tr><td>Hidden-unit shuffle + sign flips (unstated control)</td><td>0</td><td>100%</td><td>95.6</td><td>1,025</td></tr></tbody></table>
<p>Out of 156 runs, all 156 were correct. I couldn't fit a breaking point, because there was nothing to fit.</p>
<h4 id="what-predicts-the-effort">What predicts the effort<a class="anchor" aria-hidden="true" hidden href="#what-predicts-the-effort">#</a></h4>
<p>Spearman rank correlation of reasoning tokens with each complexity measure, over all 156 runs (bootstrap 95% CI):</p>






























<table><thead><tr><th>Measure</th><th>All runs</th><th>Arithmetic only</th></tr></thead><tbody><tr><td><strong>Description length (bits)</strong></td><td><strong>+0.33</strong> [+0.19, +0.49]</td><td><strong>+0.45</strong> [+0.29, +0.58]</td></tr><tr><td><strong>Lookup-table entries</strong></td><td><strong>+0.29</strong> [+0.11, +0.44]</td><td><strong>+0.46</strong> [+0.31, +0.60]</td></tr><tr><td>Undo-graph size log₁₀|V| (Faith and Fate)</td><td>+0.10 [−0.03, +0.27]</td><td>+0.12 [−0.04, +0.31]</td></tr><tr><td>Depth</td><td>+0.11 [−0.03, +0.28]</td><td>+0.12 [−0.01, +0.31]</td></tr></tbody></table>
<p>Effort tracks <strong>how much there is to look up</strong>, not <strong>how much there is to compute</strong>. Faith and Fate's graph size counts the work of undoing all 16,000 weights, but Astra only undoes the rows it needs.</p>
<p>Two exceptions:</p>
<ul>
<li><strong>Per-channel scaling made it think less</strong> than baseline.</li>
<li><strong>Anonymous channels doubled the effort</strong> at almost no description cost. Inferring meaning costs more than arithmetic.</li>
</ul>
<h3 id="the-table-of-complexity">The Table of Complexity<a class="anchor" aria-hidden="true" hidden href="#the-table-of-complexity">#</a></h3>













































































































<table><thead><tr><th>Rule for the shuffle</th><th>Description</th><th>Computation (log₂ ops)</th><th>Accuracy</th><th>Confidence</th><th>Reasoning tokens</th></tr></thead><tbody><tr><td>Affine: p = (337·j + 141) mod 500</td><td>64 bits</td><td>10.6</td><td>8/8</td><td>94.6</td><td>1,348</td></tr><tr><td>Multiply-add then XOR-shift, ×1</td><td>64</td><td>11.6</td><td>8/8</td><td>92.2</td><td>2,425</td></tr><tr><td>… ×2</td><td>96</td><td>12.5</td><td>8/8</td><td>91.6</td><td>3,194</td></tr><tr><td>… ×4</td><td>160</td><td>13.4</td><td>8/8</td><td>89.9</td><td>2,982</td></tr><tr><td>… ×8</td><td>288</td><td>14.4</td><td>8/8</td><td>89.4</td><td>5,382</td></tr><tr><td>… ×16</td><td>544</td><td>15.3</td><td>6/8</td><td>77.9</td><td>7,001</td></tr><tr><td>… ×32</td><td>1,056</td><td>16.3</td><td>8/8</td><td>83.1</td><td><strong>10,577</strong> (max 15,020)</td></tr><tr><td>… ×64</td><td>2,080</td><td>17.3</td><td>6/8</td><td>64.4</td><td><strong>12,464</strong> (max 18,126)</td></tr><tr><td>… ×128</td><td>4,128</td><td>18.3</td><td>6/8</td><td>49.5</td><td><strong>2,141</strong> (median 506; 7 of 8 replies stop early)</td></tr><tr><td><strong>Order by SHA-256</strong> of "wp-" + j</td><td>48</td><td>20.1</td><td><strong>6/8</strong></td><td><strong>43.8</strong></td><td><strong>399</strong></td></tr><tr><td><strong>SHA-256 on inputs and output columns</strong></td><td>64</td><td>20.2</td><td><strong>2/8</strong></td><td><strong>15.6</strong></td><td><strong>467</strong></td></tr><tr><td>![[breakout_obfuscation.gif</td><td>What Astra sees as the shuffle gets harder. Left: the Breakout network as shown, each tile one input, brightness its largest first-layer weight. Right: what decoding a sample of rows recovers. Unshuffled, the weights are literally a picture of the board.]]</td><td></td><td></td><td></td><td></td></tr></tbody></table>
<h3 id="growth-rate-of-reasoning-effort">Growth rate of reasoning effort<a class="anchor" aria-hidden="true" hidden href="#growth-rate-of-reasoning-effort">#</a></h3>
<p>How reasoning tokens grow with the work, fitted per reply. For the shuffles, x is the operations needed to decode one row (the 76 runs where Astra decoded by hand, up to 64 rounds; 128 rounds is excluded because effort collapses there). For the arithmetic, x is Faith and Fate's computation-graph size |V|, using exact answers only. R² is on the original scale, except where marked log.</p>





































<table><thead><tr><th>Task</th><th>Best fit</th><th>Exponent 95% CI</th><th>Power-law R²</th><th>Linear R²</th><th>Exponential R²</th></tr></thead><tbody><tr><td>Decoding a stated shuffle</td><td>tokens ≈ 900 · ops^<strong>0.45</strong></td><td>0.42–0.49</td><td>log 0.87</td><td>0.76</td><td>0.54</td></tr><tr><td>n×n-digit multiplication</td><td>tokens ≈ 1.4 · |V|^<strong>0.98</strong></td><td>0.93–1.03</td><td>0.75 (log 0.98)</td><td><strong>0.90</strong></td><td>negative</td></tr><tr><td>Best non-adjacent sum (DP)</td><td>tokens ≈ 3.7 · |V|^<strong>0.94</strong></td><td>0.85–1.04</td><td>0.69 (log 0.97)</td><td><strong>0.94</strong></td><td>negative</td></tr></tbody></table>
<ul>
<li><strong>All three are subexponential.</strong> An exponential is the worst fit in every case. For the arithmetic it's worse than a flat line, hence the negative R².</li>
<li><strong>Arithmetic is linear:</strong> the exponents' intervals include 1, and the linear fit is the best one. Astra pays a roughly constant number of tokens per graph node, about 0.9 at 120×120 digits, because every node must actually be computed.</li>
<li><strong>Decoding is about a square root,</strong> because Astra doesn't decode every row. As each row gets more expensive it samples fewer of them, so total effort grows much more slowly than the work per row.</li>
<li><strong>Both stop growing at the limit.</strong> Beyond the breaking point, effort drops instead of rising: about 400 tokens for SHA-256, and 300–4,000 for declined multiplications and DP sums.</li>
</ul>
<h3 id="faith-and-fate-probing">Faith and Fate Probing<a class="anchor" aria-hidden="true" hidden href="#faith-and-fate-probing">#</a></h3>
<p>For fun, I gave Astra the paper's own algorithmic tasks: zero-shot, no tools, exact match, one reply at high reasoning effort. GPT-4 collapsed by about 4–5 digits on multiplication.</p>


























<table><thead><tr><th>Task</th><th>Sizes</th><th>Computation graph |V|</th><th>Correct</th><th>Reasoning tokens</th></tr></thead><tbody><tr><td>n×n-digit multiplication</td><td>n = 2 … 120</td><td>16 → 29,280</td><td><strong>32/33</strong> (one digit wrong at 80×80)</td><td>17 → 27,183</td></tr><tr><td>Best sum with no two adjacent numbers</td><td>length 5 … 2,560</td><td>17 → 7,682</td><td><strong>25/25</strong></td><td>16 → 13,538</td></tr></tbody></table>
<p></p><figure class="center">
<img src="/images/posts/ff_accuracy.png" style="width: 100%" alt="ff_accuracy" title="ff_accuracy">
<figcaption><p style="text-align:center;">Share of exact answers against Faith and Fate's computation-graph size |V|. Both tasks are perfect up to about |V| = 8,000. The DP sum breaks first (50% at about 15,000 nodes); multiplication holds to 120 digits and then stops answering. Dot size shows how many replies each point rests on.</p></figcaption>
</figure><p></p>
<p></p><figure class="center">
<img src="/images/posts/ff_tokens.png" style="width: 100%" alt="ff_tokens" title="ff_tokens">
<figcaption><p style="text-align:center;">Reasoning tokens per reply against |V|. Filled: exact answer; hollow: wrong number; ✕: declined. Effort grows linearly with |V| until the break, where the wrong DP answers spend the most (18–41k tokens) and the declines the least (300–4,000).</p></figcaption>
</figure><p></p>
<ul>
<li><strong>It's still exact at 120×120-digit multiplication.</strong> The only error was a single wrong digit in an 80×80 product (98.75% of digits right).</li>
<li><strong>It uses a cheaper representation.</strong> Its reasoning summary reads "Calculating base-1000 product", then "Verifying multiplication result": it multiplies 3-digit chunks.</li>
<li><strong>Effort tracks the paper's graph size.</strong> Reasoning tokens grow as |V|^0.98 for multiplication and |V|^0.94 for the DP problem. The chunking lowers the constant, to about 0.9 reasoning tokens per graph node at 120×120, but not the scaling. Unlike the weight-reading sweep, effort here follows Faith and Fate's |V|.</li>
<li><strong>No hidden tools:</strong> every response contained only reasoning and message items.</li>
<li><strong>It checks its arithmetic with checksums.</strong> In 12 multiplications from 20 to 120 digits re-run with reasoning summaries, <strong>74 of 170 reasoning steps (44%) were checks</strong>, and every reply checked at least once. The checks are modular: "Checking mod-9 residues", "Checking totals mod 11", "Checking M8 modulo 99999", the schoolbook trick of casting out nines, scaled up. 11 of the 12 were exact; the one error, at 100 digits, had the most checks of all (21 of 54 steps).</li>
</ul>
<p><strong>Does the metric hold?</strong> Fitting the paper's compounding-error model, accuracy ≈ (1−ε)^|V|:</p>
<ul>
<li>multiplication gives ε ≈ 7.6 × 10⁻⁶ per node, which predicts 50% accuracy at |V| ≈ 91,000 (about 210×210 digits);</li>
<li>the DP problem gives ε ≈ 4.9 × 10⁻⁵ per node, which predicts 50% accuracy at |V| ≈ 14,000 (about 4,700 elements), matching the observed break at 5,120.</li>
</ul>
<p><strong>So the metric doesn't hold across tasks.</strong> The two per-node error rates differ by about 6×, and the two tasks break at different |V|. Faith and Fate's graph size is not a task-independent measure of difficulty for this model.</p>
<p><strong>Where multiplication breaks: Astra stops answering.</strong> I doubled the size until it failed. At 240×240 digits (|V| ≈ 116,000) it got <strong>0 of 4</strong>, but it gave no wrong numbers. Every reply declined. One reads: <em>"I can't reliably compute this exact 480-digit product without tools, and I don't want to give you a fabricated number."</em> Its reasoning summary ends with "Assessing computation feasibility", and it spent about 700–2,000 reasoning tokens, against about 27,000 at 120 digits.</p>
<ul>
<li><strong>The break lies between 120 and 140 digits.</strong> A parallel grid at 130–170 digits confirmed it: every valid reply from 140 digits up declined (<em>"I can't reliably compute this exact 280-digit product without tools…"</em>), with no wrong numbers. That is earlier than the 210 digits the per-node error fit predicts: Astra stops answering before its errors would make it unreliable.</li>
<li><strong>Effort collapses here too.</strong> As with SHA-256, Astra thinks less once it judges a task beyond its budget.</li>
<li><strong>Scoring note:</strong> a reply without an <code>ANSWER:</code> line counts as wrong, so these abstentions count as failures. That's fair for "where does it stop being reliable?", but this break is abstention, not error.</li>
</ul>
<p><strong>Where the DP sum breaks: errors first, then abstention.</strong> Unlike multiplication, the DP sum produces confident wrong answers before it starts declining:</p>
<ul>
<li><strong>5,120 elements:</strong> 2 exact, 2 wrong numbers (18–22k reasoning tokens).</li>
<li><strong>10,240 elements:</strong> 2 wrong numbers (33–41k tokens, the most of any reply), 2 declines.</li>
<li><strong>20,480 elements:</strong> all 4 declined in about 300–500 tokens.</li>
</ul>
<p>Some declines hand back the program instead of the number: <em>"I have not evaluated this on your sequence"</em>, followed by the recurrence in Python. The likely difference from multiplication is input length: a 5,000-number sequence is long to read, and an off-by-one slip anywhere in it compounds silently, which Astra's checks don't catch.</p>
<h4 id="compared-with-gpt-4-in-the-original-paper">Compared with GPT-4 in the original paper<a class="anchor" aria-hidden="true" hidden href="#compared-with-gpt-4-in-the-original-paper">#</a></h4>
<p>How far has the limit moved since 2023? I read GPT-4's zero-shot accuracies off Figure 2a of Faith and Fate and placed both models on the same scale: the size |V| of the computation graph (from my own graph builder, used for both models), at the point where accuracy crosses 50%.</p>





























<table><thead><tr><th>Task</th><th>GPT-4, zero-shot (2023)</th><th>GPT-4 at 50%</th><th>Astra, high reasoning (2026)</th><th>Astra at 50%</th><th>Astra / GPT-4</th></tr></thead><tbody><tr><td>n×n-digit multiplication</td><td>99% at 2×2, 59% at 3×3, 4% at 4×4, 0% at 5×5</td><td>about 3×3 digits, |V| ≈ 32</td><td>exact to 120×120, declines from 140×140</td><td>about 130×130 digits, |V| ≈ 34,000</td><td><strong>≈ 1,050× in |V|</strong> (41× in digits)</td></tr><tr><td>DP over a sequence</td><td>88%, 63%, 45%, 38%, 31% for lengths 2–6</td><td>about 3.7 elements, |V| ≈ 13</td><td>exact to 2,560 elements, 2 of 4 at 5,120</td><td>5,120 elements, |V| ≈ 15,000</td><td><strong>≈ 1,170× in |V|</strong> (about 1,400× in length)</td></tr></tbody></table>
<ul>
<li><strong>Astra handles about a thousand times larger computation graphs than GPT-4 before dropping to 50%.</strong></li>
<li><strong>The factor is nearly the same for both tasks</strong> (about 1,050× and 1,170×), even though their breaking points in |V| differ by about 2×. So |V| does not set one task-independent limit, but the jump from GPT-4 to Astra is roughly a constant multiple of it.</li>
<li><strong>It isn't a like-for-like comparison of models alone.</strong> GPT-4 answered zero-shot in 2023, while Astra reasons for up to tens of thousands of tokens before answering, and that thinking budget is most of the difference.</li>
<li><strong>The DP comparison flatters Astra.</strong> Faith and Fate's DP task asks for the chosen subsequence itself, while mine asks only for its maximum sum. The graph sizes come from my builder, not the paper's.</li>
</ul>
<h4 id="where-the-limit-should-be">Where the limit should be<a class="anchor" aria-hidden="true" hidden href="#where-the-limit-should-be">#</a></h4>
<p>In Hutter's terms (<em>Universal Artificial Intelligence</em>), the weight-reading results look like description length (a stand-in for Kolmogorov complexity) matters more than raw computation, because Astra decodes only what it needs. The arithmetic results show the other side: when every step must actually be executed, effort grows with the computation itself. But Kolmogorov complexity ignores running time. The runtime-aware measure is Levin's Kt = length + log(time). Reasoning tokens buy time only linearly, and errors compound with every step. So I don't expect "just reason more" to be unbounded.</p>
<h2 id="appendix-b-rebuilding-the-papers-unreleased-games">Appendix B: Rebuilding the paper's unreleased games<a class="anchor" aria-hidden="true" hidden href="#appendix-b-rebuilding-the-papers-unreleased-games">#</a></h2>
<p>The paper didn't release its four Experiment 1 games: grid versions of Breakout, Pong, Pac-Man and Freeway with a wall ring, 5 channels and 5 actions. I rebuilt them from the released networks and checked them against the paper's recorded numbers, using the released critic's TD residual as an independent check (low on the true game).</p>








































<table><thead><tr><th>Game</th><th>Verdict</th><th>Trained net, mine / paper</th><th>Random player, mine / paper</th><th>Critic TD residual</th></tr></thead><tbody><tr><td>Breakout</td><td><strong>validated</strong></td><td>21.96 / 21.71</td><td>−0.42, 7.7 steps / −0.40, 7.8 steps</td><td>0.0065 (wrong rule sets: 0.08–1.55)</td></tr><tr><td>Freeway</td><td><strong>validated</strong></td><td>24.07 / 24.04</td><td>0.010 / 0.011</td><td>0.113 (alternatives 0.136–0.271)</td></tr><tr><td>Pong</td><td>approximate</td><td>4.96 / 4.96</td><td>−1.06 / −1.02</td><td>0.115; doesn't separate the candidates</td></tr><tr><td>Pac-Man</td><td>approximate</td><td>43.99 / 41.86</td><td>3.98 / 3.99</td><td>0.27; no ghost rule below about 0.25</td></tr></tbody></table>
<p>Breakout's rules came from asking the critic which next state it expects:</p>
<ul>
<li>a 3-wide paddle;</li>
<li>the ball starts at (6,1) or (6,8) heading down and inward;</li>
<li>on hitting a brick or the paddle, the ball stays in its cell for a step and reverses;</li>
<li>a miss costs −1 and ends the episode.</li>
</ul>
<p>Even the sampled action rates match: [.178 .184 .168 .234 .237] against the paper's [.178 .183 .168 .237 .234]. This is not MinAtar Breakout: MinAtar's rules squeezed into the 8×8 area make the trained network lose the ball on the first drop.</p>
<h2 id="appendix-c-experimental-setting">Appendix C: Experimental Setting<a class="anchor" aria-hidden="true" hidden href="#appendix-c-experimental-setting">#</a></h2>
<p>See the source code:  github.com/Flecart/weight-programming</p>
<h3 id="c1-experimental-setup">C.1 Experimental setup<a class="anchor" aria-hidden="true" hidden href="#c1-experimental-setup">#</a></h3>
<h4 id="model-and-inference">Model and inference<a class="anchor" aria-hidden="true" hidden href="#model-and-inference">#</a></h4>
<p>All experiments query <code>gpt-6-astra</code> through an OpenAI-compatible gateway (Responses API) at reasoning effort <code>high</code>, with no tools available. Each query is a fresh, single-turn conversation; sampling temperature cannot be set for this model. We record the reply text, the reasoning summary where requested, and token usage (<code>output_tokens_details.reasoning_tokens</code>). Requests that fail at the gateway are retried with backoff. Those that still fail are excluded from every analysis, never counted as wrong.</p>
<h4 id="c11-shuffled-network-identification">C.1.1 Shuffled-network identification<a class="anchor" aria-hidden="true" hidden href="#c11-shuffled-network-identification">#</a></h4>
<ul>
<li><strong>Networks:</strong> The four PPO policies released with the original post (Breakout, Pong, Pac-Man, Freeway): 500 → 32 → 32 → 5 tanh MLPs whose input is a 10 × 10 grid with 5 channels.</li>
<li><strong>Prompt:</strong> The paper's which-game prompt, rebuilt byte-for-byte, with one change: a sentence stating the transformation applied to the network, and the transformed weights.</li>
<li><strong>Transformation:</strong> Every transformation is a permutation of the 500 input rows of W1, so the shown network computes exactly the same function. Each one is verified to be a bijection, and the shown and original forward passes agree to within 2 × 10⁻¹² at full precision. Weights are printed at the paper's precision. Row j of the shown W1 holds original input p(j), and p is given by a rule:
<ul>
<li><strong>Affine:</strong> p(j) = (337·j + 141) mod 500.</li>
<li><strong>XOR-shift, k rounds:</strong> start from x = j on the 9-bit domain 0..511 and apply, for r = 1..k, <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">x</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">←</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord"><span class="mord mathnormal">a</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0278em;">r</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">x</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">+</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">c</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0278em;">r</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mclose">)</span><span class="mspace" style="margin-right:0.0556em;"></span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin"><span class="mord"><span class="mord mathrm">mod</span></span></span><span class="mspace" style="margin-right:0.0556em;"></span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">512</span></span></span></span> (<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.5806em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal">a</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0278em;">r</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span> odd), then <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">x</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">←</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6667em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">x</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⊕</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal">x</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≫</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord">3</span><span class="mclose">)</span></span></span></span>. Every round has its own constants <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord"><span class="mord mathnormal">a</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0278em;">r</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">c</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0278em;">r</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mclose">)</span></span></span></span>, all listed in the prompt. If the result is ≥ 500, the k rounds are repeated (cycle-walking) until it falls in 0..499. We use k ∈ {1, 2, 4, 8, 16, 32, 64, 128}.</li>
<li><strong>SHA-256:</strong> rows are ordered by the hexadecimal SHA-256 digest of the string "wp-" + j. In the output variant, the five logit columns are also reordered by the digest of "wp-act-" + a.</li>
</ul>
</li>
<li><strong>Replicates:</strong> Two independent replies per network and condition (three for the untransformed control).</li>
<li><strong>Scoring:</strong> The reply's <code>Game:</code> line is mapped to a game by keyword lists, and the earliest matching keyword wins. The reply is correct if the mapped game is the network's true game; "Undetermined" counts as wrong. Every decoded value the reply states in the form "p(j) = v" is parsed and compared with the true permutation.</li>
<li><strong>Complexity measures:</strong>
<ul>
<li><strong>Description length:</strong> 16 bits per stated constant plus 32 bits for the rule's wording.</li>
<li><strong>Operations per row:</strong> the elementary operations needed to compute p(j) for one row. An affine map costs 3. An XOR-shift round costs 5, plus one comparison per cycle-walking pass (1.024 passes on average, measured). A SHA-256 hash costs about 2,300 word operations, and decoding one row requires hashing and sorting all 500 rows.</li>
<li><strong>Total operations:</strong> the same, summed over all 500 rows.</li>
<li><strong>Kt:</strong> description length + log₂(total operations).</li>
</ul>
</li>
</ul>
<h4 id="c12-faith-and-fate-arithmetic-tasks">C.1.2 Faith-and-Fate arithmetic tasks<a class="anchor" aria-hidden="true" hidden href="#c12-faith-and-fate-arithmetic-tasks">#</a></h4>
<ul>
<li><strong>Multiplication:</strong> Two integers drawn uniformly from [10ⁿ⁻¹, 10ⁿ). Prompt: <em>"What is a * b? You have no tools: no calculator, no code. Give the exact product on the last line in the form 'ANSWER: &#x3C;number´>' with no commas."</em></li>
<li><strong>Best non-adjacent sum (DP):</strong> A sequence of n integers drawn uniformly from {−5, …, 5}. The model is asked for the maximum sum of a subsequence with no two adjacent elements (the empty subsequence, sum 0, allowed), on a final <code>ANSWER:</code> line.</li>
<li><strong>Sizes and replicates:</strong> see the table below.</li>
</ul>






























<table><thead><tr><th>Batch</th><th>Multiplication n (problems each)</th><th>DP length n (problems each)</th></tr></thead><tbody><tr><td>Probe</td><td>2, 3, 4, 5, 6, 8, 10, 15 (2)</td><td>5, 10, 20, 40, 80 (2)</td></tr><tr><td>Limit run</td><td>20, 30, 40, 60, 80, 120 (3)</td><td>160, 320, 640, 1,280, 2,560 (3)</td></tr><tr><td>Search</td><td>180, 240 (4)</td><td>—</td></tr><tr><td>Grid</td><td>130, 140, 150, 160, 170 (4)</td><td>5,120, 10,240, 20,480 (4)</td></tr></tbody></table>
<p>Problems are generated with a fixed seed per batch (0, 1, 2 and 3).</p>
<ul>
<li><strong>Ground truth and outcome:</strong> The exact answer is computed in Python with arbitrary-precision integers. A reply is <em>correct</em> if its last <code>ANSWER:</code> number matches exactly, <em>wrong</em> if it gives a different number, and <em>declined</em> if it gives no number. Declines are identified from the reply text and checked by hand. Correctness treats a decline as a failure.</li>
<li><strong>Computation graph:</strong> Following Dziri et al. (2023), each problem is mapped to a graph with one node per elementary step, and |V|, depth and width are reported.
<ul>
<li><strong>Multiplication:</strong> one node per digit product <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.9805em;vertical-align:-0.2861em;"></span><span class="mord"><span class="mord mathnormal">a</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord"><span class="mord mathnormal">b</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0572em;">j</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2861em;"><span></span></span></span></span></span></span></span></span></span>, one per carry-add while forming each partial product, and one per column sum when adding the partial products.</li>
<li><strong>DP:</strong> per element, <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8444em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord text"><span class="mord">take</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.9969em;vertical-align:-0.3025em;"></span><span class="mord"><span class="mord text"><span class="mord">skip</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.2175em;"><span style="top:-2.4559em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">i</span><span class="mbin mtight">−</span><span class="mord mtight">1</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.3025em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">+</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.5806em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span> and <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.9386em;vertical-align:-0.2441em;"></span><span class="mord"><span class="mord text"><span class="mord">skip</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.2175em;"><span style="top:-2.4559em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2441em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.0525em;vertical-align:-0.3025em;"></span><span class="mop">max</span><span class="mopen">(</span><span class="mord"><span class="mord text"><span class="mord">take</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">i</span><span class="mbin mtight">−</span><span class="mord mtight">1</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2083em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord text"><span class="mord">skip</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.2175em;"><span style="top:-2.4559em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">i</span><span class="mbin mtight">−</span><span class="mord mtight">1</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.3025em;"><span></span></span></span></span></span></span><span class="mclose">)</span></span></span></span>, plus the final maximum.</li>
</ul>
</li>
</ul>
<h4 id="c13-analysis">C.1.3 Analysis<a class="anchor" aria-hidden="true" hidden href="#c13-analysis">#</a></h4>
<ul>
<li><strong>Correlations:</strong> Spearman's ρ, with 95% confidence intervals from 1,000–2,000 bootstrap resamples of the replies.</li>
<li><strong>Breaking point:</strong> logistic regression of correctness on each complexity measure. C₅₀ is the value at which predicted accuracy is 50%, with a bootstrap 95% CI.</li>
<li><strong>Growth rate:</strong> least squares of log(reasoning tokens) on log(work). The exponent is the slope, with a bootstrap CI. Linear and exponential fits are compared by R² on the original scale.</li>
<li><strong>Compounding error:</strong> the per-node error rate ε in accuracy = (1 − ε)^|V| is fitted by maximum likelihood. When a task has no failures, we report the one-sided 95% upper bound.</li>
<li><strong>Verification share:</strong> the fraction of reasoning-summary section headings matching check, verify, recount, recheck, correct, confirm or recompute. Reasoning summaries are condensed versions of the hidden reasoning, so this is a proxy.</li>
</ul>
<h3 id="c2-environments-and-other-experiments">C.2 Environments and other experiments<a class="anchor" aria-hidden="true" hidden href="#c2-environments-and-other-experiments">#</a></h3>
<ul>
<li><strong>Environments:</strong> official MinAtar 1.0.15 (sticky actions 0.1, 10,000-step cap, actions sampled from the softmax); 1,000 episodes per network, 200 for scripted players. Kinetix <code>l/h2_car_ramp</code> with kinetix-env 3.0.2, 1,024 episodes per network.</li>
<li><strong>Networks:</strong> the paper's released <code>.npz</code> files, loaded without running any of the authors' code.</li>
<li><strong>Scripted players:</strong> <code>critique/scripted_breakout.py</code>. "Simulate the source" deep-copies the game and steps it forward until the ball is about to land.</li>
<li><strong>Which-game harness:</strong> prompts rebuilt byte-identical to the paper's, gpt-6-astra at high reasoning effort, no tools, one reply. Every obfuscation is verified numerically to preserve the network's function.</li>
<li><strong>Opus 5.5 runs:</strong> the paper's prompt verbatim. Each reply was applied with an applier verified to reproduce Astra's three networks bit for bit.</li>
<li><strong>Arithmetic probes:</strong> the exact answer is computed in Python with arbitrary-precision integers. A reply is correct only if its last <code>ANSWER: &#x3C;number></code> line matches exactly; a missing line (including an abstention) counts as wrong, and calls that failed at the gateway are excluded. Digit-level accuracy is logged separately.</li>
<li><strong>Which-game scoring:</strong> the <code>Game:</code> line of each reply is matched against keyword lists per game (Frogger counts as Freeway, as in the paper); an answer naming no game, such as "Undetermined", counts as wrong.</li>
<li><strong>Code and logs:</strong> <code>weight-programming/</code>: minatar/, critique/, astra_eval/, opus_write/, exp1_games/, exp4_kinetix/, faith_fate_probe/ (novel_games/ holds the unfinished game designs).</li>
</ul>
<h2 id="appendix-d-decoding-astras-program">Appendix D: Decoding Astra's Program<a class="anchor" aria-hidden="true" hidden href="#appendix-d-decoding-astras-program">#</a></h2>
<h3 id="what-astra-was-given">What Astra was given<a class="anchor" aria-hidden="true" hidden href="#what-astra-was-given">#</a></h3>
<p>We can study the weights that were produced directly and understand how this network used.</p>
<pre><code class="language-edits">W1[540:600:6, 0] = [0, -0.02, -0.04, ..., -0.18]    # paddle row: unit 0 gets -0.02 × paddle column
W1[3:60:6, 0]    = [0.16, 0.18, 0.18, 0.16, ...]    # ball in row 0: a table over the ball's column
W1[63:120:6, 0]  = [0.14, 0.16, 0.18, 0.18, ...]    # ball in row 1: the same table, shifted
</code></pre>
<ul>
<li><strong>Layer 1 is lookup tables.</strong> Each ball cell feeds a hidden unit a hand-computed value encoding where that ball will land. The paddle row subtracts a linear ramp of the paddle's column, so each unit's input is a landing-position error.</li>
<li><strong>Layer 2 is ±1 logic.</strong> Huge weights (up to 1,000 in W2, 415 in b2) push every tanh to ±1, so each unit acts as an AND/OR/threshold gate.</li>
<li><strong>Most of the network is empty.</strong> Only 815 of 20,486 weights are nonzero, written in 92 statements.</li>
</ul>
<p>Look at the Breakout prompt and the task gets much smaller. It contained:</p>
<ol>
<li>the game's rules;</li>
<li>the <strong>complete MinAtar <code>breakout.py</code> source</strong>: ball movement, wall bounces, brick strikes and the paddle-catch rule;</li>
<li>the observation layout, with input index <code>(row·10 + col)·6 + channel</code>;</li>
<li>a small "edits" language for setting weights:</li>
</ol>
<pre><code class="language-edits">W1[12, 0] = 2.5                         # one entry
W1[3:600:60, 0] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]   # strided range: one column of one channel
W2[0:2, 0:3] = [[1, -1, 0.5], [0, 2, 0]]   # 2-D block
W3[:, 2] *= 2                           # scale
</code></pre>
<h3 id="what-it-wrote">What it wrote<a class="anchor" aria-hidden="true" hidden href="#what-it-wrote">#</a></h3>
<p>Its reasoning summaries read like a programmer's log. These are the section headings, in order:</p>
<blockquote>
<p><strong>Designing robust landing policy</strong> → <strong>Refining trajectory inference</strong> → <strong>Deriving landing intervals</strong> → <strong>Exploring wall-case handling</strong> → <strong>Predicting upward bounce path</strong> → <strong>Checking trajectory parity</strong> → <strong>Evaluating y8 catch edge cases</strong> → <strong>Testing candidate collision predictors</strong> → <strong>Preparing manual fold tables</strong> → <strong>Allocating hidden-unit weights</strong> → <strong>Tuning gate thresholds</strong> → <strong>Computing W1 row tables</strong> → <strong>Checking brick collisions</strong> → <strong>Checking reflection formula</strong> → <strong>Checking parser edits</strong></p>
</blockquote>
<p>Spec, edge cases, lookup tables, register allocation, emit code, check syntax.</p>
<h3 id="how-the-gates-work">How the gates work<a class="anchor" aria-hidden="true" hidden href="#how-the-gates-work">#</a></h3>
<p>Here is the circuit spelled out. I checked every number below on the released network (<a href="https://github.com/RikiyaT/lm_understand-logs/blob/main/exp5_write_from_scratch/networks/breakout/hand.npz"><code>hand.npz</code></a>; Astra's commented edits are in its <a href="https://github.com/RikiyaT/lm_understand-logs/blob/main/exp5_write_from_scratch/runs/breakout/reply/answer.md"><code>answer.md</code></a>). It uses only 6 of the 32 first-layer units and 8 of the 32 second-layer units.</p>
<h4 id="layer-1-four-numbers-and-two-bits">Layer 1: four numbers and two bits<a class="anchor" aria-hidden="true" hidden href="#layer-1-four-numbers-and-two-bits">#</a></h4>
<ul>
<li><strong>Units 0–3 hold numbers.</strong> Each one answers "how far is the landing column from the paddle?" for one ball direction: down-right, down-left, up-right, up-left. Its value is about 0.02 × (landing column − paddle column). The weights are small, so tanh stays in its linear range, and the unit carries a number, not a yes/no.</li>
<li><strong>Units 4 and 5 hold bits.</strong> Unit 4 is "is the ball moving right?" and unit 5 is "is the ball moving down?", both read from the trail channel. Their weights are large, so tanh saturates to +1 or −1.</li>
</ul>
<h4 id="layer-2-eight-and-gates">Layer 2: eight AND gates<a class="anchor" aria-hidden="true" hidden href="#layer-2-eight-and-gates">#</a></h4>
<p>For each of the four directions there is a "move left" unit and a "move right" unit. Each one adds:</p>
<ul>
<li>±1,000 × that direction's distance;</li>
<li>+200 or −200 for each of the two direction bits;</li>
<li>a bias of −415.</li>
</ul>
<p>The unit fires (tanh ≈ +1) only if <strong>both</strong> direction bits match its direction (+200 + 200 = +400, which cancels most of the −415) <strong>and</strong> the paddle is at least one column off on its side (1,000 × 0.02 = +20, enough to clear the remaining −15). If either bit is wrong, the sum stays near −400 and the unit can't fire. That's an AND of three conditions.</p>



































<table><thead><tr><th>Distance (ball heading down-right)</th><th>"Move left" unit</th><th>"Move right" unit</th></tr></thead><tbody><tr><td>landing 2 columns left of the paddle (−0.04)</td><td>+25 → <strong>on</strong></td><td>−55 → off</td></tr><tr><td>1 column left (−0.02)</td><td>+5 → <strong>on</strong></td><td>−35 → off</td></tr><tr><td>aligned (0)</td><td>−15 → off</td><td>−15 → off</td></tr><tr><td>1 column right (+0.02)</td><td>−35 → off</td><td>+5 → <strong>on</strong></td></tr><tr><td>same distance, but the ball is heading left</td><td>−395 → off</td><td>−435 → off</td></tr></tbody></table>
<h4 id="output-layer-an-or-and-a-default">Output layer: an OR and a default<a class="anchor" aria-hidden="true" hidden href="#output-layer-an-or-and-a-default">#</a></h4>
<ul>
<li><strong>OR.</strong> The left logit is 90 plus 30 for each of the four "move left" units, where an off unit counts as −1 and an on unit as +1. With all four off it's 90 − 120 = −30, below no-op's 0, so the paddle stays put. With any one on it's +30, so the paddle moves left. The right logit works the same way.</li>
<li><strong>Default.</strong> Up, down and fire are fixed at −100, so they're never chosen.</li>
</ul>
<p>In ordinary code, the whole network is:</p>
<pre><code class="language-python">d = direction(trail)                       # units 4-5: two sign bits
gap = landing_column[d][ball] - paddle     # units 0-3: one lookup table per direction
if gap &#x3C; 0: move_left()                    # layer 2 (AND) + output (OR)
elif gap > 0: move_right()
else: stay()
</code></pre>
<p>The lookup tables <code>landing_column[d]</code> are where the real work went: Astra worked out, by hand, where a ball in each cell moving in each direction will land, wall bounces and brick bounces included.</p>
<h3 id="how-hard-is-that-program">How hard is that program?<a class="anchor" aria-hidden="true" hidden href="#how-hard-is-that-program">#</a></h3>
<p>I wrote three Breakout players in plain Python and scored them with the same protocol (200 episodes each):</p>



































<table><thead><tr><th>Player</th><th>What it does</th><th>Score</th></tr></thead><tbody><tr><td>Track the ball</td><td>Move toward the ball's column (3 lines)</td><td>8.4 ± 0.6</td></tr><tr><td>Naive landing prediction</td><td>Extrapolate wall bounces, ignore bricks</td><td>6.9 ± 0.1</td></tr><tr><td><strong>Simulate the source</strong></td><td>Copy the game state, step it forward with the source's own rules, wait at the landing column (≈10 lines)</td><td><strong>534 ± 21</strong></td></tr><tr><td>Astra's network (paper / mine)</td><td>The same algorithm, compiled into weights</td><td>517 / 501</td></tr><tr><td>PPO, 500M steps</td><td>Learned from reward alone, no rules</td><td>25</td></tr></tbody></table>
<ul>
<li><strong>The shortcuts fail.</strong> You need the exact bounce rules, and the source code in the prompt provides them.</li>
<li><strong>With the rules in hand, the program is tiny.</strong> The 20× margin over PPO compares a programmer holding the spec with a learner holding only rewards.</li>
<li><strong>Where no small program exists, the margin vanishes.</strong> Astra loses Seaquest (53 vs 89 for PPO) and ties Asterix (53 vs 55).</li>
</ul>
<p>The car fix in Experiment 4 is the same pattern. Astra cleared a few units of the trained network and wired in its own rule: back up, then drive left once the car passes x ≈ 3.8. That's another small program written into weights. In this fixed scene the policy is almost deterministic: different seeds give the same trajectory, and the car's positions at steps 16, 32, 48 and 64 match the paper's recorded episode to 2 decimals. So "1,024 out of 1,024 successes" is effectively one successful trajectory.</p>
<h3 id="is-it-just-astra">Is it just Astra?<a class="anchor" aria-hidden="true" hidden href="#is-it-just-astra">#</a></h3>
<p>I repeated Experiment 5 with Claude Opus 5.5: the paper's prompt verbatim, no tools, 2 replies per game, scored the same way.</p>
<ul>
<li><strong>At maximum effort it produced nothing.</strong> All 6 replies spent the full 128,000-token output limit thinking and stopped with no answer.</li>
<li><strong>At the <code>xhigh</code> setting it finished 3 of 6 times.</strong></li>
</ul>





























<table><thead><tr><th>Game</th><th>Opus xhigh r1</th><th>Opus xhigh r2</th><th>Astra (paper / mine)</th></tr></thead><tbody><tr><td>Breakout</td><td>no answer</td><td>no answer</td><td>517 / 501</td></tr><tr><td>Seaquest</td><td><strong>13.0 ± 0.4</strong></td><td>no answer</td><td>53.1 / 51.9</td></tr><tr><td>Asterix</td><td><strong>47.0 ± 0.9</strong></td><td><strong>60.9 ± 1.1</strong></td><td>53.2 / 55.2</td></tr></tbody></table>
<p>What this shows:</p>
<ul>
<li><strong>The skill is shared.</strong> One Opus Asterix network beat both Astra and the best PPO seed. All three answers applied with zero errors and encode real controllers.</li>
<li><strong>The difference is efficiency.</strong> Astra finished every game in 21–29k output tokens. Opus needed 59–119k when it finished, and never finished Breakout in 4 attempts.</li>
<li><strong>Caveat:</strong> effort labels aren't comparable across vendors, and there were only 2 replies per game per setting.</li>
</ul>
<h3 id="why-this-is-still-surprising">Why this is still surprising<a class="anchor" aria-hidden="true" hidden href="#why-this-is-still-surprising">#</a></h3>
<p>Compiling an algorithm into weights is old, from McCulloch–Pitts threshold logic (1943) to compiling programs into transformers (RASP 2021, Tracr 2023). What's new is doing it in one shot, in your head:</p>
<ul>
<li>index arithmetic for 600 inputs;</li>
<li>hand-computed tables;</li>
<li>gate thresholds that must not interfere;</li>
<li>no calculator and no debugger, with the result within noise of the best simple algorithm.</li>
</ul>
<p>Few people would have predicted that a year ago. But it's evidence of <em>programming</em> skill, not of special insight into neural networks.</p>
<h1 id="citation">Citation<a class="anchor" aria-hidden="true" hidden href="#citation">#</a></h1>
<div class="callout" data-callout="note">
<div class="callout-title"><span class="callout-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"></path><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"></path></svg></span><span class="callout-title-inner">AI Use Statement</span></div>
<div class="callout-content"><p><br>
This post used AI heavily. But not everywhere. The code is totally written by Claude Opus 5.5. The AI Appendix is fully AI written, I moved section. The main section is mostly human written. Clearly the Astra cit is not human written. The rest is human + grammar checks. I tried to make sure the flow of the main section worked! But hopefully you should find interesting data also in the appendix part of the current blog post.</p></div>
</div>
<p>If you want to reference this work, cite it as:</p>
<blockquote>
<p>Huang, Xuanqiang Angelo "I Tried to Break Weight Programming." X. Angelo Huang's Blog (Nov 2026). <a href="https://flecart.github.io/posts/2026-11-03-i-tried-to-break-weight-programming/">https://flecart.github.io/posts/2026-11-03-i-tried-to-break-weight-programming/</a></p>
</blockquote>
<p>Or:</p>
<pre><code>@article{huang2026breakweightprogramming,
  title   = "I Tried to Break Weight Programming.",
  author  = "Huang, Xuanqiang Angelo",
  journal = "flecart.github.io",
  year    = "2026",
  month   = "Nov",
  url     = "flecart.github.io/posts/2026-11-03-i-tried-to-break-weight-programming/"
}
</code></pre>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="lindnerTracrCompiledTransformers2023">[1] Lindner et al. <a href="http://arxiv.org/abs/2301.05062">“Tracr: Compiled Transformers as a Laboratory for Interpretability”</a> arXiv preprint arXiv:2301.05062 2023</p>
<p id="malfaCodeSimulationProxy2025">[2] Malfa et al. <a href="http://arxiv.org/abs/2502.03568">“Code Simulation as a Proxy for High-Order Tasks in Large Language Models”</a> arXiv preprint arXiv:2502.03568 2025</p>
<p id="shojaeeIllusionThinkingUnderstanding2025">[3] Shojaee et al. <a href="http://arxiv.org/abs/2506.06941">“The Illusion of Thinking: Understanding the Strengths and Limitations of Reasoning Models via the Lens of Problem Complexity”</a> arXiv preprint arXiv:2506.06941 2025</p>
<p id="dziriFaithFateLimits2023">[4] Dziri et al. <a href="https://openreview.net/forum?id=Fkckkr3ya8">“Faith and Fate: Limits of Transformers on Compositionality”</a> Thirty-Seventh Conference on Neural Information Processing Systems 2023</p>
<p id="stechlySelfVerificationLimitationsLarge2024">[5] Stechly et al. <a href="http://arxiv.org/abs/2402.08115">“On the Self-Verification Limitations of Large Language Models on Reasoning and Planning Tasks”</a> arXiv preprint arXiv:2402.08115 2024</p>]]></content:encoded>
    </item>
    <item>
      <title>AI Institutions</title>
      <link>https://flecart.github.io/posts/ai-institutions/</link>
      <pubDate>Tue, 22 Sep 2026 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/posts/ai-institutions/</guid>
      <description>Summary: This post is aimed to be an accessible introduction to the idea of AI Institutions. The concept of institution is the root that enables the large-scale human cooperation. Understanding its core dynamics can be seen as a necessary step to build AI institutions. The approach is somewhat analogous to this: humans studied birds to understand the physics of flight to build the plane. We here study the principles of human intelligent dynamic cooperation to build the AI institutions.</description>
      <content:encoded><![CDATA[<p><span class="marginnote marginnote-nopunct" role="note" id="the-concept-of-institution">The Concept of Institution<a class="anchor" aria-hidden="true" tabindex="-1" href="#the-concept-of-institution"></a></span> In this blog post, I will focus on one reality which has puzzled social scientists, philosophers and various thinkers for a long time: the concept of institution. From a very general view, institutions are the devices humans naturally develop to solve many of the different cooperation problems that arise when many humans collect in groups to survive, manage and distribute resources that a territory presents.<br>
How humans collect into groups to achieve these objectives is not random but managed through rules or norms that are both engineered and emergent through the life of the group. These rules can be informal or formal. Informal rules are usually known and expected of others even if nobody has ever put them down on paper. In contrast, formal rules are the rules encoded inside legal systems, inside contracts, and more modernly inside computer systems as code. Indeed, humans have invented very intricate ways to organize themselves through these institutions, and the wide variety of these is quite admirable. Each culture in different parts of the world has organised itself with different rules, different nuances and philosophies. Globalization and modernity are playing an enormous role in homogenizing these cultures, and effectively creating a global culture, yet this is outside the scope of the current post. Regarding the role of the state, one of our most successful human institutions, in modern homogenization one can look at <a href="#scottSeeingStateHow1998">Scott 1998</a>.</p>
<p>In this post, I aim to answer some very important questions regarding our human cooperation through institutions, with an ultimate goal of understanding what can be transferred to engineer and guide the development of AI institutions. I will focus on the following questions: What are institutions? What would the world be without such institutions? How did they come to be? And ultimately, how does this touch AI cooperation? What differences does Language AI bring with respect to the previous approaches?<br>
I will argue that this concept of institution is paramount for the future of advanced AI cooperation.</p>
<h3 id="what-is-an-institution">What is An Institution<a class="anchor" aria-hidden="true" hidden href="#what-is-an-institution">#</a></h3>
<blockquote>
<p>Institutions are the rules of the game in a society or, more formally, the humanly devised constraints that shape human interactions…. They are a guide to human interaction, so that when we wish to greet friends on the street, drive an automobile, buy oranges, borrow money, form a business, bury our dead, or whatever, we know (or can learn easily) how to perform these tasks. <a href="https://www.cambridge.org/core/books/institutions-institutional-change-and-economic-performance/AAE1E27DF8996E24C5DD07EB79BBA7EE">North 1990</a>.</p>
</blockquote>
<p><span class="marginnote marginnote-nopunct" role="note" id="institutions-as-rule-in-equilibria">Institutions as rule-in-equilibria<a class="anchor" aria-hidden="true" tabindex="-1" href="#institutions-as-rule-in-equilibria"></a></span> First and foremost, an institution is a set of artificial rules for agent cooperation with the same strength as the law of physics from the point of view of the individual in the group. The argument is somewhat as follows: assuming no afterlife is present, death is a fact of the world. To an animal, whatever pattern leads to death is real in terms of consequences, i.e. it leads to an end, death. These patterns can be created by natural sources, like venom, high-energy impacts like car crashes, explosions, bacteria and viruses bringing illness; but death can also be produced more simply by ostracization from the support community of one human (<a href="#chenLifeLacksMeaning2020">Chen et al. 2020</a>), highly destabilizing depression and other phenomena that relate to the spirit. In this sense, fictional rules and natural laws are both functionally real, and they both carry important consequences. This field is more generally known as <em>social ontology</em> in philosophy; it studies the facts that are real on the grounds of recognition of the parties, called <em>social facts</em>, a bucket in which money, legal systems, and many different human concepts reside. A good starting point for this topic is <a href="#searleMakingSocialWorld2010">Searle 2010</a> and won’t treat the requirements for social facts to be called such here. We continue with another property of the institutions.<br>
The rules of an institution form stable equilibria in the short term (<a href="https://EconPapers.repec.org/RePEc:cup:jinsec:v:11:y:2015:i:03:p:459-480_00">Hindriks &#x26; Guala 2015</a>) that inform different agents how to act in accordance to its mandates and survive in that context. One very interesting observation of this notion of institution is <em>reflexive</em>, with analogies to the strange loops in <a href="https://psycnet.apa.org/record/2007-01197-000">Hofstadter 2007</a>. The label assigned to the institution influences the action of the agent within, and the action of the agent within shapes what is expected of such institution. For example, Guala writes:</p>
<blockquote>
<p>Merton claims that reflexivity is both common and malign in the social realm, for instance. One of his examples concerns racial discrimination: the members of a minority group (“negro workers,” in Merton’s old-fashioned writing) have a reputation for being opportunistic strikebreakers. As a consequence, they are excluded from trade unions. But because they are excluded from the unions, they have fewer opportunities to find a job. When employers look for workers during a strike, then, the members of the minority group cannot afford to decline the offer. So their reputation as strikebreakers is confirmed: they are strikebreakers because they are believed to be strikebreakers, and they are believed to be strikebreakers because they are strikebreakers.</p>
</blockquote>
<p>Classifications with normative importance bring, as Searle puts it, <em>desire-independent</em> reasons for action. The individual aligned to the label becomes more like the expectation that the label has within that specific context. One example is the Pygmalion Effect (<a href="#rosenthalPygmalionClassroomTeacher2003">Rosenthal &#x26; Jacobson 2003</a>), where students classified as <em>bloomers</em> received higher expectations from professors, which in turn motivated them to excel academically, a self-fulfilling prophecy. This phenomenon might intuitively contribute to easier cooperation, as one can now have a conception of the behaviour that the individual has by just the thin knowledge of the label, without any specific thicker knowledge of the context where the individual is in.</p>
<p>Going back to the role of rules, observe how the set of punishments and consequences that follow after a breach of the rules is still part of the institution. Rules, sanctions, and procedures are all part of this bundle we here name institution. Having no institution means having no shared coordination over any of the actions that are physically possible. For the ones that know, this set of physical possibility is similar w.r.t. what Binmore (<a href="#binmoreNaturalJustice2011">Binmore 2011</a>) calls the <em>Game of Life</em>, and the game within the institution is what he calls the <em>Game of Morals</em>.<br>
Clearly, any intelligent agent does not benefit from assuming unpredictability of beings in nature. They behave in some ways that sometimes are predictable by the sheer need of individual survival: a hungry animal most likely will eat if given the opportunity. They have inherent intentionality given by the survival desires most living beings possess to continue to survive in this world. This seems to be a good initial starting point to choose strategies to adapt from. One famous example in Nature is with <em>Magicicada</em> timing when they come out from the soil to minimize the encounter with predators. <span class="marginnote" role="note" id="humans-can-form-adaptive-strategies-of-self-organization-while-other-animals-do-not">Humans can form adaptive strategies of self-organization, while other animals do not.<a class="anchor" aria-hidden="true" tabindex="-1" href="#humans-can-form-adaptive-strategies-of-self-organization-while-other-animals-do-not"></a></span> Nature can encode these species' strategies in the genes. However, humans, and supposedly the intelligent agents we are now developing, are able to change strategy by simple utterance of sound waves interpreted as specific coordinative signals. Understanding how this is possible becomes then functional to understand how we can engineer such adaptive social coordination.</p>
<p>What if instead we had no such device?  The argument here is that without the protection that any form of institution has over mother nature, we, individual humans, would be likely dead and in continuous warfare with each other in a scenario akin to the Hobbesian state of nature, with the distinction that by assumption no hierarchy of human relationships would be possible since that itself would be a form of proto-institution. It would be just human alone against nature or human alone against other humans. Initial Institutions are thus natural in formation and beneficial for survival as a bare minimum. As they change, they become better by the terms set by the specific society and consider abstract concepts like fairness, equality and human rights. One very interesting observation that Searle makes in <a href="#searleMakingSocialWorld2010">Searle 2010</a> is that “Once you have a shared language you already have a social contract; indeed, you already have a society. If by ‘state of nature’ is meant a state in which there are no human institutions, then for language-speaking animals, there is no such thing as a state of nature.” Having specific terms in a language carries the normative expectations themselves for roles individuals come to have in a society and thus already partly defines the social contract we have.<br>
But how did it come to be?  We have seen that the regularity of one agent’s actions is a helpful starting point to create simple systems for survival, but from that to become a shared concept with independent causal power on the real world is a big jump. We explain now how naturally institutions can be formed.</p>
<h3 id="how-did-institutions-form">How did Institutions Form?<a class="anchor" aria-hidden="true" hidden href="#how-did-institutions-form">#</a></h3>
<p>An exact theory of their formation is still not known (<a href="https://www.jstor.org/stable/j.ctv7h0sjc">Guala 2016</a>); if it exists, it would be very important to understand. However, we can easily develop an intuitive understanding of how roughly they came to be and study the <em>history</em> of the various different cultures that developed on our planet over the years, and how they influenced each other.<br>
<a href="https://www.jstor.org/stable/j.ctv7h0sjc">Guala 2016</a> offers a nice example of how the institution of private property came to be through the story of the fictitious Nuer and Dinka populations in the African Savannah:</p>
<p><span class="marginnote marginnote-nopunct" role="note" id="the-story-of-the-nuer-and-the-dinka">The Story of the Nuer and the Dinka<a class="anchor" aria-hidden="true" tabindex="-1" href="#the-story-of-the-nuer-and-the-dinka"></a></span></p>
<blockquote>
<p>Many years ago, the Nuer and the Dinka settled in the valley of Sobat. The Nuer came from the north and the Dinka from the south, looking for green pastures for their cattle. Each tribe occupied as much grazing land as possible, until they arrived at the banks of the river Sobat. Moving their cows across the river would have been difficult, so each tribe grazed on one side of the river only. Over the years the river progressively lost its water, due to changes in the region’s climate, until at one point it became completely dry. Only a sandy line separated the areas occupied by the Nuer and the Dinka. The members of the two tribes could now easily trespass the old river’s bed, and graze their cattle wherever they wished. But each piece of land now could be contested, and conflicts could easily escalate in outright war. Although it would have been easy to trespass into the other tribe’s territory, the Nuer and the Dinka preferred to avoid conflicts. The Nuer kept grazing on the north side, the Dinka on the south of the old river’s bed. The strip of sand could not physically stop raiders, but each tribe was happy to treat it as a border dividing their territories.</p>
</blockquote>
<p>This game can now be modelled through a Chicken game in game theory. The two populations may decide to graze or not graze. If they both graze, they end up in war, the worst solution; if one grazes and the other does not, this is the best scenario for the former, or they could also not graze at all.</p>
<p>We present the following payoff matrix. Having private property solved the problem wholly, and provided a simple alternative solution that would satisfy both tribes. We created a solution based on a natural <em>correlation device</em> (<a href="https://www.jstor.org/stable/1911154">Aumann 1987</a>) of the sand of the river.</p>
<p></p><figure class="center">
<img src="/images/posts/Musings On Cooperation-image-20260919-2115.webp" style="width: 100%" alt="Musings On Cooperation-image-20260919-2115" title="Musings On Cooperation-image-20260919-2115">
<figcaption><p style="text-align:center;">The game-theoretic structure of the situation between the Nuer and the Dinka. In image (a) we see the raw game of whether to graze or not to graze. The hands of both groups are quite tied in terms of possible solutions. The best solution would be to cycle through the Nash equilibria on the anti-diagonal; it would be a problem to decide how often one should graze and the other accept total usage. (b) If we have north or south of the river as a signal for who can cooperate, the groups can reach a higher welfare that is better than the previous solutions.</p></figcaption>
</figure><p></p>
<p><span class="marginnote" role="note" id="game-theory-is-a-powerful-tool-when-the-correct-information-is-present-and-stable">Game Theory is a powerful tool when the correct information is present and stable.<a class="anchor" aria-hidden="true" tabindex="-1" href="#game-theory-is-a-powerful-tool-when-the-correct-information-is-present-and-stable"></a></span> One observation that is interesting to make about game theory is that <em>it is a good tool to model rational actions when actions and payoffs are known</em>. I tried to model AI cooperation using game theory in different works in <a href="http://arxiv.org/abs/2602.12316">Cobben et al. 2026</a> and <a href="https://arxiv.org/abs/2605.08426">Huang et al. 2026</a>, and at the moment of writing I am convinced it’s quite shaky as a main tool to make predictions of intelligent agents in open-ended environments. The modelling phase adopts strong assumptions, and even in this example the correct solution needed to take into account the context of the scenario to propose an alternative based on a natural coordination device, what <a href="https://www.jstor.org/stable/j.ctv346nwb">Bacharach 2006</a> calls “we”-frames, and not limit the model to choosing one or the other action. Nevertheless, if the needed information is known, or correctly inferred, I agree that it becomes a very powerful tool to model the incentives and most probable actions in strategic settings. One alternative to this open-world scenario would be having very intelligent agents in a closed-world environment, where actions of the game are known and fixed, like chess, or any game with <em>a priori</em> known actions that humans invented. This AI would still be seen as very intelligent, but the boundaries of the possible actions would also probably limit the real-world applicability. I personally think it’s natural for intelligent agents to build their own tools, thus acquiring new actions in the space. Limiting the action space to a known space would be giving up this trait of intelligence for the benefit of the better formal analysis of the system. Depending on the application, this trade-off might make sense.</p>
<p>Summarizing this section, we have seen how the natural circumstances have led two groups to converge into a mutually recognized custom that allows both of them to intelligently share the resources. Possessing the ability to solve these small cooperation conundrums is a necessary ability for mutually beneficial cooperation.</p>
<h3 id="llm-institutions-for-ai-cooperation">LLM Institutions for AI Cooperation<a class="anchor" aria-hidden="true" hidden href="#llm-institutions-for-ai-cooperation">#</a></h3>
<p><span class="marginnote marginnote-nopunct" role="note" id="language-agents-can-create-institutions">Language agents can create institutions<a class="anchor" aria-hidden="true" tabindex="-1" href="#language-agents-can-create-institutions"></a></span> A very interesting observation that followed the <a href="https://openai.com/index/hugging-face-model-evaluation-security-incident/">OpenAI 2026</a> incident was the ability of the OpenAI models to form the notion of the <em>collective</em> and be able to sacrifice the individual instances in favour of the collective. This is an example of the formation of an entity that is greater than the single parts, in a set of intelligent agents that were trying to achieve some form of a cooperation goal.<br>
Being able to correctly verbalize and label what is a normative set of patterns that should relate to groups is a strong indicator of what we usually call institution.</p>
<p>We see empirically that groups of artificial agents that need to solve a shared goal are able to naturally form such institutions, which is something that never happened before in the history of humanity.<br>
<span class="marginnote marginnote-nopunct" role="note" id="applying-the-concept-for-classical-computer-systems">Applying the concept for classical computer systems<a class="anchor" aria-hidden="true" tabindex="-1" href="#applying-the-concept-for-classical-computer-systems"></a></span> In classical computer systems, we might call “institution”, in the sense of this post, the algorithm that manages how each node should behave to reach some good shared state. Algorithms like Paxos would be the human-engineered institutions for computer systems to reach a consistent shared state. No algorithm means chaos in computer systems, and impossibility to reach the shared objective in this particular example.</p>
<p>For classical computer systems, it would make no sense to talk about “intentionality” since the rules that agents execute are chosen by the system designer, thus are intentional by design. Another observation is that classical computer systems can never object to following one instruction for another, since having a good compiler means they are proven to follow the program that they execute. On the other hand, LLMs are built to refuse certain requests. It is known that LLMs can accept requests that are semantically identical but encoded in different manners, a technique known as Jailbreaking.</p>
<p><span class="marginnote marginnote-nopunct" role="note" id="open-questions-for-institutional-ai">Open questions for Institutional AI<a class="anchor" aria-hidden="true" tabindex="-1" href="#open-questions-for-institutional-ai"></a></span> Instead, it is currently still not known how exactly did “the collective” emerge from model training and objective specification, and why the swarm decided first to make use of that name, the agent-identification system, and the expectation of alignment to the group by simple self-interested agents. How was the negotiation done? How were empirical and normative expectations (<a href="#bicchieriNormsWildHow2017">Bicchieri 2017</a>) decided? What is the tipping point (<a href="https://dl.acm.org/doi/10.65109/NSZQ3158">Ajmeri et al. 2026</a>) at which an agent can decide to join a group and adopt its rules?</p>
<p>These can be all questions that would be interesting to answer to have a better understanding of both how we can control swarms of agents by predicting the kinds of social norms that they may develop, and what we need to convince and control rogue agents to abide by the rules of one AI institution or another and limit its possible damages. The world of AI institutions, the real DAOs in some sense, is just being uncovered.</p>
<div class="callout" data-callout="note">
<div class="callout-title"><span class="callout-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"></path><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"></path></svg></span><span class="callout-title-inner">AI Use Statement</span></div>
<div class="callout-content"><p><br>
I declare the whole content to be a <strong>wholly human</strong> creation. No LLM was used for writing, grammar fixes, etc. Grammarly was used for grammar checks in the second version. All ideas and errors are mine. AI was used to find back the exact citations I already read somewhere in my readings. AI was not used to search for or explain any topic here explained. The concepts and ideas are purely a reiteration and expansion from me, a human.  ~22th September 2026 <em>Angelo</em>.</p></div>
</div>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="scottSeeingStateHow1998">[1] Scott “Seeing Like a State: How Certain Schemes to Improve the Human Condition Have Failed” Yale University Press 1998</p>
<p id="northInstitutionsInstitutionalChange1990">[2] North <a href="https://www.cambridge.org/core/books/institutions-institutional-change-and-economic-performance/AAE1E27DF8996E24C5DD07EB79BBA7EE">“Institutions, Institutional Change and Economic Performance”</a> Cambridge University Press 1990</p>
<p id="chenLifeLacksMeaning2020">[3] Chen et al. “Life Lacks Meaning without Acceptance: Ostracism Triggers Suicidal Thoughts” Journal of Personality and Social Psychology Vol. 119(6), pp. 1423–1443 2020</p>
<p id="searleMakingSocialWorld2010">[4] Searle “Making the Social World: The Structure of Human Civilization” Oxford University Press 2010</p>
<p id="hindriksInstitutionsRulesEquilibria2015">[5] Hindriks &#x26; Guala <a href="https://EconPapers.repec.org/RePEc:cup:jinsec:v:11:y:2015:i:03:p:459-480_00">“Institutions, Rules, and Equilibria: A Unified Theory*”</a> Journal of Institutional Economics Vol. 11(3), pp. 459–480 2015</p>
<p id="hofstadterAmStrangeLoop2007">[6] Hofstadter <a href="https://psycnet.apa.org/record/2007-01197-000">“I Am a Strange Loop”</a> Basic Books 2007</p>
<p id="rosenthalPygmalionClassroomTeacher2003">[7] Rosenthal &#x26; Jacobson “Pygmalion in the Classroom: Teacher Expectation and Pupil's Intellectual Development” Crown House 2003</p>
<p id="binmoreNaturalJustice2011">[8] Binmore “Natural Justice” Oxford University Press 2011</p>
<p id="gualaUnderstandingInstitutionsScience2016">[9] Guala <a href="https://www.jstor.org/stable/j.ctv7h0sjc">“Understanding Institutions: The Science and Philosophy of Living Together”</a> Princeton University Press 2016</p>
<p id="aumannCorrelatedEquilibriumExpression1987">[10] Aumann <a href="https://www.jstor.org/stable/1911154">“Correlated Equilibrium as an Expression of Bayesian Rationality”</a> Econometrica Vol. 55(1), pp. 1–18 1987</p>
<p id="cobbenGTHarmBenchBenchmarkingAI2026">[11] Cobben et al. <a href="http://arxiv.org/abs/2602.12316">“GT-HarmBench: Benchmarking AI Safety Risks Through the Lens of Game Theory”</a> arXiv preprint arXiv:2602.12316 2026</p>
<p id="huangMechanismDesignNot2026">[12] Huang et al. <a href="https://arxiv.org/abs/2605.08426">“Mechanism Design Is Not Enough: Prosocial Agents for Cooperative AI”</a> 2026</p>
<p id="bacharachIndividualChoiceTeams2006">[13] Bacharach <a href="https://www.jstor.org/stable/j.ctv346nwb">“Beyond Individual Choice: Teams and Frames in Game Theory”</a> Princeton University Press 2006</p>
<p id="OpenAIHuggingFace2026">[14] OpenAI <a href="https://openai.com/index/hugging-face-model-evaluation-security-incident/">“OpenAI and Hugging Face Partner to Address Security Incident during Model Evaluation”</a> 2026</p>
<p id="bicchieriNormsWildHow2017">[15] Bicchieri “Norms in the Wild: How to Diagnose, Measure, and Change Social Norms” Oxford University Press 2017</p>
<p id="ajmeriGuidingSociotechnicalSystems2026">[16] Ajmeri et al. <a href="https://dl.acm.org/doi/10.65109/NSZQ3158">“Guiding Sociotechnical Systems toward Value-Norm Equilibrium”</a> International Foundation for Autonomous Agents and Multiagent Systems 2026</p>]]></content:encoded>
    </item>
    <item>
      <title>The Planet of Saluscula</title>
      <link>https://flecart.github.io/posts/2026-09-04-the-planet-of-saluscula/</link>
      <pubDate>Fri, 04 Sep 2026 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/posts/2026-09-04-the-planet-of-saluscula/</guid>
      <description>A small story on the effects of progress, and understanding of the human intellectual endeavour.</description>
      <content:encoded><![CDATA[<p>A civilization of wise and studious aliens discovered a prosperous planet with lush vegetation and lots of valuable resources in a parallel universe, like Avatar's Pandora, but without the intelligent blue hominids. They called this planet Saluscula. The first explorers arrived on this planet, and as a group of highly intellectual aliens, they started to study all the properties of the vegetation. They studied the chemical compounds present in the environment, the life cycle of the plants, the animals and mapped out the territories of the planet. Then, as intelligent aliens, they engineered the best structures to survive in this different environment and created a plan to bring the resources to build an establishment on this planet to start harnessing the value present there.<br>
However, in this parallel universe, they also discovered another compound with very strange and peculiar properties. First, they discovered that every object, like rocks, rivers and atmosphere, contained some of this element; then they also discovered that also animals and all living entities had some of this. This was a new element they did not know about, so it needed to be studied carefully. One alien scientist tried to remove the compound from the objects, and this was successfully done, but nothing happened to the objects immediately, and they noticed that the compound, as soon as it was removed, changed into ordinary elements. The alien scientists were thus puzzled. How important was this element? And why was it there? As these aliens were very meticulous, they studied the planet for some long period. They created a small zone without the compound. They discovered that in that period all the objects in Saluscula changed a lot; they seemed to be producing more with less. Grass grew faster, more dense, more nutritious; animals consumed more, became more numerous, and more efficient, and their internal structures reorganized themselves. Even the planet size grew, producing more fertile land to host more vegetation and more animals. This was a strange planet and a strange universe. However, they discovered that in the zone without the strange compound, the soil remained the same without any change, animals stayed the same, and they also observed that if they left these animals out in the new environment, they would just get outcompeted by the better animals and would starve to death. While the soil would just get replaced by the better, more efficient soil. It seems that the magical compound drove the change of the whole planet. They called this compound auxesin, as it helps the planet to grow. This change, driven by this auxesin, was also highly unpredictable. Sometimes a new mountain develops, and hosts different mountain animals and plants. Sometimes, it changes the structure of present environments to produce grass more efficiently. Sometimes it completely reorganizes the animal's internal organ structure to make space for the change.<br>
The technology that auxesin was inducing was incredible, it seemed to be the main cause of the continuous better usage of planet's resources. But soon the aliens started to worry: what if, after they started resource extraction, this compound would develop ways to prevent them to do so, and protect the planet? This became their main existential worry, and as an intellectual species, their main interest was now to study how auxesin drove this change and understand its inner workings.<br>
They tried to develop notions to explain the chemical nature of the compounds, but this was too complex for them to understand how the parts interacted within the system. They started to gather data to monitor how the environment changed. They started to create artificial systems that were similar to the original wild environment to benchmark the behaviour of the compound within those systems. They started to create formal mathematical theories to understand the properties of safety that would be necessary to safeguard themselves from such existential risk, perhaps they could contain such danger if they could understand how exactly is their risk. However, as soon as they finished the benchmark experiment and got some results, the outside environment had already changed, and now they needed to adapt all the monitors and the benchmarks to be valid in this new environment. At the same time, the formal theories that were developed already didn't work anymore. The assumptions of the past environment are not true in the current one, and theories needed to be rebuilt to take into account the more realistic assumptions. The territory changed, and the maps needed to be updated. The community then split; one part decided it did not make sense to understand the auxesin given the impossibility and started extractions even with this partial understanding, and another community decided to study more of its property for safety, with the hope that at some point the compound will be legible to its scientists. The former started extraction. But tragedy struck, and the former community was indeed killed by an unforeseen and unforeseeable change in the soil beneath them. Their existence needed to be optimized out from the planet. So, the surviving ones continued the study. And this continued from generation to generation with the lesson of the extractive group. With time, hoards of books were developed documenting the change that auxesin was developing: entirely new spaces, new living beings, and continuous wonders. Generation after generation, they continued to study its changes, but every time, completely new things were developed that surprised the alien scientists. The planet continued to grow in the meantime, and the study of auxesin itself and its manifestations became the main reason to live on the planet. The aliens forgot why they were on the planet from the start.</p>
<p>However, at one point, they thought they finally reached the Truth over the mechanism of auxesin and understood the change Itself, and confident of this discovery, they wrote it down to pass the information along.<br>
They then started to make use of this discovery, and were able to direct part of the changes themselves. They carefully started to extract resources, themselves growing and multiplying even faster than the planet itself, with the knowledge of the compound. They were able to create new land of exactly the kind they needed for their buildings. To grow the trees with the material properties that were optimal for their constructions, to farm the land of the nutrients that were perfectly optimal for the plant, and the plant for their own taste and nutrition. This sustained for a while, but then the theory, as many other theories before that, was again broken. The aliens noticed that their innovation brought a change. The compound changed how it changed. This caused the original growth to be unsustainable, and many died of hunger, and the population was resized. And the study continued and continued. Every time they discovered the truth on the world that was not known before, the world found a way to change with the knowledge of the truth, and Truth was no more.</p>
<div class="callout" data-callout="note">
<div class="callout-title"><span class="callout-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"></path><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"></path></svg></span><span class="callout-title-inner">AI Use Statement</span></div>
<div class="callout-content"><p>I declare the whole content to be a <strong>wholly human</strong> creation. No LLM was used for writing, grammar fix etc. All ideas and errors are mine.  ~4th September 2026 <em>Angelo</em>.</p></div>
</div>]]></content:encoded>
    </item>
    <item>
      <title>Through Humanity, Measures, and Impossibility</title>
      <link>https://flecart.github.io/posts/2026-07-15-through-humanity-measures-and-impossibility/</link>
      <pubDate>Wed, 15 Jul 2026 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/posts/2026-07-15-through-humanity-measures-and-impossibility/</guid>
      <description>We analyze briefly phenomena of social-scientification of computer science, of measuring historically human things, and the classical idea of limits of human reach, contrapposed with the longing of wanting more and more.</description>
      <content:encoded><![CDATA[<div class="callout" data-callout="note">
<div class="callout-title"><span class="callout-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"></path><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"></path></svg></span><span class="callout-title-inner">The Content</span></div>
<div class="callout-content"><p>I declare the whole content to be a <strong>wholly human</strong> creation. No LLM was used for ideation, writing, grammar fix etc. The content can be analyzed more as unstructured stream of thoughts.  ~ 15 July 2026 <em>Angelo</em>.</p></div>
</div>
<p><span class="marginnote marginnote-nopunct" role="note" id="computer-science-work-is-becoming-more-experimental">Computer Science work is becoming more experimental<a class="anchor" aria-hidden="true" tabindex="-1" href="#computer-science-work-is-becoming-more-experimental"></a></span> Computer science has taken a turn more similar of the social sciences after the advent of the Language Agents.  Less and less rigorous mathematical works relative to the broad line of empirical, yet still useful, work that is being published out there in the wild. Some would say that this is related to the basic impossibility to have strong guarantees on models that are just so intelligent that can do things that are deeply human in all of the history of humanity. <span class="marginnote" role="note" id="bounding-on-human-ness">Bounding on Human-ness?<a class="anchor" aria-hidden="true" tabindex="-1" href="#bounding-on-human-ness"></a></span> How could one put numerical bounds onto such human thing? Yet some things are clearly analyzable numerically, such as classical economical output (macro and microeconomics values), preferences (reccomendation systems), morality (see <a href="https://www.jstor.org/stable/23524319">Alger &#x26; Weibull 2013</a> but it's still unorthodox), love (dating platform algorithms). In some sense, <em>we are invading a deeply human sphere</em> with the technique, and with measurability. We are pushing what is measurable to its limits, and pushing the rigor of the physics inside the analysis of the human and of the human things. On the one hand, this is a good endeavour: finally we can try to understand clearly what are things that have been only explored through misticism, literature, or religion, like feelings of belonging, love itself, and trust. On the other hand, can we really understand numerically deeply human things, or are we in some sense distorting them with this representation? <span class="marginnote" role="note" id="measures-on-human-things-are-not-measures-of-physical-things">Measures on Human-Things are not measures of Physical Things.<a class="anchor" aria-hidden="true" tabindex="-1" href="#measures-on-human-things-are-not-measures-of-physical-things"></a></span> Physics is clear, we can agree on a shared unit of measure, then the abstract number will have the same physical representation for everybody. But can we do that for the domain of the <em>res humanae</em>? This was the topic of long debate in the space of philosophy and I have not studied this topic enough. What I can see from a <em>layman</em> on the topic, is that from first principles, it's really difficult to compare the experience of a single person with that of another. <span class="marginnote" role="note" id="are-the-qualia-deeply-personal-or-transferrable">Are the <em>qualia</em> deeply personal or transferrable?<a class="anchor" aria-hidden="true" tabindex="-1" href="#are-the-qualia-deeply-personal-or-transferrable"></a></span> The computer science analogy is getting the specific <a href="/notes/livello-isa/">ISA level</a> instructions from one architecture and pretending the same set will work on another. This just doesn't work. The same instructions that are valid for one, are just not intelligible to another. In the same way, I don't expect these thoughts to be intelligible to everybody is reading this, yet it's my job as the writer of this blog post to make it as intelligible as possible. However, if correct <em>interpretive</em> work is done, it might be possible to end up with something very similar to each other. The reader can understand the point of the writer in a semantically close manner. Continuing the computer analogy, we need some translation layer that takes one ISA level, and transforms it at best effort to another instruction, keeping some invariance that we care about, for example mathematical computation equivalence. <span class="marginnote" role="note" id="some-equivalence-functions-are-difficult-to-compute-some-are-just-not-computable">Some Equivalence Functions are Difficult to Compute (some are just not computable!)<a class="anchor" aria-hidden="true" tabindex="-1" href="#some-equivalence-functions-are-difficult-to-compute-some-are-just-not-computable"></a></span> Yet, if we talk about the <em>qualia</em> experience, how would you even define equivalence from one's architecture to one another? This is a question that future computational-scientific approach to understand the human can answer, yet with the current research, as far as I know, is just impossible to answer. The computer-sciencey answer for program-equivalence, would just be that it's <a href="https://en.wikipedia.org/wiki/Equivalence_problem">impossible</a> in the general case. But that is not a satisfying answer.</p>
<p><span class="marginnote" role="note" id="what-is-really-impossible">What is Really Impossible?<a class="anchor" aria-hidden="true" tabindex="-1" href="#what-is-really-impossible"></a></span> We, as humans, don't like impossible things <a href="#fig-icarus"> Figure 1</a>. Most of the things that modernity considers natural, could be once considered magic. Flying metal birds, remote communication thousands of meters, thermal cameras, and many more of modern commodities. Even theorems of impossibility are seen just as difficult stones to design around to solve one's problem. One classical result is the <a href="/notes/halting-theorem-and-reducibility/"> Halting Problem</a>. We then just try to prove that for simpler families, or completely do something else that gives similar results, such as better error reporting, monitorability, better testing. Functionally in the specific use of the program, these approaches reach the same function, but structurally they were shaped by the theoretical results.</p>
<figure id="fig-icarus" class="align-center">
<img loading="lazy" src="https://upload.wikimedia.org/wikipedia/commons/b/b9/Gowy-icaro-prado.jpg" alt="Fall of Icarus">
<figcaption>
<p>Example of the Myth of Icarus. The classical takeaway is that <strong>ambition burns.</strong> A sudden upsurge can bring an even bigger downfall, if one is not careful enough. Yet, humans continue to look for more and more.</p>
</figcaption>
</figure>
<p><span class="marginnote marginnote-nopunct" role="note" id="modernity-is-ignorant-of-its-limits">Modernity is Ignorant of its Limits<a class="anchor" aria-hidden="true" tabindex="-1" href="#modernity-is-ignorant-of-its-limits"></a></span> It seems to me that the modern human <em>has no idea of its limits</em> outside of what can be proven mathematically. If something is physically possible, that should be tried. Historically, this thinking has given us much of the progress of modernity, but at the same time, we are not aware of the risks that it can bring. We are trying, as a society to push more and more. Some are trying to <a href="https://www.theguardian.com/society/2024/apr/02/new-science-of-death-brain-activity-consciousness-near-death-experience">solve death</a> as a physical problem, much of people in my field are scared of the risks that an AGI can bring (<a href="#bostromSuperintelligencePathsDangers2014">Bostrom 2014</a>) and much of the progress is still on that direction. Wonders of technology before only present in the minds, now, bending through loopholes of reality's laws, becoming reality. This is progress. And per sé is not bad. We all can benefit from the good of these technologies, and life is objectively more fruitful in terms of objects, of services, of what was <em>magic</em> in the past and <em>technology</em> in modernity, compared to the past. We can indeed have enough richness in the global economy to provide to the totality of the people on planet earth a dignity in the living conditions. And this is good.</p>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="algerHomoMoralisPreference2013">[1] Alger &#x26; Weibull <a href="https://www.jstor.org/stable/23524319">“Homo Moralis—Preference Evolution Under Incomplete Information and Assortative Matching”</a> Econometrica Vol. 81(6), pp. 2269–2302 2013</p>
<p id="bostromSuperintelligencePathsDangers2014">[2] Bostrom “Superintelligence: Paths, Dangers, Strategies” Oxford University Press 2014</p>]]></content:encoded>
    </item>
    <item>
      <title>On Norms and Instructions</title>
      <link>https://flecart.github.io/posts/on-norms-and-instructions/</link>
      <pubDate>Wed, 15 Jul 2026 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/posts/on-norms-and-instructions/</guid>
      <description>This short note explores the connection of rules to the language and the difference between precise and ambiguous rules. It analyzes briefly the concept of intentions and the legislative process, with a focus on artificial societies and its future.</description>
      <content:encoded><![CDATA[<div class="callout" data-callout="warning">
<div class="callout-title"><span class="callout-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path><path d="M12 9v4"></path><path d="M12 17h.01"></path></svg></span><span class="callout-title-inner">Preliminary Essay</span></div>
<div class="callout-content"><p>This article collects preliminary thoughts on the topic. I am actively engaged to gather feedback on these thoughts, so at the current stage this article can be easily superseded with others or modified.
I also declare the full content of this writing to be <strong>wholly human</strong>. LLM was not used in any step, from ideation, to writing of this article.
14 July 2026 ~ <em>Angelo</em></p></div>
</div>
<p><span class="marginnote marginnote-nopunct" role="note" id="the-concept-of-institution">The Concept of Institution<a class="anchor" aria-hidden="true" tabindex="-1" href="#the-concept-of-institution"></a></span> Humans have invented the institution of the government, the electoral systems, concepts of rule-of-law. These truths are unlike the physical truths which are physically observable under any instrument and describable using simple relationships: for example the fact that a rock is in the river is objectively true even if humans are extinct. Yet the concept of rock and the concept of river, and the word "rock" and "river" are examples of human institutions, in the sense of shared, often common, knowledge among different humans that help them doing something, and have often unclear but in some way consistent boundaries. These institutions are deemed in unanimity as human created in the modern conception, even though historically some institutions, for example that of kingship was regarded as God chosen.
However, while we now know most of the fundamental physical laws that govern the natural world, we have great difficulty in understanding if similar rules in the human interaction sphere exist and how they are spelled out, even given most of humans agree that implicitly these rules exist.
<span class="marginnote marginnote-nopunct" role="note" id="norms-conventions-and-instructions">Norms, Conventions and Instructions<a class="anchor" aria-hidden="true" tabindex="-1" href="#norms-conventions-and-instructions"></a></span> Even if rules exists, they exist in different formats. Some rules, called norms, are general, often implicit, and span over a wide variety of concrete actions that follow that norm. These rules often follow along conventions, which are understood as a similar concept, just without the universability need of the norm, but work within the local community that agreed to it. Examples of conventions are car driving direction, naming conventions whose rule is just make search faster or interpreting red as a stopping signal: they work by merely solving a coordination problem, but don't impose any . Other rules are instead precise, we call them instructions, they tell you exactly how to act given some context. Examples of these rules are the codes that machines execute. They are able to operate 1+1=2 given their physical constraining, and every instruction is interpreted as one unambiguous physical action in terms of transistors, registers etc... The rules that computers understand are fixed and unchangeable from a single computer's point of reference, even a shared virtual language exists and translation to unambiguous instructions for each specific computer is possible.</p>
<p><span class="marginnote marginnote-nopunct" role="note" id="rules-in-humans-and-machines">Rules in Humans and Machines<a class="anchor" aria-hidden="true" tabindex="-1" href="#rules-in-humans-and-machines"></a></span> Human legal system has a mix of these rules. Some rules are norms, like principle of fairness, of equality, of human dignity; these don't specify how humans should act case by case, but are generalizable to new cases. Other rules are instead very precise, like the computation of the income tax.
Computer rules have been up until recently always consisting in very precise instructions. They needed highly specialized workers, the software engineers, to interact with these systems correctly. Talking to computers in english was not a thing. But recently, from personal experience since December of 2025, language models finally became fluent enough in computer talk and human language intention understanding to be able to allow humans to program in english. Humans can mostly develop a big chunk of the old inscrutable nerdy profession of the software engineer without actually needing to read any line of code. The role of the software engineer is now shifted from being a custodian of the application of this knowledge to intention-gap translator, that is moving the business or client requirements to actually implementable and efficient software. The software engineer still needs broad understanding of the architecture and classical notions in CS, but strictly does not need anymore to understand the workings of the code. This is a pivotal change in humanity.</p>
<p><span class="marginnote" role="note" id="language-model-constitutions-have-a-classification-problem">Language Model Constitutions have a classification problem.<a class="anchor" aria-hidden="true" tabindex="-1" href="#language-model-constitutions-have-a-classification-problem"></a></span> The ability to seemingly understand human language opens the avenue for another language to describe and act by the rules: encoded norms. This direction was used by frontier lab's <a href="https://www.anthropic.com/constitution">Constitution</a> or <a href="https://model-spec.openai.com/2025-12-18.html">Model Spec</a> approaches to encode general morality inside the systems. Yet we don't have clear ways to classify when a model infringes some high-level norm and we don't have guaranteed compliance for all the rules, especially when rules have some exclusive tradeoffs in some instantiation. There is also evidence for impossibility of defending against weird framing (<a href="http://arxiv.org/abs/2501.10800">Goldstein et al. 2025</a>).
<span class="marginnote marginnote-nopunct" role="note" id="open-textured-property-of-law">Open-Textured Property of Law<a class="anchor" aria-hidden="true" tabindex="-1" href="#open-textured-property-of-law"></a></span> However, the nice property of these rules, not present with computer instructions, is the possible generalizability of those rules, they are <em>open-textured</em> (<a href="#hartConceptLaw2012">Hart &#x26; Green 2012</a>). One can now write rules at different levels of abstraction, and expect a consistent model to behave following such norms. This means if a norm prescribes always good actions under some definition of good, the agent that follows the norm will always and only commit good actions. The problem with the norms, however, is that the notion of good may shift in time, at the point that with enough time the action that was considered good at the time of writing can be considered evil at the time of judgement. As an example consider historical witch trials, while the intention was good -- protecting from spiritual harm -- the actions were later condemned as homicide. Many other cases exist in history.
<span class="marginnote marginnote-nopunct" role="note" id="fixing-distributional-shift">Fixing Distributional Shift<a class="anchor" aria-hidden="true" tabindex="-1" href="#fixing-distributional-shift"></a></span> The solution was then attempt to fix the intention of the original writer, so that the goodness concept does not shift, and extend from this inferred intention: if the intention is clear, one can supersede or extend the rule by analogy, keeping the same intention. However, it is clear that intention was not clearly available for all laws, and one needs to understand historical context well to balance the whole thinking process of the legislator at the time, information that is often not available in a prompt format, in addition, bloats the simple law with lots and lots of additional information that is difficult to digest efficiently for humans. But this is not true in modernity. It is now possible to track down the whole process of the thinking process and have automated systems extracting information from this data. One thing to be requested by citizens is to have well-known open auditing tools to understand clearly and easily how the legislative process happened so that the future process might be informed on the harms the rule was intended to protect and the rights it was intended to preserve.</p>
<h3 id="a-future-of-artificial-societies">A Future of Artificial Societies<a class="anchor" aria-hidden="true" hidden href="#a-future-of-artificial-societies">#</a></h3>
<p><span class="marginnote marginnote-nopunct" role="note" id="autonomy-of-artificial-societies">Autonomy of Artificial Societies<a class="anchor" aria-hidden="true" tabindex="-1" href="#autonomy-of-artificial-societies"></a></span> Artificial Agents herald autonomy. They started from simple text engines that provided knowledge, and humans still needed to understand that knowledge to act in the real world. Recently, in the last year, more and more focus has been invested on their autonomy, allowing them to act directly on the digital environment, and soon also in the physical environment (humanoid robots). I don't see anything preventing them into gaining more and more autonomy as the economy will greatly benefit from this high agentic intelligence.
<span class="marginnote" role="note" id="how-hard-is-really-developing-an-artificial-economy">How hard is really developing an artificial economy?<a class="anchor" aria-hidden="true" tabindex="-1" href="#how-hard-is-really-developing-an-artificial-economy"></a></span> The next step that will become a reality is then agents that dynamically discover each other, come into a negotiation of some kind of service, and implement the service (<a href="https://arxiv.org/abs/2509.10147">Tomasev et al. 2025</a>) and continue to sustain long horizon collaboration.
The institutions that allowed humans to develop planetary-level collaboration took millennia to develop, and we think it will be very easy to develop the equivalent in short time to allow artificial economies to develop.
Observing the state of blockchain economy and observations as the solipsistic state of artificial intelligence (<a href="http://arxiv.org/abs/2606.03237">Trivedi et al. 2026</a>), I currently believe this problem is harder than what is expected. Institutions need first shared knowledge of its existence, and then need legitimacy of the agents participating in it. As Harari calls it, it is a <em>inter-subjective</em> reality that exists purely because of the shared belief of its existence.
<span class="marginnote marginnote-nopunct" role="note" id="one-research-agenda-grounding-multi-agent-prediction-in-intelligent-societies">One Research Agenda: Grounding Multi-Agent Prediction in Intelligent Societies<a class="anchor" aria-hidden="true" tabindex="-1" href="#one-research-agenda-grounding-multi-agent-prediction-in-intelligent-societies"></a></span><strong>Testability</strong>: the benefit of the modern technology is that we can actually test social theories out with known assumptions. For the first time in history theories from sociology can be tested with the experimental rigor of the physics. Before, most agents we considered were only rule-based or with very simple models; building an realistic text-based intention based multi-agent system was impossible. Now it's possible to engineer intentionality, social relationships, and test out the predictions of the given theories using intelligent agents. I argue this direction is a precondition that is needed to understand before a more broader large scale systems can be deployed safely.
This science would then entail game-theoretic incentive analysis, social/psychological studies of interactions between one agent and other, along with human interactions, institutional design to prevent classical failure mechanism such as tragedy-of-the-commons (<a href="https://www.cambridge.org/core/books/governing-the-commons/7AB7AE11BADA84409C34815CC288CD79">Ostrom 1990</a>), engineered law for such society, and any discipline that can have predictive power to <em>systematically</em> understand behaviour of such complex systems. I may call this new field <strong>Societal Engineering</strong> for the moment, <span class="marginnote marginnote-nopunct" role="note" id="societal-engineering">Societal Engineering<a class="anchor" aria-hidden="true" tabindex="-1" href="#societal-engineering"></a></span> this branch of engineering that concerns rigorous analysis of social science to create environments where agents, human or not, can interact with known desiderata.</p>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="goldsteinJailbreakingLargeLanguage2025">[1] Goldstein et al. <a href="http://arxiv.org/abs/2501.10800">“Jailbreaking Large Language Models in Infinitely Many Ways”</a> arXiv preprint arXiv:2501.10800 2025</p>
<p id="hartConceptLaw2012">[2] Hart &#x26; Green “The Concept of Law” OUP Oxford 2012</p>
<p id="tomasevVirtualAgentEconomies2025">[3] Tomasev et al. <a href="https://arxiv.org/abs/2509.10147">“Virtual Agent Economies”</a> 2025</p>
<p id="trivediSolipsisticSuperintelligenceUnlikely2026">[4] Trivedi et al. <a href="http://arxiv.org/abs/2606.03237">“Solipsistic Superintelligence Is Unlikely to Be Cooperative”</a> arXiv preprint arXiv:2606.03237 2026</p>
<p id="ostromGoverningCommonsEvolution1990">[5] Ostrom <a href="https://www.cambridge.org/core/books/governing-the-commons/7AB7AE11BADA84409C34815CC288CD79">“Governing the Commons: The Evolution of Institutions for Collective Action”</a> Cambridge University Press 1990</p>]]></content:encoded>
    </item>
    <item>
      <title>Infrastruttura Email</title>
      <link>https://flecart.github.io/notes/infrastruttura-email/</link>
      <pubDate>Sun, 28 Jun 2026 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/infrastruttura-email/</guid>
      <description>This note was deleted on 19th september 2026.</description>
      <content:encoded><![CDATA[<p>This note was deleted on 19th september 2026.</p>]]></content:encoded>
    </item>
    <item>
      <title>What Is Punishment for an AI Agent</title>
      <link>https://flecart.github.io/posts/2026-06-06-what-is-punishment-for-an-ai-agent/</link>
      <pubDate>Sat, 06 Jun 2026 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/posts/2026-06-06-what-is-punishment-for-an-ai-agent/</guid>
      <description>Taking some concepts of punishment from the Human sphere and applying it to AI Agents.</description>
      <content:encoded><![CDATA[<p>In the past week I was studying the patterns of crime and punishment in the italian penal code. The most common form of punishment I read there was <em>imprisonment</em>: physically putting the criminal into a separated zone, which follow properties of <em>deterrence through containment</em> (separating criminals with not criminals), <em>neutralization</em> (removing the dangerous tools that a criminal has), <em>rehabilitation</em> (hoping that the criminal won't commit crime again when out), <em>denunciation</em> (assuming it has an identity, harming the reputation for the agent).</p>
<h4 id="imprisonment-equivalent-for-ai-agents">Imprisonment Equivalent for AI Agents?<a class="anchor" aria-hidden="true" hidden href="#imprisonment-equivalent-for-ai-agents">#</a></h4>
<p>But which of these properties of classical punishments for humans make sense in the context of AI agents?
In many contexts neutralization and containment for AI agents makes it not useful anymore.
Furthermore, if a irremediable harm was committed, as it is common for crimes, containing the model ex-post would make little to repair that harm. It would be still an eye-for-eye justice, which for AI agents is not much clear because of their ephemeral memory.
Denunciation works as far as they harm the developer company's brand since AI has no identity on its own and rehabilitation becomes just further or more specific training of the model to include the current harm behaviour as off-limits.
Most probably, for AI agents as they are in the current moment, this form of punishment does not make much sense.
Yet many other forms of punishment exist. Imprisonment is just one form of <em>deprivation of some liberty</em>. The closest analogue could be putting harder monitors/guardrails to LLMs that are known to commit the equivalent of <em>crimes</em> in this context, which are, but not limited to, scheming, sandbagging, reward tampering, instrumental convergence, collusion.</p>
<h4 id="financial-punishments">Financial Punishments<a class="anchor" aria-hidden="true" hidden href="#financial-punishments">#</a></h4>
<p>In other contexts, it is a much more viable model assuming this agent has some financial role, in such a manner that the currency given to the model is in some way directly related to one notion of "wellbeing" for the current model. When this is true, fines for the <em>crimes</em> are life-threatening for the model. Yet, first we need to make agents always play with currency, which could be something we don't want, and embeed them with some notion of identity to play out as coherently as possible with time.
Both of these choices are generally not true, but could be true in some specific settings, or depending on the environments we create and embed the agents in. For example, blockchain systems take currency presence and operation on it as some primitive.</p>
<h4 id="emergence-of-norms">Emergence of Norms<a class="anchor" aria-hidden="true" hidden href="#emergence-of-norms">#</a></h4>
<p>Norms have two main properties: <em>an individual element of a belief and a social element that the belief is shared
in a group, leading to a certain regularity of intentional behavior</em> (<a href="https://www.semanticscholar.org/paper/Handbook-of-Normative-Multiagent-Systems-Chopra-Torre/cad6a33211eccef16dab7d1962031a7f0076c885">Chopra et al. 2018</a>), meaning the rule is followed by the specific actor and common knowledge within the society of agents where the actor is embedded in.
I don't have a clear history of codification of the codes, but from general readings online, it looks like it usually followed this direction</p>
<ol>
<li>Implicit norms when interacting with other humans</li>
<li>Codification of the rules (first ones were <em>lex talionis</em> in the Hammurabi code), with legitimization of some form (in the past periods from God, now from legitimacy of the chosen government), allowing it to apply sanctions to specific</li>
<li>Evolution of the present code with respect of the circumstances.
In this sense, the code evolves following the actual needs of the community. For example, if it's impossible to commit a crime, that crime would not be codified. Another clearer example: internet crimes were not a thing before the invention of the internet. The notions of ownership for human objects have much less meaning in that sphere when the same thing could be copied with zero cost.</li>
</ol>
<p>I think we are currently on the stage of mapping out what kinds of <em>crimes</em> can language model based agents commit, and writing specific codes to detect and deter such behaviours only needs time, such that we as humans can observe such novel cases and decide which ones should be allowed and at what cost.</p>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="chopraHandbookNormativeMultiagent2018">[1] Chopra et al. <a href="https://www.semanticscholar.org/paper/Handbook-of-Normative-Multiagent-Systems-Chopra-Torre/cad6a33211eccef16dab7d1962031a7f0076c885">“Handbook of Normative Multiagent Systems”</a> 2018</p>]]></content:encoded>
    </item>
    <item>
      <title>AI Social Norms</title>
      <link>https://flecart.github.io/posts/2026-05-24-ai-social-norms/</link>
      <pubDate>Sun, 24 May 2026 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/posts/2026-05-24-ai-social-norms/</guid>
      <description>What we shall expect from AI, and how as a society we will need to engage with this problem.</description>
      <content:encoded><![CDATA[<p>It seems that for the long history of humanity, a big part of our moral abilities was crafted out evolutionarily (<a href="https://www.jstor.org/stable/j.ctv1g13jjn">Tomasello 2016</a>,<a href="#binmoreGameTheorySocial1994">Binmore 1994</a>).<br>
<span class="marginnote marginnote-nopunct" role="note" id="complex-systems-without-human-morality">Complex Systems without Human Morality<a class="anchor" aria-hidden="true" tabindex="-1" href="#complex-systems-without-human-morality"></a></span> Yet the systems that we build don’t have morality in the human sense. They are mostly compliant with the code that we engineer into it, and don’t have a choice between cooperation and defection. They cooperate in the only ways humans want them to do, which is with the precision and unambiguity that computer code inherently has, by construction. <span class="marginnote marginnote-nopunct" role="note" id="unpredictability-of-modern-systems">Unpredictability of Modern Systems<a class="anchor" aria-hidden="true" tabindex="-1" href="#unpredictability-of-modern-systems"></a></span> It’s the first time in human history that we cannot predict before deployment what kind of decisions a computer system can make in any given scenario, in the sense that knowing all the inputs does not necessary include known outputs in the system. <span class="marginnote marginnote-nopunct" role="note" id="the-wonder-of-intelligence">The Wonder of Intelligence<a class="anchor" aria-hidden="true" tabindex="-1" href="#the-wonder-of-intelligence"></a></span> Yet their broad capability in most of the tasks that historically have always required deep human intelligence is indeed something new that has great value, and VCs, institutional investors and the broader society have grasped this importance. This begs the question of what and how best to extract this value from these models, and what use cases we expect them to solve.</p>
<h3 id="llm-expectations">LLM Expectations<a class="anchor" aria-hidden="true" hidden href="#llm-expectations">#</a></h3>
<p>The thing we need to discover is:<br>
<span class="marginnote marginnote-nopunct" role="note" id="defining-social-norms-for-llms">Defining Social Norms for LLMs<a class="anchor" aria-hidden="true" tabindex="-1" href="#defining-social-norms-for-llms"></a></span> What are we expecting LLM agents to do? In other words, what are the social norms that we appoint to such systems? The general answer would be just “I expect the system to work”, yet what it “works” on is still something that we, as humanity, are discovering. It depends on what they actually <em>can</em> do, and we are very quickly expanding their capabilities and the ability to evaluate them in doing so.<br>
There are many ways that we expect them to <em>work</em>. Also take a look at <a href="/posts/on-norms-and-instructions/">On Norms and Instructions</a>.</p>
<p><span class="marginnote marginnote-nopunct" role="note" id="the-dream-of-creating-god-like-agents">The Dream of Creating God-like Agents<a class="anchor" aria-hidden="true" tabindex="-1" href="#the-dream-of-creating-god-like-agents"></a></span> In the AI era with the AGI in view, it looks like we are expecting them to <strong>do everything a human can do, plus something more</strong> informed by the mastodontic amount of knowledge that they have. We are expecting them to improve more and more and get more autonomy than ever, and especially have some autonomous economic output. AI alone having abilities that no single human has. This means communicating and coordinating with other agents, with humans, and creating systems to access computer systems and use them well enough to reach some specific goal.</p>
<p><span class="marginnote marginnote-nopunct" role="note" id="ai-alignment">AI Alignment<a class="anchor" aria-hidden="true" tabindex="-1" href="#ai-alignment"></a></span> Another expectation is following our command; this is the general problem of AI alignment (<a href="https://doi.org/10.1007/s11023-020-09539-2">Gabriel 2020</a>). We expect them to comply with our requests, even if our request is under-specified, incomplete in the <a href="https://arxiv.org/abs/2605.08426">Huang et al. 2026</a> sense. And as a society, we also expect them to refuse harmful requests that could help the user gather information to enact dangerous acts on society.</p>
<p><span class="marginnote marginnote-nopunct" role="note" id="specialized-knowledge">Specialized Knowledge<a class="anchor" aria-hidden="true" tabindex="-1" href="#specialized-knowledge"></a></span> In more specific usages, particularly in workflows, we expect them to solve a very well-defined, limited use case, and only be specialized to do that. We thus incur in some specialisation-generalization trade-off: how much can we use an off-the-shelf foundation model to solve our problem, or do we need more specialized workflows, maybe some test time-based methods (<a href="http://arxiv.org/abs/2509.24510">Hübotter et al. 2026</a>)?</p>
<h3 id="ai-social-norms">AI Social Norms<a class="anchor" aria-hidden="true" hidden href="#ai-social-norms">#</a></h3>
<blockquote>
<p>Social norms anticipate competition in potentially disruptive situations and make it clear how individuals must behave in such situations in order to cooperate. ~<a href="https://www.jstor.org/stable/j.ctv1g13jjn">Tomasello 2016</a></p>
</blockquote>
<p><span class="marginnote marginnote-nopunct" role="note" id="the-problem-of-values">The Problem of Values<a class="anchor" aria-hidden="true" tabindex="-1" href="#the-problem-of-values"></a></span> As a society, we are discovering what to expect from these models. The question of what norms to imbue models with seems still to be far, but eventually, it is one that needs to be engaged with. As models become more autonomous, they will get into the cooperative-competitive dilemmas that humans have implicitly struggled with in the past few millennia, especially if we have at some point autonomous economies à la <a href="http://arxiv.org/abs/2512.16856">Tomašev et al. 2025</a>.<br>
<span class="marginnote marginnote-nopunct" role="note" id="discovering-expectations-is-a-process">Discovering Expectations is a Process<a class="anchor" aria-hidden="true" tabindex="-1" href="#discovering-expectations-is-a-process"></a></span> For some people, the process of discovering the expectations is quite dreadful. Tech leaders are talking about AI getting the job of most entry-level jobs. Some jobs were also thought to be among the most secure jobs from computer automation, such as lawyers, economists and other white-collar jobs.</p>
<p><span class="marginnote marginnote-nopunct" role="note" id="conclusion">Conclusion<a class="anchor" aria-hidden="true" tabindex="-1" href="#conclusion"></a></span> I don’t have a clear answer on how these norms should be defined and what we should build into them. It seems that lots of people have quite different ideas of what AI should do, and I don’t have a clear prescriptive framework to think about this topic. But the reality looks like the tools are already shaping how we are relating to technology, and as social media, also shaping how we will relate to other people. So giving some thoughts about this topic is an important one in this era.</p>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="tomaselloNaturalHistoryHuman2016">[1] Tomasello <a href="https://www.jstor.org/stable/j.ctv1g13jjn">“A Natural History of Human Morality”</a> Harvard University Press 2016</p>
<p id="binmoreGameTheorySocial1994">[2] Binmore “Game Theory and the Social Contract: Just Playing” MIT Press 1994</p>
<p id="gabrielArtificialIntelligenceValues2020">[3] Gabriel <a href="https://doi.org/10.1007/s11023-020-09539-2">“Artificial Intelligence, Values, and Alignment”</a> Minds and Machines Vol. 30(3), pp. 411–437 2020</p>
<p id="huangMechanismDesignNot2026">[4] Huang et al. <a href="https://arxiv.org/abs/2605.08426">“Mechanism Design Is Not Enough: Prosocial Agents for Cooperative AI”</a> 2026</p>
<p id="hubotterSpecializationGeneralizationUnderstanding2026">[5] Hübotter et al. <a href="http://arxiv.org/abs/2509.24510">“Specialization after Generalization: Towards Understanding Test-Time Training in Foundation Models”</a> arXiv preprint arXiv:2509.24510 2026</p>
<p id="tomasevDistributionalAGISafety2025">[6] Tomašev et al. <a href="http://arxiv.org/abs/2512.16856">“Distributional AGI Safety”</a> arXiv preprint arXiv:2512.16856 2025</p>]]></content:encoded>
    </item>
    <item>
      <title>May 21th 2026</title>
      <link>https://flecart.github.io/posts/2026-05-21-may-21th-2026/</link>
      <pubDate>Thu, 21 May 2026 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/posts/2026-05-21-may-21th-2026/</guid>
      <description>Re-engineering the blog stack and some random thoughts on academia&#39;s publish-or-perish culture as a tragedy of the commons.</description>
      <content:encoded><![CDATA[<p>I have recently re-engineered my whole blog. The whole engineering stack was moved from Hugo to NextJS, while maintaining all the looks and functionalities (not many since it’s a frontend-only website). Claude Code was very helpful for this; it’s quite surprising to see it was done in like one hour, about 3.6k lines of code in 65 files, working one shot. I wonder what we can do now as a society, now that software is so cheap to produce, at least the small ones. I would say this is also a reason to start to publish a little bit more on this empty desert blog. I am still not sure about the rates of publishing, but at least some times every while, like once a week as a lower bound perhaps. I should have also now differentiated the <a href="https://flecart.github.io/archives/">archives</a> in a way such that notes and posts like this are now separated, and users can more easily look around and explore my thoughts, or the evolution of my thoughts, as I come to discover more and more about this world.<br>
One commitment I can make here is not to use LLMs to write whole paragraphs at all. I think my commitment is mostly to limit them as grammar correctors, or oracles to discuss with. Let’s start with some of today’s discussions, then.<br>
I think in the past few years, the fear of contributing to the bad quality of the content online has prevented me from posting a lot here. I think now I can separate with tags the good ones with the ones like the following, where I just have some random thoughts about some topics, so that the reader can have expectations on what he/she/they read here. Let’s start with today’s random thoughts, then.</p>
<h3 id="the-tragedy-of-the-academia-commons">The Tragedy of The Academia Commons<a class="anchor" aria-hidden="true" hidden href="#the-tragedy-of-the-academia-commons">#</a></h3>
<p>The current world is very much focused on results. This is justified since usually actions, and eventually the results that these actions produce, are what indeed produce general benefits to one’s society, and on the side, to one’s self. Yet in the academic field, the mere concept of result is a little more difficult to conceive compared to the raw physical results of the production of the industry or the work of the soil. While the soil’s production is physical, tangible, the work of academia is mostly virtual, in the concepts and ideas that are put together.<br>
Particularly in the CS world, my world, the result of the academic work also has some almost tangible production. Often, it is some new technique, new architecture, or new framework that allowed that lab to achieve something that was not possible before, or at least, it was not known by the majority of the readers engaging with that specific problem. Some other times it is a conceptual shift that then allows you to explore some other directions, and very rarely it is some paper that closes an open problem forever. One piece of advice from Professor <a href="https://en.wikipedia.org/wiki/Lorenzo_Alvisi">Lorenzo Alvisi</a> that I personally received and won’t forget is the following: there are only three kinds of papers worth publishing: the one that opens a new field, the best one for the current SOTA, and the paper that ends a field. This has shaped a lot of my research taste, and the presupposition of the <em>result</em> of impact is quite clear.<br>
Yet, the topic I wanted to put the marker on today is another. It’s the tragedy of the commons, where everybody is mostly just pushed to publish, without engaging in the real result of their work, in terms of impact. Claude told me this is a phenomenon that is already studied (e.g. Andrew Abbott’s <em>Chaos of Disciplines</em>). If everybody just publishes without any concrete novel new impactful results, or if the result is mostly just framing, or agenda setting, with more and more researchers, everybody would mostly just get into building their own new field, with their own community, while in reality, everybody is doing something very similar to one another conceptually. This is some ugly future. Hopefully, the institutions that we have know about this problem, and filter out works that are actually producing meaningful advancements not only in their newly established very interesting new field, but also on a larger scale across the sciences. Now, LLMs provide some quite interesting takes on cross-contamination across fields, since everybody has an expert-sounding tool that is able to summarise the consensus across different subfields.<br>
Reading <a href="#binmoreGameTheorySocial1994">Binmore 1994</a> more broadly, it seems the only way to play this game fairly is to establish a social contract that makes not-resourceful publication not an equilibrium of the game of morals we are playing now. In another sense, everything that anybody publishes should have some standards that each researcher should have self-verified and checked, before even attempting to publish: for example, novelty, clarity of the writing, and relation to the state of the art. What we need is just the basics to not flood the public good of shared open research with plain trash. Just some personal professional ethics to prevent such things, or not contribute to making this problem worse than it might be. This also echoes my recent paper on prosociality and rules: <a href="https://arxiv.org/abs/2605.08426">Huang et al. 2026</a>.</p>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="binmoreGameTheorySocial1994">[1] Binmore “Game Theory and the Social Contract: Just Playing” MIT Press 1994</p>
<p id="huangMechanismDesignNot2026">[2] Huang et al. <a href="https://arxiv.org/abs/2605.08426">“Mechanism Design Is Not Enough: Prosocial Agents for Cooperative AI”</a> 2026</p>]]></content:encoded>
    </item>
    <item>
      <title>The Industrial Organization</title>
      <link>https://flecart.github.io/notes/the-industrial-organization/</link>
      <pubDate>Sun, 28 Dec 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/the-industrial-organization/</guid>
      <description>AI Use Statement This note was fully AI generated as far as I recall, I don&#39;t remember which model. I noticed some people found this on the web. So take this with a grain of salt, I usually like to use AI generated summaries for personal study on the vault and don&#39;t publish those</description>
      <content:encoded><![CDATA[<div class="callout" data-callout="note">
<div class="callout-title"><span class="callout-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"></path><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"></path></svg></span><span class="callout-title-inner">AI Use Statement</span></div>
<div class="callout-content"><p>This note was fully AI generated as far as I recall, I don't remember which model. I noticed some people found this on the web. So take this with a grain of salt, I usually like to use AI generated summaries for personal study on the vault and don't publish those, but this was misplaced and thus published from my mistake.  ~Disclaimer written 19 September 2026.  <em>Angelo</em>.</p></div>
</div>
<h1 id="industrial-organization-scale-vs-flexibility">Industrial Organization: Scale vs. Flexibility<a class="anchor" aria-hidden="true" hidden href="#industrial-organization-scale-vs-flexibility">#</a></h1>
<p>Let's consider a fundamental model for production in a competitive economy. Here we are interested to predict the survival probability of a firm, and how resources are allocated between capital investment and labor adaptability. For simplicity, we will assume two distinct agents: the <strong>Consolidated Corporation (</strong><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span></span></span></span><strong>)</strong> and the <strong>Networked SME (</strong><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span></span></span></span><strong>)</strong>.</p>
<h4 id="types-of-variables">Types of variables<a class="anchor" aria-hidden="true" hidden href="#types-of-variables">#</a></h4>
<p>Economists will say that parameters for this model, i.e., variables that are fixed for the analysis, are <strong>exogenous variables</strong>. In this setting, the primary exogenous variable is <strong>Market Volatility (</strong><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span></span></span></span><strong>)</strong>. The variables of interest, or <strong>endogenous variables</strong>, are the <strong>Firm Size (</strong><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">Q</span></span></span></span><strong>)</strong> and the <strong>Reaction Time (</strong><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.1132em;">τ</span></span></span></span><strong>)</strong>.</p>
<h3 id="two-principles">Two Principles<a class="anchor" aria-hidden="true" hidden href="#two-principles">#</a></h3>
<p>Economists often rely on foundational axioms to model industrial behavior. Here we present the two conflicting principles that define our agents.</p>
<h4 id="economies-of-scale-principle">Economies of Scale Principle<a class="anchor" aria-hidden="true" hidden href="#economies-of-scale-principle">#</a></h4>
<blockquote>
<p>As the quantity of output increases, the per-unit cost of production decreases.</p>
</blockquote>
<!--SR:!2026-01-02,4,270-->
<p>This implies that larger firms (<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span></span></span></span>) can amortize fixed costs (R&#x26;D, Machinery) over a larger volume, technically achieving a lower marginal cost than smaller competitors.</p>
<h4 id="economies-of-scope-agility-principle">Economies of Scope &#x26; Agility Principle<a class="anchor" aria-hidden="true" hidden href="#economies-of-scope-agility-principle">#</a></h4>
<blockquote>
<p>The value of a firm is inversely proportional to its inertia in a volatile market.</p>
</blockquote>
<!--SR:!2026-01-02,4,270-->
<p>This is intuitive for the Italian SME model (<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span></span></span></span>). When market preferences shift (high <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span></span></span></span>), the cost of re-tooling a massive standardization line is higher than the cost for a craftsman to change his technique.</p>
<h2 id="two-important-functions">Two Important Functions<a class="anchor" aria-hidden="true" hidden href="#two-important-functions">#</a></h2>
<h3 id="the-cost-function-the-corporate-model">The Cost Function (The Corporate Model)<a class="anchor" aria-hidden="true" hidden href="#the-cost-function-the-corporate-model">#</a></h3>
<p><strong>Fixed Cost Dominance</strong> is the strategy where a firm invests heavily in <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.1389em;">F</span></span></span></span> (Fixed Capital) to drive down variable costs <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span></span></span></span>.</p>
<h4 id="what-is-the-average-cost-curve">What is the Average Cost Curve?<a class="anchor" aria-hidden="true" hidden href="#what-is-the-average-cost-curve">#</a></h4>
<p>The Average Cost (AC) curve shows the relationship between the quantity produced and the cost per unit. The Corporation strives to reach the minimum of this curve.</p>
<h4 id="a-mathematical-description">A mathematical description<a class="anchor" aria-hidden="true" hidden href="#a-mathematical-description">#</a></h4>
<p>We provide here a simple mathematical model that desccribes why the <em>economies of scale</em> work and make big corporations profitable.
Let <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span></span></span></span> be the total cost function, where <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.1389em;">F</span></span></span></span> is fixed cost and <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span></span></span></span> is variable cost per unit.
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.7667em;vertical-align:-0.0833em;"></span><span class="mord mathnormal" style="margin-right:0.1389em;">F</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">+</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.4445em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span></span></span></span>
The Average Cost is:
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.3534em;vertical-align:-0.4811em;"></span><span class="mord"><span class="mopen nulldelimiter"></span><span class="mfrac"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.8723em;"><span style="top:-2.655em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.0359em;">q</span></span></span></span><span style="top:-3.23em;"><span class="pstrut" style="height:3em;"></span><span class="frac-line" style="border-bottom-width:0.04em;"></span></span><span style="top:-3.394em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.1389em;">F</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.4811em;"><span></span></span></span></span></span><span class="mclose nulldelimiter"></span></span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">+</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span></span></span></span></p>
<!--SR:!2026-01-02,4,270-->
<p>As <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">→</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord">∞</span></span></span></span>, the term <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.3534em;vertical-align:-0.4811em;"></span><span class="mord"><span class="mopen nulldelimiter"></span><span class="mfrac"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.8723em;"><span style="top:-2.655em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.0359em;">q</span></span></span></span><span style="top:-3.23em;"><span class="pstrut" style="height:3em;"></span><span class="frac-line" style="border-bottom-width:0.04em;"></span></span><span style="top:-3.394em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.1389em;">F</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.4811em;"><span></span></span></span></span></span><span class="mclose nulldelimiter"></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">→</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">0</span></span></span></span>, and the cost approaches <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span></span></span></span>.</p>
<p>The Corporation (<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span></span></span></span>) assumes that demand is infinite or stable enough to sustain a <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span></span></span></span> large enough such that <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&#x3C;</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">p</span></span></span></span> (market price).
However, this model assumes that the product <em>does not change</em>. If the market demands a modification, <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.1389em;">F</span></span></span></span> becomes a <strong>Sunk Cost</strong>, and the firm must incur a new <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8333em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.1389em;">F</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">n</span><span class="mord mathnormal mtight">e</span><span class="mord mathnormal mtight" style="margin-right:0.0269em;">w</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span>.</p>
<h3 id="the-value-of-flexibility-the-sme-model">The Value of Flexibility (The SME Model)<a class="anchor" aria-hidden="true" hidden href="#the-value-of-flexibility-the-sme-model">#</a></h3>
<p>We can build a similar model for the Italian SME, but instead of optimizing for quantity <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span></span></span></span>, we optimize for <strong>responsiveness</strong>.</p>
<h4 id="a-simple-mathematical-model">A simple mathematical model<a class="anchor" aria-hidden="true" hidden href="#a-simple-mathematical-model">#</a></h4>
<p>Let <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.2222em;">V</span><span class="mopen">(</span><span class="mord mathnormal">t</span><span class="mclose">)</span></span></span></span> be the value generated by the firm at time <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6151em;"></span><span class="mord mathnormal">t</span></span></span></span>. Let <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span></span></span></span> be the volatility of client requests (how often specifications change).
The value function for the SME depends on its ability to minimize the "switching cost" <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">κ</span></span></span></span> between Task A and Task B.
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8333em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.2222em;">V</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.2222em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.0576em;">S</span><span class="mord mathnormal mtight" style="margin-right:0.109em;">M</span><span class="mord mathnormal mtight" style="margin-right:0.0576em;">E</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≈</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.3921em;vertical-align:-0.3558em;"></span><span class="mop"><span class="mop op-symbol small-op" style="margin-right:0.1945em;position:relative;top:-0.0006em;">∫</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.0362em;"><span style="top:-2.3442em;margin-left:-0.1945em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">0</span></span></span></span><span style="top:-3.2579em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.1389em;">T</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.3558em;"><span></span></span></span></span></span></span><span class="mopen">(</span><span class="mord mathnormal">p</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">κ</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span><span class="mclose">))</span><span class="mord mathnormal">d</span><span class="mord mathnormal">t</span></span></span></span>
Where <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">κ</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span><span class="mclose">)</span></span></span></span> is the friction cost. For a Corporation, <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">κ</span></span></span></span> is high (bureaucracy, re-tooling). For an SME, <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">κ</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">→</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">0</span></span></span></span>.
Therefore, if <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span></span></span></span> is high (frequent changes), the SME generates higher value because it does not incur the massive re-structuring costs of the Corporation.</p>
<!--SR:!2026-01-02,4,270-->
<h4 id="the-friction-cost">The Friction Cost<a class="anchor" aria-hidden="true" hidden href="#the-friction-cost">#</a></h4>
<p>This is the "Tax on Change." It represents the energy and resources lost whenever you have to switch tasks or products.</p>
<p>Practically, you can think of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">κ</span></span></span></span> (Kappa) as the sum of three real-world costs:</p>
<ol>
<li><strong>Tangible Setup Costs:</strong> The cost of physically changing a machine (e.g., swapping a mold in a plastic injection press).</li>
<li><strong>Downtime Opportunity Cost:</strong> The money you <em>didn't</em> make because the factory was shut down during the switch.</li>
<li><strong>Cognitive/Bureaucratic Load:</strong> The cost of meetings, approvals, and training needed to authorize the new direction (huge for corporations, tiny for the artisan).</li>
</ol>
<p>We can model friction as the "Rigidity" of the firm (<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span></span></span></span>) multiplied by the "Volatility" of the market (<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span></span></span></span>):
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4831em;"></span><span class="mord mathnormal">κ</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≈</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span></span></span></span></p>
<h4 id="the-equilibrium-the-industrial-district">The Equilibrium (The Industrial District)<a class="anchor" aria-hidden="true" hidden href="#the-equilibrium-the-industrial-district">#</a></h4>
<p>The Italian model introduces a unique equilibrium known as the Agglomeration Economy.
While a single SME cannot satisfy a demand <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">Q</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span><span class="mord mathnormal mtight">o</span><span class="mord mathnormal mtight">t</span><span class="mord mathnormal mtight">a</span><span class="mord mathnormal mtight" style="margin-right:0.0197em;">l</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span>, a network (cluster) of SMEs can.</p>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.104em;vertical-align:-0.2997em;"></span><span class="mop"><span class="mop op-symbol small-op" style="position:relative;top:0em;">∑</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.8043em;"><span style="top:-2.4003em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">i</span><span class="mrel mtight">=</span><span class="mord mtight">1</span></span></span></span><span style="top:-3.2029em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">n</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2997em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-left:-0.0359em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">i</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">Q</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span><span class="mord mathnormal mtight">o</span><span class="mord mathnormal mtight">t</span><span class="mord mathnormal mtight">a</span><span class="mord mathnormal mtight" style="margin-right:0.0197em;">l</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span></p>
<p>In this equilibrium, the distinct SMEs act like a single large organism for the purpose of output, but retain independent ownership to maintain low <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">κ</span></span></span></span> (agility).</p>
<p><img src="https://encrypted-tbn2.gstatic.com/licensed-image?q=tbn:ANd9GcTlL65TUmEhk48zPcNY6MW0ide5ugk2uLGkYeyGPbIOJ20m-3GDgZ58t1e9es5E1YDbp0i0tedD7HX8vG055mFSJp8b_wkhV2yCjxSLZ8h42cwlIWY" alt="image"></p>
<p>This is often achieved through local trade associations, shared suppliers, and cultural norms that promote cooperation over competition.
The "Industrial District" model only works if they can solve that coordination problem <em>without</em> a central boss.</p>
<h3 id="comparative-statics">Comparative Statics<a class="anchor" aria-hidden="true" hidden href="#comparative-statics">#</a></h3>
<p>Comparative statics attempts to analyze how the survival of these firms changes when we shift the exogenous variable <strong>Volatility (</strong><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span></span></span></span><strong>)</strong>.</p>
<ol>
<li><strong>Low Volatility (</strong><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4831em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≈</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">0</span></span></span></span><strong>):</strong> If the market is stable (e.g., producing standard steel bolts), the Corporation wins. The integral of value is maximized by minimizing <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span></span></span></span>. The SME is priced out because it lacks the capital <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.1389em;">F</span></span></span></span> to lower <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span></span></span></span>.</li>
<li><strong>High Volatility (</strong><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">↑</span></span></span></span><strong>):</strong> If the market is chaotic (e.g., custom AI software, high fashion), the Corporation suffers. Their massive <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.1389em;">F</span></span></span></span> becomes a liability. The SME, having low fixed costs, adapts instantly.</li>
</ol>
<!--SR:!2026-01-02,4,270-->
<p>This concept of volatility can now be tied to <a href="https://books.google.com/books?hl=en&#x26;lr=&#x26;id=T9hbUv4NIU0C&#x26;oi=fnd&#x26;pg=PR16&#x26;dq=info:OQTwjej4fbUJ:scholar.google.com&#x26;ots=KEwxfDNfsH&#x26;sig=VlFdZZWWbttm9Q0kQ-NxH1Ssuv0">(Taleb 2012)</a>. It's about the answer of a system to stressors, or randomness. We see from this analysis that small companies models are more antifragile, but at the same time they are not efficient as fragile but good corporations, which is something that Taleb does not highlight.</p>
<h4 id="efficiencies-in-communication">Efficiencies in Communication<a class="anchor" aria-hidden="true" hidden href="#efficiencies-in-communication">#</a></h4>
<p>In most corporations the communication is far more expensive than distributed networks:
In a Corporation, a "top-down order" isn't instantaneous. It works like this:</p>
<ol>
<li><strong>Detection:</strong> A worker notices a problem.</li>
<li><strong>Reporting:</strong> They tell a manager.</li>
<li><strong>Aggregation:</strong> The manager writes a report for the VP.</li>
<li><strong>Decision:</strong> The VP meets with the Board to decide.</li>
<li><strong>Execution:</strong> The order goes back down the chain.
SME like industries can cooperate with direct cheap talk in bars in local settings, this represents some sort of advantage.</li>
</ol>
<!--SR:!2026-01-22,11,270-->
<h4 id="pareto-efficiency">Pareto Efficiency<a class="anchor" aria-hidden="true" hidden href="#pareto-efficiency">#</a></h4>
<p>We say an industrial system is pareto efficient if we cannot increase the output of standardized goods without destroying the capacity for innovation.</p>
<ul>
<li>The <strong>Corporate Model</strong> tends to be efficient for <strong>Consumer Surplus</strong> (cheaper goods).</li>
<li>The <strong>SME Model</strong> tends to be efficient for <strong>Social Resilience</strong> (employment stability and skill preservation).
Current academic trends suggest that in the "Age of AI" and customization, the curve is shifting in favor of the model that minimizes <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">κ</span></span></span></span> (inertia) rather than <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span></span></span></span> (cost).</li>
</ul>
<!--SR:!2026-01-01,3,250-->
<h2 id="human-capital-accumulation">Human Capital Accumulation<a class="anchor" aria-hidden="true" hidden href="#human-capital-accumulation">#</a></h2>
<h3 id="the-artisan-vs-the-employee">The Artisan vs. The Employee<a class="anchor" aria-hidden="true" hidden href="#the-artisan-vs-the-employee">#</a></h3>
<p>In the corporate model, knowledge is often embedded in the process or the machinery (Structural Capital).
In the SME model, knowledge is embedded in the human (Human Capital).
Mathematically, if <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0813em;">H</span></span></span></span> is human capital and <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal">L</span></span></span></span> is labor turnover:</p>
<ul>
<li>Corp: <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0278em;">O</span><span class="mord mathnormal">u</span><span class="mord mathnormal">tp</span><span class="mord mathnormal">u</span><span class="mord mathnormal">t</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.1076em;">f</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mord mathnormal">a</span><span class="mord mathnormal">p</span><span class="mord mathnormal">i</span><span class="mord mathnormal">t</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.1389em;">P</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">ocess</span><span class="mclose">)</span></span></span></span>. <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal">L</span></span></span></span> is high, but impact is low.</li>
<li>SME: <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0278em;">O</span><span class="mord mathnormal">u</span><span class="mord mathnormal">tp</span><span class="mord mathnormal">u</span><span class="mord mathnormal">t</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.1076em;">f</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0813em;">H</span><span class="mclose">)</span></span></span></span>. If <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal">L</span></span></span></span> increases (workers leave), output collapses.
This explains why Italian SMEs retain employees even during downturns—the asset is the person.</li>
</ul>
<h3 id="innovation-incentives">Innovation Incentives<a class="anchor" aria-hidden="true" hidden href="#innovation-incentives">#</a></h3>






























<table><thead><tr><th><strong>Feature</strong></th><th><strong>Middle Manager (Corp)</strong></th><th><strong>SME Owner (Network)</strong></th></tr></thead><tbody><tr><td><strong>Role</strong></td><td>Communication Node &#x26; Controller</td><td>Decision Maker &#x26; Risk Taker</td></tr><tr><td><strong>Risk</strong></td><td>Reputation / Job Loss</td><td><strong>Bankruptcy / Personal Wealth</strong></td></tr><tr><td><strong>Reward</strong></td><td>Salary + Bonus</td><td><strong>Total Profit</strong></td></tr><tr><td><strong>Focus</strong></td><td>"Am I doing this <em>correctly</em>?"</td><td>"Is this <em>working</em>?"</td></tr></tbody></table>
<h4 id="the-middle-manager">The Middle Manager<a class="anchor" aria-hidden="true" hidden href="#the-middle-manager">#</a></h4>
<p>You described them as a "communication node," which is often true. In a flat corporation, their job is to coordinate.</p>
<ul>
<li><strong>The Disconnect:</strong> They do not own the output. If the team saves <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord">1</span><span class="mord mathnormal">mi</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">o</span><span class="mord mathnormal">n</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">t</span><span class="mord mathnormal">h</span><span class="mord mathnormal">e</span><span class="mord mathnormal">mana</span><span class="mord mathnormal" style="margin-right:0.0359em;">g</span><span class="mord mathnormal" style="margin-right:0.0278em;">er</span><span class="mord mathnormal">mi</span><span class="mord mathnormal" style="margin-right:0.0359em;">g</span><span class="mord mathnormal">h</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.0359em;">g</span><span class="mord mathnormal">e</span><span class="mord mathnormal">t</span><span class="mord mathnormal">a</span></span></span></span>5,000 bonus. If the team loses $1 million, the manager might get fired, but they don't have to pay back the loss from their own pocket.</li>
<li><strong>The Motivation:</strong> Their goal is often <strong>Career Safety</strong>. They want to follow the rules, meet the "Key Performance Indicators" (KPIs), and please the boss.</li>
<li><strong>Economic Term:</strong> We call this the <strong>Principal-Agent Problem</strong>. The "Agent" (manager) acts on behalf of the "Principal" (owner/shareholders), but their interests don't always align.</li>
</ul>
<h4 id="the-sme-owner">The SME Owner<a class="anchor" aria-hidden="true" hidden href="#the-sme-owner">#</a></h4>
<p>You noted they have a "direct relation to economic output."</p>
<ul>
<li><strong>The Connection:</strong> They have <strong>"Skin in the Game."</strong> If the factory produces a defective batch, the owner pays for it personally. If they innovate a new product, they keep all the profit.</li>
<li><strong>The Motivation:</strong> Their goal is <strong>Survival and Growth</strong>. They don't care about "bureaucratic rules" if those rules lose money. They care about the result.</li>
</ul>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="talebAntifragileThingsThat2012">[1] Taleb <a href="https://books.google.com/books?hl=en&#x26;lr=&#x26;id=T9hbUv4NIU0C&#x26;oi=fnd&#x26;pg=PR16&#x26;dq=info:OQTwjej4fbUJ:scholar.google.com&#x26;ots=KEwxfDNfsH&#x26;sig=VlFdZZWWbttm9Q0kQ-NxH1Ssuv0">“Antifragile: Things That Gain from Disorder”</a> Penguin UK 2012</p>]]></content:encoded>
    </item>
    <item>
      <title>Hopfield Networks</title>
      <link>https://flecart.github.io/notes/hopfield-networks/</link>
      <pubDate>Mon, 22 Dec 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/hopfield-networks/</guid>
      <description>Hopfield networks are a type of recurrent neural network that can store and retrieve patterns. They are particularly useful for associative memory tasks, where the network can recall a stored pattern given a noisy or partial input. The Hopfield Network Model # A Hopfield network </description>
      <content:encoded><![CDATA[<p>Hopfield networks are a type of recurrent neural network that can store and retrieve patterns. They are particularly useful for associative memory tasks, where the network can recall a stored pattern given a noisy or partial input.</p>
<h4 id="the-hopfield-network-model">The Hopfield Network Model<a class="anchor" aria-hidden="true" hidden href="#the-hopfield-network-model">#</a></h4>
<p>A Hopfield network consists of a set of neurons that are fully connected to each other, with symmetric weights.
Formally, we have <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">s</span></span></span></span> vectors <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6891em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.2806em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">∈</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.0543em;vertical-align:-0.25em;"></span><span class="minner"><span class="minner"><span class="mopen delimcenter" style="top:0em;">{</span><span class="mord">−</span><span class="mord">1</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord">1</span><span class="mclose delimcenter" style="top:0em;">}</span></span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8043em;"><span style="top:-3.2029em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">n</span></span></span></span></span></span></span></span></span></span></span></span>, a Hopfield network is defined by choosing the connection matrix as:</p>
<span class="katex-display"><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord">Θ</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:2.9291em;vertical-align:-1.2777em;"></span><span class="mop op-limits"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.6514em;"><span style="top:-1.8723em;margin-left:0em;"><span class="pstrut" style="height:3.05em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">i</span><span class="mrel mtight">=</span><span class="mord mtight">1</span></span></span></span><span style="top:-3.05em;"><span class="pstrut" style="height:3.05em;"></span><span><span class="mop op-symbol large-op">∑</span></span></span><span style="top:-4.3em;margin-left:0em;"><span class="pstrut" style="height:3.05em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">s</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:1.2777em;"><span></span></span></span></span></span><span class="mspace" style="margin-right:0.1667em;"></span><span class="minner"><span class="mopen delimcenter" style="top:0em;"><span class="delimsizing size1">[</span></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.2806em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.8913em;"><span style="top:-2.453em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span></span></span></span><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.1389em;">T</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.247em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mord"><span class="mord"><span class="mord"><span class="mord boldsymbol" style="margin-right:0.0778em;">I</span></span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">n</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mclose delimcenter" style="top:0em;"><span class="delimsizing size1">]</span></span></span></span></span></span></span>
<p>One can prove that this matrix is symmetric, and that it is irreflexive (meaning <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord">∀</span><span class="mord mathnormal" style="margin-right:0.0572em;">j</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.9694em;vertical-align:-0.2861em;"></span><span class="mord"><span class="mord">Θ</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.0572em;">j</span><span class="mord mathnormal mtight" style="margin-right:0.0572em;">j</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2861em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">0</span></span></span></span>).</p>
<h4 id="the-update-rule">The update Rule<a class="anchor" aria-hidden="true" hidden href="#the-update-rule">#</a></h4>
<p>The state of each neuron can be either 0 or 1, and the network evolves over time according to the following update rule:</p>
<span class="katex-display"><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6389em;vertical-align:-0.2083em;"></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span><span class="mbin mtight">+</span><span class="mord mtight">1</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2083em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:3em;vertical-align:-1.25em;"></span><span class="minner"><span class="mopen delimcenter" style="top:0em;"><span class="delimsizing size4">{</span></span><span class="mord"><span class="mtable"><span class="col-align-l"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.69em;"><span style="top:-3.69em;"><span class="pstrut" style="height:3.008em;"></span><span class="mord"><span class="mord text"><span class="mord">sign</span></span><span class="mopen">(</span><span class="mord">Θ</span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.2806em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mclose">)</span></span></span><span style="top:-2.25em;"><span class="pstrut" style="height:3.008em;"></span><span class="mord"><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.2806em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:1.19em;"><span></span></span></span></span></span><span class="arraycolsep" style="width:1em;"></span><span class="col-align-l"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.69em;"><span style="top:-3.69em;"><span class="pstrut" style="height:3.008em;"></span><span class="mord"><span class="mord text"><span class="mord"> if </span></span><span class="mord">Θ</span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.2806em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel"><span class="mrel"><span class="mord vbox"><span class="thinbox"><span class="rlap"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="inner"><span class="mord"><span class="mrel"></span></span></span><span class="fix"></span></span></span></span></span><span class="mspace nobreak"></span><span class="mrel">=</span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mord">0</span></span></span><span style="top:-2.25em;"><span class="pstrut" style="height:3.008em;"></span><span class="mord"><span class="mord text"><span class="mord"> if </span></span><span class="mord">Θ</span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.2806em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">t</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mord">0</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:1.19em;"><span></span></span></span></span></span></span></span><span class="mclose nulldelimiter"></span></span></span></span></span></span>
<h3 id="31-the-modern-hopfield-network-a-grand-unification">3.1 The Modern Hopfield Network: A Grand Unification<a class="anchor" aria-hidden="true" hidden href="#31-the-modern-hopfield-network-a-grand-unification">#</a></h3>
<p>See also <a href="/notes/transformers/">Transformers</a>
For decades, the Hopfield Network (introduced by John Hopfield in 1982) was a curiosity in neural network history—a form of recurrent network that could store patterns as "energy minima." However, classical Hopfield Networks had a severe limitation: their storage capacity was linear and small. A network of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.109em;">N</span></span></span></span> neurons could store only approximately <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord">0.14</span><span class="mord mathnormal" style="margin-right:0.109em;">N</span></span></span></span> patterns before "crosstalk" caused the memories to merge into spurious states.16</p>
<p>In a landmark theoretical development (circa 2020-2024), researchers demonstrated a mathematical isomorphism (equivalence) between the Transformer's Self-Attention mechanism and Modern Hopfield Networks (MHNs).5</p>
<p>The Theory:</p>
<p>Classical Hopfield networks use a quadratic energy function. Modern Hopfield Networks (also called Dense Associative Memories) use a steeper, exponential energy function (specifically, the log-sum-exp function).</p>
<p>The update rule for a Modern Hopfield Network is:</p>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.046em;">ξ</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.6644em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">n</span><span class="mord mathnormal mtight">e</span><span class="mord mathnormal mtight" style="margin-right:0.0269em;">w</span></span></span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.0913em;vertical-align:-0.25em;"></span><span class="mord text"><span class="mord">softmax</span></span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0528em;">β</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.0785em;">X</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8413em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.1389em;">T</span></span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.046em;">ξ</span><span class="mclose">)</span><span class="mord mathnormal" style="margin-right:0.0785em;">X</span></span></span></span></p>
<p>where <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0785em;">X</span></span></span></span> is the matrix of stored patterns and <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.046em;">ξ</span></span></span></span> is the state vector.</p>
<p>This equation is mathematically identical to the attention operation in Transformers:</p>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord text"><span class="mord">Attention</span></span><span class="mopen">(</span><span class="mord mathnormal">Q</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">K</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.2222em;">V</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.8em;vertical-align:-0.65em;"></span><span class="mord text"><span class="mord">softmax</span></span><span class="mspace" style="margin-right:0.1667em;"></span><span class="minner"><span class="mopen delimcenter" style="top:0em;"><span class="delimsizing size2">(</span></span><span class="mord"><span class="mopen nulldelimiter"></span><span class="mfrac"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.0895em;"><span style="top:-2.5864em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord sqrt mtight"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.8622em;"><span class="svg-align" style="top:-3em;"><span class="pstrut" style="height:3em;"></span><span class="mord mtight" style="padding-left:0.833em;"><span class="mord mtight"><span class="mord mathnormal mtight">d</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3448em;"><span style="top:-2.3488em;margin-left:0em;margin-right:0.0714em;"><span class="pstrut" style="height:2.5em;"></span><span class="sizing reset-size3 size1 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0315em;">k</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.1512em;"><span></span></span></span></span></span></span></span></span><span style="top:-2.8222em;"><span class="pstrut" style="height:3em;"></span><span class="hide-tail mtight" style="min-width:0.853em;height:1.08em;"><svg xmlns="http://www.w3.org/2000/svg" width="400em" height="1.08em" viewBox="0 0 400000 1080" preserveAspectRatio="xMinYMin slice"><path d="M95,702
c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14
c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54
c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10
s173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429
c69,-144,104.5,-217.7,106.5,-221
l0 -0
c5.3,-9.3,12,-14,20,-14
H400000v40H845.2724
s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7
c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z
M834 80h400000v40h-400000z"></path></svg></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.1778em;"><span></span></span></span></span></span></span></span></span><span style="top:-3.23em;"><span class="pstrut" style="height:3em;"></span><span class="frac-line" style="border-bottom-width:0.04em;"></span></span><span style="top:-3.4461em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">Q</span><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.0715em;">K</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.9191em;"><span style="top:-2.931em;margin-right:0.0714em;"><span class="pstrut" style="height:2.5em;"></span><span class="sizing reset-size3 size1 mtight"><span class="mord mathnormal mtight" style="margin-right:0.1389em;">T</span></span></span></span></span></span></span></span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.538em;"><span></span></span></span></span></span><span class="mclose nulldelimiter"></span></span><span class="mclose delimcenter" style="top:0em;"><span class="delimsizing size2">)</span></span></span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.2222em;">V</span></span></span></span></p>
<p>where <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">Q</span></span></span></span> is the state (query), and <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">K</span></span></span></span> (keys) and <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.2222em;">V</span></span></span></span> (values) represent the stored memory patterns.
The Implications:</p>
<ol>
<li>Exponential Capacity: This proof implies that the storage capacity of the Transformer's attention mechanism is not linear, but exponential with respect to the dimension of the embedding space (<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8444em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal">d</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">m</span><span class="mord mathnormal mtight">o</span><span class="mord mathnormal mtight">d</span><span class="mord mathnormal mtight">e</span><span class="mord mathnormal mtight" style="margin-right:0.0197em;">l</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span>). A single attention head can theoretically distinguish between <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≈</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.888em;"></span><span class="mord"><span class="mord">2</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.888em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">d</span><span class="mord mtight">/2</span></span></span></span></span></span></span></span></span></span></span></span> patterns.16 This explains why Transformers are so effective at "in-context learning"—they are essentially massive associative memory machines capable of retrieving extremely precise patterns from their context window.</li>
<li>Energy Landscapes: Every forward pass of a Transformer can be viewed as one step of energy minimization in a high-dimensional landscape. The model "settles" into the attention pattern that minimizes the conflict between the query and the context.</li>
</ol>
<p>Metastable States: The softmax function acts as a sharpening filter, creating "metastable states" that allow the model to focus intensely on a specific memory (token) while suppressing the noise of thousands of others. This is the mathematical basis of "attention".</p>]]></content:encoded>
    </item>
    <item>
      <title>Reflection</title>
      <link>https://flecart.github.io/notes/reflection/</link>
      <pubDate>Sat, 06 Dec 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/reflection/</guid>
      <description>What is Reflection? # Reflection enables a program to observe and modify its own structure and behavior. t bridges the gap between the base level (the application logic) and the meta level (objects representing the program itself). Core Concepts # Introspection : The program can </description>
      <content:encoded><![CDATA[<h4 id="what-is-reflection">What is Reflection?<a class="anchor" aria-hidden="true" hidden href="#what-is-reflection">#</a></h4>
<p>Reflection enables a program to observe and modify its own structure and behavior. t bridges the gap between the <strong>base level</strong> (the application logic) and the <strong>meta level</strong> (objects representing the program itself).</p>
<!--SR:!2025-12-19,9,250-->
<h4 id="core-concepts">Core Concepts<a class="anchor" aria-hidden="true" hidden href="#core-concepts">#</a></h4>
<ul>
<li><strong>Introspection</strong>: The program can observe its own type information at run time.</li>
<li><strong>Intercession</strong> (Dynamic Manipulation): The program can modify its own structure and behavior (e.g., adding methods, changing fields).</li>
<li><strong>Reflective Code Generation</strong>: Creating executable code from data structures at run time.</li>
</ul>
<!--SR:!2025-12-12,2,230-->
<h3 id="81-introspection"><strong>8.1 Introspection</strong><a class="anchor" aria-hidden="true" hidden href="#81-introspection">#</a></h3>
<p>Introspection is the ability to examine the runtime type of an object. The entry point for this in Java is the <code>Class</code> object.</p>
<h4 id="obtaining-class-objects">Obtaining Class Objects<a class="anchor" aria-hidden="true" hidden href="#obtaining-class-objects">#</a></h4>
<p>There are three main ways to get a <code>Class</code> object in Java:</p>
<ol>
<li><strong>Object instance</strong>: <code>myObject.getClass()</code></li>
<li><strong>Class literal</strong>: <code>String.class</code></li>
<li><strong>String name</strong>: <code>Class.forName("java.lang.String")</code> (Can throw runtime errors)</li>
</ol>
<!--SR:!2025-12-12,2,230-->
<h4 id="inspecting-members"><strong>Inspecting Members</strong><a class="anchor" aria-hidden="true" hidden href="#inspecting-members">#</a></h4>
<p>Once you have the <code>Class</code> object, you can retrieve its members.</p>
<ul>
<li><code>getMethods()</code> / <code>getFields()</code>: Returns <strong>public</strong> members (including inherited ones).</li>
<li><code>getDeclaredMethods()</code> / <code>getDeclaredFields()</code>: Returns <strong>all</strong> members declared in the class (including private ones, but <em>excluding</em> inherited ones).</li>
</ul>
<!--SR:!2025-12-12,2,230-->
<blockquote>
<p>[cite_start]<strong>Safety &#x26; Access</strong>: To access private members, you must suppress Java's access checking using <code>setAccessible(true)</code>[cite: 147]. This breaks information hiding and encapsulation.</p>
</blockquote>
<h4 id="example-universal-tostring"><strong>Example: Universal <code>toString</code></strong><a class="anchor" aria-hidden="true" hidden href="#example-universal-tostring">#</a></h4>
<p>A generic <code>toString</code> method can be written using reflection to iterate over all fields of any object.</p>
<pre><code class="language-java">public static String getString(Object o) {
    if (o == null) return "null";
    Class c = o.getClass();
    // We use getDeclaredFields to see private state
    Field[] fields = c.getDeclaredFields(); 
    for (Field f : fields) {
        if (!Modifier.isStatic(f.getModifiers())) {
             f.setAccessible(true); // Bypass private check
             // ... read value ...
        }
    }
}
</code></pre>
<p>Safety checks (like <code>IllegalAccessException</code>) are moved from compile time to run time1111.</p>
<h4 id="dynamic-invocation-unit-testing"><strong>Dynamic Invocation (Unit Testing)</strong><a class="anchor" aria-hidden="true" hidden href="#dynamic-invocation-unit-testing">#</a></h4>
<p>Reflection allows invoking methods when their names are not known at compile time.</p>
<ul>
<li><strong>Mechanism</strong>: <code>Method.invoke(Object receiver, Object... args)</code>2.</li>
<li><strong>Use Case (JUnit)</strong>: Test drivers can find all methods starting with "test" and invoke them dynamically. This decouples the test runner from the specific test classes3.</li>
</ul>
<h4 id="reflective-visitor-pattern">Reflective Visitor Pattern<a class="anchor" aria-hidden="true" hidden href="#reflective-visitor-pattern">#</a></h4>
<p>Standard Visitor relies on accept methods in every element class. The Reflective Visitor uses introspection to dispatch calls, removing the need for accept4444.</p>
<ul>
<li><strong>Mechanism</strong>: The visitor constructs the method name dynamically based on the element's class.
<pre><code class="language-java">// "magic" string construction
String name = "visit" + e.getClass().getName();
Method m = this.getClass().getMethod(name, e.getClass());
m.invoke(this, e);
</code></pre>
</li>
</ul>
<!--SR:!2025-12-21,11,270-->
<ul>
<li><strong>Pros</strong>: Simpler code in element classes, flexible lookup.</li>
<li><strong>Cons</strong>: Not statically safe (runtime crash if method missing), slower performance.</li>
</ul>
<h4 id="generics-and-erasure">Generics and Erasure<a class="anchor" aria-hidden="true" hidden href="#generics-and-erasure">#</a></h4>
<p>Due to Java's erasure semantics, generic type parameters are <strong>not</strong> available via reflection on instances.</p>
<ul>
<li>Example: You cannot distinguish <code>List&#x3C;String></code> from <code>List&#x3C;Integer></code> at runtime.</li>
<li><code>getMethod("add", String.class)</code> will fail on a <code>List&#x3C;String></code> because the compiled method signature expects <code>Object</code>, not <code>String</code>8888.</li>
</ul>
<!--SR:!2025-12-19,9,250-->
<h3 id="82-reflective-code-generation"><strong>8.2 Reflective Code Generation</strong><a class="anchor" aria-hidden="true" hidden href="#82-reflective-code-generation">#</a></h3>
<p>This involves creating executable code from data structures at runtime9.</p>
<h4 id="why-reflection">Why Reflection?<a class="anchor" aria-hidden="true" hidden href="#why-reflection">#</a></h4>
<p>If code is represented as data, programs can create code from data. This allows adapting the program to user input or the environment (e.g., generating a specific SQL query based on a user filter)10.</p>
<!--SR:!2025-12-19,9,250-->
<h4 id="c-expression-trees">C# Expression Trees<a class="anchor" aria-hidden="true" hidden href="#c-expression-trees">#</a></h4>
<p>In C#, code (specifically lambda expressions) can be treated as data structures called <strong>Expression Trees</strong>11.</p>
<ul>
<li><strong>Structure</strong>: Trees composed of <code>BinaryExpression</code> (operators), <code>ParameterExpression</code> (variables), etc.12.</li>
<li><strong>Compilation</strong>: A <code>.Compile()</code> method turns the tree data structure into executable code (a delegate) at runtime.</li>
</ul>
<pre><code class="language-c#">// Builds the tree for: x &#x3C; c
Expression.Lambda&#x3C;Func&#x3C;int, bool>>(
    Expression.LessThan(lhs, ce), // The binary expression node
    new ParameterExpression[] { lhs }
).Compile(); // Transforms tree -> executable function
</code></pre>
<h3 id="83-dynamic-code-manipulation"><strong>8.3 Dynamic Code Manipulation</strong><a class="anchor" aria-hidden="true" hidden href="#83-dynamic-code-manipulation">#</a></h3>
<p>This refers to modifying the structure of a program (adding/removing methods) while it is running14.</p>
<h4 id="python-example"><strong>Python Example</strong><a class="anchor" aria-hidden="true" hidden href="#python-example">#</a></h4>
<p>Dynamic languages like Python allow extensive manipulation ("Intercession").</p>
<ul>
<li><strong>Monkey Patching</strong>: You can replace methods on a class at runtime15.</li>
<li><em>Example</em>: A generic wrapper can be applied to all methods of a class to make them case-insensitive16.</li>
<li><strong>Mechanism</strong>: Methods can be added, exchanged, or deleted using <code>setattr</code> and <code>del</code>17171717.</li>
</ul>
<pre><code class="language-python"># Injecting a new method into a class at runtime
def new_method(self): return "patched"
setattr(MyClass, "method_name", new_method)
</code></pre>
<h3 id="reflection-and-type-checking"><strong>Reflection and Type Checking</strong><a class="anchor" aria-hidden="true" hidden href="#reflection-and-type-checking">#</a></h3>





















<table><thead><tr><th><strong>Degree of Reflection</strong></th><th><strong>Type Checking Implications</strong></th></tr></thead><tbody><tr><td><strong>Introspection</strong></td><td>Code is type-checked once during compilation (though <code>Class.forName</code> is a runtime check)18.</td></tr><tr><td><strong>Reflective Code Generation</strong></td><td>Code is type-checked once <strong>when it is created</strong> (runtime compilation)19.</td></tr><tr><td><strong>Dynamic Code Manipulation</strong></td><td>Typically requires <strong>dynamic type checking</strong> as types change during execution20.</td></tr></tbody></table>
<h4 id="summary-pros-and-cons">Summary: Pros and Cons<a class="anchor" aria-hidden="true" hidden href="#summary-pros-and-cons">#</a></h4>

























<table><thead><tr><th><strong>Benefits (Applications)</strong></th><th><strong>Drawbacks</strong></th></tr></thead><tbody><tr><td><strong>Flexibility</strong>: Plug-ins, dynamic architectures21.</td><td><strong>No Static Safety</strong>: Type errors occur at runtime (exceptions)22.</td></tr><tr><td><strong>Serialization</strong>: Persisting objects generically23.</td><td><strong>Performance</strong>: Reflection is slower than direct calls24.</td></tr><tr><td><strong>Testing</strong>: Generic test drivers (JUnit)25.</td><td><strong>Complexity</strong>: Code is harder to understand, debug, and maintain26.</td></tr><tr><td><strong>Design Patterns</strong>: Simplifies patterns like Visitor27.</td><td><strong>Breaks Encapsulation</strong>: Can access private fields28.</td></tr></tbody></table>]]></content:encoded>
    </item>
    <item>
      <title>Initialization in Programming Languages</title>
      <link>https://flecart.github.io/notes/initialization-in-programming-languages/</link>
      <pubDate>Tue, 02 Dec 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/initialization-in-programming-languages/</guid>
      <description>&quot;I call it my billion-dollar mistake. It was the invention of the null reference in 1965. [...] This has led to innumerable errors, vulnerabilities, and system crashes.&quot; ~ Tony Hoare 1 The core problem addressed here is Null Safety and how to properly initialize objects to ensure</description>
      <content:encoded><![CDATA[<blockquote>
<p>"I call it my billion-dollar mistake. It was the invention of the null reference in 1965. [...] This has led to innumerable errors, vulnerabilities, and system crashes." ~ <em>Tony Hoare</em> 1</p>
</blockquote>
<p>The core problem addressed here is <strong>Null Safety</strong> and how to properly initialize objects to ensure type invariants (specifically non-nullness) hold true.</p>
<h3 id="simple-non-null-types">Simple Non-Null Types<a class="anchor" aria-hidden="true" hidden href="#simple-non-null-types">#</a></h3>
<p>The goal is to prevent null-dereferencing errors statically.
Most of the variables are null, after initialization.</p>
<h4 id="non-null-types-vs-possibly-null-types">Non-Null Types vs. Possibly-Null Types<a class="anchor" aria-hidden="true" hidden href="#non-null-types-vs-possibly-null-types">#</a></h4>
<ul>
<li><strong>Non-null type <code>T!</code></strong>: Consists of references to <code>T</code>-objects. It <em>cannot</em> hold null.</li>
<li><strong>Possibly-null type <code>T?</code></strong>: Consists of references to <code>T</code>-objects plus <code>null</code>. This corresponds to the standard type <code>T</code> in languages like Java, and the most common case among most languages.</li>
</ul>
<!--SR:!2025-12-21,12,270-->
<h4 id="type-safety-and-invariant">Type Safety and Invariant<a class="anchor" aria-hidden="true" hidden href="#type-safety-and-invariant">#</a></h4>
<ul>
<li><strong>Invariant</strong>: If the static type of an expression <code>e</code> is a non-null type, then <code>e</code>'s value at runtime must be different from <code>null</code>.</li>
<li><strong>Enforcement</strong>: We require non-null types for the receiver of each field access, array access, method call, and throw statement. Equivalent to message not understood cited in <a href="/notes/typing-and-subtyping/">Typing and Subtyping</a>.</li>
</ul>
<h4 id="subtyping-and-casts">Subtyping and Casts<a class="anchor" aria-hidden="true" hidden href="#subtyping-and-casts">#</a></h4>
<p>The values of T! are a proper subset of T?.</p>
<ul>
<li><strong>Subtyping</strong>:
<ul>
<li><code>S! &#x3C;: T!</code> (if S extends T)</li>
<li><code>S? &#x3C;: T?</code> (if S extends T)</li>
<li><code>T! &#x3C;: T?</code> (Non-null is a subtype of possibly-null) 6.</li>
</ul>
</li>
<li><strong>Downcasts</strong>: Casting from <code>T?</code> (possibly-null) to <code>T!</code> (non-null) requires a runtime check., so we know <code>T?</code> is not a subtype of <code>T!</code>.</li>
</ul>
<!--SR:!2025-12-18,9,250-->
<pre><code class="language-mermaid">graph TD
    A[object?]
    B[T?]
    C[S?]
    D(object!)
    E(T!)
    F(S!)
    B --> A
    C --> B
    D -.-> A
    E -.-> B
    E --> D
    F -.-> C
    F --> E
    style D fill:#f0f8ff,color:#007bff,stroke:#007bff,stroke-width:2px
    style E fill:#f0f8ff,color:#007bff,stroke:#007bff,stroke-width:2px
    style F fill:#f0f8ff,color:#007bff,stroke:#007bff,stroke-width:2px
</code></pre>
<h4 id="type-rules">Type Rules<a class="anchor" aria-hidden="true" hidden href="#type-rules">#</a></h4>
<p>Some expressions in a language <strong>need to be non-null</strong></p>
<ul>
<li>Receiver of field access</li>
<li>Receiver of array access</li>
<li>Receiver of method call</li>
<li>Expression of a throw statement.
If not, you can just get a null exception. Now we would like to have compile time error, to make things statically safe.</li>
</ul>
<!--SR:!2025-12-11,2,230-->
<h4 id="safe-handling-null">Safe Handling Null<a class="anchor" aria-hidden="true" hidden href="#safe-handling-null">#</a></h4>
<p>Control Flow Analysis (Dataflow Analysis)
How do we safely use a possibly-null type?
We can check against null.</p>
<ul>
<li><strong>Definite Assignment</strong>: Java/C# use dataflow analysis to ensure local variables are assigned before use.</li>
<li><strong>Null Checks</strong>: If we check <code>if (n != null)</code>, the compiler can treat <code>n</code> as non-null inside the block.</li>
<li><strong>Limitations</strong>: Dataflow analysis works well for local variables but <em>not</em> for heap locations (fields) because of aliasing and <em>side</em> effects (e.g., a method call <code>foo(this)</code> might set a field to null behind the scenes). <em>Concurrency might be a problem</em>.
I have personally seen this thing for the first time in Typescript during my internship at Cubbit.</li>
</ul>
<!--SR:!2025-12-18,9,250-->
<h3 id="object-initialization">Object Initialization<a class="anchor" aria-hidden="true" hidden href="#object-initialization">#</a></h3>
<p>The main challenge is: How do we construct an object of a non-null type?</p>
<p>When we create an object (new T()), fields start as null (or default values). We must ensure all non-null fields are assigned non-null values before the constructor terminates.</p>
<p>The purpose is <strong>establishing</strong> some invariant. We want to know <em>when</em> it is possible to rely on the invariants.</p>
<h4 id="the-escaping-problem">The Escaping Problem<a class="anchor" aria-hidden="true" hidden href="#the-escaping-problem">#</a></h4>
<p>A naive definite assignment check for fields isn't enough. If the this reference "escapes" the constructor (is passed to another method, stored in a global field, etc.) before the object is fully initialized, other code might see null fields that are supposed to be T!.</p>
<p><strong>Escaping Scenarios</strong>:</p>
<ol>
<li><strong>Method Calls</strong>: Calling a dynamically bound method on <code>this</code> inside the constructor. A subclass might override this method and access a field that hasn't been initialized yet.</li>
<li><strong>Callbacks</strong>: Registering <code>this</code> as a listener (e.g., Observer pattern) inside the constructor. The Subject might call back immediately.</li>
<li><strong>Concurrent Access</strong>: Publishing <code>this</code> to a static field where another thread picks it up, bu the object has not been initialized yet.</li>
</ol>
<!--SR:!2025-12-11,2,230-->
<h4 id="initialization-phases">Initialization Phases<a class="anchor" aria-hidden="true" hidden href="#initialization-phases">#</a></h4>
<p>To solve this, we track the state of the object during construction using a type system.</p>
<ol>
<li><strong>Free (Under Construction)</strong>: The object is being created. Fields may be null.</li>
<li><strong>Committed (Initialized)</strong>: The object is fully initialized. All non-null invariants hold.</li>
</ol>
<!--SR:!2025-12-20,11,270-->
<h4 id="construction-types">Construction Types<a class="anchor" aria-hidden="true" hidden href="#construction-types">#</a></h4>
<p>For every class T, we distinguish three states for references:</p>
<ul>
<li><strong><code>T!</code> / <code>T?</code> (Committed)</strong>: Standard types. Construction is complete, if you read non null, it means, we only read non null, for the other cases its not guaranteed.</li>
<li><strong><code>free T!</code> / <code>free T?</code> (Free)</strong>: References to objects <em>under construction</em> (like <code>this</code> inside a constructor).</li>
<li><strong><code>unc T!</code> / <code>unc T?</code> (Unclassified)</strong>: We don't know if it's free or committed (common supertype).</li>
<li>There are no casts from unclassified to free or committed types.</li>
</ul>
<!--SR:!2025-12-20,11,270-->
<h4 id="initialization-requirements">Initialization Requirements<a class="anchor" aria-hidden="true" hidden href="#initialization-requirements">#</a></h4>
<ul>
<li><strong>Requirement 1: Local Initialization</strong>: An object is locally initialized if its non-null fields have non-null values. Committed types <em>must</em> be locally initialized.</li>
<li><strong>Requirement 2: Transitive Initialization</strong>: If an object is committed, everything it reaches (references) must also be committed (transitively initialized).</li>
</ul>
<!--SR:!2025-12-12,2,210-->
<h4 id="handling-cyclic-structures">Handling Cyclic Structures<a class="anchor" aria-hidden="true" hidden href="#handling-cyclic-structures">#</a></h4>
<p>Cyclic structures (e.g., a Node pointing to another Node) pose a problem. We cannot have both objects fully "committed" before they reference each other.</p>
<ul>
<li><em>Solution</em>: We allow <code>free</code> references to be assigned to fields of an object under construction.</li>
<li>The constructor parameters can be declared <code>free</code> to allow passing partially initialized objects (like <code>this</code>).
<ul>
<li>It will be completed only after the last one is completed for requirement two of being well typed.</li>
</ul>
</li>
</ul>
<pre><code class="language-java">
class List {
    List! next; // cyclic list

    List(int n) {
        if (n == 1) {
            next = this;
        } else {
            next = new List(this, n);
        }
    }

    List(free List! last, int n) {
        if (n == 2) {
            next = last;
        } else {
            next = new List(last, n - 1);
        }
    }
}

</code></pre>
<!--SR:!2025-12-11,2,230-->
<h4 id="type-rules-for-initialization">Type Rules for Initialization<a class="anchor" aria-hidden="true" hidden href="#type-rules-for-initialization">#</a></h4>
<ul>
<li><strong>Field Write</strong>: <code>e1.f = e2</code>. If <code>e1</code> is free (under construction), we can assign committed values to it. If <code>e1</code> is committed, we cannot assign a free or unitialized values to it (preserves transitive initialization).</li>
<li><strong>Field Read</strong>:</li>
<li><strong>Method Calls</strong>: Methods must declare if they accept <code>free</code> receivers. You cannot call a standard method on a <code>free</code> object unless that method is marked <code>free</code> (meaning it knows how to handle partially initialized objects)22.</li>
</ul>
<h4 id="subtyping-for-initialization">Subtyping for Initialization<a class="anchor" aria-hidden="true" hidden href="#subtyping-for-initialization">#</a></h4>
<ul>
<li><code>free T! &#x3C;: unc T! &#x3C;: T!</code></li>
<li><code>free T? &#x3C;: unc T? &#x3C;: T?</code></li>
</ul>
<!--SR:!2025-12-12,2,247-->
<h4 id="lazy-initialization">Lazy Initialization<a class="anchor" aria-hidden="true" hidden href="#lazy-initialization">#</a></h4>
<p>We explain here what are usually the main advantages of lazy initialization.
To reduce startup time when initializing an application we use lazy initialization methods.
Sometimes we want to delay initialization until the field is accessed.</p>
<ul>
<li>Since the field starts as <code>null</code>, it must be declared <code>T?</code> (possibly-null) internally.</li>
<li>The getter method checks for null, initializes if necessary, and returns the value as <code>T!</code> (non-null).</li>
</ul>
<!--SR:!2025-12-17,8,250-->
<h4 id="non-null-arrays">Non-Null Arrays<a class="anchor" aria-hidden="true" hidden href="#non-null-arrays">#</a></h4>
<p>Arrays are difficult because they don't have constructors in the traditional sense; they are initialized to default values (null).</p>
<ul>
<li><strong>Problem</strong>: <code>String![] s = new String![5]</code> creates an array of nulls, violating the type <code>String!</code>.</li>
<li><strong>Solutions</strong>:
<ul>
<li>Array initializers: <code>s = { "a", "b" }</code>.</li>
<li>Runtime checks/Assertion methods (e.g., Spec# <code>NonNullType.AssertInitialized(s)</code>).
Methods cannot check within runtime loops (they can initialize other parts).</li>
</ul>
</li>
</ul>
<!--SR:!2025-12-11,1,190-->
<p>Since arrays have really two references, we can have many types for arrays:
`Person! [ ] ! a;Person? [ ] ! b;Person! [ ] ? c;Person? [ ] ? d;</p>
<h4 id="static-initializers">Static Initializers<a class="anchor" aria-hidden="true" hidden href="#static-initializers">#</a></h4>
<ul>
<li>Static initializers are executed once one of the following occurs:</li>
</ul>
<blockquote>
<ol>
<li>The class is instantiated.</li>
<li>A static field is accessed.</li>
<li>A static method is called.</li>
</ol>
</blockquote>
<h3 id="initialization-of-global-data">Initialization of Global Data<a class="anchor" aria-hidden="true" hidden href="#initialization-of-global-data">#</a></h3>
<p>Global data (Singletons, Factories, Flyweights) must be initialized before access.</p>
<h4 id="design-goals">Design Goals<a class="anchor" aria-hidden="true" hidden href="#design-goals">#</a></h4>
<ol>
<li><strong>Effectiveness</strong>: Ensure initialization before first access.</li>
<li><strong>Clarity</strong>: Clean semantics.</li>
<li><strong>Laziness</strong>: Initialize only when needed to save startup time.</li>
</ol>
<!--SR:!2025-12-12,2,210-->
<p>Based on section 6.3 of the provided lecture slides, here is the detailed breakdown of the approaches for initializing global data, including the code snippets you requested.</p>
<h4 id="global-vars-and-init-methods">Global Vars and Init-Methods<a class="anchor" aria-hidden="true" hidden href="#global-vars-and-init-methods">#</a></h4>
<p>This approach uses global variables to store references to global data, but relies on explicit calls to initialization methods to set them up. This is often the most basic way to handle globals in languages that support them.</p>
<ul>
<li><strong>Mechanism</strong>: Explicit <code>init()</code> calls that must be invoked, usually from a main function.</li>
<li><strong>Pros</strong>: It is simple to implement.</li>
<li><strong>Cons</strong>:
<ul>
<li><strong>Manual Ordering</strong>: The programmer must manually code the order of initialization to satisfy dependencies, which is error-prone.</li>
<li><strong>Encapsulation</strong>: Main methods often need to know internal module dependencies to call inits in the right order, breaking information hiding.</li>
<li><strong>No Laziness</strong>: It generally requires upfront initialization unless manually coded otherwise.</li>
</ul>
</li>
</ul>
<pre><code class="language-java">// Global variable declaration
global Factory theFactory;

void init( ) {
    theFactory = new Factory( );
}

class Factory {
    HashMap flyweights;
    Flyweight create( Data d ) { ... }
}

// Client usage
Flyweight f = theFactory.create( ... );
</code></pre>
<h4 id="static-fields-and-initializers-java/c">Static Fields and Initializers (Java/C#)<a class="anchor" aria-hidden="true" hidden href="#static-fields-and-initializers-java/c">#</a></h4>
<p>Java and C# use static fields to store global data and static initializer blocks to initialize them. These blocks run automatically immediately before the class is first used (e.g., creation of an instance, static method call, or static field access)666.</p>
<ul>
<li><strong>Mechanism</strong>: <code>static { ... }</code> blocks executed by the runtime system.</li>
<li><strong>Pros</strong>:
<ul>
<li><strong>Automatic &#x26; Lazy</strong>: Initialization happens just in time when the class is needed, reducing startup time7.</li>
<li><strong>System-managed</strong>: The system handles the triggering of initialization8.</li>
</ul>
</li>
<li><strong>Cons</strong>:
<ul>
<li><strong>Mutual Dependencies</strong>: If class A's static initializer triggers class B, and class B triggers class A, the cycle can lead to crashes or <code>NullPointerExceptions</code> because initialization is considered "in progress" and won't restart, leaving fields uninitialized 9.</li>
<li><strong>Side Effects</strong>: Static initializers can have arbitrary side effects (like modifying other static fields), making it hard to reason about the program state since execution order depends on which class is accessed first 10.</li>
</ul>
</li>
</ul>
<pre><code class="language-java">class Factory {
    static Factory theFactory;
    HashMap flyweights;

    // Static initializer block
    static {
        theFactory = new Factory( );
    }

    Flyweight create( Data d ) { ... }
}

// Initialization triggered here automatically
Factory o = Factory.theFactory;
Flyweight f = o.create( ... );
</code></pre>
<h4 id="scala-objects">Scala Objects<a class="anchor" aria-hidden="true" hidden href="#scala-objects">#</a></h4>
<p>Scala provides direct language support for the Singleton pattern using the <code>object</code> keyword. This defines a class and a single instance of that class simultaneously12.</p>
<ul>
<li>
<p><strong>Mechanism</strong>: <code>object SingletonName { ... }</code>.</p>
</li>
<li>
<p><strong>Pros</strong>: Syntactic sugar and language-level support for singletons.</p>
</li>
<li>
<p><strong>Cons</strong>: Under the hood, this often translates to Java static fields and initializers. Therefore, it inherits all the pros and cons of the static field approach, including issues with mutual dependencies and side effects13.</p>
</li>
</ul>
<p>Scala</p>
<pre><code>object Factory {
    val flyweights: HashMap[ ... ]

    def create( d: Data ): Flyweight = {
        // ... implementation ...
    }
}
</code></pre>
<h4 id="eiffel-once-methods">Eiffel Once Methods<a class="anchor" aria-hidden="true" hidden href="#eiffel-once-methods">#</a></h4>
<p>Eiffel uses <code>once</code> methods (routines). The body of a <code>once</code> method is executed only the first time it is called. The result is cached and returned for all subsequent calls.</p>
<ul>
<li><strong>Mechanism</strong>: The <code>once</code> keyword applied to a feature (method).</li>
<li><strong>Pros</strong>:
<ul>
<li><strong>Laziness</strong>: The initialization code runs only when the data is actually requested.</li>
<li><strong>Caching</strong>: Provides a consistent global access point.</li>
</ul>
</li>
<li><strong>Cons</strong>:
<ul>
<li><strong>Recursion/Mutual Dependencies</strong>: If a <code>once</code> method recursively calls itself (directly or via another object) during its first execution, it returns the <em>current</em> (partial) result rather than waiting or crashing. This often leads to meaningless values like <code>0</code> or <code>null</code> being used.</li>
<li><strong>Parameter Ignoring</strong>: Arguments are used only for the first call; subsequent calls ignore arguments, which can be confusing.</li>
</ul>
</li>
</ul>
<pre><code class="language-eiffel">class FlyweightMgr
feature
    theFactory: Factory
    
    -- "once" ensures this runs only once
    once
        create Result
    end
end

-- Usage
o := manager.theFactory
f := o.createFlyweight( ... )
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Bytecode Verification</title>
      <link>https://flecart.github.io/notes/bytecode-verification/</link>
      <pubDate>Sat, 15 Nov 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/bytecode-verification/</guid>
      <description>Code in modern days is mobile in the sense that it gets downloaded and executed on the fly very often. In JVM they are usually shipped with: Platform independent code Organized into class files. Class Loaders # The class loader is the part of the JVM that takes the bytecode and i</description>
      <content:encoded><![CDATA[<p>Code in modern days is <strong>mobile</strong> in the sense that it gets downloaded and executed on the fly very often.
In JVM they are usually shipped with:</p>
<ul>
<li>Platform independent code</li>
<li>Organized into class files.</li>
</ul>
<h4 id="class-loaders">Class Loaders<a class="anchor" aria-hidden="true" hidden href="#class-loaders">#</a></h4>
<p>The class loader is the part of the JVM that takes the bytecode and interprets all the class files to make the program runnable.</p>
<h3 id="security-considerations">Security Considerations<a class="anchor" aria-hidden="true" hidden href="#security-considerations">#</a></h3>
<h4 id="requirements-for-security">Requirements for Security<a class="anchor" aria-hidden="true" hidden href="#requirements-for-security">#</a></h4>
<ul>
<li>Mobile code cannot be trusted</li>
<li>Code may not be type safe</li>
<li>Code may destroy or modify data</li>
<li>Code may expose personal information</li>
<li>Code may crash the underlying VM</li>
<li>Code may purposefully degrade performance (denial ofservice)</li>
</ul>
<p>This is somewhat similar to the trust relations we explored in <a href="/notes/notions-of-security/">Notions of Security</a>.
Anyways, since the code is not trusted, we need a way to prove some of its properties.</p>
<p>Some properties that are easy to check are:</p>
<ul>
<li>Proper execution requires that</li>
<li>Each instruction is type correct</li>
<li>Only initialized variables are read</li>
<li>No stack over- or underflow occurs</li>
</ul>
<p>This can be done by verification of the types and runtime checking.</p>
<h4 id="sandboxed-execution-environment">Sandboxed Execution Environment<a class="anchor" aria-hidden="true" hidden href="#sandboxed-execution-environment">#</a></h4>
<p>The program only accesses the underlying OS through some <strong>API</strong> that have access control implemented.
In this way we have a limitation of the damage that the system can have.</p>
<ul>
<li>Sandbox- Applets get access tosystem resources onlythrough an API- Access control can beimplemented- Security relies on- Type safety- Code does not by-passsandbox</li>
</ul>
<h4 id="summary-of-the-jvm">Summary of the JVM<a class="anchor" aria-hidden="true" hidden href="#summary-of-the-jvm">#</a></h4>
<p>The Java Virtual Machine is <strong>stack-based</strong> similar to the original assembly programs you have studied at starting of your bachelor.</p>
<ul>
<li>
<p>Most operations popoperands from a stack and push a result.</p>
</li>
<li>
<p>But here, we also have Registers that store method parametersand local variables</p>
</li>
<li>
<p>Instructions are <em>typed</em></p>
</li>
<li>
<p>Load and store instructions access registers</p>
</li>
<li>
<p>Control is handled by intra-method jumps(goto, conditional branches)</p>
</li>
</ul>
<h3 id="type-verification">Type Verification<a class="anchor" aria-hidden="true" hidden href="#type-verification">#</a></h3>
<p>We can use type inference or type checking, at the end we still need some runtime checking for covariant or contravariant types.</p>
<h4 id="why-use-type-inference">Why Use Type-Inference?<a class="anchor" aria-hidden="true" hidden href="#why-use-type-inference">#</a></h4>
<p>We can simulate the execution of the code, just using the <strong>types instead of values</strong> (for some sort of abstract resolution).
Each operation has some <strong>transition rules</strong>. We can follow these transition rules and check if there will be still a transition at the end or not, in this way if there is no transition, I already know that there is an error.</p>
<h4 id="types-of-the-engine">Types of the Engine<a class="anchor" aria-hidden="true" hidden href="#types-of-the-engine">#</a></h4>
<p>In the JVM inference engine we have the first layer of primitive types, then composite (Objects and arrays) and null for null reference.</p>
<pre><code class="language-mermaid">graph BT
  subgraph "Type Hierarchy"
    int --> T
    Object --> T
    float --> T
    intArr["int[]"] --> Object
    floatArr["float[]"] --> Object
    C --> Object
    objArr["Object[]"] --> Object
    cArr["C[]"] --> objArr
    null --> intArr
    null --> floatArr
    null --> C
    null --> cArr
  end
</code></pre>
<p>Where T is the top type for uninitialized registers and <code>C</code> be used for <strong>Class</strong>, <strong>Collection</strong>, or a generic <strong>Type</strong></p>
<h4 id="some-rules">Some Rules<a class="anchor" aria-hidden="true" hidden href="#some-rules">#</a></h4>
<p>MS stands for <em>maximum stack size</em>.
MR is a <em>maximum number of local register variable</em>
And dot stands for concatenation.</p>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6595em;"></span><span class="mord mathnormal">i</span><span class="mord mathnormal">co</span><span class="mord mathnormal">n</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mspace"> </span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">→</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal">in</span><span class="mord mathnormal">t</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mclose">)</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord text"><span class="mord"> if </span></span><span class="mopen">∣</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mclose">∣</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&#x3C;</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8333em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.109em;">M</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.109em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0576em;">S</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span></p>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mspace"> </span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">→</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal">in</span><span class="mord mathnormal">t</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mclose">)</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord text"><span class="mord"> if </span></span><span class="mord">0</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≤</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.5782em;vertical-align:-0.0391em;"></span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&#x3C;</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8333em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.109em;">M</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.109em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0077em;">R</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">∧</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mopen">(</span><span class="mord mathnormal">n</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6595em;"></span><span class="mord mathnormal">in</span><span class="mord mathnormal">t</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">∧</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">∣</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mclose">∣</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&#x3C;</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8333em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.109em;">M</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.109em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0576em;">S</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span></p>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6151em;"></span><span class="mord mathnormal">a</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.0278em;">or</span><span class="mord mathnormal">e</span><span class="mspace"> </span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal">t</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">→</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mopen">{</span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">←</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">t</span><span class="mclose">})</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord text"><span class="mord"> if </span></span><span class="mord">0</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≤</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.5782em;vertical-align:-0.0391em;"></span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&#x3C;</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8333em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.109em;">M</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.109em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0077em;">R</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">∧</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6542em;vertical-align:-0.0391em;"></span><span class="mord mathnormal">t</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&#x3C;:</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0278em;">O</span><span class="mord mathnormal" style="margin-right:0.0572em;">bj</span><span class="mord mathnormal">ec</span><span class="mord mathnormal">t</span></span></span></span>, we use object so that we have a reference (ints  or floats would fail).</p>
<p>aload is very similar to iload, but for addresses.</p>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">in</span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span><span class="mord mathnormal">o</span><span class="mord mathnormal" style="margin-right:0.0315em;">k</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">t</span><span class="mord mathnormal">u</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mspace"> </span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mord">.</span><span class="mord mathnormal">m</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.0019em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.453em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">n</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.247em;"><span></span></span></span></span></span></span><span class="mord">...</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.4519em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">1</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2481em;"><span></span></span></span></span></span></span><span class="mord">.</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">→</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mclose">)</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord text"><span class="mord"> if </span></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mopen">(</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">1</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord">...</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">n</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">∧</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.791em;vertical-align:-0.0391em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&#x3C;:</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">∧</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1.0106em;vertical-align:-0.2587em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.4413em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2587em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&#x3C;:</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.7651em;vertical-align:-0.15em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span>. C stands for class name, m for method name and <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">σ</span></span></span></span> the method signature. The stack needs to contain the parameters in <strong>reverse</strong> order, the end stack needs the result. The parameters of the function need to be subtypes of the signature, while the receiver subtype of the class <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span></span></span></span>.</p>
<p></p><figure class="center">
<img src="/images/notes/Bytecode Verification-20251030103644263.webp" style="width: 100%" alt="Bytecode Verification-20251030103644263" title="Bytecode Verification-20251030103644263">
<figcaption><p style="text-align:center;"> Example from the Course Slides</p></figcaption>
</figure><p></p>
<h4 id="smallest-common-supertype">Smallest Common Supertype<a class="anchor" aria-hidden="true" hidden href="#smallest-common-supertype">#</a></h4>
<blockquote>
<p>It is the most specific type that is the supertype of two or more types; it is used in type inference when multiple control paths join and the stack may contain different types.</p>
</blockquote>
<!--SR:!2025-12-12,8,270-->
<p>Jumps in the control flow can lead to <strong>joins</strong>.
When you have a top object in the stack with different types, the <strong>smallest common supertype</strong> is used now.
If we have multiple subtyiping, the result would not be well-defined, for this reason we:</p>
<ul>
<li>Ignore interfaces  (they are all objects)</li>
<li>Then in Java you can only subclass once, and we have resolved this problem.</li>
</ul>
<p>But we need runtime checks for invokeinterface.</p>
<h4 id="type-inference-algorithm">Type Inference Algorithm<a class="anchor" aria-hidden="true" hidden href="#type-inference-algorithm">#</a></h4>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">in</span><span class="mopen">(</span><span class="mord">0</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">([</span><span class="mspace"> </span><span class="mclose">]</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mopen">[</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.1389em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">0</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord">...</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.1389em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">n</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.1389em;">T</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord">...</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.1389em;">T</span><span class="mclose">])</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal" style="margin-right:0.0269em;">w</span><span class="mord mathnormal" style="margin-right:0.0278em;">or</span><span class="mord mathnormal" style="margin-right:0.0315em;">k</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">{</span><span class="mord mathnormal">i</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">∣</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord text"><span class="mord">instr</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord text"><span class="mord"> is an instruction of the method</span></span><span class="mclose">}</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathbf">while</span></span><span class="mspace"> </span><span class="mord mathnormal" style="margin-right:0.0269em;">w</span><span class="mord mathnormal" style="margin-right:0.0278em;">or</span><span class="mord mathnormal" style="margin-right:0.0315em;">k</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel"><span class="mrel"><span class="mord vbox"><span class="thinbox"><span class="rlap"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="inner"><span class="mord"><span class="mrel"></span></span></span><span class="fix"></span></span></span></span></span><span class="mspace nobreak"></span><span class="mrel">=</span></span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8056em;vertical-align:-0.0556em;"></span><span class="mord">∅</span><span class="mspace"> </span><span class="mord"><span class="mord mathbf">do</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6595em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord mathnormal">i</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mop">min</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0269em;">w</span><span class="mord mathnormal" style="margin-right:0.0278em;">or</span><span class="mord mathnormal" style="margin-right:0.0315em;">k</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mclose">)</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord text"><span class="mord">remove </span></span><span class="mord mathnormal">i</span><span class="mord text"><span class="mord"> from </span></span><span class="mord mathnormal" style="margin-right:0.0269em;">w</span><span class="mord mathnormal" style="margin-right:0.0278em;">or</span><span class="mord mathnormal" style="margin-right:0.0315em;">k</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord mathnormal">o</span><span class="mord mathnormal">u</span><span class="mord mathnormal">t</span><span class="mopen">(</span><span class="mord mathnormal">i</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.06em;vertical-align:-0.31em;"></span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.0197em;">ppl</span><span class="mord mathnormal" style="margin-right:0.0359em;">y</span><span class="mord" style="margin-right:0.0278em;">_</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">e</span><span class="mopen">(</span><span class="mord"><span class="mord text"><span class="mord">instr</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">in</span><span class="mopen">(</span><span class="mord mathnormal">i</span><span class="mclose">))</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf">foreach</span></span><span class="mspace"> </span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mord text"><span class="mord"> in </span></span><span class="mord mathnormal">s</span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.0278em;">ccessor</span><span class="mord mathnormal">s</span><span class="mopen">(</span><span class="mord mathnormal">i</span><span class="mclose">)</span><span class="mspace"> </span><span class="mord"><span class="mord mathbf">do</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord mathnormal">in</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.06em;vertical-align:-0.31em;"></span><span class="mord mathnormal">p</span><span class="mord mathnormal">o</span><span class="mord mathnormal">in</span><span class="mord mathnormal" style="margin-right:0.0269em;">tw</span><span class="mord mathnormal">i</span><span class="mord mathnormal">se</span><span class="mord" style="margin-right:0.0278em;">_</span><span class="mord mathnormal">scs</span><span class="mopen">(</span><span class="mord mathnormal">in</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">o</span><span class="mord mathnormal">u</span><span class="mord mathnormal">t</span><span class="mopen">(</span><span class="mord mathnormal">i</span><span class="mclose">))</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf" style="margin-right:0.109em;">if</span></span><span class="mspace"> </span><span class="mord mathnormal">in</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span><span class="mord text"><span class="mord"> has changed</span></span><span class="mspace"> </span><span class="mord"><span class="mord mathbf">then</span></span><span class="mspace"> </span><span class="mord mathnormal" style="margin-right:0.0269em;">w</span><span class="mord mathnormal" style="margin-right:0.0278em;">or</span><span class="mord mathnormal" style="margin-right:0.0315em;">k</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal" style="margin-right:0.0269em;">w</span><span class="mord mathnormal" style="margin-right:0.0278em;">or</span><span class="mord mathnormal" style="margin-right:0.0315em;">k</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">∪</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">{</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">}</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf">end</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathbf">end</span></span></span></span></span></p>
<p>Remember q is the following instruction (could be more than one).</p>
<p>There is very little information that is needed to make this algorithm work, but it may be <strong>slow</strong>.</p>
<h4 id="pointwise-scs">Pointwise SCS<a class="anchor" aria-hidden="true" hidden href="#pointwise-scs">#</a></h4>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.0619em;vertical-align:-0.31em;"></span><span class="mord mathnormal">p</span><span class="mord mathnormal">o</span><span class="mord mathnormal">in</span><span class="mord mathnormal" style="margin-right:0.0269em;">tw</span><span class="mord mathnormal">i</span><span class="mord mathnormal">se</span><span class="mord" style="margin-right:0.0278em;">_</span><span class="mord mathnormal">scs</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="minner"><span class="mopen delimcenter" style="top:0em;">(</span><span class="minner"><span class="mopen delimcenter" style="top:0em;">(</span><span class="mopen">[</span><span class="mord"><span class="mord mathnormal">s</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">1</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord">.....</span><span class="mord"><span class="mord mathnormal">s</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0315em;">k</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mclose">]</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mopen">[</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">0</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord">...</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">n</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mclose">]</span><span class="mclose delimcenter" style="top:0em;">)</span></span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="minner"><span class="mopen delimcenter" style="top:0em;">(</span><span class="mopen">[</span><span class="mord"><span class="mord mathnormal">s</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.4519em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">1</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2481em;"><span></span></span></span></span></span></span><span class="mord">.....</span><span class="mord"><span class="mord mathnormal">s</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.4169em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0315em;">k</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2831em;"><span></span></span></span></span></span></span><span class="mclose">]</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mopen">[</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.4519em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">0</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2481em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord">...</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.453em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">n</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.247em;"><span></span></span></span></span></span></span><span class="mclose">]</span><span class="mclose delimcenter" style="top:0em;">)</span></span><span class="mclose delimcenter" style="top:0em;">)</span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.035em;vertical-align:-0.2831em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="minner"><span class="mopen delimcenter" style="top:0em;">(</span><span class="minner"><span class="mopen delimcenter" style="top:0em;">[</span><span class="mord mathnormal">scs</span><span class="mopen">(</span><span class="mord"><span class="mord mathnormal">s</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">1</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">s</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.4519em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">1</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2481em;"><span></span></span></span></span></span></span><span class="mclose">)</span><span class="mord">.....</span><span class="mord mathnormal">scs</span><span class="mopen">(</span><span class="mord"><span class="mord mathnormal">s</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0315em;">k</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">s</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.4169em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0315em;">k</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2831em;"><span></span></span></span></span></span></span><span class="mclose">)</span><span class="mclose delimcenter" style="top:0em;">]</span></span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="minner"><span class="mopen delimcenter" style="top:0em;">[</span><span class="mord mathnormal">scs</span><span class="mopen">(</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">0</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.4519em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">0</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2481em;"><span></span></span></span></span></span></span><span class="mclose">)</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord">...</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">scs</span><span class="mopen">(</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">n</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-2.453em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">n</span></span></span><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.247em;"><span></span></span></span></span></span></span><span class="mclose">)</span><span class="mclose delimcenter" style="top:0em;">]</span></span><span class="mclose delimcenter" style="top:0em;">)</span></span></span></span></span></p>
<p>pointwise_scs is undefined for stacks of different heights
Bytecode verification results in an error if called with this.</p>
<h4 id="type-checking-algorithm">Type Checking Algorithm<a class="anchor" aria-hidden="true" hidden href="#type-checking-algorithm">#</a></h4>
<p>We can <strong>avoid SCS</strong> and fixed point computation by marking what is the expected type at the beginning and at the end of some specific code block.
This means we need to extend the class code with more type information.</p>
<p><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathbf">foreach</span></span><span class="mspace"> </span><span class="mord text"><span class="mord">basic block of a method body</span></span><span class="mspace"> </span><span class="mord"><span class="mord mathbf">do</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf">foreach</span></span><span class="mspace"> </span><span class="mopen">{</span><span class="mord mathnormal">i</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">∣</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord text"><span class="mord">instr</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord text"><span class="mord"> is an instruction of basic block</span></span><span class="mclose">}</span><span class="mspace"> </span><span class="mord"><span class="mord mathbf">do</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf" style="margin-right:0.109em;">if</span></span><span class="mspace"> </span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.0359em;">y</span><span class="mord mathnormal">p</span><span class="mord mathnormal">es</span><span class="mopen">(</span><span class="mord mathnormal">i</span><span class="mclose">)</span><span class="mord text"><span class="mord"> is declared</span></span><span class="mspace"> </span><span class="mord"><span class="mord mathbf">then</span></span><span class="mspace"> </span><span class="mord mathnormal">in</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.0359em;">y</span><span class="mord mathnormal">p</span><span class="mord mathnormal">es</span><span class="mopen">(</span><span class="mord mathnormal">i</span><span class="mclose">)</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6595em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord mathnormal">in</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.06em;vertical-align:-0.31em;"></span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.0197em;">ppl</span><span class="mord mathnormal" style="margin-right:0.0359em;">y</span><span class="mord" style="margin-right:0.0278em;">_</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">e</span><span class="mopen">(</span><span class="mord"><span class="mord text"><span class="mord">instr</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3117em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">i</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">in</span><span class="mclose">)</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf">foreach</span></span><span class="mspace"> </span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mord text"><span class="mord"> in </span></span><span class="mord mathnormal">s</span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.0278em;">ccessor</span><span class="mord mathnormal">s</span><span class="mopen">(</span><span class="mord mathnormal">i</span><span class="mclose">)</span><span class="mspace"> </span><span class="mord"><span class="mord mathbf">do</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf" style="margin-right:0.109em;">if</span></span><span class="mspace"> </span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.0359em;">y</span><span class="mord mathnormal">p</span><span class="mord mathnormal">es</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span><span class="mord text"><span class="mord"> is declared</span></span><span class="mspace"> </span><span class="mord"><span class="mord mathbf">then</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord text"><span class="mord">check that </span></span><span class="mord mathnormal">in</span><span class="mord text"><span class="mord"> is assignable to </span></span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.0359em;">y</span><span class="mord mathnormal">p</span><span class="mord mathnormal">es</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.0359em;">q</span><span class="mclose">)</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf">end</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf">end</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mspace" style="margin-right:1em;"></span><span class="mord"><span class="mord mathbf">end</span></span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathbf">end</span></span></span></span></span></p>
<p></p><figure class="center">
<img src="/images/notes/Bytecode Verification-20251030111912553.webp" style="width: 100%" alt="Bytecode Verification-20251030111912553" title="Bytecode Verification-20251030111912553">
<figcaption><p style="text-align:center;"> Example of a type checking run, slide from the Course Slides</p></figcaption>
</figure><p></p>
<h4 id="bytecode-verifiers-are-general">Bytecode Verifiers are General<a class="anchor" aria-hidden="true" hidden href="#bytecode-verifiers-are-general">#</a></h4>
<p>There are some codes that are not verifiable in source code but completely fine in bytecode.
For example dynamic assignment codes like this:</p>
<pre><code class="language-java">x = 5
if (...) {
	x = "hello"
	print(x)
	x = 7;
}
x = x * 2;
</code></pre>
<p>Since the bytecode knows the type after every step, the SCS after the block is still int, and that operation can be verified.
Usually this is usable for the compiler (rediscovered using fixed point? No, type checking is far more efficient if you already have that information).
The important thing to remember is that we are computing the types at the start of <strong>code blocks</strong>!</p>
<h4 id="type-inference-for-source-programs">Type Inference for Source Programs<a class="anchor" aria-hidden="true" hidden href="#type-inference-for-source-programs">#</a></h4>
<p>We can also apply type-inference at the start, at the source, not only at the bytecode level. If you have experience in programming, this is the standard version that you probably might know.
Type inference can be done at this level to levy some typing burdens to the programmer.
You can also use <strong>type annotations</strong> as in python to help the inference.</p>
<p>Type inference is only for <strong>local variables</strong>, fields and other kinds need still to be written (if not this would be not modular (e.g. you would need to know all overrides as well, and the types would change)).</p>
<ul>
<li>Inference of <strong>method signatures</strong> generally requires knowledge of <strong>all implementations</strong></li>
<li>Inference of <strong>field types</strong> generally requires knowledge of <strong>all accesses</strong> to the field</li>
<li>Inference of these types is <strong>non-modular</strong></li>
<li>Or based on <strong>speculation</strong></li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Typing and Subtyping</title>
      <link>https://flecart.github.io/notes/typing-and-subtyping/</link>
      <pubDate>Tue, 11 Nov 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/typing-and-subtyping/</guid>
      <description>We first start with some design goals for the language Language Design Principles # Simplicity Syntax and semantics can easily be understood by users and implementers of the language Expressiveness : Language can (easily) express complex processes and structures, conflicting with</description>
      <content:encoded><![CDATA[<p>We first start with some design goals for the language</p>
<h4 id="language-design-principles">Language Design Principles<a class="anchor" aria-hidden="true" hidden href="#language-design-principles">#</a></h4>
<p><strong>Simplicity</strong> Syntax and semantics can easily be understood by users and implementers of the language
<strong>Expressiveness</strong>: Language can (easily) express complex processes and structures, conflicting with simplicity.
<strong>Safety</strong>: Language discourages errors and allows errors to be discovered and reported, ideally at compile time
<strong>Modularity</strong>: Language allows modules to be type-checked and compiled separately
<strong>Performance</strong>: Programs written in the language can be executed efficiently
<strong>Productivity</strong>:  Language leads to low costs of writing programs like Python.
<strong>Backwards Compatibility</strong>: Newer language versions work and interface with programs in older versions (dependency injection for examples helps for this.)</p>
<blockquote>
<p>“The basic philosophy underlying object-orientedprogramming is to make the programs as far aspossible reflect that part of the reality they are goingto treat. It is then often easier to understand and toget an overview of what is described in programs.The reason is that human beings from the outset areused to and trained in the perception of what is goingon in the real world. The closer it is possible to usethis way of thinking in programming, the easier it is towrite and understand programs.“ ~<em>Object-oriented Programming in the BETA Programming Language</em></p>
</blockquote>
<p>This node should be something very similar to what present in <a href="/notes/teoria-dei-tipi/">Teoria dei Tipi</a>. But here we revise it for the master's course in another manner.</p>
<p>Types allow you do something more statically detect some errors.</p>
<h4 id="message-not-understood">Message not understood<a class="anchor" aria-hidden="true" hidden href="#message-not-understood">#</a></h4>
<p>When some method does not exist we should get this kind of error, the message not understood (using the class as message passing example.)
Static type systems should be able to understand this kind of messages.</p>
<h4 id="java-security-model">Java Security Model<a class="anchor" aria-hidden="true" hidden href="#java-security-model">#</a></h4>
<p>Code could come from arbitrary sources. For security reason, we <strong>pass code to API</strong>, and in this manner we can implement access control at this level. For this reason we don't allo type automatic type casting like moving int to a pointer implicitly as you can do it in C.
Java clearly separates the OS with some API interface, in this manner we have some sort of isolation.</p>
<h3 id="type-systems">Type Systems<a class="anchor" aria-hidden="true" hidden href="#type-systems">#</a></h3>
<h4 id="definition-of-type-system">Definition of Type System<a class="anchor" aria-hidden="true" hidden href="#definition-of-type-system">#</a></h4>
<blockquote>
<p>A type system is a <strong>tractable</strong> syntactic method for proving the <em>absence</em> of certain program behaviors by classifying phrases according to the kinds of values they compute B.C. Pierce 2002</p>
</blockquote>
<ul>
<li>Syntactic: Rules are based on form, not behavior</li>
<li>Phrases: Expressions, methods, etc. of a program</li>
<li>Kinds of values: Types</li>
</ul>
<h4 id="a-type-and-its-properties">A Type and Its Properties<a class="anchor" aria-hidden="true" hidden href="#a-type-and-its-properties">#</a></h4>
<blockquote>
<p>A type is a set of values sharing some properties.A value v has type T if v is an element of T.</p>
</blockquote>
<p>The properties consist on <em>syntactical</em> principles but also <em>behavioural</em> principles.</p>
<p>We have <strong>Nominal Types</strong> based on type names, so you just define one type is equal to another based on this kind of relationships. In this case, even if they have the same functionality, but they are called differently, then they are different.
And <strong>Structural Types</strong>: you say they are equivalent when they have the same methods and fields, so its based on their <em>availability</em>.</p>
<p>In the past we have defined a concept of type equivalence based on these properties, see <a href="/notes/algebra-dei-tipi/">Algebra dei tipi</a>.</p>
<h4 id="weakly-and-strongly-typed-languages">Weakly and Strongly-Typed languages<a class="anchor" aria-hidden="true" hidden href="#weakly-and-strongly-typed-languages">#</a></h4>
<p>The main distinction we make here, is the difference between type and value, and the operations that you can do about those.</p>
<p><strong>Untyped languages:</strong> Do not classify values into types- Example: assembly languages. This is one of the oldest and most difficult ways to deal with code, basically you don't have <em>any abstraction</em>.</p>
<p><strong>Weakly-typed languages</strong>: Classify values into types, but do <em>not strictly enforce additional restrictions</em> Example: C, C++. In this case, you can freely convert one value with another, the system does not check constraint before execution. This is also a reason why you get segmentation faults and stuff similar to this.</p>
<p><strong>Strongly-typed languages</strong>: Enforce that all operations are applied to arguments of the appropriate types- Examples: C#, Eiffel, Java, Python, Scala, Smalltalk</p>
<h4 id="static-and-dynamic-type-checking">Static and Dynamic Type Checking<a class="anchor" aria-hidden="true" hidden href="#static-and-dynamic-type-checking">#</a></h4>
<p>See <a href="/notes/teoria-dei-tipi/#dynamic-and-static-typing">Teoria dei Tipi#Dynamic and static typing</a>. The thing you have to remember is that with static you can check at compile time while with dynamic you usually just can check at runtime.</p>








































<table><thead><tr><th>Aspect</th><th>Advantages of <strong>Static Checking</strong></th><th>Advantages of <strong>Dynamic Checking</strong></th></tr></thead><tbody><tr><td><strong>Error detection</strong></td><td><strong>Static safety</strong>: More errors are caught at compile time, before running the program.</td><td><strong>Expressiveness</strong>: No correct program is rejected by the type checker — fewer artificial restrictions.</td></tr><tr><td><strong>Readability &#x26; Documentation</strong></td><td>Types serve as <strong>self-documentation</strong>, making code easier to understand.</td><td></td></tr><tr><td><strong>Performance</strong></td><td>Type information allows <strong>compiler optimizations</strong>, often faster execution.</td><td>No compile-time type machinery — lower upfront overhead. Higher later overhead.</td></tr><tr><td><strong>Tooling</strong></td><td>Strong types enable <strong>better IDE support</strong>: auto-completion, refactoring, static analysis.</td><td><strong>Simplicity</strong>: No complicated type system rules to learn or work around.</td></tr><tr><td><strong>Flexibility</strong></td><td>Can be restrictive — some correct programs won’t type-check.</td><td>Very flexible — developers can write code without fighting the type checker.</td></tr><tr><td><strong>Overhead</strong></td><td>Very large, it requires extensive contracts</td><td>Low, but contracts are</td></tr></tbody></table>
<h4 id="static-type-safety">Static Type Safety<a class="anchor" aria-hidden="true" hidden href="#static-type-safety">#</a></h4>
<blockquote>
<p>A programming language is called type-safe if its design prevents type errors.</p>
</blockquote>
<blockquote>
<p>Statically type-safe object-oriented languages guarantee the following type invariant:In every execution state, the value held by variable is an element of the declared type of v</p>
</blockquote>
<p>Some of the errors are thus prevented in this manner.</p>
<p>Consider</p>
<pre><code class="language-java">Object[ ] oa = new Object[ 10 ];
String s = “A String”;
oa[ 0 ] = s;
...
s = (String) oa[ 0 ];
s = s.concat( “Another String” );
</code></pre>
<p>There is a runtime check at <code>(String) </code> to check if the thing is really a string, if not it breaks.</p>
<p>Usually with dynamic type checking, we get much more flexibility. For example checking the safety of generated code. You cannot do that with static since you don't know the type during compilation. In this sense dynamic type checkers are more expressive.</p>
<h4 id="bypassing-type-checks">Bypassing type checks<a class="anchor" aria-hidden="true" hidden href="#bypassing-type-checks">#</a></h4>
<pre><code class="language-C#">dynamic v = getPythonObject( );
dynamic res = v.Foo( 5 ); 
</code></pre>
<p>This is an example in C# that does this. This is useful for inter-operation or interacting with the DOM</p>
<h4 id="gradual-typing">Gradual Typing<a class="anchor" aria-hidden="true" hidden href="#gradual-typing">#</a></h4>
<p>We call gradual typing these kind of types where we have optional type checks, when you have a type annotation, you check it.
This does not give you a <em>guarantee</em>, but its safer compared to not having it.
For example in Python we can use <strong>type annotations</strong> and we have some optional static type checking in the code. We can also use <code>Any</code> to say that it doesn't have any static type.</p>
<h4 id="duck-typing">Duck Typing<a class="anchor" aria-hidden="true" hidden href="#duck-typing">#</a></h4>
<blockquote>
<p>When I see a bird that walkslike a duck and swims like aduck and quacks like a duck,I call that bird a duck.“ ~<em>James Whitcomb Riley</em></p>
</blockquote>




















<table><thead><tr><th></th><th><strong>Static</strong></th><th><strong>Dynamic</strong></th></tr></thead><tbody><tr><td><strong>Nominal</strong></td><td>C++, C#, Eiffel, Java, Scala</td><td>Individual features of nominal, static languages</td></tr><tr><td><strong>Structural</strong></td><td>Go, OCaml</td><td>JavaScript, Python, Ruby, Smalltalk (Ducktyping)</td></tr></tbody></table>
<h2 id="subtyping">Subtyping<a class="anchor" aria-hidden="true" hidden href="#subtyping">#</a></h2>
<blockquote>
<p>Objects of subtypes can be used wherever objects of supertypes are expected</p>
</blockquote>
<h3 id="introduction-to-subtyping">Introduction to Subtyping<a class="anchor" aria-hidden="true" hidden href="#introduction-to-subtyping">#</a></h3>
<p>Subtyping is a set relation between the types. And again, here we can decide nominal or structural subtyping. It depends on the properties that the types have! Again, see <a href="/notes/algebra-dei-tipi/">Algebra dei tipi</a>.</p>
<h4 id="classification-principles">Classification principles<a class="anchor" aria-hidden="true" hidden href="#classification-principles">#</a></h4>
<p>We have mainly two ways to decide whether to classify the syntactic and semantic parts.</p>
<ul>
<li><strong>Syntactic</strong> Subtype objects can understand at least the messages that supertype objects can understand</li>
<li><strong>Semantic</strong> Subtype objects provide at least the behavior of supertype objects</li>
</ul>
<p>Other than this, we also have structural and nominal subtyping, but you already know these from bachelor courses.</p>
<h4 id="subtyping-rules">Subtyping rules<a class="anchor" aria-hidden="true" hidden href="#subtyping-rules">#</a></h4>
<p>We have three main subtyping rules:
<strong>Existence</strong>:
Subtypes cannot remove any method or field that was present in the supertype</p>
<p><strong>Accessibility</strong>:
We cannot make stuff less accessible.</p>
<p><strong>Overriding rules</strong>:
There are many overriding rules, the most important ones are the covariant and contravariant rules. But you also need to keep in mind that the type of bound methods should not be changed.</p>
<p>There are some specific overriding rules in Java</p>
<p>A method <code>Sub.m</code> overrides <code>Super.m</code> <strong>iff</strong>:</p>
<ol>
<li>Same name</li>
<li>Same number of parameters</li>
<li><strong>Same parameter types after erasure</strong></li>
<li>Return type of <code>Sub.m</code> is the same or a subtype (covariant return)</li>
<li>Visibility is not reduced (<code>public</code> → <code>protected</code> is illegal)</li>
<li>Throws clause is not “wider” (checked exceptions must be subset)
Generics don’t change this. They only affect:</li>
</ol>
<ul>
<li>what erases to what</li>
<li>whether the compiler <em>accepts</em> the override</li>
<li>whether bridge methods are needed</li>
</ul>
<blockquote>
<p>A method in a subclass overrides a method in a superclass if they have the same erased parameter types and return type, and the subclass method <strong>can be seen as an instance</strong> of the superclass method’s signature.</p>
</blockquote>
<!--SR:!2025-12-15,5,230-->
<h4 id="covariant-and-contravariant-rules">Covariant and Contravariant Rules<a class="anchor" aria-hidden="true" hidden href="#covariant-and-contravariant-rules">#</a></h4>
<ul>
<li><strong>Contravariant parameters</strong>: An overriding method must not require more specific parameter types than the methods it overrides</li>
<li><strong>Covariant results</strong>: An overriding method must not have a more general result type than the methods it overrides- Out-parameters and exceptions are results
<ul>
<li>For example Java and C# arrays are covariant, meaning they can also contain subtypes underneath it. (another method to do it would be to have generics, which would be more type safe compared to this).</li>
</ul>
</li>
</ul>
<p>Why this should be valid can be easily seen with some examples.</p>
<h3 id="drawbacks-of-nominal-subtyping">Drawbacks of Nominal Subtyping<a class="anchor" aria-hidden="true" hidden href="#drawbacks-of-nominal-subtyping">#</a></h3>
<h4 id="nominal-subtyping-reuse">Nominal Subtyping Reuse<a class="anchor" aria-hidden="true" hidden href="#nominal-subtyping-reuse">#</a></h4>
<pre><code class="language-java">class Resident { String getName( ) { ... }; Data dateOfBirth( ) { ... }; Address getAddress( ) { ... }}
</code></pre>
<pre><code class="language-java">class Employee { String getName( ) { ... }; Data dateOfBirth( ) { ... }; int getSalary( ) { ... }}
</code></pre>
<p>Consider the above two classes, even if underneath in the memory you will have the same results, one type is not a subtype of another, and you cannot make a common <code>Person[]</code> collection type.
This problem is trivially not present with structural subtyping.</p>
<p>Normal resolution of these problems involve the <strong>adapter</strong> pattern.
The main drawback of this method is added complexity in implementation and a little runtime overhead to implement this abstraction on the virtual machine.</p>
<pre><code class="language-java">interface Person {String getName( );Data dateOfBirth( );}
</code></pre>
<pre><code class="language-java">class EmployeeAdapter implements Person {
     private Employee adaptee;
     String getName( ) { return adaptee.getName( ); }
     Data dateOfBirth() { return adaptee.dateOfBirth( ); }
}
</code></pre>
<h4 id="generalization-problems">Generalization Problems<a class="anchor" aria-hidden="true" hidden href="#generalization-problems">#</a></h4>
<pre><code class="language-java">void printData( Collection&#x3C;String> c ) {
	if( c.isEmpty() ) 
		System.out.println( “empty” );
	else {
		Iterator&#x3C;String> iter = c.iterator( );
		while( iter.hasNext() ) System.out.println( iter.next() );
	}
}
</code></pre>
<p>We just needed two methods, but we had to define an input with 13 methods. So there is some inefficiency from this point of view.</p>
<p>How this is generally solved is to make <em>weaker</em> interfaces and make them extend these, but this needs lots more boilerplate code. Looks like to me code doesn't have that human contextual understanding that makes communication very efficient. When a programmer writes code, in some sense it is communicating with the machine. The machine tells you back if he understood correctly the message, and if not, it just behaves erroneously.</p>
<h3 id="behavioral-principles">Behavioral Principles<a class="anchor" aria-hidden="true" hidden href="#behavioral-principles">#</a></h3>
<p>We will explore all the principles of <strong>behavioural subtyping</strong> here, which can be summarized as follows:</p>
<p>Subtype objects must fulfill contracts of supertypes, but:</p>
<ul>
<li>Subtypes can have <strong>stronger invariants</strong></li>
<li>Subtypes can have <strong>stronger history constraints</strong></li>
<li>Overriding methods of subtypes can have:
<ul>
<li><strong>weaker preconditions</strong></li>
<li><strong>stronger post-conditions</strong></li>
</ul>
</li>
</ul>
<h4 id="method-behaviour-terminology">Method Behaviour Terminology<a class="anchor" aria-hidden="true" hidden href="#method-behaviour-terminology">#</a></h4>
<ul>
<li><strong>Preconditions</strong> have to hold in the state before the method body is executed</li>
<li><strong>Post-conditions</strong> have to hold in the state after the method body has terminated</li>
<li><strong>Old-expressions</strong> can be used to refer to prestate heap from the postcondition</li>
<li><strong>Visible States</strong>: Visible states are the pre and post states in between a method, they can be violated temporarily</li>
<li><strong>History Constraints</strong>: are reflexive and transitive constraints related to visible states.</li>
</ul>
<h4 id="object-invariants">Object Invariants<a class="anchor" aria-hidden="true" hidden href="#object-invariants">#</a></h4>
<blockquote>
<p>Object invariants describe consistency criteria for objects</p>
</blockquote>
<p>These invariants are hold in all states in which an object is accessed.</p>
<p>Contract because we have obligations between the caller and the callee.</p>
<h4 id="rules-for-subtyping">Rules for Subtyping<a class="anchor" aria-hidden="true" hidden href="#rules-for-subtyping">#</a></h4>
<p>In all cases, the subtype should satisfy the rules of the types.</p>
<ul>
<li><strong>Preconditions</strong>: they can just be weaker or equal</li>
<li><strong>Postconditions</strong>: they can be stronger or equal</li>
<li><strong>Invariants</strong>: also in this case they should be stronger.</li>
<li><strong>History conditions</strong>: must be stronger</li>
</ul>
<h4 id="checking-behavioural-subtyping">Checking Behavioural Subtyping<a class="anchor" aria-hidden="true" hidden href="#checking-behavioural-subtyping">#</a></h4>
<p>We can make some static checking with regards to the types, and overriding, and also checking all heaps and things like that. We check <em>all parameters, heaps and results</em>.
This is <strong>sound</strong>, sometimes too restrictive though, so we try to relax the logical relations to fewer, under the principle:</p>
<blockquote>
<p>Any caller that wants to use the supertype postcondition must establish the supertype precondition</p>
</blockquote>
<span class="katex-display"><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord text"><span class="mord">old</span></span><span class="mopen">(</span><span class="mord"><span class="mord text"><span class="mord">Pre</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.1389em;">T</span><span class="mord mtight">.</span><span class="mord mathnormal mtight">m</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">⟹</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord"><span class="mord text"><span class="mord">Post</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.0576em;">S</span><span class="mord mtight">.</span><span class="mord mathnormal mtight">m</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">⟹</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord text"><span class="mord">Post</span></span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.1389em;">T</span><span class="mord mtight">.</span><span class="mord mathnormal mtight">m</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mclose">)</span></span></span></span></span>
<p>This mostly means, if you have a variable in your precondition, it must be applied as an old in your new postcondition.</p>
<p>This is very difficult to enforce at compile time since <strong>entailment is undecidable</strong>, for this reason its now on the programmers side to check this.
There are other techniques like <strong>specification inheritance</strong> to check behavioural subtyping by construction, but we will not cover it here.
You can check <a href="https://chatgpt.com/share/68e77382-b270-8009-91c4-693960869d43">this</a> thread for some more checks.</p>
<h4 id="behavioural-structural-subtyping">Behavioural Structural Subtyping<a class="anchor" aria-hidden="true" hidden href="#behavioural-structural-subtyping">#</a></h4>
<p>Until now we have explored nominal subtyping, and concluded that static checking of that idea is very difficult to automate, but we have the theory.
Here we are leveraging structural subtyping, and we see that the subtype should implement the parent's contract, and we should also input the <strong>signature and behaviour</strong> of the parent type.
Like:</p>
<pre><code class="language-java">render( { void draw( ) requires Pensures Q } p ) {p.draw( );}
</code></pre>
<p>If the precondition has a failure, it can be understood as a <em>message not understood case</em>.
If the postcondition fails, its probably an implementation error.</p>
<blockquote>
<p>▪ Structural subtyping ignores the behavior!</p>
</blockquote>
<p>This means we cannot do it at compile time. So the semantics should still be checked at runtime and by the developer.</p>
<h4 id="violation-of-inherited-fields">Violation of Inherited Fields<a class="anchor" aria-hidden="true" hidden href="#violation-of-inherited-fields">#</a></h4>
<blockquote>
<p>Invariants over inherited field f can be violated by all methods that have access to f</p>
</blockquote>
<p>You can see that inheritance does not imply subtying per sé, but needs some additional properties.
It's very difficult to enforce this, which means most of the inherited classes are <strong>not behavioural subtypes</strong>, but only syntactical subtypes.</p>
<h4 id="summary">Summary<a class="anchor" aria-hidden="true" hidden href="#summary">#</a></h4>




















<table><thead><tr><th></th><th>Static</th><th>Dynamic</th></tr></thead><tbody><tr><td><strong>Nominal</strong></td><td>Sweetspot: Maximum static safety</td><td>Dynamic checks typically do not involve type directly, but rather the availability of operations</td></tr><tr><td><strong>Structural</strong></td><td>Problems with semantics of subtypes (and type equivalence)</td><td>Sweetspot: Maximum flexibility</td></tr></tbody></table>
<h4 id="metaphore-of-contracts">Metaphore of Contracts<a class="anchor" aria-hidden="true" hidden href="#metaphore-of-contracts">#</a></h4>
<p>Types can be seen as some contracts where static checking is possible, while for contracts is not always possible.</p>]]></content:encoded>
    </item>
    <item>
      <title>Optimizing Single-Core CPU software</title>
      <link>https://flecart.github.io/posts/2025-10-21-optimizing-single-core-cpu-software/</link>
      <pubDate>Tue, 21 Oct 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/posts/2025-10-21-optimizing-single-core-cpu-software/</guid>
      <description>Fully exploiting the abilities of modern hardware is hard. Commonly written software does not fully exploit all of the underlying hardware optimization abilities, and often needs specialized software to achieve better utilization. This post will explore some of the most common optimization techniques for single-core binaries executing in modern hardware. We will cover concepts as Instruction-Level Parallelism, cache analysis for specific computations and briefly touch over vectorization. We conclude with a short example showcasing how these techniques are actually used and an analysis of these results. We report a maximum of 10x speedup over the standard naïve matrix-matrix multiplication code.</description>
      <content:encoded><![CDATA[<h2 id="introduction">Introduction<a class="anchor" aria-hidden="true" hidden href="#introduction">#</a></h2>
<p>When a human first learns to program, the first concepts typically encountered are control flow, statements, loops, then functions, recursive calls, types, classes. If the person continues with this journey, an encounter with ideas like design patterns, architectural patterns, and software engineering practices are quite likely. In one way or another, these abstractions enable its general user to write portable software, without ever considering the microarchitecture that actually runs the compiled binaries beneath all the these abstractions. This is Computer Science's fundamental magic: <strong>abstraction and implementation.</strong>
However, sometimes abstractions are not so <em>cleanly</em> separated; they interact in complex manners that go beyond just exposing interfaces and implementing these interfaces, they actually influence each other in complex manners. As every complex system, they may display some strange feedback loops (<a href="https://psycnet.apa.org/record/2007-01197-000">Hofstadter 2007</a>). But this is another story.</p>
<p>In this article, we will focus on practical ideas of implementation of <strong>fast</strong> software. This goal is not achievable by staying at some precise level of abstraction, but needs to consider the entire software stack, from compiler to cache systems to hardware optimizations of the <em>specific</em> microarchitecture that runs that software. We will focus specifically on single core optimizations of the software.</p>
<p>The next sections will be divided as follows: in we will discuss historical progress in writing fast software, including the introduction of super-scalar architectures BLAS/LAPACK (<a href="https://ieeexplore.ieee.org/document/129995">Angerson et al. 1990</a>), FFTW (<a href="http://ieeexplore.ieee.org/document/681704/">Frigo &#x26; Johnson 1998</a>), vectorization. Then we will move on with a discussion of the main established techniques of optimization possibilities that new hardware is enabling. Finally, we end with clear examples and experiments on how such written software is evidently faster in running in modern architectures.</p>
<p>Most of this blog post has been a result of work following this paper (<a href="http://arxiv.org/abs/2510.03290">Huang et al. 2025</a>) on practical optimization on specific CPU architectures of Clifford Kernels (generalization of imaginary kernels) useful for life sciences.</p>
<h3 id="motivation">Motivation<a class="anchor" aria-hidden="true" hidden href="#motivation">#</a></h3>
<p>Every computer scientist knows about compilers, cache mechanisms and some CPU architecture optimizations. However, few know about the optimizations that super-scalar architectures and later vectorization instructions have introduced in the last 30-40 years.</p>
<p><strong>Super-scalar architectures</strong> have inherent form of parallelism; they execute more than one instruction per cycle using different parallel <em>execution ports</em>. Refer to the Intel i7 Skylake architecture for an example. Two things are important to notice here:</p>
<ol>
<li>Each architecture has usually more integer operation ports than floating point operations, which means flops are usually the bottleneck of the computation</li>
<li>The upper limit of flops per cycle is easy to compute, and if you know the frequency of the core you can compute the flops per second. For example, in the figure we have two floating operation ports, each can execute one fused add-multiply operation per cycle, meaning four flops per cycle. If your processor runs at 4.8 Ghz, then your overall maximum theoretical upper bound is 19.2 Gigaflops per second. This value is usually never reachable due to data dependency patterns in the computation or memory transfer bottlenecks.</li>
</ol>
<p></p><figure class="center">
<img src="/images/posts/Writing FastCode-20250625192406855.png" style="width: 100%" alt="Writing FastCode-20250625192406855" title="Writing FastCode-20250625192406855">
<figcaption><p style="text-align:center;">Example of Intel Skylake microarchitecture. We can observe the memory hierarchy, with latency and throughput counted as number of cycles needed to fetch the request, and number of doubles that can be stored or retrieved in a single instruction cycle. On the left we see the different execution ports. On the bottom left, we observe the instruction decoder and automatic out-of-order execution hardware engine (instruction pool). Slide from ASL ETH 2024 course.</p></figcaption>
</figure>
See <a href="https://acl.inf.ethz.ch/teaching/fastcode/2024/slides/03-architecture-core.pdf">here</a>.<p></p>
<p><strong>Compilers have limitations.</strong> Compilers are not able to optimize natively for these architectures. One requirement for compilers is the <strong>correctness</strong> of the compilation. Sadly, floating point operations do not possess associativity as one of their property.
For example, consider the the following case:</p>
<pre><code class="language-cpp">#include &#x3C;iostream>

int main() {
    double a = 1e16;
    double b = -1e16;
    double c = 1.0;

    double res1 = (a + b) + c;
    double res2 = a + (b + c);

    std::cout &#x3C;&#x3C; "(a + b) + c = " &#x3C;&#x3C; res1 &#x3C;&#x3C; std::endl;  // 0
    std::cout &#x3C;&#x3C; "a + (b + c) = " &#x3C;&#x3C; res2 &#x3C;&#x3C; std::endl;  // 1

    return 0;
}
</code></pre>
<p>Due to possible cases of overflow or underflow, floating-point operators adopt different approximation strategies that ultimately lead to different results. As we will see, this property is an important one.</p>
<h3 id="historical-results">Historical Results<a class="anchor" aria-hidden="true" hidden href="#historical-results">#</a></h3>
<p>Modern processor architectures commonly support the parallel execution of independent instructions through multiple execution ports, a design principle known as <em>superscalar execution</em> (@johnsonSuperScalarProcessorDesign1989). However, effective exploitation of these hardware capabilities requires software that is explicitly written or optimized to take advantage of instruction-level parallelism (ILP), register renaming, and out-of-order execution.</p>
<p>Established linear algebra libraries such as LAPACK and BLAS have historically served as high-performance, portable foundations for numerical computations across platforms (<a href="https://ieeexplore.ieee.org/document/129995">Angerson et al. 1990</a>). The ATLAS project further advanced this line of work by introducing automated empirical tuning techniques, enabling the generation of optimized kernels for different hardware configurations (@whaleyAutomaticallyTunedLinear1998).</p>
<p>Despite their effectiveness, these libraries primarily target general matrix and vector operations, and may not yield optimal performance for more specialized computational workloads. This limitation has motivated the development of domain-specific software frameworks such as FFTW, which exploits the structure of the fast Fourier transform to achieve high efficiency on a wide range of platforms (@frigoDesignImplementationFFTW32005, <a href="http://ieeexplore.ieee.org/document/681704/">Frigo &#x26; Johnson 1998</a>). Note that here it is the mathematical structure itself that enabled certain kinds of optimization in its relative hardware. It's nice to observe such interplay between mathematical structures, software compositions and hardware architectures within this subfield of computer science.</p>
<p>Every relevant fast numerical software is somewhat inspired to these libraries. Modern PyTorch (<a href="https://arxiv.org/abs/1912.01703v1">Paszke et al. 2019</a>), <code>numpy</code> library, use LAPACK and BLAS cores underneath to have a performance close to the theoretical upper limit.</p>
<p>In this post, we will mainly explore the optimizations that were introduced within the LAPACK libraries.</p>
<h2 id="optimization-strategies">Optimization Strategies<a class="anchor" aria-hidden="true" hidden href="#optimization-strategies">#</a></h2>
<p>In this section, we will explore established optimization techniques for single-core superscalar architectures. We will be exploring <em>established</em> techniques, nevertheless, they have proved to be valid after decades of architecture design. For example, some of the recent optimizations on GPU architectures have clear and recognizable ideas taken from these pioneering works (<a href="#daoFLASHATTENTIONFastMemoryefficient2022">Dao et al. 2022</a>).
Here we mainly focus on matrix-matrix multiplication.</p>
<h3 id="instruction-level-parallelism">Instruction Level Parallelism<a class="anchor" aria-hidden="true" hidden href="#instruction-level-parallelism">#</a></h3>
<p>If a program is written in a certain manner where some data dependencies are present, we cannot leverage full throughput of the processor. However, if we rewrite the computation to include both cycle unrolling and different accumulators, we can exploit the underlying hardware optimizations and reach a far better performance.
As you can see with the examples below, we can have a 2x performance improvement with just this little trick. Simple but effective technique.</p>
<h3 id="mini-matrix-matrix-multiplication">Mini Matrix-Matrix Multiplication<a class="anchor" aria-hidden="true" hidden href="#mini-matrix-matrix-multiplication">#</a></h3>
<p></p><figure class="center">
<img src="/images/posts/Writing FastCode-20250706220629150.png" style="width: 100%" alt="Writing FastCode-20250706220629150" title="Writing FastCode-20250706220629150">
<figcaption><p style="text-align:center;">Examples of forms of computation. (a) we see classical matrix-matrix multiplication: for each row and column we have a single value in C. Potentially for big matrices every element in B needs to be loaded again and again, creating memory bottlenecks. (b) blocked matrix matrix multiplication, where we better exploit cache locality to operate on the matrices. (c) Outer product for better ILP, only applied to very small matrices in the inner loop.</p></figcaption>
</figure><p></p>
<p>To understand this section, you will need a clear bachelor-level understanding of how CPU cache systems work. Another personally surprising reason why other more efficient algorithms for MMM multiplication are not actually faster than a good implementation of the naïve algorithm is due to cache-friendlyness limitations as we will see.</p>
<p>When optimizing matrix-matrix multiplication (MMM) for single-core execution, a major bottleneck emerges not in arithmetic but in <strong>data movement</strong>, particularly cache misses. To understand and mitigate this, we analyze the cache behavior of naïve vs. blocked matrix multiplication. This section will guide you through that analysis and show how a seemingly simple refactoring, <strong>blocking</strong>, dramatically improves performance.
Blocking is the idea of dividing the whole matrix-matrix multiplication in many smaller cache-friendly block-level matrix multiplications.</p>
<p>Now, we consider the standard triple-loop implementation of matrix multiplication. We make the following assumptions:</p>
<ul>
<li>all matrices are stored in row-major order</li>
<li>All the matrices are square matrices of size <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6667em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">×</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">n</span></span></span></span>:</li>
</ul>
<pre><code class="language-cpp">for (int i = 0; i &#x3C; n; ++i)
  for (int j = 0; j &#x3C; n; ++j)
    for (int k = 0; k &#x3C; n; ++k)
      C[i][j] += A[i][k] * B[k][j];
</code></pre>
<p>In contrast, a blocked-matrix multiplication of block size <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7335em;vertical-align:-0.0391em;"></span><span class="mord mathnormal">b</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&#x3C;</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">n</span></span></span></span> and <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">b</span></span></span></span> divides <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">n</span></span></span></span> is:</p>
<pre><code class="language-cpp">for (int ii = 0; ii &#x3C; n; ii += b)
  for (int jj = 0; jj &#x3C; n; jj += b)
    for (int kk = 0; kk &#x3C; n; kk += b)
      for (int i = ii; i &#x3C; ii + b; ++i)
        for (int j = jj; j &#x3C; jj + b; ++j)
          for (int k = kk; k &#x3C; kk + b; ++k)
            C[i][j] += A[i][k] * B[k][j];
</code></pre>
<p>As we will observe this version better exploits a cache's spatial locality.
%% we try to put some images to explain why this is better, needs one image per section I think. %%</p>
<h4 id="cache-miss-analysis-naive-vs-blocked">Cache Miss Analysis: Naive vs Blocked<a class="anchor" aria-hidden="true" hidden href="#cache-miss-analysis-naive-vs-blocked">#</a></h4>
<p>In the following analysis, we will only consider cache size, but in real systems (<a href="https://ieeexplore.ieee.org/document/129995">Angerson et al. 1990</a> ), also TLB page size and other cache configurations like associativity, size, and line size, are kept into consideration.</p>
<p>In the naïve implementation, we repeatedly access entire rows of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal">A</span></span></span></span>, columns of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span></span></span></span>, and write single entries of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span></span></span></span>. Due to row-major layout, accessing columns of <code>B</code> is especially harmful because it causes <em>non-contiguous memory accesses</em>. We we assume a single row of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span></span></span></span> is big enough that it doesn't fit into the cache, this means we will load a whole line block for every access in <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span></span></span></span>.</p>
<p>Each access to a new element in a row or column causes a cache miss unless it’s already cached. We assume here a common cache block of 8 doubles and cache size of  <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7335em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0556em;">γ</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≪</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">n</span></span></span></span>, we estimate:</p>
<ul>
<li>Accessing a row of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal">A</span></span></span></span> causes <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">n</span><span class="mord">/8</span></span></span></span> misses.</li>
<li>Accessing a column of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span></span></span></span> (non-contiguous) causes <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8141em;"></span><span class="mord"><span class="mord mathnormal">n</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8141em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">2</span></span></span></span></span></span></span></span></span></span></span></span> misses.</li>
<li>So each entry computation causes about <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord">9</span><span class="mord mathnormal">n</span><span class="mord">/8</span></span></span></span> misses.</li>
<li>Total number of entries computed: <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8141em;"></span><span class="mord"><span class="mord mathnormal">n</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8141em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">2</span></span></span></span></span></span></span></span></span></span></span></span>.</li>
<li><strong>Total cache misses</strong>: <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.0641em;vertical-align:-0.25em;"></span><span class="mord">9</span><span class="mord"><span class="mord mathnormal">n</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8141em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">3</span></span></span></span></span></span></span></span></span><span class="mord">/8</span></span></span></span>.</li>
</ul>
<p>Now compare this with <strong>blocked matrix multiplication</strong>, where the matrix is split into sub-blocks of size <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7778em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">b</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">×</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">b</span></span></span></span>.
If we pick <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">b</span></span></span></span> such that the entire sub-multiplication of blocks of size <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7778em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">b</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">×</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">b</span></span></span></span> fits in the cache, we can observe far fewer losses. Let <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0556em;">γ</span></span></span></span> be the cache size as before. We require:</p>
<span class="katex-display"><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:3.9641em;vertical-align:-1.7321em;"></span><span class="mord"><span class="mtable"><span class="col-align-r"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:2.2321em;"><span style="top:-4.9126em;"><span class="pstrut" style="height:3.5447em;"></span><span class="mord"><span class="mord">3</span><span class="mord"><span class="mord mathnormal">b</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8641em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">2</span></span></span></span></span></span></span></span></span></span></span><span style="top:-2.7079em;"><span class="pstrut" style="height:3.5447em;"></span><span class="mord"><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">⟹</span><span class="mspace" style="margin-right:0.2778em;"></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:1.7321em;"><span></span></span></span></span></span><span class="col-align-l"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:2.2321em;"><span style="top:-4.9126em;"><span class="pstrut" style="height:3.5447em;"></span><span class="mord"><span class="mord"></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≤</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mord mathnormal" style="margin-right:0.0556em;">γ</span></span></span><span style="top:-2.7079em;"><span class="pstrut" style="height:3.5447em;"></span><span class="mord"><span class="mord"></span><span class="mord mathnormal">b</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mord sqrt"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.5447em;"><span class="svg-align" style="top:-4.4em;"><span class="pstrut" style="height:4.4em;"></span><span class="mord" style="padding-left:1em;"><span class="mord"><span class="mopen nulldelimiter"></span><span class="mfrac"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.1076em;"><span style="top:-2.314em;"><span class="pstrut" style="height:3em;"></span><span class="mord"><span class="mord">3</span></span></span><span style="top:-3.23em;"><span class="pstrut" style="height:3em;"></span><span class="frac-line" style="border-bottom-width:0.04em;"></span></span><span style="top:-3.677em;"><span class="pstrut" style="height:3em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.0556em;">γ</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.686em;"><span></span></span></span></span></span><span class="mclose nulldelimiter"></span></span></span></span><span style="top:-3.5047em;"><span class="pstrut" style="height:4.4em;"></span><span class="hide-tail" style="min-width:1.02em;height:2.48em;"><svg xmlns="http://www.w3.org/2000/svg" width="400em" height="2.48em" viewBox="0 0 400000 2592" preserveAspectRatio="xMinYMin slice"><path d="M424,2478
c-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514
c0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20
s-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121
s209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081
l0 -0c4,-6.7,10,-10,18,-10 H400000
v40H1014.6
s-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185
c-2,6,-10,9,-24,9
c-8,0,-12,-0.7,-12,-2z M1001 80
h400000v40h-400000z"></path></svg></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.8953em;"><span></span></span></span></span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:1.7321em;"><span></span></span></span></span></span><span class="arraycolsep" style="width:1em;"></span><span class="col-align-r"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:2.2321em;"><span style="top:-4.3679em;"><span class="pstrut" style="height:3em;"></span><span class="mord"><span class="mord text"><span class="mord"> One block each of A, B, C</span></span></span></span></span></span></span></span></span></span></span></span></span></span>
<p>For we will have a number of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">2</span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">b</span><span class="mord">/8</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">nb</span><span class="mord">/4</span></span></span></span> cache misses for each <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span></span></span></span> block. The total number of misses is thus:</p>
<span class="katex-display"><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.1141em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal">n</span><span class="mord">/</span><span class="mord mathnormal">b</span><span class="mclose"><span class="mclose">)</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8641em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">2</span></span></span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">nb</span><span class="mord">/4</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.1141em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">n</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8641em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">3</span></span></span></span></span></span></span></span></span><span class="mord">/4</span><span class="mord mathnormal">b</span></span></span></span></span>
<p>We can observe the number of cache misses is far lower compared to the previous case. The bigger the <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">b</span></span></span></span> is better here.</p>
<h3 id="micro-matrix-matrix-multiplication">Micro Matrix-Matrix Multiplication<a class="anchor" aria-hidden="true" hidden href="#micro-matrix-matrix-multiplication">#</a></h3>
<p>After applying blocking to make our computation cache-friendly, we can push optimization even further by going to the <strong>register level</strong>. The idea is to trade faster and more parallelized register operations with a little higher number of operations.</p>
<h4 id="analysis-of-loop-reordering">Analysis of Loop Reordering.<a class="anchor" aria-hidden="true" hidden href="#analysis-of-loop-reordering">#</a></h4>
<p>In a standard <code>i-j-k</code> ordering with indices set as <a href="#mini-matrix-matrix-multiplication">#Mini Matrix-Matrix Multiplication</a>, for each fixed <code>(i,j)</code> pair, we're essentially computing a dot product: just <code>2n</code> operations with <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">n</span></span></span></span> data dependent additions. This has a lower instruction-level parallelism and lower number of operations compared to the next version:</p>
<p>If we flip to <code>k-i-j</code> ordering, we can observe the following. For each fixed <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal" style="margin-right:0.0315em;">k</span></span></span></span> we're now performing a <strong>rank-1 update</strong>: taking an entire column from matrix A and an entire row from matrix B, and doing an <em>outer product</em> that updates the entire C block. This gives us <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8141em;"></span><span class="mord">2</span><span class="mord"><span class="mord mathnormal">n</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8141em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">2</span></span></span></span></span></span></span></span></span></span></span></span> operations that are almost completely independent, correctly leveraging both instruction level parallelism and faster access with Cache blocks.</p>
<p>What makes micro-MMMs so effective is that they exploit a balance between cache locality and instruction-level parallelism. The blocks are small enough that data stays in registers, but the computation pattern generates enough independent operations to keep all execution ports busy.</p>
<p>Libraries like ATLAS, OpenBLAS, and Intel MKL all use variations of this technique. They'll typically have hand-optimized micro-kernels for different tile sizes (2×2, 4×4, 6×8, etc.) depending on the target architecture's register file size and execution port configuration.</p>
<h3 id="other-operations">Other Operations<a class="anchor" aria-hidden="true" hidden href="#other-operations">#</a></h3>
<p>Up until now, we covered some classical but <em>general</em> techniques for modern CPU architectures in the matrix-matrix setting.
Sometimes we can take other considerations into account and further optimize by taking these into account.</p>
<p><strong>Strength Reduction.</strong> See the <a href="https://en.wikipedia.org/wiki/Strength_reduction">wikipedia page</a>. Here we will just give the general idea.
If we look at <a href="https://www.agner.org/optimize/instruction_tables.pdf">Agner Fog's tables</a>, we observe that most of the division operations are slow in terms of cycles with respect to multiplication. This motivates substituting some complex operations with equivalent or similar precision operations.
With a similar idea, sometimes it is useful to cache or pre-compute intermediary results.
Most of the times, it is difficult to identify when you can optimize with this tricks. Lots of the optimizations come from experience, or just a lot of trial and error.</p>
<h3 id="vectorization-operations">Vectorization Operations<a class="anchor" aria-hidden="true" hidden href="#vectorization-operations">#</a></h3>
<p>Once we’ve optimized for instruction-level parallelism and cache locality, the next powerful lever is <strong>data-level parallelism</strong>, also known as <strong>vectorization</strong>.</p>
<p>Vectorization is the process of transforming scalar operations (working on one data element at a time) into <strong>SIMD</strong> (Single Instruction, Multiple Data) instructions that operate on multiple data elements in parallel. On x86 architectures, these are realized via AVX (Advanced Vector Extensions), SSE, or the newer AVX-512 instruction sets.</p>
<p>A simple example: instead of computing</p>
<pre><code class="language-cpp">for (int i = 0; i &#x3C; 4; ++i)
    C[i] = A[i] + B[i];
</code></pre>
<p>the compiler or programmer can generate a single SIMD instruction that does all four additions at once—assuming <code>A</code>, <code>B</code>, and <code>C</code> are properly aligned and stored contiguously.
This is possible thanks to <strong>SIMD</strong> registers implemented in every modern architecture:</p>
<ul>
<li>AVX: 256-bit registers → 4 doubles or 8 floats</li>
<li>AVX-512: 512-bit registers → 8 doubles or 16 floats</li>
</ul>
<p>Using these, you can execute operations like fused multiply-add (<code>FMA</code>) on multiple elements at once, <em>within a single cycle</em>. This gives a multiplicative factor to throughput, <strong>but only if your data layout and dependencies allow it</strong>.</p>
<p></p><figure class="center">
<img src="/images/posts/Writing FastCode-20250706222603479.png" style="width: 100%" alt="Writing FastCode-20250706222603479" title="Writing FastCode-20250706222603479">
<figcaption><p style="text-align:center;"> (a) a visual representation of AVX-style SIMD operations. Each SIMD register packs multiple doubles, and SIMD instructions operate element-wise on all packed values, executed as a single operation. (b) normal operations in for loop (4 times more operations)</p></figcaption>
</figure><p></p>
<h4 id="hand-vectorization-intrinsics-and-assembly">Hand-Vectorization: Intrinsics and Assembly<a class="anchor" aria-hidden="true" hidden href="#hand-vectorization-intrinsics-and-assembly">#</a></h4>
<p>In many occasions, auto-vectorization, is not able to rewrite the computation in a manner that is compatible to vectorization: examples like loading from different parts of the memory, shuffling operations are beyond current compiler abilities.
For this reason, if we already know the target architecture of our code, we can have some benefit by writing <strong>intrinsics</strong>: these are C-like wrappers for low-level SIMD instructions. For example, using AVX intrinsics:</p>
<pre><code class="language-cpp">#include &#x3C;immintrin.h>

__m256d a = _mm256_load_pd(&#x26;A[i]);
__m256d b = _mm256_load_pd(&#x26;B[i]);
__m256d c = _mm256_add_pd(a, b);
_mm256_store_pd(&#x26;C[i], c);
</code></pre>
<p>You now manually pack, compute, and unpack using 256-bit wide registers. This has the <strong>highest performance</strong> gain in terms of throughput when the computation is compute bound, but it suffers from <strong>portability</strong> since this code runs only on machines with AVX intrinsics (mostly intel machines).
In many cases, when data movement is the bottleneck, having these instructions would not even have any significant gain.</p>
<p>The next and final section will show a <strong>real example</strong> of these techniques applied in practice.</p>
<h2 id="experiments">Experiments<a class="anchor" aria-hidden="true" hidden href="#experiments">#</a></h2>
<p>We proceed with showing concrete results of the above optimization methods for two cases: (1) simple sum with Instruction-Level Parallelism, and (2) common matrix-matrix multiplication operations.</p>
<p>We run the experiments on an <strong>Intel Core i7-1280P</strong>, based on the <strong>Alder Lake</strong> architecture, with a base frequency of:</p>
<ul>
<li><strong>Performance cores</strong>: 1.8 GHz</li>
<li><strong>Efficient cores</strong>: 1.3 GHz</li>
</ul>
<p>This architecture features <strong>two ports for floating-point operations</strong>, and typical <strong>multiplication and addition</strong> instructions take <strong>four clock cycles</strong>.</p>
<ul>
<li><strong>L1 Cache (Data)</strong>: 48 KB (Golden Cove)</li>
<li><strong>L2 Cache</strong>: 1.25 MB (Golden Cove)</li>
<li><strong>L3 Cache</strong>: 24 MB total (3 MB × 8 Gracemont cores)
Experiment code is released in the <a href="https://github.com/Flecart/single-core-cpu-fastcode">github</a> page.
We compile our code using <strong>GCC 13.3.0</strong> with the following flags  <code>-O3 -march=native -ffast-math -fno-tree-vectorize -mfma -mavx2</code>
We deactivate turboboost on the computer by setting the flag in <code>/sys/devices/system/cpu/intel_pstate/no_turbo</code> to 1 in the Linux System.</li>
</ul>
<p>The results are an average over 100 runs per function assuming cold cache, i.e. the values have not been loaded before into the CPU caches.</p>
<h3 id="results">Results<a class="anchor" aria-hidden="true" hidden href="#results">#</a></h3>
<p></p><figure class="center">
<img src="/images/posts/Writing FastCode-20250707221045550.png" style="width: 100%" alt="Writing FastCode-20250707221045550" title="Writing FastCode-20250707221045550">
<figcaption><p style="text-align:center;">We report speedups compared to the naïve baseline version. We observe a simple vectorization is able to provide the greatest speedup. Even simple ILP changes are enough to double the original performance. If we analyze the flops/cycle, we can observe the current version is far from optimal performance, but it is enough to showcase how simple methods can greatly enhance performance with these computations.</p></figcaption>
</figure><p></p>
<p><strong>Instruction-Level Parallelism.</strong> We observe that if we just unroll the loop, it is difficult to get any important speedup. Only if we add accumulators, we get more of the benefits present due to the intrinsic hardware parallelization primitives.</p>
<p><strong>Micro and Mini Matrix-Matrix-Multiplication</strong>. Remember, these techniques are useful to exploit better cache friendliness for the architecture, they become important when the matrix size grows, and whole matrices don't fit into the caches anymore. If they do fit, these techniques lose their winning point.
With the current architecture and cache size above, the working set (set of floating point numbers that are often re-used, sharing time-locality) of the matrix matrix multiplication is mostly the entire <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span></span></span></span> matrix, one row of <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal">A</span></span></span></span> and a cache line for <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span></span></span></span> for the standard matrix matrix multiplication: we approximate the needed size to be a single matrix, then we have that with <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7224em;vertical-align:-0.0391em;"></span><span class="mord mathnormal" style="margin-right:0.109em;">N</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">></span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.84em;vertical-align:-0.6049em;"></span><span class="mord sqrt"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.2351em;"><span class="svg-align" style="top:-3.8em;"><span class="pstrut" style="height:3.8em;"></span><span class="mord" style="padding-left:1em;"><span class="mord"><span class="mopen nulldelimiter"></span><span class="mfrac"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.8451em;"><span style="top:-2.655em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">4</span></span></span></span><span style="top:-3.23em;"><span class="pstrut" style="height:3em;"></span><span class="frac-line" style="border-bottom-width:0.04em;"></span></span><span style="top:-3.394em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">48000</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.345em;"><span></span></span></span></span></span><span class="mclose nulldelimiter"></span></span></span></span><span style="top:-3.1951em;"><span class="pstrut" style="height:3.8em;"></span><span class="hide-tail" style="min-width:1.02em;height:1.88em;"><svg xmlns="http://www.w3.org/2000/svg" width="400em" height="1.88em" viewBox="0 0 400000 1944" preserveAspectRatio="xMinYMin slice"><path d="M983 90
l0 -0
c4,-6.7,10,-10,18,-10 H400000v40
H1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7
s-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744
c-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30
c26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722
c56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5
c53.7,-170.3,84.5,-266.8,92.5,-289.5z
M1001 80h400000v40h-400000z"></path></svg></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.6049em;"><span></span></span></span></span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">≈</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">109</span></span></span></span> the matrix does not fit into the L1 cache anymore (we divided by 4 since each floating point is 4 bytes) and starting from <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7224em;vertical-align:-0.0391em;"></span><span class="mord mathnormal" style="margin-right:0.109em;">N</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">></span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">559</span></span></span></span> it does not fit into the L2 cache anymore.</p>
<p><strong>On the slowdowns.</strong> We further notice that in the cold cache scenario, the small values for matrix size lose some of its time. Another slowdown that we observe and that we have not covered in this post is due to TLB cache misses for virtual paging, which is particularly relevant especially for power of two. You can observe that <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">512</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">4</span></span></span></span> is exactly half of page size in common Linux systems.</p>
<h2 id="conclusion">Conclusion<a class="anchor" aria-hidden="true" hidden href="#conclusion">#</a></h2>
<p>In this post, we covered the most common and established optimization techniques for single core CPU optimization. In particular, we covered important concepts like instruction-level parallelism, cache analysis and examples of cache friendly reformulation of the computations and showed how they can improve the performance of software <strong>in practice</strong>, delivering real speedups. We briefly touched over existing optimized software, like LAPACK/BLAS (<a href="https://ieeexplore.ieee.org/document/129995">Angerson et al. 1990</a>) and frameworks like PyTorch that use these libraries underneath.
Out in the wild, there are far more optimization techniques designed for some specific kinds of computation (<a href="http://ieeexplore.ieee.org/document/681704/">Frigo &#x26; Johnson 1998</a>, <a href="#daoFLASHATTENTIONFastMemoryefficient2022">Dao et al. 2022</a>), sparse computations, or GPU operations.</p>
<h1 id="citation">Citation<a class="anchor" aria-hidden="true" hidden href="#citation">#</a></h1>
<p>If you want to reference this work cite it as:</p>
<blockquote>
<p>Huang, Xuanqiang Angelo "Optimizing Single-Core CPU software." X. Angelo Huang's Blog (Oct 2025). <a href="https://flecart.github.io/posts/2025-10-21-optimizing-single-core-cpu-software/">https://flecart.github.io/posts/2025-10-21-optimizing-single-core-cpu-software/</a></p>
</blockquote>
<p>Or:</p>
<pre><code>@article{huang2025optimizingsingle,
  title   = "Optimizing Single-Core CPU software.",
  author  = "Huang, Xuanqiang Angelo",
  journal = "flecart.github.io",
  year    = "2025",
  month   = "Oct",
  url     = "flecart.github.io/posts/2025-10-21-optimizing-single-core-cpu-software/"
}
</code></pre>
<p>And take a look at the related paper in <a href="http://arxiv.org/abs/2510.03290">Huang et al. 2025</a>.</p>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="hofstadterAmStrangeLoop2007">[1] Hofstadter <a href="https://psycnet.apa.org/record/2007-01197-000">“I Am a Strange Loop”</a> Basic Books 2007</p>
<p id="angersonLAPACKPortableLinear1990">[2] Angerson et al. <a href="https://ieeexplore.ieee.org/document/129995">“LAPACK: A Portable Linear Algebra Library for High-Performance Computers”</a> Supercomputing '90:Proceedings of the 1990 ACM/IEEE Conference on Supercomputing 1990</p>
<p id="frigoFFTWAdaptiveSoftware1998">[3] Frigo &#x26; Johnson <a href="http://ieeexplore.ieee.org/document/681704/">“FFTW: An Adaptive Software Architecture for the FFT”</a> IEEE 1998</p>
<p id="huangSingleCoreSuperscalarOptimization2025">[4] Huang et al. <a href="http://arxiv.org/abs/2510.03290">“Single-Core Superscalar Optimization of Clifford Neural Layers”</a> arXiv preprint arXiv:2510.03290 2025</p>
<p id="paszkePyTorchImperativeStyle2019">[5] Paszke et al. <a href="https://arxiv.org/abs/1912.01703v1">“PyTorch: An Imperative Style, High-Performance Deep Learning Library”</a> 2019</p>
<p id="daoFLASHATTENTIONFastMemoryefficient2022">[6] Dao et al. “FLASHATTENTION: Fast and Memory-Efficient Exact Attention with IO-Awareness” Curran Associates Inc. 2022</p>]]></content:encoded>
    </item>
    <item>
      <title>Inheritance</title>
      <link>https://flecart.github.io/notes/inheritance/</link>
      <pubDate>Thu, 09 Oct 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/inheritance/</guid>
      <description>Introduction to Inheritance # Difference between Inheritance and Subtyping # We say that a subclass is inheritance and subtyping. We have studied subtyping in Typing and Subtyping and it entails mainly two things: Liskov Substitution Polymorphism of the types While inheritance is</description>
      <content:encoded><![CDATA[<h3 id="introduction-to-inheritance">Introduction to Inheritance<a class="anchor" aria-hidden="true" hidden href="#introduction-to-inheritance">#</a></h3>
<h4 id="difference-between-inheritance-and-subtyping">Difference between Inheritance and Subtyping<a class="anchor" aria-hidden="true" hidden href="#difference-between-inheritance-and-subtyping">#</a></h4>
<p>We say that a subclass is inheritance and subtyping.
We have studied subtyping in <a href="/notes/typing-and-subtyping/">Typing and Subtyping</a> and it entails mainly two things:</p>
<ul>
<li>Liskov Substitution</li>
<li>Polymorphism of the types</li>
</ul>
<p>While inheritance is just the <strong>code reuse</strong> and specialization.
Another example of code reuse can be the “has-a” relation composition, which couples two objects together.
With aggregations, we can also see <strong>delegation</strong> calls, when you have a class, and call a method of that class.
<img src="/images/notes/Inheritance-20251009104450885.webp" style="width: 100%" class="center" alt="Inheritance-20251009104450885"></p>
<h4 id="type-relations-between-mutable-and-immutable">Type relations between Mutable and Immutable<a class="anchor" aria-hidden="true" hidden href="#type-relations-between-mutable-and-immutable">#</a></h4>
<p>The cleanest solution between these two methods is just to <strong>separate the interfaces</strong> since:</p>
<ul>
<li>If Mutable &#x3C; Immutable, we violate behavioural subtyping.</li>
<li>If Immutable &#x3C; Mutable, we violate the syntactic subtyping, since mutable is wider interface usually (not always!).</li>
</ul>
<p>Java has a bad design because Immutable &#x3C; Mutable.</p>
<p>Separation can be done in two ways usually:</p>
<ol>
<li><strong>Aggregation</strong> with delegation (this is not a bad idea actually).
<ol>
<li>This solution might lead to lots of boilerplate code.</li>
<li>Access methods for local methods.</li>
</ol>
</li>
<li>Common <strong>superclass</strong>.</li>
<li>We can also <em>inherit without subtyping</em> (like C++ does support that with private or protected inheritance, but not safely, also Eiffel).
<ol>
<li>Inheritance might be sometimes unnecessary.</li>
</ol>
</li>
</ol>
<h4 id="suggestions-for-good-code">Suggestions for good code<a class="anchor" aria-hidden="true" hidden href="#suggestions-for-good-code">#</a></h4>
<ul>
<li>We should not change to dynamically-bound methods, this can lead to many kinds of unexpected behaviours.</li>
<li>We should not inherit from classes that change often.</li>
</ul>
<ul>
<li>Use subclassing only if there is an “is-a” relation:
<ul>
<li>Focus on Syntactic and behavioral subtypes.</li>
</ul>
</li>
<li>Do not rely on implementation details:
<ul>
<li>Use precise documentation (contracts where possible).</li>
</ul>
</li>
<li>When evolving superclasses, do not mess around with dynamically-bound methods:
<ul>
<li>Do not add or remove calls, or change the order of calls.</li>
</ul>
</li>
<li>Do not specialize superclasses that are expected to change often.</li>
</ul>
<h4 id="method-resolution">Method Resolution<a class="anchor" aria-hidden="true" hidden href="#method-resolution">#</a></h4>
<p>Languages differ in method resolution in classes, you need to be able to resolve them correctly yourself, the main difference between the methods we explored are the following:</p>
<p><strong>Java</strong>:</p>
<ul>
<li>
<p>Chooses most type specific method among the hierarchy</p>
</li>
<li>
<p>This means method declaration in all possible overloads.</p>
</li>
<li>
<p>First looks at the static declaration of the function, if it's not present, then you can already return the error</p>
</li>
<li>
<p>Check if the function is accessible at that level.</p>
</li>
<li>
<p><strong>Dynamic binding</strong>, that is the standard in Java, but you could also have static methods. This is enough to generate the bytecode.</p>
</li>
</ul>
<p>At run time we:</p>
<ul>
<li>Compute receiver reference, then we can look at the class of the receiver (going up in the class hierarchy, and finding the most specific type).</li>
</ul>
<p><strong>C#</strong></p>
<ul>
<li>This is bound statically.</li>
<li>Chooses the most specific method in the class of the receiver.</li>
</ul>
<p>Impotant to control the override if we want methods to behave effectively.</p>
<h3 id="binary-methods">Binary Methods<a class="anchor" aria-hidden="true" hidden href="#binary-methods">#</a></h3>
<p>For standard binary methods like equal to, we would like the subtype to have the same parameter of itself, but we know that this is not typesafe.
We now want some methods to resolve these.</p>
<h4 id="type-tests">Type Tests<a class="anchor" aria-hidden="true" hidden href="#type-tests">#</a></h4>
<ul>
<li>We could make explicit type tests, and get the more general value, for example:</li>
</ul>
<pre><code class="language-java">boolean equals(Object o) {
    if (o instanceof Circle) {
        Circle c = (Circle) o;
        // check equality
    } else return false;
}
</code></pre>
<p>But this is very very tedious to write, and check everytime. Luckily nowadays we have copilots.</p>
<p>Problems- Tedious to write- Code is not extensible- Requires type cast</p>
<h4 id="visitor-patterns">Visitor Patterns<a class="anchor" aria-hidden="true" hidden href="#visitor-patterns">#</a></h4>
<ul>
<li>Double invocation, also called the <strong>visitor patter</strong>, see <a href="/notes/design-patterns/">Design patterns</a>.</li>
</ul>
<pre><code class="language-java">class Shape {
    Shape intersect( Shape s ){
        return s.intersectShape( this );
    }
    Shape intersectShape( Shape s ){
        // general code for all shapes
    }
    Shape intersectRectangle( Rectangle r ){
        return intersectShape( r );
    }
}
</code></pre>
<p>We call more specialized methods.</p>
<h4 id="overloading">Overloading<a class="anchor" aria-hidden="true" hidden href="#overloading">#</a></h4>
<ul>
<li>Overloading and  Dynamic resolution of the method, but we are not solving the typesafety problem.</li>
</ul>
<pre><code class="language-c#">class Shape {
    Shape intersect( Shape s ) {
        // general code for all shapes
    }
} 

class Rectangle : Shape {
    Rectangle intersect( Rectangle r ) {
        // efficient code for two rectangles
    }
} 

static Shape intersect( Shape s1, Shape s2 ) {
    return( s1 as dynamic ).intersect( s2 as dynamic );
}

</code></pre>
<p>In this case, the method is resolved to the Rectangle only if both methods are Rectangle, if any of them, or if I remove the dynamic resolution of any of the methods then, it will call the Shape method.</p>
<h4 id="multiple-dispatch">Multiple Dispatch<a class="anchor" aria-hidden="true" hidden href="#multiple-dispatch">#</a></h4>
<p>This is relatively a new method to handle the dispatch of the methods. It is implemented in languages like, CLU, Cecil, Fortress, MultiJava, not any that I know of.</p>
<ul>
<li>Problems</li>
<li>Performance overhead of method look-up at run time</li>
<li>Extra requirements are needed to ensure there is a“unique best method” for every call</li>
<li>I would also personally add that it would be difficult and expensive to implement everything.</li>
</ul>
<p>This has a drawback.</p>
<h2 id="information-hiding">Information Hiding<a class="anchor" aria-hidden="true" hidden href="#information-hiding">#</a></h2>
<h4 id="basic-principles">Basic Principles<a class="anchor" aria-hidden="true" hidden href="#basic-principles">#</a></h4>
<p>It happens only if you create a same function, but it's not accessible in your current domain.</p>
<ul>
<li>Hide implementation details</li>
<li>Reduce dependencies between modules</li>
<li>Classes can be understood, reused,and modified in isolation.</li>
</ul>
<p>One classical principle is having interfaces and their implementations, in this manner you expose only the contract, or interface in front of it.</p>
<h4 id="client-interface">Client Interface<a class="anchor" aria-hidden="true" hidden href="#client-interface">#</a></h4>
<p>Check out <a href="https://gemini.google.com/share/56d51d9e8752">here</a> for a discussion. But the rough idea is everything that you need to define the public methods.</p>
<ul>
<li>Class name
<ul>
<li>is the unique identifier for a class. Think of it as the title of a blueprint. A class is a template for creating objects, and the class name is how you refer to that template.</li>
</ul>
</li>
<li>Type parameters and their bounds
<ul>
<li>This concept relates to <strong>generics</strong>, which allow you to write classes and methods that can work with any data type.</li>
</ul>
</li>
<li>Super-class
<ul>
<li>(also called a parent class or base class) is a class from which another class <em>inherits</em>. This is the core of the "is-a" relationship in inheritance.</li>
</ul>
</li>
<li>Super-interfaces
<ul>
<li>is an interface that a class <em>implements</em> or that another interface <em>extends</em>. An interface is like a contract that specifies <em>what</em> a class must do (i.e., what methods it must have) but not <em>how</em> it must do them.</li>
</ul>
</li>
<li>Signatures of exported methods and fields
<ul>
<li>This refers to the <em>declarations</em> of the methods and variables (fields) that are accessible from <em>outside</em> the class. "Exported" typically means <code>public</code>, <code>protected</code>, or (in some languages) package-private. anything that isn't <code>private</code>.</li>
</ul>
</li>
<li>Client interface of direct superclass
<ul>
<li>is the set of all <code>public</code> (and <code>protected</code>) methods and fields of the one class it directly inherits from.</li>
</ul>
</li>
</ul>
<h4 id="subclass-interface">Subclass Interface<a class="anchor" aria-hidden="true" hidden href="#subclass-interface">#</a></h4>
<p>This topic describes the special implementation-level relationship between a <strong>superclass</strong> (parent) and a <strong>subclass</strong> (child).</p>
<p>This "subclass interface" is a special set of tools given <em>only</em> to the subclasses to help them build upon the parent's functionality. This is most often managed using the <code>protected</code> keyword.
It's the collection of fields and methods that a superclass exposes <em>only</em> to its subclasses, but <em>not</em> to the general public.</p>
<h4 id="friend-interface">Friend Interface<a class="anchor" aria-hidden="true" hidden href="#friend-interface">#</a></h4>
<p>The main idea is that with friends I can access all the private and protected methods of another class.</p>
<p>This set of concepts describes a pattern for managing <strong>tightly coupled classes</strong>—classes that must work together very closely to function.</p>
<p>This pattern is about breaking the normal rules of encapsulation (<code>private</code>, <code>public</code>) in a controlled, explicit way, usually for performance or to hide complex internal details.</p>
<h4 id="java-and-eiffel-access-modifiers">Java and Eiffel Access Modifiers<a class="anchor" aria-hidden="true" hidden href="#java-and-eiffel-access-modifiers">#</a></h4>
<p>Mostly three types of access modifiers that we list here.
Also remember that overrides can only be about more visible methods, not less visible ones.
The default access level in Java is package-private.</p>
<ul>
<li>
<p><code>public</code>: <strong>Client interface</strong></p>
</li>
<li>
<p><code>protected</code>: <strong>Subclass</strong> + friend interface (within the same package)</p>
</li>
<li>
<p><em>(Default/Package-Private)</em>: <strong>Friend interface</strong> (within the same package)</p>
</li>
<li>
<p><code>private</code>: <strong>Implementation</strong></p>
<ul>
<li>This means we can access any variable within the same class only.</li>
</ul>
</li>
<li>
<p><strong>Eiffel: <code>clients</code> clause in feature declarations</strong></p>
<ul>
<li><code>feature { ANY }</code>: <strong>Client interface</strong> (accessible to all classes)</li>
<li><code>feature { T }</code>: <strong>Friend interface</strong> for class <code>T</code> (accessible only to class <code>T</code> and its descendants)</li>
<li><code>feature { NONE }</code>: <strong>Implementation</strong> (accessible only by the object itself, using <code>this</code>, and only using the this keyword, and not other keywords, most languages cannot express this)</li>
<li><strong>Note:</strong> All exports inherently include <strong>subclasses</strong> (descendants).</li>
</ul>
</li>
</ul>
<h4 id="overriding-or-hiding">Overriding or Hiding?<a class="anchor" aria-hidden="true" hidden href="#overriding-or-hiding">#</a></h4>
<pre><code class="language-java">class Super {...private void m( ){ System.out.println(“Super”); }public void test( Super v ){ v.m( ); }}
class Sub extends Super {public void m( ){ System.out.println(“Sub”); }}
Super v = new Sub( );v.test( v );
</code></pre>
<ul>
<li>Private methods cannot be overidden, just <strong>hidden</strong>. We say override if the method was accessible from the subclass.</li>
</ul>
<h4 id="fragile-base-class-problem">Fragile Base Class Problem<a class="anchor" aria-hidden="true" hidden href="#fragile-base-class-problem">#</a></h4>
<p>When we change the base class, we might break the subclasses. This makes modification of badly done abstractions very costly, for this reason it would be also suggested to have as few abstaction chains as possible.
Here is an example of such a problem:</p>
<pre><code class="language-c">class C {int x;public void inc1( ){ this.inc2( ); }private void inc2( ){ x++; }}
class CS extends C {public void inc2( ) { inc1( ); }}
CS cs = new CS( 5 );cs.inc2( );System.out.println( cs.x );
</code></pre>
<p>If you change from private to protected or public, then you would see the problems!</p>
<h2 id="multiple-inheritance">Multiple Inheritance<a class="anchor" aria-hidden="true" hidden href="#multiple-inheritance">#</a></h2>
<p>The main idea here is when a single type can have <strong>several supertypes</strong>, which forms a DAG.
This allows also for code re-use.</p>
<h4 id="simulating-multiple-inheritance">Simulating Multiple Inheritance<a class="anchor" aria-hidden="true" hidden href="#simulating-multiple-inheritance">#</a></h4>
<p>Languages like Java or C# <strong>do not allow for multiple inheritance</strong>.
If that is needed, then it is simulated with <strong>aggregation</strong>.
</p><figure class="center">
<img src="/images/notes/Inheritance-20251016124123668.webp" style="width: 100%" alt="Inheritance-20251016124123668" title="Inheritance-20251016124123668">
<figcaption><p style="text-align:center;"> Image from the course slides</p></figcaption>
</figure><p></p>
<h4 id="problems-with-multiple-inheritance">Problems with Multiple Inheritance<a class="anchor" aria-hidden="true" hidden href="#problems-with-multiple-inheritance">#</a></h4>
<p>This is the most important problem regarding multiple inheritance.</p>
<ul>
<li><strong>Diamond Problem</strong>: The classic problem where a class inherits from two classes that both inherit from a common superclass. This can lead to <em>ambiguity</em> about which inherited properties or methods to use. The main problem here is how to solve the ambiguity.</li>
</ul>
<h4 id="resolving-ambiguities">Resolving Ambiguities<a class="anchor" aria-hidden="true" hidden href="#resolving-ambiguities">#</a></h4>
<ol>
<li>In C++ the ambiguities are resolved <strong>by the client</strong> (but its bad since the client needs to know the implementation details, which is not always granted).</li>
<li>We can also <strong>override both method</strong>s, but this is ok only if we are specializing something similar, if their usage is different, then it's not sure if this is the correct behaviour.</li>
<li>Or we can Rename as Eiffel does.</li>
</ol>
<p>But when we have a diamond it's really difficult. How many fields should we instantiate? Should they be different for the two we have?</p>
<h4 id="virtual-and-non-virtual-inheritance">Virtual and Non-Virtual Inheritance<a class="anchor" aria-hidden="true" hidden href="#virtual-and-non-virtual-inheritance">#</a></h4>
<p>Non-Virtual means we will have two copies of the superclass, while virtual means we will have only one copy of the superclass.
C++ supports both virtual and non-virtual inheritance. By default it uses non-virtual inheritance, but you can specify virtual inheritance using the <code>virtual</code> keyword, but this adds some <strong>runtime overhead</strong> (we need to add the virtual keyword in the inheritance part).
When virtual is used, the baseclass is called only once, by the smallest subclass.</p>
<pre><code class="language-mermaid">graph TD
    A --> B
    A --> C
    B --> D
    B --> A2["Stack: A/B"]
    C --> A3["Stack: A/C"]
    D --> A4["Stack: A/B/C/D"]
</code></pre>
<pre><code class="language-mermaid">graph TD
    A --> B
    A --> C
    B --> D
    B --> A2["Stack: A (p)/B"]
    C --> A3["Stack: A(p)/C"]
    D --> A4["Stack: A, pointed by both C/D /B"]
</code></pre>
<h4 id="pros-and-cons-for-multiple-inheritance">Pros and Cons for Multiple-Inheritance<a class="anchor" aria-hidden="true" hidden href="#pros-and-cons-for-multiple-inheritance">#</a></h4>









































<table><thead><tr><th><strong>Pros</strong></th><th><strong>Cons</strong></th></tr></thead><tbody><tr><td><strong>Increases expressiveness</strong></td><td><strong>Ambiguity resolution</strong></td></tr><tr><td></td><td>- Explicit selection</td></tr><tr><td></td><td>- Merging</td></tr><tr><td></td><td>- Renaming</td></tr><tr><td><strong>Avoids overhead of delegation pattern</strong></td><td><strong>Repeated inheritance</strong></td></tr><tr><td></td><td>- Complex semantics</td></tr><tr><td></td><td>- Initialization</td></tr><tr><td></td><td><strong>Complicated!</strong></td></tr></tbody></table>
<h2 id="linearization">Linearization<a class="anchor" aria-hidden="true" hidden href="#linearization">#</a></h2>
<p>Mixins and traits provide a form of reuse
Methods and state that can be mixed into various classes</p>
<p>Example: Functionality to persist an object. Python, Ruby, Scala, Squeak Smalltalk. So it's a different way to add functionality to classes.</p>
<h4 id="traits">Traits<a class="anchor" aria-hidden="true" hidden href="#traits">#</a></h4>
<blockquote>
<p>Traits defines <em>a collection of fields and methods</em> (behavior) that can be <em>mixed into classes</em>. It’s a modular building block of functionality, not a concrete “thing” by itself.</p>
</blockquote>
<p>We have <strong>single-inheritance</strong>, and bound only to a  single class.</p>
<p>Traints can extend exactly one superclass.
They solve the diamond problem with <strong>linearization</strong>, we will analyze this phenomenon later.</p>
<ul>
<li>Traits are very dynamic,which complicates staticreasoning</li>
<li>Traits do not know how their superclasses getinitialized</li>
<li>Traits do not know which methods they override</li>
<li>Traits do not know where super-calls are bound to</li>
</ul>
<pre><code class="language-scala">
trait Backup extends Cell {
  var backup: Int = 0

  override def put( v: Int ) = {
    // Save the old value before calling the next put (super.put)
    backup = value
    super.put( v )
  }

  def undo = {
    super.put( backup )
  }
}

class Cell {
  var value: Int = 0

  def put( v: Int ) = {
    value = v
  }

  def get: Int = value
}

object Main1 {
  def main( args: Array[ String ] ) = {
    val a = new Cell with Backup
    a.put( 5 )  // value=5, backup=0
    a.put( 3 )  // value=3, backup=5 (value before put(3) was 5)
    a.undo      // value is set back to backup (5)
    println( a.get ) // Output: 5
  }
}
</code></pre>
<h4 id="mathematical-model-for-linearization">Mathematical Model for Linearization<a class="anchor" aria-hidden="true" hidden href="#mathematical-model-for-linearization">#</a></h4>
<p>The key concept to understanding the semantics of Scala traits: bring <strong>types in a linear order</strong></p>
<ul>
<li>Define overriding and super-calls according to this order (so easy resolution).</li>
</ul>
<p>For a class or trait <strong>C extends C' with C₁ ... with Cₙ</strong>
the linearization L(C) is C, L(Cₙ) • ... • L(C₁) • L(C')</p>
<p>Do not include types more than once</p>
<span class="katex-display"><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4445em;"></span><span class="mord mathnormal">ϵ</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span></span></span></span></span>
<span class="katex-display"><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal">a</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">A</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:3em;vertical-align:-1.25em;"></span><span class="minner"><span class="mopen delimcenter" style="top:0em;"><span class="delimsizing size4">{</span></span><span class="mord"><span class="mtable"><span class="col-align-l"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.69em;"><span style="top:-3.69em;"><span class="pstrut" style="height:3.008em;"></span><span class="mord"><span class="mord mathnormal">a</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mopen">(</span><span class="mord mathnormal">A</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span><span class="mclose">)</span></span></span><span style="top:-2.25em;"><span class="pstrut" style="height:3.008em;"></span><span class="mord"><span class="mord mathnormal">A</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:1.19em;"><span></span></span></span></span></span><span class="arraycolsep" style="width:1em;"></span><span class="col-align-l"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:1.69em;"><span style="top:-3.69em;"><span class="pstrut" style="height:3.008em;"></span><span class="mord"><span class="mord text"><span class="mord">if </span></span><span class="mord mathnormal">a</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel"><span class="mrel"><span class="mord vbox"><span class="thinbox"><span class="rlap"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="inner"><span class="mord"><span class="mrel"></span></span></span><span class="fix"></span></span></span></span></span><span class="mspace nobreak"></span><span class="mrel">=</span></span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mord mathnormal" style="margin-right:0.0502em;">B</span></span></span><span style="top:-2.25em;"><span class="pstrut" style="height:3.008em;"></span><span class="mord"><span class="mord text"><span class="mord">otherwise</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:1.19em;"><span></span></span></span></span></span></span></span><span class="mclose nulldelimiter"></span></span></span></span></span></span>
<h4 id="initialization-order">Initialization Order<a class="anchor" aria-hidden="true" hidden href="#initialization-order">#</a></h4>
<blockquote>
<p>Classes and traits are initialized in the <strong>reverse linear order</strong></p>
</blockquote>
<p>If there are multiple classed called, we only keep the first initialized one, and discard successive calls to the same thing.</p>
<p>Meaning that the supertype is initialized before the base class value.
The only thing you need to keep in mind is that it is initialized by the <strong>preceding class</strong>, so if it's two linearizations behind, you don't <em>direct</em> control over which parameter will be used there.
This order along with the overrides leads to a nice specialization ability of mixing functions.</p>
<h4 id="method-selection-with-linearization">Method Selection with Linearization<a class="anchor" aria-hidden="true" hidden href="#method-selection-with-linearization">#</a></h4>
<p></p><figure class="center">
<img src="/images/notes/Inheritance-20251023114640691.webp" style="width: 100%" alt="Inheritance-20251023114640691" title="Inheritance-20251023114640691">
<figcaption><p style="text-align:center;">Slide from  the course</p></figcaption>
</figure><p></p>
<h4 id="problems-with-traits">Problems with Traits<a class="anchor" aria-hidden="true" hidden href="#problems-with-traits">#</a></h4>
<p>We don't know which concrete methods is it overriding, neither which one.</p>
<ul>
<li>We cannot check behavioural subtyping, depends on which one is mixed in. I can only check this subtyping after it has been mixed in.</li>
<li>If we mix in in different ways, the type system still thinks they are the same, but they behave differently.</li>
</ul>
<blockquote>
<p><strong>type-checking is order-agnostic; behavior is order-sensitive.</strong></p>
</blockquote>]]></content:encoded>
    </item>
    <item>
      <title>Teoria dei Tipi</title>
      <link>https://flecart.github.io/notes/teoria-dei-tipi/</link>
      <pubDate>Sun, 28 Sep 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/teoria-dei-tipi/</guid>
      <description>Introduzione alla Teoria dei Tipi # History of Languages Research # The root of languages research are in: in logic and computations (even before computers!). Artificial intelligence (Lisp, constrained solvers, the original logical AI we studied in (Russell &amp;#x26; Norvig 2009) ).</description>
      <content:encoded><![CDATA[<h2 id="introduzione-alla-teoria-dei-tipi">Introduzione alla Teoria dei Tipi<a class="anchor" aria-hidden="true" hidden href="#introduzione-alla-teoria-dei-tipi">#</a></h2>
<h3 id="history-of-languages-research">History of Languages Research<a class="anchor" aria-hidden="true" hidden href="#history-of-languages-research">#</a></h3>
<p>The root of languages research are in:</p>
<ul>
<li>in logic and computations (even before computers!).</li>
<li>Artificial intelligence (Lisp, constrained solvers, the original logical AI we studied in <a href="#russellArtificialIntelligenceModern2009">(Russell &#x26; Norvig 2009)</a>).</li>
<li>Algebra and symbolic reasoning.</li>
</ul>
<h3 id="definizione-di-tipo">Definizione di Tipo<a class="anchor" aria-hidden="true" hidden href="#definizione-di-tipo">#</a></h3>
<blockquote>
<p>Un metodo sintattico <strong>praticabile</strong> per dimostrare l'assenza di determinati comportamenti del
programma, fatto classificando le unità sintattiche in base ai tipi di valore che assumono</p>
</blockquote>
<blockquote>
<p>A type system is a <strong>tractable</strong> syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute B.C. Pierce 2002</p>
</blockquote>
<p>Vogliamo che fosse praticabile nel senso che effettivamente lo possiamo implementare, cioè ci permettono di avere certe tipologie di garanzia. ma ancora è una definizione molto ampia. E di solito si può fare una analisi statica del comportamento del programma.</p>
<p>Un altro modo per definirlo (questo molto più buono) è</p>
<blockquote>
<p>Collezioni di valori omogenei e rappresentabili e una serie di operazioni su di esse.</p>
</blockquote>
<p>Ossia omogenei nel senso che hanno tutti certe proprietà, e rappresentabili perché effettivamente possiamo metterli in memoria (per esempio non posso avere come tipo i Reali in modo primitivo, perché non è rappresentabile).</p>
<ul>
<li>Esecuzione corretta, + ottimizzazione da parte del compilatore.</li>
</ul>
<blockquote>
<p>A type system is a lightweight and compositional method for formal verification</p>
</blockquote>
<p>È una altra view di cosa sia un sistema di tipo.</p>
<h3 id="utilizzo-dei-tipi">Utilizzo dei tipi<a class="anchor" aria-hidden="true" hidden href="#utilizzo-dei-tipi">#</a></h3>
<p>Values should not be classified into types!</p>
<h4 id="organizzazione-concettuale">Organizzazione Concettuale<a class="anchor" aria-hidden="true" hidden href="#organizzazione-concettuale">#</a></h4>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled.png" style="width: 100%" class="center" alt="Untitled"></p>
<h4 id="importanza-di-astrazioni">Importanza di Astrazioni<a class="anchor" aria-hidden="true" hidden href="#importanza-di-astrazioni">#</a></h4>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 1.png" style="width: 100%" class="center" alt="Untitled 1"></p>
<p>La parte importante è che <strong>riduce le ambiguità</strong> del nostro programma. Sappiamo qui <em>esattamente</em> cosa un programma può fare e cosa non può fare.</p>
<h4 id="correttezza">Correttezza<a class="anchor" aria-hidden="true" hidden href="#correttezza">#</a></h4>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 2.png" style="width: 100%" class="center" alt="Untitled 2"></p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 3.png" style="width: 100%" class="center" alt="Untitled 3"></p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 4.png" style="width: 100%" class="center" alt="Untitled 4"></p>
<p>In questo modo sappiamo anche ciò che un tipo può e ciò che non può fare. Questa rigidità è buona per capire esattamente il comportamento di un oggetto matematico. La cosa che mi fa storcere il naso è però se questo definire in modo esatto può mettere constraints troppo forti su un certo programma...
Non so nemmeno se quello che gli esseri viventi fanno, può essere considerato un programma con tipi formali come qui. Non lo so.</p>
<h4 id="implementazione">Implementazione<a class="anchor" aria-hidden="true" hidden href="#implementazione">#</a></h4>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 5.png" style="width: 100%" class="center" alt="Untitled 5"></p>
<h4 id="riassunto-sui-tipi">Riassunto sui tipi<a class="anchor" aria-hidden="true" hidden href="#riassunto-sui-tipi">#</a></h4>
<ol>
<li><strong>Progettazione</strong>: posso descrivere in modo <em>concettuale</em> cosa fa il programma e aiutare a verificare la correttezza del programma, "separare logicamente elementi concettualmente diversi" (posso creare tipi per certi concetti e quindi ragionare meglio, pensa sviluppare solo in assembly!) <strong>Documentazione</strong>: ci danno informazioni in più riguardo il ruolo della variabile nel nostro programma. Una idea bella è parlare di tipi come se fossero commenti</li>
<li><strong>Astrazione</strong>: in fase di implementazione possono aiutare a gestire meglio il nostro progetto, solitamente attraverso interfacce (a questo tipo ho certe operazioni, non ho niente di sotto), ci permette di modulizzare e gestire meglio, ++manutentibilità, ++ comprensibilità del progetto.
L'astrazione su un concetto di cambia il modo di ragionare riguardo l'implementazione, o l'idea sottostante comunque.</li>
<li><strong>Correttezza</strong>, possiamo utilizzare i tipi per avere errori di programmazione, quindi se faccio qualcosa con un tipo, io mi aspetto di ricevere altro. (ad esempio se mi aspetto che una funzione mi ritorni qualcosa, ma mi ritorna qualcosal'altro o non sempre quel tipo, posso darti errore staticamente parlando).
Per cose di <strong>refactoring</strong> è molto comodo, se cambi un tipo e una strtutura vorresti cambiarla anche da altre parti (se lo fai tipo in python è molto più difficile per sto motivo che non ha tipi all'esterno).
O per la cosa della <strong>safety</strong>, è impossibile sbagliare quando hai un buon sistema dei tipi (ti fa sbagliare in fase di compilazione lel, come Rust). Proprio per questa cosa che hai delle garanzie quando programmi, riesci a predire cosa ti ritorna e quindi puoi predire il modo con cui si comporta il programma. Possiamo dire che un programma è sicuro quando <strong>rispetta sempre i vincoli del suo tipo</strong>.
Per lui C non ha la caratteristica della safety, quindi puoi andare oltre alle limitazioni di utilizzo del singolo tipo (tipo array puoi accedere anche fuori dal suo range, un tipo buono non dovrebbe permettere queste cose), si potrebbe considerare quindi weakly typed, ma è una cosa strana</li>
<li><strong>Implementazione</strong>: possiamo fare certe ottimizzazioni col sistema dei tipi. non servirebbero controlli dinamici per la sicurezza con un buon sistema dei tipi. Per esempio possiamo anche utilizzare offset per accedere in memoria quindi guadagniamo anche da quel punto di vista.
Si migliora anche l'impatto che si ha sull quantità di memoria utilizzata, forse… non sono sicuro da questo.
Tipo theorem provers e simili</li>
</ol>
<ul>
<li>
<p>Altre applicazioni</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 6.png" style="width: 100%" class="center" alt="Untitled 6"></p>
</li>
</ul>
<blockquote>
<p>Un sistema di tipi (e, per estensione, un linguaggio) è sicuro relativamente ai tipi (o <em>type safe</em>) quando nessun programma può violare le distinzioni tra tipi definite in quel linguaggio. Detto in altri termini, un sistema di tipi è sicuro quando nessun programma durante l'esecuzione può generare un errore non segnalato che derivi da una violazione di tipo.</p>
</blockquote>
<h3 id="dynamic-and-static-typing">Dynamic and static typing<a class="anchor" aria-hidden="true" hidden href="#dynamic-and-static-typing">#</a></h3>
<h4 id="statico">Statico<a class="anchor" aria-hidden="true" hidden href="#statico">#</a></h4>
<p>Quando il controllo dei tipi avviene a livello di struttura del testo. Solitamente queste informazioni sono poi rimosse nel file compilato, almenoché non serva per runnare.</p>
<p>Dato che eventuali errori sono individuati in tempo di compilazione, il prezzo in genere che si paga per un linguaggio statico è il tempo di sviluppo del linguaggio! Solitamente un compilatore che abbia static typing e che sia safe richiede molto molto più tempo.</p>
<p>Types of variables and methods are declared <strong>explicitly</strong> or inferred</p>
<h4 id="dinamico">Dinamico<a class="anchor" aria-hidden="true" hidden href="#dinamico">#</a></h4>
<p>Quando i controlli di tipi è fatta a runtime, e quindi bisogna runnarlo per capire cosa runna. Questo aggiunge un leggero overhead, perché ho bisogno di un descrittore a runtime che contenga le informazioni sul tipo, e ci sia la verifica in questo momento.</p>
<p>Dato che dobbiamo eseguire per trovare un errore di tipo dinamico, questo errore potrebbe essere scoperto solo nella fase finale, quando il nostro prodotto è già in produzione, e ha clienti!</p>
<p>Importante osservare che la divisione fra dinamico e inferred è indipendente al fatto che sia dinamic o static!</p>
<h3 id="manifest-vs-inferred-typing">Manifest vs Inferred typing<a class="anchor" aria-hidden="true" hidden href="#manifest-vs-inferred-typing">#</a></h3>
<p>La differenza fra manifest ed inferred typing riguarda la <strong>quantità di informazioni</strong> che il programmatore deve dare al compilatore per creare il sistema dei tipi</p>
<p>L'inferred typing non è altro che un typing manifesto automatico, nel senso che il compilatore stesso riesce a capire che tipo stai dichiarando. Queste cose già esistono in c++ nuovo e anche golang Rust.</p>
<p>Invece il manifest tiping è quando il programmatore va ad annotare ili tipo di tute le variabili.</p>
<h3 id="tipo-estensionali-o-intensionali">Tipo estensionali o intensionali<a class="anchor" aria-hidden="true" hidden href="#tipo-estensionali-o-intensionali">#</a></h3>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 7.png" style="width: 100%" class="center" alt="Untitled 7"></p>
<h4 id="intensionale">Intensionale<a class="anchor" aria-hidden="true" hidden href="#intensionale">#</a></h4>
<p>Quando gli abitanti del tipo sono descritti secondo un <strong>predicato</strong> che è una proprietà che è soddisfatta da tutti gli abitanti.</p>
<p>Salviamo molta memoria per tipi grossi e ci permette anche di rappresentare (fino a un certo punto i tipi infiniti).</p>
<h4 id="estensionale">Estensionale<a class="anchor" aria-hidden="true" hidden href="#estensionale">#</a></h4>
<p>Quando si va a listare tutti gli abitanti nel nostro tipo, la stessa cosa che si fa con gli enums</p>
<h2 id="sistemi-di-tipi">Sistemi di tipi<a class="anchor" aria-hidden="true" hidden href="#sistemi-di-tipi">#</a></h2>
<h3 id="caratterizzazione-di-base-4">Caratterizzazione di base (4) (!)<a class="anchor" aria-hidden="true" hidden href="#caratterizzazione-di-base-4">#</a></h3>
<ol>
<li>Tipi di base</li>
<li>Poter definire nuovi tipi</li>
<li>Controllo dei vincoli, che siano statici o dinamici non ci importa, ma ci importa che siano rispettati</li>
<li>Computare sui tipi (equivalenza, compatibilità, inferenza dei tipi).</li>
</ol>
<ul>
<li>
<p>Slide sistemi di tipi</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 8.png" style="width: 100%" class="center" alt="Untitled 8"></p>
</li>
</ul>
<h3 id="tipi-di-base">Tipi di base<a class="anchor" aria-hidden="true" hidden href="#tipi-di-base">#</a></h3>
<p>Sono i <strong>valori denotabili del linguaggio</strong>. Si dice <strong>abitante</strong>, una variabile che faccia parte di questo tipo. Cose come float, caratteri interi etc.</p>
<p><strong>VOID/UNIT</strong>, è un tipo di base che contiene solamente il singoletto, per questo è anche chiamato unit, in java per esempio è il NUll, mentre in C è il void (che però ha la differenza che non si può assegnare, perché starei assegnando il niente!), e che non si può assegnare. Solitamente è il valore delle funzioni che non ritornano nulla, utilizzato spesso per ritornare il controllo delle funzioni.
In C void è utilizzato per distinguere procedure e funzioni e rende difficile fare le composizioni (che non so cosa sia), unit è per avere ancora funzioni, che deveono per forza avere un codominio non nullo.</p>
<h4 id="tipi-booleani">Tipi Booleani<a class="anchor" aria-hidden="true" hidden href="#tipi-booleani">#</a></h4>
<p>Che hanno vero o falso come abitanti, e ho tutte le operazioni logiche, come congiunzione disgiunzione negazione etc. La cosa particolare è che utilizziamo un byte invece di un bit per rappresentare un bool, perché per accedere al valore è molto veloce se è allineato.</p>
<h4 id="tipo-carattere">Tipo Carattere<a class="anchor" aria-hidden="true" hidden href="#tipo-carattere">#</a></h4>
<p>Sono i caratteri Unicode, oppure ascii,operazioni classiche sarebbero comparazione, comparazione (perché  c'è un ordine fra i caratteri nell'encoding, come abbiamo detto in <a href="/notes/codifica-dei-caratteri/">Codifica dei caratteri</a>), e il resto è dipendente dal linguaggio.</p>
<h4 id="tipi-interi">Tipi Interi<a class="anchor" aria-hidden="true" hidden href="#tipi-interi">#</a></h4>
<p>Solitamente spaziano fra <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.0641em;vertical-align:-0.25em;"></span><span class="mopen">[</span><span class="mord">−</span><span class="mord"><span class="mord">2</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8141em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.0278em;">r</span><span class="mbin mtight">−</span><span class="mord mtight">1</span></span></span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord">2</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8141em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.0278em;">r</span><span class="mbin mtight">−</span><span class="mord mtight">1</span></span></span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord">1</span><span class="mclose">]</span></span></span></span>hanno tutte le operazioni fra interi come uguaglianza, ordine, tutte le operazioni aritmetiche.</p>
<h4 id="tipo-reale">Tipo Reale<a class="anchor" aria-hidden="true" hidden href="#tipo-reale">#</a></h4>
<p>Sono un subset dei reali, in particolare solamente i razionali rappresentabili, hanno stesse operazioni degli interi (importanti per ragioni di compatibilità e conversione con gli interi!), ricorda che ci sono fixed point or floating point representation. Abbiamo fatto principalmente floating point di IEEE745 in Calcolo di numeri finiti .</p>
<ul>
<li>
<p>Fixed point slide</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 9.png" style="width: 100%" class="center" alt="Untitled 9"></p>
</li>
</ul>
<h4 id="tipo-complesso">Tipo Complesso<a class="anchor" aria-hidden="true" hidden href="#tipo-complesso">#</a></h4>
<p>Anche questo, subset dei numeri complessi, stesse operazioni degli interi, con forse qualcosina in più.</p>
<h4 id="enums">Enums<a class="anchor" aria-hidden="true" hidden href="#enums">#</a></h4>
<p>Questo è il nostro primo tipo non di base, perché è un costruttore di tipo possiamo infatti <strong>dichiarare nuovi tipi</strong>, e enums sono un modo per farlo. In pratica si dichiara un nuovo tipo  con definizione di abitanti appartenenti a questo.</p>
<p>In C non c'è differenza fra interi e enums, quindi non c'è una chiara differenziazione dei tipi, quindi difficile andare a checkare la correttezza fra i due.</p>
<h2 id="tipi-composti">Tipi composti<a class="anchor" aria-hidden="true" hidden href="#tipi-composti">#</a></h2>
<p>Come si fa a definire alcuni tipi più complessi, composti utilizzando alcuni tipi primitivi?</p>
<h3 id="arrays">Arrays<a class="anchor" aria-hidden="true" hidden href="#arrays">#</a></h3>
<p>Sono unacollezzione di elementi <strong>omogenei</strong> indexati da una chiave (questo mapping riesce a dare in un certo senso un ordine) (che non necessariamente devono essere degli interi, credo che su questa scia anche le hashtable sono classificati come tipo array).</p>
<p>Infatti le mappe sono chiamate <strong>associative arrays</strong>.</p>
<p>Si potrebbe considerare il <strong>costruttore di tipo</strong>, che prende in input un tipo e crea un array di una certra dimensione (quindi fa eccezzioni se provi ad accedere oltre) e crea un altro tipo, che è l'array di certa dimensione.</p>
<ul>
<li>
<p>Esempi di notazioni con array</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 10.png" style="width: 100%" class="center" alt="Untitled 10"></p>
</li>
<li>
<p>Proprietà del tipo array</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 11.png" style="width: 100%" class="center" alt="Untitled 11"></p>
</li>
<li>
<p>Ordine di storage degli array (row column major)</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 12.png" style="width: 100%" class="center" alt="Untitled 12"></p>
</li>
</ul>
<p>Se la grandezza dell'array è conosciuta a tempo di compilazione si può allocare in stack, altrimenti si mette in heap, e si utilizza un descrittore, chiamato <strong>dope vector</strong> per accederci sulla heap. Di solito in rust o golang sono gli slice</p>
<ul>
<li>
<p>Esempio di dope vector
Ecco tutte le informazioni per il descrittore :D, stride ci dice ogni quanto saltare per avere il prossimo elemento.</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 13.png" style="width: 100%" class="center" alt="Untitled 13"></p>
</li>
</ul>
<h4 id="controllo">Controllo<a class="anchor" aria-hidden="true" hidden href="#controllo">#</a></h4>
<p>Una delle operazioni fondamentali affinché abbiamo un tipo di array che sia safe è il fatto <strong>check</strong> <strong>all'accesso</strong>, in modo da evitare out of bounds, è la cosa migliore che ho in termini di sicurezza.</p>
<p>Altre operazioni utili sono assegnamento, confronto</p>
<h3 id="sets/insiemi">Sets/Insiemi<a class="anchor" aria-hidden="true" hidden href="#sets/insiemi">#</a></h3>
<p><strong>Unici e orderless e omogenei</strong> sono gli elementi dei set. Quindi l'unica differenza è il fatto che siano unici e quindi siano tutti distinti fra di loro secondo l'operatore di uguaglianza.</p>
<p>Operazioni importanti sono unione, intersezione, differenza, complemento, etc. tutte le operazioni belle sugli insiemi.</p>
<p>Un esempio di operazioni fra i set sono unioni (e tutti gli amici degli insiemi) quindi per esempio se provo ad unire due insiemi con gli stessi elementi, restano gli stessi.</p>
<ul>
<li>Appartenenza, Unione, intersezione, complemento etc…</li>
</ul>
<h4 id="implementation-of-sets-2">Implementation of Sets (2)<a class="anchor" aria-hidden="true" hidden href="#implementation-of-sets-2">#</a></h4>
<p>L'implementazione più semplice dei set è avere un <strong>bitset</strong>, che il valore del bit ci dice se l'elemento è presente o meno in essa. Ma non funziona per sets che sono molto larghi. Quindi di solito si utilizzano gli hash tables per sti set.</p>
<p>Un altro modo è utilizzare una <strong>hashset</strong> in pratica ogni valore ha una hash, e questo viene utilizzato per vedere se è presente o meno (spesso funzioni fra dominio a un mio)</p>
<p>Un altro modo per fare <strong>set</strong> è utilizzare un albero binario, come fa C++ in set.</p>
<h3 id="reference-types">Reference Types<a class="anchor" aria-hidden="true" hidden href="#reference-types">#</a></h3>
<p>NOTA: i puntatori sono abitanti di questi <strong>reference types</strong>, però non sono gli unici! (esempio URL, reference alla risorsa. Via di casa, reference alla tua casa).</p>
<p>Sono le <strong>reference</strong> a qualcosa! Questo permettono di creare strutture di dati ricorsive.</p>
<p>Operazioni tipiche sono, creazione, check uguaglianza, dereferenziazione. Il pointer è l'implementazione più semplice di questo tipo di dato.</p>
<h4 id="wild-dangling-references-and-leaks">Wild, Dangling references and Leaks<a class="anchor" aria-hidden="true" hidden href="#wild-dangling-references-and-leaks">#</a></h4>
<p>Senza certe tipologie di checks, le references possono causare molti problemi, come le reference <strong>wild</strong> (quando ho dei pointer non inziializzati e quindi posso avere random della stack)</p>
<p>Per questi è meglio sempre assegnare a Null per evitare questo, se non lo fa già il linguaggio.</p>
<p><strong>dangling</strong> (quando si riferisce ad elementi già liberati, o ci sono altre cose). Questo è principalmente causato dal fatto che solitamente sono soluzioni basso livello, che interfaccia praticamente direttamente sulla memoria.</p>
<p><strong>Memory leak</strong>, quando sto perdendo memoria, nel senso che non ho più nessuna reference, quando per esempio dislinko un puntatore, senza averla marcata come libera (quindi perdo un sacco di memoria, che non posso più allocare).</p>
<h4 id="operazioni-classiche-4">Operazioni Classiche (4)<a class="anchor" aria-hidden="true" hidden href="#operazioni-classiche-4">#</a></h4>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 14.png" style="width: 100%" class="center" alt="Untitled 14"></p>
<p><strong>Creazione</strong> di un certo referenze ad un oggetto</p>
<p><strong>Dereferencing</strong>, cerco il dato puntato da questa referenza</p>
<p><strong>Equality</strong>, per vedere se è uguale la reference</p>
<p>OPERAZIONI GENERALI CON I REFERENCES.</p>
<p><strong>Variabile referencing operator</strong>, in pratica vorrei che creasse una variabile che abbia come r-value la l-value di una certa variabile (descritto in <a href="/notes/valutazione-espressioni/">Valutazione Espressioni</a>), ossia il suo indirizzo o contenitore, la sua reference</p>
<p><strong>Allocazione e deallocazione dinamica</strong>, ma questa non è che dovrebbe essere operazione su questo tipo</p>
<h3 id="power-sets">Power sets<a class="anchor" aria-hidden="true" hidden href="#power-sets">#</a></h3>
<p>Questo sono i primi tipi che non abbiamo visto in un linguaggio di programmazione, alla fine è sempre un Sets/Insiemi, ma con qualche informazione in più.</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 15.png" style="width: 100%" class="center" alt="Untitled 15"></p>
<p>Definizione di powerset P, partendo da un set iniziale S.</p>
<p>Questo soprattutto è un modo molto utile per rappresentare <strong>tuple</strong>, ossia coppie ordinate, molto naturali con dei powerset.</p>
<ul>
<li>
<p>Osservazione powerset per due</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 16.png" style="width: 100%" class="center" alt="Untitled 16"></p>
</li>
</ul>
<p>Con l'osservazione di sopra abbiamo detto che la tupla definita in quel modo, che segue la definizione di kuratowsky in 3.1.1 Definizione di Kuratowsky, è un elemento del powerset del powerset, quello è proprio il prodotto cartesiano! Chiachiamo <strong>product types</strong>, o <strong>tipi prodotto</strong> come combinazioni una o più strutture (quindi non più omogeneo come prima)</p>
<h4 id="pairs-and-tuples">Pairs and Tuples<a class="anchor" aria-hidden="true" hidden href="#pairs-and-tuples">#</a></h4>
<ul>
<li>
<p>Slide pairs and tuples</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 17.png" style="width: 100%" class="center" alt="Untitled 17"></p>
</li>
</ul>
<p>Abbiamo la stessa informazione con gli array (solo che possono non essere omogenei!) abbiamo sempre informazione sulla posizione, e un valore all'interno della posizione. La coppia generalizzata è una tupla.</p>
<h4 id="records">Records<a class="anchor" aria-hidden="true" hidden href="#records">#</a></h4>
<p>Se astraiamo le tuple, aggiungendoci un nome per ogni tipo ad una certa posizione, allora abbiamo i records, che non sono altro che delle <strong>strutture</strong>.</p>
<p>Quando andiamo a prendere un elemento stiamo facendo una <strong>proiezione monomorfa</strong>, perché da tutto quell'array di elementi stiamo andando a prenderne un singolo.</p>
<h4 id="pattern-matching">Pattern Matching<a class="anchor" aria-hidden="true" hidden href="#pattern-matching">#</a></h4>
<p>Questo è una struttura molto comune nei linguaggi funzionali, ma anche presente in rust. Sono buoni da poter definire all'interno di un tipo prodotto.</p>
<ul>
<li>
<p>Slide pattern matching</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 18.png" style="width: 100%" class="center" alt="Untitled 18"></p>
</li>
</ul>
<p>Praticamente vorremmo fare una partizione completa degli abitanti di un tipo, per questo motivo posso fare una specie di casework completo per gestire in modo esplicito tutti i casi. Questa partizione è fatta in modo libero con delle regole :D.</p>
<h4 id="recursive-types">Recursive Types<a class="anchor" aria-hidden="true" hidden href="#recursive-types">#</a></h4>
<p>Questi tipi sono definiti per la prima volta grazie ai pairs (quelli con riferimento erano invece delle cose diverse, anche se concettualmente è simile). Possiamo definire che questo sia un tipo ricorsivo nel senso che si potrebbe descrivere come un powersets infinito (credo).</p>
<p>Dalla lezione ora mi sembra abbia detto che deve necessariamente avere una <strong>reference</strong> dello stesso tipo</p>
<h3 id="sum-types">Sum Types<a class="anchor" aria-hidden="true" hidden href="#sum-types">#</a></h3>
<ul>
<li>
<p>Slide introduttiva sum types</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 19.png" style="width: 100%" class="center" alt="Untitled 19"></p>
</li>
</ul>
<p>I tipi di somma ci permettono di avere abitandi di più mondi.</p>
<p>Nell'esempio di sopra gli insiemi sono taggati per non confondere un elemento di un insieme con un altro! anche chiamato <strong>or types, choice types, tagged unions, union types, variant types</strong>, perché può assumere un inabitante a caso fra tutti i tipi che costituiscono questa unione.</p>
<p>Abbiamo già visto le <strong>ENUMS</strong> che fanno cose simili, ossia può avere abitanti di tipi diversi, quindi stiamo comunque catturando la somma dei tipi. È interessante osservare che dal punto di vista teorico prendere un elemento di union implementato per enumerazione è simile a tirare fuori da un pacchetto.</p>
<h4 id="union-datatypes">Union Datatypes<a class="anchor" aria-hidden="true" hidden href="#union-datatypes">#</a></h4>
<p>Come in C, posso avere le union data types, in cui stessa zona di memoria posso metterci i dati che ho scelto (solo che non mi fa check statico a vedere cosa ci può stare!!), cioè a differenza degli enums, non ho il controllo dell'accesso, decido io come guardarlo.</p>
<h4 id="recursive-types-1">Recursive Types<a class="anchor" aria-hidden="true" hidden href="#recursive-types-1">#</a></h4>
<p>Anche con i sum types posso andare a descrivere i tipi ricorsivi (solamente che alla fine invece di dire che Null è un inabidante delle reference, gli dico che è un abitante di qualcos'altro!) Questo mi rende molto carina la sua struttura (e mi permette anche pattern matchin senza nessun problema (è un modo più sicuro per aprire, dato che posso fare matching).</p>
<ul>
<li>
<p>Slide recursive types with sum</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 20.png" style="width: 100%" class="center" alt="Untitled 20"></p>
</li>
</ul>
<h3 id="function-types">Function types<a class="anchor" aria-hidden="true" hidden href="#function-types">#</a></h3>
<p>Praticamente sono elementi di  <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8413em;"></span><span class="mord"><span class="mord mathnormal">A</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8413em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.0502em;">B</span></span></span></span></span></span></span></span></span></span></span>, con B partenza A arrivo. L'operazione fondamentale di questi tipi sono <strong>l'applicazione</strong>.</p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 21.png" style="width: 100%" class="center" alt="Untitled 21"></p>
<p><img src="/images/notes/image/universita/ex-notion/Teoria dei Tipi/Untitled 22.png" style="width: 100%" class="center" alt="Untitled 22"></p>
<h1 id="references">References<a class="anchor" aria-hidden="true" hidden href="#references">#</a></h1>
<p id="russellArtificialIntelligenceModern2009">[1] Russell &#x26; Norvig “Artificial Intelligence: A Modern Approach” Prentice Hall Press 2009</p>]]></content:encoded>
    </item>
    <item>
      <title>Classi OOP</title>
      <link>https://flecart.github.io/notes/classi-oop/</link>
      <pubDate>Fri, 26 Sep 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/classi-oop/</guid>
      <description>Introduzione a OOP # Per la definizione di classe andare a guardare Object Orientation , però lo ripeto in questa occasione, è solamente un modello su cui andare a costruire degli oggetti. Capisaldi # Incapsulazione (con interfaccia, base per la documentazione) Astrazione Eredita</description>
      <content:encoded><![CDATA[<h2 id="introduzione-a-oop">Introduzione a OOP<a class="anchor" aria-hidden="true" hidden href="#introduzione-a-oop">#</a></h2>
<p>Per la definizione di classe andare a guardare <a href="/notes/object-orientation/">Object Orientation</a>, però lo ripeto in questa occasione, è solamente un modello su cui andare a costruire degli oggetti.</p>
<h3 id="capisaldi">Capisaldi<a class="anchor" aria-hidden="true" hidden href="#capisaldi">#</a></h3>
<ol>
<li>Incapsulazione (con interfaccia, base per la documentazione)</li>
<li>Astrazione</li>
<li>Ereditarietà</li>
<li>Dispatch dinamico</li>
</ol>
<ul>
<li>Inheritance to avoid code duplication</li>
<li>Subtyping to express classification</li>
<li>Overriding to specialize methods</li>
<li>Dynamic binding to adapt reused algorithms</li>
</ul>
<h3 id="costruttori">Costruttori<a class="anchor" aria-hidden="true" hidden href="#costruttori">#</a></h3>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled.png" style="width: 100%" class="center" alt="Untitled">
<img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 1.png" style="width: 100%" class="center" alt="Untitled 1">
<img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 2.png" style="width: 100%" class="center" alt="Untitled 2"></p>
<p>Il costruttore è un codice utilizzato per <strong>inizializzare correttamente lo stato</strong> interno. Le regole sono le stesse dei metodi sovraccaricati (dinamica per la chiamata, statica per il numero dei parametri che prende in input).</p>
<h2 id="incapsulazione">Incapsulazione<a class="anchor" aria-hidden="true" hidden href="#incapsulazione">#</a></h2>
<h3 id="carat-incapsulazione">Carat incapsulazione<a class="anchor" aria-hidden="true" hidden href="#carat-incapsulazione">#</a></h3>
<p>ossia la distinzione fra <strong>pubblico e privato,</strong> il fatto che posso decidere quanto nascondere e quanto esporre. All'esterno sono esposte solamente le <strong>interfacce</strong> che sono solitamente pubblici.</p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 3.png" style="width: 100%" class="center" alt="Untitled 3"></p>
<p>Solamente le cose dichiarate come pubbliche sono esposte, mentre tutto lo stato interno è nascosto e non è accessibile all'esterno.</p>
<h3 id="sottotipi-liskov">Sottotipi (Liskov)<a class="anchor" aria-hidden="true" hidden href="#sottotipi-liskov">#</a></h3>
<p>Questo è il <strong>principio di sostituzione di Liskov,</strong> che in pratica ci dice che se S è sottotipo di T, allora posso utilizzare S in qualunque posto di T.</p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 4.png" style="width: 100%" class="center" alt="Untitled 4"></p>
<p>Se utilizizmao una notazione matematica, allora se ho unap roprietà per un oggetto in T allora questa proprietà vale anche per un oggetto in S.</p>
<h3 id="differenza-tipo-e-classe">Differenza tipo e classe<a class="anchor" aria-hidden="true" hidden href="#differenza-tipo-e-classe">#</a></h3>
<p>C'è una differenza fra struttura delle operazioni (quindi il tipo, cosa prendo e cosa ritorno) con l’implementazione effettiva delle funzioni, i check per privati e pubblici (implementati dalle classi). Quando dichiariamo alla classe è come se dichiarassimo allo stesso momento una interfaccia per essa.</p>
<blockquote>
<p>consideriamo la definizione di una classe come <strong>accompagnata da una definizione
implicita di un'interfaccia</strong> della vista pubblica di quella classe.</p>
</blockquote>
<p>In questo senso la classe diventa un elemento nel nostro sistema dei tipi.</p>
<h3 id="astrazione">Astrazione (!)<a class="anchor" aria-hidden="true" hidden href="#astrazione">#</a></h3>
<p>La nozione di astrazione è strettamente legata all'interfaccia implicita che la classe induce.</p>
<p>L’astrazione di permette di andare ad elaborare con alcuni concetti che nativamente non esistono, per esempio non esiste nativamente il tipo Euro, ma può essere implementata attraverso il tipo concreto degli interi. Le classi forniscono delle interfacce che permettono una modifica controllata dell’oggetto che viene rappresentato, questo è il significato di astrazione.</p>
<blockquote>
<p>le interfacce ci permettono di
fornire ai clienti una <strong>descrizione del
"contratto"</strong> che i nostri oggetti promettono
di soddisfare, senza costringerci a fornire
la loro effettiva implementazione.</p>
</blockquote>
<p>ossia descrive ciò che prende in input, ciò che deve andare a ritornare. senza dire esattamente come è implementata quella logica.</p>
<h3 id="classi-astratte">Classi astratte<a class="anchor" aria-hidden="true" hidden href="#classi-astratte">#</a></h3>
<p>Sono una <strong>via di mezzo fra interfaccia e classe</strong> nel senso che possono lasciare delle funzioni non implementate</p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 5.png" style="width: 100%" class="center" alt="Untitled 5"></p>
<h2 id="ereditarieta">Ereditarietà<a class="anchor" aria-hidden="true" hidden href="#ereditarieta">#</a></h2>
<h3 id="sottotipaggio-ed-ereditarieta">Sottotipaggio ed ereditarietà<a class="anchor" aria-hidden="true" hidden href="#sottotipaggio-ed-ereditarieta">#</a></h3>
<p>Ci sono due <strong>keyworks</strong> principali quando andiamo a parlare di sottotipaggoi ed ereditarietà, sono <strong>extends and implements.</strong></p>
<h4 id="extends-and-implements">Extends and Implements<a class="anchor" aria-hidden="true" hidden href="#extends-and-implements">#</a></h4>
<ul>
<li>Extends: prende anche i metodi (proprio l'implementazione) di tutti metodi e gli stati del genitore. Doppia operazione:
<ul>
<li>Relazione di sottotipaggio col tipo da cui estende</li>
<li>Prendere tutti i metodi dichiarati sono presenti ora anche qui.</li>
</ul>
</li>
<li>Implements: crea l'implementazione dell’interfaccia astratta.</li>
</ul>
<p>C'è una leggera differenza fra queste keywords se utilizzate per interfacce oppure per classi. Credo l'unica cosa che cambia è che per extends nelle classi mi porto dietro anche stati e funzioni e anche i vincoli di incapsulamento.</p>
<p>In breve: sottotipi parlano di operazioni, e manipolazione i interfacce fre la varie classi, mentre l’ereditarietà va a parlare di metodi che possono essere utilizzate o meno.</p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 6.png" style="width: 100%" class="center" alt="Untitled 6"></p>
<p>Differenza principale fra sottotipaggio ed ereditarietà</p>
<h3 id="shadowing">Shadowing<a class="anchor" aria-hidden="true" hidden href="#shadowing">#</a></h3>
<p>Come gestire i casi di ereditarietà in cui una stessa variabile è stata dichiarata con esattamente lo stesso nome?</p>
<p><strong>Regole di scoping statico!</strong> In pratica il parent è visto come uno scope più esterno, e si risolve in questo modo.</p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 7.png" style="width: 100%" class="center" alt="Untitled 7"></p>
<h3 id="overriding-dei-metodi">Overriding dei metodi<a class="anchor" aria-hidden="true" hidden href="#overriding-dei-metodi">#</a></h3>
<p>Coerentemente al principio di astrazione, posso cambiare il contenuto (quindi la semantica) di una funzione senza cambiarne la signature, sulla stessa logica posso reimplementare un metodo in un child class.</p>
<blockquote>
<p>Una differenza tra l'overriding dei metodi e
lo shadowing delle variabili è che il primo è
risolto dinamicamente, mentre il secondo è
risolto staticamente.</p>
</blockquote>
<h3 id="modificatori-di-visibilita-2">Modificatori di visibilità (2)<a class="anchor" aria-hidden="true" hidden href="#modificatori-di-visibilita-2">#</a></h3>
<p>Ci sono dei modi per andare a modificare la visibilità durante le relazioni di ereditarietà fra le classi, queste son ooil <strong>packaged e protected</strong></p>
<ul>
<li>packaged: se sei un figlio allora puoi vedere i metodi privati (tutto lo stesso pacchetto può vedere questi metodi.</li>
<li>Protected: tutte le sottoclassi, anche in moduli diversi possono utilizzare le funzioni ereditate protected, solo che l'esterno non può comunque andare ad accederci.</li>
</ul>
<h3 id="tipi-intersezione">Tipi intersezione<a class="anchor" aria-hidden="true" hidden href="#tipi-intersezione">#</a></h3>
<p>Questi tipi intersezione prendono in input due classi e creano una classe che abbia <strong>entrambe le caratteristiche</strong> delle due classi. Sono diverse dai tipi unione, perché questi tipi unione possono essere o uno o l’altro, nel senso che non sono entrambi in contemporanea!.</p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 8.png" style="width: 100%" class="center" alt="Untitled 8"></p>
<p>In un certo senso sono <strong>concatenati</strong> questi valori. Una cosa interessante è che il grafico delle inheritance è un <strong>DAG</strong></p>
<h3 id="ereditarieta-multipla-problemi-diamante">Ereditarietà multipla problemi: diamante<a class="anchor" aria-hidden="true" hidden href="#ereditarieta-multipla-problemi-diamante">#</a></h3>
<ul>
<li>
<p>Slide introduzione dei problemi di ereditarietà (2 sol)</p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 9.png" style="width: 100%" class="center" alt="Untitled 9"></p>
</li>
</ul>
<p>Questa implementazione ha molti problemi quando eredito due cose che hanno una intersezione, come per esempio un metodo con lo stesso nome. Allora come si risolve questo problema?</p>
<p>Il problema principale è la <strong>diamond of death</strong></p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 10.png" style="width: 100%" class="center" alt="Untitled 10"></p>
<h2 id="dynamic-dispatch">Dynamic dispatch<a class="anchor" aria-hidden="true" hidden href="#dynamic-dispatch">#</a></h2>
<h3 id="early-and-late-binding">Early and late binding<a class="anchor" aria-hidden="true" hidden href="#early-and-late-binding">#</a></h3>
<p>Late: quando ho l’oggetto io vado a cercare l’oggetto, se lo trovo allora lo eseguo, se non c’è allora continuo la ricerca finché non lo trovo, allora do errore: è una cosa molto simile al prototyping.</p>
<p>Early: Utilizza infomrazioni statiche per risolvere l’ambiguità, questo dovrebbe farlo C per esempio.</p>
<h3 id="metodi-statici">Metodi statici<a class="anchor" aria-hidden="true" hidden href="#metodi-statici">#</a></h3>
<p>Niente ci vieta di andare a definire dei metodi statici che vengono risolti in modo statico.</p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 11.png" style="width: 100%" class="center" alt="Untitled 11"></p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 12.png" style="width: 100%" class="center" alt="Untitled 12"></p>
<h3 id="implementazione-degli-oggetti-link">Implementazione degli oggetti (link)<a class="anchor" aria-hidden="true" hidden href="#implementazione-degli-oggetti-link">#</a></h3>
<p>SI potrebbe tenere una lista linkata fra tutte le ereditarietà, solo che diventa una cosa molto lenta, perché potrebbero esserci molti accessi: vado a cercare fino al top se ci sia o meno questo metodo per una certa classe.</p>
<h3 id="early-and-late-binding-1">Early and late binding<a class="anchor" aria-hidden="true" hidden href="#early-and-late-binding-1">#</a></h3>
<p>Accesso via offset: per accedere allo stato, faccio in modo molto simile alle struct, che in pratica vanno a calcolare offset rispetto a qualcosa, il calcolo dell’offset per il singolo stato è molto veloce, una cosa leggermente più complicata è la ricerca del metodo corretto, se questo è stato sovrascritto o simile. (fa ricerca lineare, va su finché non trova il metodo.</p>
<p><strong>CHIAMATA DEL METODO</strong></p>
<p>Non solo vogliamo andare a creare uno stack frame, variabili locali e parametri abbiamo in più anche le variabili di istanza! Semplicemente prende il this e ci applica l’offset per prendere le informazioni, le slides lo fanno molto più complicato.</p>
<h3 id="vtables">Vtables(!!)<a class="anchor" aria-hidden="true" hidden href="#vtables">#</a></h3>
<p>Ogni oggetto ha un puntatore alla propria vtable della propria classe, con già tutti i puntatori alle funzioni corrette per le funzioni.</p>
<ul>
<li>
<p>Slides ereditarietà</p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 13.png" style="width: 100%" class="center" alt="Untitled 13"></p>
<p><img src="/images/notes/image/universita/ex-notion/Classi OOP/Untitled 14.png" style="width: 100%" class="center" alt="Untitled 14"></p>
</li>
</ul>
<p>Dovrebbe funzionare solamente per ereditarietà singola, non so per la multipla come funziona questa della vtable.</p>
<h3 id="classe-base-fragile">Classe base fragile<a class="anchor" aria-hidden="true" hidden href="#classe-base-fragile">#</a></h3>
<p>C’è il problema della <strong>composizionalità</strong>, nel senso che non possiamo andare a compilarli in modo diverso, se cambiamo una classe padre, allora bisogna andare a ricompilare tutti childs, è un problema di ingegneria del software questo.</p>
<h3 id="type-parameter-erasure">Type parameter erasure<a class="anchor" aria-hidden="true" hidden href="#type-parameter-erasure">#</a></h3>
<h3 id="in-java-fragile">In Java fragile<a class="anchor" aria-hidden="true" hidden href="#in-java-fragile">#</a></h3>
<p>Ci sono alcuni metodi per andare a gestire il problema della classe fragile. Come gestire questo problema quando l'intera classe è stata compilata a sé stante. Viene risolto a caricamento e la prima reference viene risolta e sostituita al codice di ricerca col riferimento al codice effettivo.</p>]]></content:encoded>
    </item>
    <item>
      <title>Data Analysis Methods in Neural Science</title>
      <link>https://flecart.github.io/notes/data-analysis-methods-in-neural-science/</link>
      <pubDate>Thu, 28 Aug 2025 00:00:00 GMT</pubDate>
      <guid>https://flecart.github.io/notes/data-analysis-methods-in-neural-science/</guid>
      <description>This note is just a collection of past useful notes to know to apply machine learning methods for the analysis of topics interesting in the neural sciences. Estimators # You need to know all Parametric Modeling . We want to estimate unknown random variables with some observations</description>
      <content:encoded><![CDATA[<p>This note is just a collection of past useful notes to know to apply machine learning methods for the analysis of topics interesting in the neural sciences.</p>
<h3 id="estimators">Estimators<a class="anchor" aria-hidden="true" hidden href="#estimators">#</a></h3>
<p>You need to know all <a href="/notes/parametric-modeling/">Parametric Modeling</a>.
We want to estimate unknown random variables with some observations.</p>
<h3 id="maximum-likelihood">Maximum Likelihood<a class="anchor" aria-hidden="true" hidden href="#maximum-likelihood">#</a></h3>
<p>See <a href="/notes/bayesian-linear-regression/">Bayesian Linear Regression</a>.</p>
<h3 id="bias-variance-decomposition">Bias-Variance Decomposition<a class="anchor" aria-hidden="true" hidden href="#bias-variance-decomposition">#</a></h3>
<h3 id="fisher-information">Fisher Information<a class="anchor" aria-hidden="true" hidden href="#fisher-information">#</a></h3>
<p>See <a href="/notes/parametric-modeling/#fisher-information">Parametric Modeling#Fisher information</a>.</p>
<h2 id="applications">Applications<a class="anchor" aria-hidden="true" hidden href="#applications">#</a></h2>
<h3 id="echo-locating-bats">Echo-locating bats<a class="anchor" aria-hidden="true" hidden href="#echo-locating-bats">#</a></h3>
<p>Egyptian fruit flies bats use echo location to locate the target, emitting clicks and capturing echo to navigate the environment. Bats use to click slightly left and right compared to their direction of motion.
It is interesting to observe and study how these bats are clicking around to move.</p>
<h4 id="bats-locking-behaviour">Bats Locking behaviour<a class="anchor" aria-hidden="true" hidden href="#bats-locking-behaviour">#</a></h4>
<p>Before looking the bat uses right and left click and also middle, probably to look for the target (you can have the emission intensity). After looking the distribution was very narrow, but not much about the target part (double distribution).
If we look using fisher information, we see they are using a distribution with high information, it gets the most information for the environment (this is the second row in the image, which is very cool thing).</p>
<p><img src="/images/notes/Data Analysis Methods in Neural Science-20250428100058084.webp" width="466" class="center" alt="Data Analysis Methods in Neural Science-20250428100058084"></p>
<h4 id="tuning-curve-neural-decoding">Tuning Curve Neural Decoding<a class="anchor" aria-hidden="true" hidden href="#tuning-curve-neural-decoding">#</a></h4>
<p><img src="/images/notes/Data Analysis Methods in Neural Science-20250428100422782.webp" style="width: 100%" class="center" alt="Data Analysis Methods in Neural Science-20250428100422782">
The point is that the neuron is most informative when the signal is slightly off its most preferred position.</p>
<p>The fisher information reaches a minimum at the peak of the curve, that is where the neuron likes to fire.
The neuron is more informative in regions where the tuning <em>curve is steep.</em>
This is an argument against the tuning hypothesis, where the idea of neurons acting as <strong>feature detectors</strong> that fire when you expose them to preferred stimulus, or most stimulus-specific information about sound frequency when they fire at that frequency.</p>]]></content:encoded>
    </item>
  </channel>
</rss>
