<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://cloudmark.me/feed.xml" rel="self" type="application/atom+xml" /><link href="https://cloudmark.me/" rel="alternate" type="text/html" /><updated>2026-11-30T11:33:04+01:00</updated><id>https://cloudmark.me/feed.xml</id><title type="html">cloudmark</title><subtitle>stay safe, keep hacking! - cloudmark</subtitle><author><name>Mark Galea</name></author><entry><title type="html">The Detector Was Not Impressed</title><link href="https://cloudmark.me/The-Detector-Was-Not-Impressed/" rel="alternate" type="text/html" title="The Detector Was Not Impressed" /><published>2026-11-27T08:30:00+01:00</published><updated>2026-11-27T08:30:00+01:00</updated><id>https://cloudmark.me/The-Detector-Was-Not-Impressed</id><content type="html" xml:base="https://cloudmark.me/The-Detector-Was-Not-Impressed/"><![CDATA[<style>
  .chart { margin: 2.2em 0 1.6em; padding: 22px 24px 18px; background: var(--paper, #fff) var(--grain-img, none); border: 1px solid var(--line); border-radius: 14px; }
  .chart figcaption { margin: 0 0 14px; }
  .chart figcaption strong { display: block; color: var(--ink); font: 600 18px/1.3 var(--ui); letter-spacing: -.01em; }
  .chart figcaption span { display: block; margin-top: 4px; color: var(--grey); font: 14px/1.45 var(--ui); }
  .chart .legend { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 0 0 10px; padding: 0; list-style: none; font: 13px var(--ui); color: var(--soft); }
  .chart .legend li { display: inline-flex; align-items: center; gap: 7px; margin: 0; }
  .chart .legend i { width: 11px; height: 11px; border-radius: 4px; display: inline-block; }
  .chart svg { display: block; width: 100%; height: auto; overflow: visible; font-family: var(--ui); }
  .chart .t { fill: var(--ink); font-size: 14px; }
  .chart .g { fill: var(--ink); font-size: 13px; font-weight: 600; letter-spacing: .02em; }
  .chart .s { fill: var(--grey); font-size: 12.5px; }
  .chart .v { fill: var(--ink); font-size: 13.5px; font-weight: 600; font-variant-numeric: tabular-nums; }
  .chart .grid { stroke: var(--line); stroke-width: 1; }
  .chart .dash { stroke: var(--line); stroke-width: 1; stroke-dasharray: 2 4; }
  .chart .track { fill: var(--line); opacity: .55; }
  .chart [data-tip] { cursor: default; outline: none; transition: filter .15s; }
  .chart [data-tip]:hover, .chart [data-tip]:focus-visible { filter: brightness(1.1) saturate(1.1); }
  .chart .hit { fill: transparent; }
  .chart-tip { position: fixed; z-index: 20; pointer-events: none; padding: 7px 11px; border-radius: 10px; background: var(--ink); color: var(--bg, #fff); font: 13px/1.35 var(--ui); max-width: 260px; opacity: 0; transform: translateY(4px); transition: opacity .12s, transform .12s; box-shadow: 0 8px 24px -8px rgba(var(--shadow, 28, 31, 58),.5); }
  .chart-tip b { display: block; font-size: 15px; font-variant-numeric: tabular-nums; }
  .flow ol { list-style: none; margin: 0; padding: 0; counter-reset: step; }
  .flow li { position: relative; margin: 0; padding: 0 0 18px 52px; counter-increment: step; }
  .flow li::before { content: counter(step); position: absolute; left: 0; top: 0; width: 34px; height: 34px; border-radius: 50%; background: var(--ink); color: var(--bg, #fff); font: 600 15px/34px var(--ui); text-align: center; }
  .flow li::after { content: ''; position: absolute; left: 16px; top: 40px; bottom: 4px; width: 2px; border-radius: 2px; background: var(--line); }
  .flow li:last-child { padding-bottom: 0; } .flow li:last-child::after { display: none; }
  .flow h4 { margin: 0; padding-top: 5px; font: 600 16px/1.3 var(--ui); color: var(--ink); display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
  .flow .who { font: 600 11.5px/1 var(--ui); letter-spacing: .03em; padding: 5px 9px; border-radius: 999px; color: #fff; }
  .flow .loop { font: 600 11.5px/1 var(--ui); padding: 5px 9px; border-radius: 999px; border: 1px solid var(--line); color: var(--soft); background: var(--paper, #fff); }
  .flow p { margin: 5px 0 0; font: 14.5px/1.5 var(--ui); color: var(--soft); }
  .flow ul { margin: 8px 0 0; padding: 0; list-style: none; display: flex; flex-wrap: wrap; gap: 6px; }
  .flow ul li { padding: 5px 10px; border-radius: 8px; background: var(--paper, #fff); border: 1px solid var(--line); font: 13px var(--ui); color: var(--ink); counter-increment: none; }
  .flow ul li::before, .flow ul li::after { display: none; }
  .chart circle[stroke="#fff"] { stroke: var(--paper, #fff); }
  .chart text[fill="#1c1f3a"] { fill: #1f1e1b; }
  /* At night the series colours take brighter steps, on fills, strokes and gradient stops alike. */
  :root[data-theme="dark"] .chart :is([fill="#2a78d6"], [style*="#2a78d6"]) { fill: #3987e5; background-color: #3987e5 !important; } :root[data-theme="dark"] .chart [stroke="#2a78d6"] { stroke: #3987e5; } :root[data-theme="dark"] .chart [stop-color="#2a78d6"] { stop-color: #3987e5; }
  :root[data-theme="dark"] .chart :is([fill="#eb6834"], [style*="#eb6834"]) { fill: #d95926; background-color: #d95926 !important; } :root[data-theme="dark"] .chart [stroke="#eb6834"] { stroke: #d95926; } :root[data-theme="dark"] .chart [stop-color="#eb6834"] { stop-color: #d95926; }
  :root[data-theme="dark"] .chart :is([fill="#1baf7a"], [style*="#1baf7a"]) { fill: #199e70; background-color: #199e70 !important; } :root[data-theme="dark"] .chart [stroke="#1baf7a"] { stroke: #199e70; } :root[data-theme="dark"] .chart [stop-color="#1baf7a"] { stop-color: #199e70; }
  :root[data-theme="dark"] .chart :is([fill="#b9b8b3"], [style*="#b9b8b3"]) { fill: #8d8b84; background-color: #8d8b84 !important; } :root[data-theme="dark"] .chart [stroke="#b9b8b3"] { stroke: #8d8b84; } :root[data-theme="dark"] .chart [stop-color="#b9b8b3"] { stop-color: #8d8b84; }
  @media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) .chart :is([fill="#2a78d6"], [style*="#2a78d6"]) { fill: #3987e5; background-color: #3987e5 !important; } :root:not([data-theme="light"]) .chart [stroke="#2a78d6"] { stroke: #3987e5; } :root:not([data-theme="light"]) .chart [stop-color="#2a78d6"] { stop-color: #3987e5; }
  :root:not([data-theme="light"]) .chart :is([fill="#eb6834"], [style*="#eb6834"]) { fill: #d95926; background-color: #d95926 !important; } :root:not([data-theme="light"]) .chart [stroke="#eb6834"] { stroke: #d95926; } :root:not([data-theme="light"]) .chart [stop-color="#eb6834"] { stop-color: #d95926; }
  :root:not([data-theme="light"]) .chart :is([fill="#1baf7a"], [style*="#1baf7a"]) { fill: #199e70; background-color: #199e70 !important; } :root:not([data-theme="light"]) .chart [stroke="#1baf7a"] { stroke: #199e70; } :root:not([data-theme="light"]) .chart [stop-color="#1baf7a"] { stop-color: #199e70; }
  :root:not([data-theme="light"]) .chart :is([fill="#b9b8b3"], [style*="#b9b8b3"]) { fill: #8d8b84; background-color: #8d8b84 !important; } :root:not([data-theme="light"]) .chart [stroke="#b9b8b3"] { stroke: #8d8b84; } :root:not([data-theme="light"]) .chart [stop-color="#b9b8b3"] { stop-color: #8d8b84; }
  }
</style>

<div class="view-switch voice-switch" role="group" aria-label="Which version to read">
  <button type="button" data-voice="plain" aria-pressed="false"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2.5h10A1.5 1.5 0 0 1 14.5 4v5.5A1.5 1.5 0 0 1 13 11H8l-3 2.5V11H3a1.5 1.5 0 0 1-1.5-1.5V4A1.5 1.5 0 0 1 3 2.5z" /></svg>Plain AI</button>
  <button type="button" data-voice="prompt" aria-pressed="false"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4.5" width="8.5" height="10" rx="1.5" /><path d="M5.5 4.5V3A1.5 1.5 0 0 1 7 1.5h5.5A1.5 1.5 0 0 1 14 3v7a1.5 1.5 0 0 1-1.5 1.5h-2M4.5 8h3.5M4.5 10.5h3.5" /></svg>Posts in the prompt</button>
  <button type="button" data-voice="tuned" aria-pressed="true"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.5 2.5l3 3-8 8-3.5.5.5-3.5zM9 4l3 3" /></svg>In my voice</button>
</div>
<style>
  .voice-switch { display: inline-flex; flex-wrap: wrap; gap: 4px; padding: 4px; margin: 0 0 1.6em; border-radius: 14px; background: var(--wash); }
  .voice-switch button { display: inline-flex; align-items: center; gap: 8px; }
  .voice-switch svg { flex: none; }
  .prose[data-voice="plain"] :is(.v-tuned, .v-prompt), .prose[data-voice="tuned"] :is(.v-plain, .v-prompt), .prose[data-voice="prompt"] :is(.v-plain, .v-tuned) { display: none; }
  .voice-note { color: var(--grey); font-size: 15px; margin-top: -1em; }
  .pipe-example { margin: 1.4em 0; display: grid; gap: 10px; }
  .pipe-example div { padding: 14px 16px; border-radius: 14px; border: 1px solid var(--line); background: var(--paper, #fff); font-size: 15.5px; line-height: 1.55; }
  .pipe-example b { display: block; margin-bottom: 4px; font: 600 12px var(--ui); letter-spacing: .04em; text-transform: uppercase; color: var(--grey); }
  .pipe-example .bad { border-color: color-mix(in srgb, #eb6834 45%, var(--line)); background: color-mix(in srgb, #eb6834 7%, var(--paper, #fff)); } .pipe-example .good { border-color: color-mix(in srgb, #2a78d6 45%, var(--line)); background: color-mix(in srgb, #2a78d6 7%, var(--paper, #fff)); }
  .pipe-example mark { color: inherit; background: color-mix(in srgb, #eb6834 30%, var(--paper, #fff)); padding: 0 3px; border-radius: 4px; }
</style>

<p class="voice-note"><span class="v-plain">You are reading the version a chat model wrote, with no tuning.</span><span class="v-tuned">You are reading the version written by the model trained on my own writing: ten guarded rounds, then a check of every paragraph against the plain version. In a last read, 27 small slips in 24 of the 109 paragraphs were fixed by hand, mostly dropped words and typos. For 37 paragraphs an earlier round was chosen by hand, because the last round read badly. In 11 paragraphs a word or two changed when two posts became three. The opening sentence of the second and third posts was shortened by hand. A fact check then corrected 12 paragraphs in all three versions, and in this version a further 31 sentences in 26 paragraphs where the meaning had drifted from the plain text.</span><span class="v-prompt">You are reading the version a chat model wrote with 22 of my old posts in its system prompt, and no training at all. It is the second technique, described in the first post. It was not checked against the plain version, so its asides and small additions are the model's own. Twelve paragraphs rewritten this way scored 100% AI.</span></p>

<p class="v-plain">This is the third of three posts. The <a href="/I-Did-Not-Write-This-Post/">first post</a> put the author's old posts in the prompt of a chat model, and the second trained a small model to write in the author's voice. Both sounded like the author. This post asks two harder questions about the trained model. Does an AI detector take the result for human writing? And are the facts still right afterwards?</p>
<p class="v-tuned">This is the third of three posts. In the <a href="/I-Did-Not-Write-This-Post/">first post</a> the old posts of the author were placed into the prompt of a chat model and in the second the author trained a small model to write in their voice. Both sounded like the author. In this post two harder questions are asked about the trained model. Does an AI detector take the result for human writing? Are the facts still right after?</p>
<p class="v-prompt">This is the third of three posts. In the <a href="/I-Did-Not-Write-This-Post/">first post</a> I put the author's old posts in the prompt of a chat model, and in the second I trained a small model to write in the author's voice. Both sounded like the author. Now we ask two harder questions about the trained model. Does an AI detector take the result for human writing? And are the facts still right afterwards?</p>

<p class="v-plain">The short answers: not after one rewrite, only sometimes after ten, and the facts survive only with a great deal of help. As before, the switch at the top of the page changes the whole text between the three versions.</p>
<p class="v-tuned">The short answer: not after one rewrite, only sometimes after ten, and the facts survive only with a lot of help. Like the previous exercise the switch at the top of the page will flip between the three versions.</p>
<p class="v-prompt">The short answers: not after one rewrite, only sometimes after ten, and the facts survive only with a great deal of help. As before, the switch at the top of the page changes the whole text between the three versions.</p>

<p><em>This is part 3 of three.</em></p>

<ol>
  <li><a href="/I-Did-Not-Write-This-Post/">I Didn’t Write This Post</a>: the idea, and the easy way</li>
  <li><a href="/80000-Words-Of-Me/">80,000 Words of Me</a>: training a model on my own writing</li>
  <li><strong>The Detector Was Not Impressed</strong>: the detector and the pipeline (this post)</li>
</ol>

<p><em>The code for all three posts is on GitHub: <a href="https://github.com/cloudmark/in-my-voice">cloudmark/in-my-voice</a>.</em></p>

<h2 id="what-a-detector-says">What a detector says</h2>

<p class="v-plain">The test text is twelve paragraphs, about 800 words. They come from an earlier draft of the <a href="/80000-Words-Of-Me/">second post</a>, so the figures they mention are older than the ones there. The model that rewrites them is the finished one. The detector is GPTZero. The plain version, written by a chat model, scored 100% AI. The version rewritten once by the trained model also scored 100% AI.</p>
<p class="v-tuned">The test text is twelve paragraphs, about 800 words. They are taken from a previous draft of the <a href="/80000-Words-Of-Me/">second post</a> so the figures they mention are older than the ones there. The model which rewrites them is the finished one. I will use GPTZero as a detector. The plain text written by a chat model scored 100% AI. The text rewritten once by the trained model also scored 100% AI.</p>
<p class="v-prompt">Our test text is twelve paragraphs, about 800 words. They come from an earlier draft of the <a href="/80000-Words-Of-Me/">second post</a>, so the figures they mention are older than the ones there. The model that rewrites them is the finished one. The detector is GPTZero. The plain version, written by a chat model, scored 100% AI. The version rewritten once by the trained model also scored 100% AI. Ouch!</p>

<p class="v-plain">The twelve paragraphs are not part of the held-back set from the <a href="/80000-Words-Of-Me/">second post</a>. That set, and the 50 paragraphs taken from it, were used to measure the voice. This post measures something else, so it has a test text of its own. Every score below is for these same twelve paragraphs.</p>
<p class="v-tuned">Ok now let's see these twelve paragraphs. These twelve paragraphs are not from the held back set from the <a href="/80000-Words-Of-Me/">second post</a>. We have used the set and the 50 paragraphs from it to measure the voice. Now we want to measure something else thus we have our own test text. Each score below is for these twelve paragraphs.</p>
<p class="v-prompt">The twelve paragraphs are not part of the held-back set from the <a href="/80000-Words-Of-Me/">second post</a>. That set, and the 50 paragraphs taken from it, were used to measure the voice. In this post we measure something else, so it gets a test text of its own. Every score below is for these same twelve paragraphs.</p>

<table>
  <thead>
    <tr>
      <th>In this post</th>
      <th>Count</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Model doing the rewriting</td>
      <td>The tuned adapter from the second post, trained on 1,259 pairs</td>
    </tr>
    <tr>
      <td>Test paragraphs</td>
      <td>12, the text being rewritten</td>
    </tr>
    <tr>
      <td>Runs: separate ten-round rewrites of those paragraphs, each from the plain version</td>
      <td>5</td>
    </tr>
    <tr>
      <td>Rewritten paragraphs checked for facts by a chat model</td>
      <td>60, which is 5 runs of 12</td>
    </tr>
    <tr>
      <td>Detector that scores each text as human or AI</td>
      <td>GPTZero</td>
    </tr>
    <tr>
      <td>Held-back paragraphs from the second post</td>
      <td>none are used here</td>
    </tr>
  </tbody>
</table>

<p class="v-plain">Two different things read the rewritten text in this post, and it helps to keep them apart.</p>
<p class="v-tuned">So, two things read the rewritten text in this post and it helps to keep them apart.</p>
<p class="v-prompt">Two different things read the rewritten text in this post, and it helps to keep them apart. Let us look at each in turn.</p>

<p class="v-plain"><strong>The detector</strong> This is GPTZero. It reads a whole text and estimates how much of it was written by a person and how much by AI. It does not know whether the text is correct.</p>
<p class="v-tuned"><strong>The detector</strong> This is GPTZero. GPTZero reads a whole text and estimates how much of it was written by a person and how much by AI. It does not know whether the text is correct.</p>
<p class="v-prompt"><strong>The detector</strong> The first one is GPTZero. It reads a whole text and estimates how much of it was written by a person and how much by AI. Note that it has no idea whether the text is correct.</p>

<p class="v-plain"><strong>The judge</strong> This is a chat model. It reads each rewritten paragraph next to its plain version and says whether the facts are still the same. It does not know whether the text sounds human.</p>
<p class="v-tuned"><strong>The judge</strong> This is a chat model. Given a rewritten paragraph and the plain version side by side it will state whether the facts are still the same. It will not state whether the text sounds human.</p>
<p class="v-prompt"><strong>The judge</strong> The second one is a chat model. It reads each rewritten paragraph next to its plain version and tells us whether the facts are still the same. Note that it has no idea whether the text sounds human.</p>

<p class="v-plain">A fair question is whether GPTZero simply calls everything AI. It does not. Seven samples of the author's real writing, from 2011 to 2021, were scanned as well. Six of them scored 100% human and one scored 99% human. So the detector can tell the author's real writing from the model's imitation of it, even though the imitation uses the same words and the same habits.</p>
<p class="v-tuned">So a fair question is does the GPTZero just say everything is AI. No. I also scanned seven samples of my own real writing (2011 - 2021). Six of them scored 100% human and one scored 99% human. So the detector can tell the authors real writing from the model’s imitation of the writing, even though it uses the same words and the same habits.</p>
<p class="v-prompt">A fair question to ask is whether GPTZero simply calls everything AI. It does not. I scanned seven samples of the author's real writing, from 2011 to 2021, as well. Six of them scored 100% human and one scored 99% human. So the detector can tell the author's real writing from the model's imitation of it, even though the imitation uses the same words and the same habits.</p>

<figure class="chart " role="group" aria-label="Stacked bars of GPTZero scores for each text">
<figcaption><strong>The detector knows my real writing from the imitation</strong><span>GPTZero verdict for each text, as shares of human, mixed and AI.</span></figcaption>
<ul class="legend"><li><i style="background:#2a78d6"></i>Human</li><li><i style="background:#b9b8b3"></i>Mixed</li><li><i style="background:#eb6834"></i>AI</li></ul>
<svg viewBox="0 0 640 328" role="img" aria-label="Stacked bars of GPTZero scores for each text">
<clipPath id="c20"><rect x="200" y="10.0" width="432" height="20" rx="7" /></clipPath>
<text class="t" x="186" y="25.0" text-anchor="end">Plain AI version</text><g clip-path="url(#c20)">
<rect x="200.0" y="10.0" width="432.0" height="20" fill="#eb6834" tabindex="0" data-tip="100% AI|Plain AI version" />
<text x="209.0" y="24.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c21"><rect x="200" y="46.0" width="432" height="20" rx="7" /></clipPath>
<text class="t" x="186" y="61.0" text-anchor="end">Rewritten once</text><g clip-path="url(#c21)">
<rect x="200.0" y="46.0" width="432.0" height="20" fill="#eb6834" tabindex="0" data-tip="100% AI|Rewritten once" />
<text x="209.0" y="60.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c22"><rect x="200" y="82.0" width="432" height="20" rx="7" /></clipPath>
<text class="t" x="186" y="97.0" text-anchor="end">My writing, 2011</text><g clip-path="url(#c22)">
<rect x="200.0" y="82.0" width="432.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2011" />
<text x="209.0" y="96.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c23"><rect x="200" y="118.0" width="432" height="20" rx="7" /></clipPath>
<text class="t" x="186" y="133.0" text-anchor="end">My writing, 2016 (a)</text><g clip-path="url(#c23)">
<rect x="200.0" y="118.0" width="432.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2016 (a)" />
<text x="209.0" y="132.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c24"><rect x="200" y="154.0" width="432" height="20" rx="7" /></clipPath>
<text class="t" x="186" y="169.0" text-anchor="end">My writing, 2016 (b)</text><g clip-path="url(#c24)">
<rect x="200.0" y="154.0" width="425.7" height="20" fill="#2a78d6" tabindex="0" data-tip="99% human|My writing, 2016 (b)" />
<text x="209.0" y="168.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">99%</text>
<rect x="627.7" y="154.0" width="4.3" height="20" fill="#eb6834" tabindex="0" data-tip="1% AI|My writing, 2016 (b)" />
</g>
<clipPath id="c25"><rect x="200" y="190.0" width="432" height="20" rx="7" /></clipPath>
<text class="t" x="186" y="205.0" text-anchor="end">My writing, 2016 (c)</text><g clip-path="url(#c25)">
<rect x="200.0" y="190.0" width="432.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2016 (c)" />
<text x="209.0" y="204.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c26"><rect x="200" y="226.0" width="432" height="20" rx="7" /></clipPath>
<text class="t" x="186" y="241.0" text-anchor="end">My writing, 2017</text><g clip-path="url(#c26)">
<rect x="200.0" y="226.0" width="432.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2017" />
<text x="209.0" y="240.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c27"><rect x="200" y="262.0" width="432" height="20" rx="7" /></clipPath>
<text class="t" x="186" y="277.0" text-anchor="end">My writing, 2019</text><g clip-path="url(#c27)">
<rect x="200.0" y="262.0" width="432.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2019" />
<text x="209.0" y="276.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c28"><rect x="200" y="298.0" width="432" height="20" rx="7" /></clipPath>
<text class="t" x="186" y="313.0" text-anchor="end">My writing, 2021</text><g clip-path="url(#c28)">
<rect x="200.0" y="298.0" width="432.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2021" />
<text x="209.0" y="312.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th>Text scanned with GPTZero</th>
      <th>Words</th>
      <th>AI</th>
      <th>Mixed</th>
      <th>Human</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Earlier draft, plain AI version</td>
      <td>1,080</td>
      <td>100%</td>
      <td>0%</td>
      <td>0%</td>
    </tr>
    <tr>
      <td>Twelve paragraphs of it, rewritten once</td>
      <td>797</td>
      <td>100%</td>
      <td>0%</td>
      <td>0%</td>
    </tr>
    <tr>
      <td>My writing, 2011</td>
      <td>270</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2016 (a)</td>
      <td>260</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2016 (b)</td>
      <td>260</td>
      <td>1%</td>
      <td>0%</td>
      <td>99%</td>
    </tr>
    <tr>
      <td>My writing, 2016 (c)</td>
      <td>300</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2017</td>
      <td>260</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2019</td>
      <td>260</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2021</td>
      <td>260</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
  </tbody>
</table>

<p><em>The plain version was scanned as a whole draft of 1,080 words. The twelve test paragraphs are about 800 of those words.</em></p>

<h2 id="then-i-ran-it-again-and-again">Then I ran it again, and again</h2>

<p class="v-plain">The method in the paper is iterative: the rewriter is run on its own output several times. So the trained model was run over the twelve paragraphs for ten rounds in a row. Every round moves the wording a little further from what the chat model wrote. After one round the rewrite still shares 77% of its words with the plain version. After five rounds it shares 65%, and after ten rounds 63%.</p>
<p class="v-tuned">One thing which we can note here is that the method in the paper is iterative - the rewriter is applied to it's own output several times. So we have applied the trained model to the twelve paragraphs for ten rounds. Each round will move the wording further from what the chat model wrote. After one round the rewrite still shares 77% of it's words with the plain version. After five rounds it shares 65% and after ten rounds it shares 63%.</p>
<p class="v-prompt">The method in the paper is iterative: we run the rewriter on its own output several times. So I ran the trained model over the twelve paragraphs for ten rounds in a row. Every round moves the wording a little further away from what the chat model wrote. After one round the rewrite still shares 77% of its words with the plain version. After five rounds it shares 65% and after ten rounds 63%.</p>

<p class="v-plain">The model does not write the same thing twice. Every candidate is drawn at random, so rewriting the same twelve paragraphs for ten rounds a second time gives a different text. One text would prove little. So the ten rounds were repeated five times, each time starting again from the plain version with a different random seed. That gives five separate rewrites of the same twelve paragraphs, and each one is called a run here.</p>
<p class="v-tuned">Our model will not write the same thing twice. We draw a candidate randomly and if we ran the same twelve paragraphs for ten rounds we would get another text. One text would prove little. We have decided to repeat the ten rounds five times each time starting off with the original twelve paragraphs again but each time with a different random seed. This will give us five different rewrites of the same twelve paragraphs. We will refer to each of the five rewrites as a run.</p>
<p class="v-prompt">The model does not write the same thing twice. Every candidate is drawn at random, so rewriting the same twelve paragraphs for ten rounds a second time gives you a different text. One text would prove very little. So I repeated the ten rounds five times, each time starting again from the plain version with a different random seed. That gives us five separate rewrites of the same twelve paragraphs and we will call each one a run.</p>

<div class="v-plain"><p>Every run was scanned twice, after five rounds and after ten. After five rounds the five runs scored 69%, 81%, 43%, 0% and 70% human. After ten rounds the same five scored 89%, 74%, 0%, 81% and 96%. Repetition is what moves the detector, but it does not move it reliably.</p><ul><li>One run fell from 81% to 74% between round five and round ten.</li><li>One was rated fully AI at round five and 81% human at round ten.</li><li>And one went the other way, from 43% human to fully AI.</li></ul></div>
<div class="v-tuned"><p>So let us now go back to our runs and scan the runs twice - after five and after ten. After five the five runs scored 69%, 81%, 43%, 0%, 70% human. After ten the five scored 89%, 74%, 0%, 81% and 96%. Repetition is what moves the detector but not reliably.</p><ul><li>One run fell from 81% to 74%.</li><li>One rated fully AI at round five but rated as 81% human at round ten.</li><li>And one went the other way from 43% human to fully AI.</li></ul></div>
<p class="v-prompt">Every run was scanned twice, after five rounds and after ten. After five rounds the five runs scored 69%, 81%, 43%, 0% and 70% human. After ten rounds the same five scored 89%, 74%, 0%, 81% and 96%. Repetition is what moves the detector, but it does not move it reliably. One run fell from 81% to 74% between round five and round ten. One was rated fully AI at round five and 81% human at round ten. And one went the other way, from 43% human to fully AI. Go figure!</p>

<figure class="chart " role="group" aria-label="Dot chart of GPTZero human scores at each stage of rewriting">
<figcaption><strong>More rounds move the detector, but not reliably</strong><span>GPTZero human score for the same twelve paragraphs at each stage. Each dot is one scanned run.</span></figcaption>

<svg viewBox="0 0 640 268" role="img" aria-label="Dot chart of GPTZero human scores at each stage of rewriting">
<line class="grid" x1="150.0" y1="0" x2="150.0" y2="240" /><text class="s" x="150.0" y="258" text-anchor="middle">0%</text>
<line class="dash" x1="249.5" y1="0" x2="249.5" y2="240" /><text class="s" x="249.5" y="258" text-anchor="middle">25%</text>
<line class="dash" x1="349.0" y1="0" x2="349.0" y2="240" /><text class="s" x="349.0" y="258" text-anchor="middle">50%</text>
<line class="dash" x1="448.5" y1="0" x2="448.5" y2="240" /><text class="s" x="448.5" y="258" text-anchor="middle">75%</text>
<line class="grid" x1="548.0" y1="0" x2="548.0" y2="240" /><text class="s" x="548.0" y="258" text-anchor="middle">100%</text>
<rect x="349.0" y="0" width="199.0" height="240" fill="#2a78d6" opacity=".045" />
<text class="s" x="448.5" y="11" text-anchor="middle">rated human</text>
<text class="s" x="640" y="11" text-anchor="end">mean</text>
<text class="t" x="136" y="54.0" text-anchor="end">Plain AI</text>
<rect x="141.0" y="40.0" width="18.0" height="18" rx="9" fill="#2a78d6" opacity=".14" />
<line x1="150.0" y1="34.0" x2="150.0" y2="64.0" stroke="var(--ink)" stroke-width="2.5" stroke-linecap="round" />
<text class="v" x="640" y="54.0" text-anchor="end" font-size="15">0%</text>
<circle cx="150.0" cy="49.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="150.0" cy="49.0" r="12" tabindex="0" data-tip="0% human|Plain AI, run 1" />
<text class="t" x="136" y="108.0" text-anchor="end">Rewritten once</text>
<rect x="141.0" y="94.0" width="18.0" height="18" rx="9" fill="#2a78d6" opacity=".14" />
<line x1="150.0" y1="88.0" x2="150.0" y2="118.0" stroke="var(--ink)" stroke-width="2.5" stroke-linecap="round" />
<text class="v" x="640" y="108.0" text-anchor="end" font-size="15">0%</text>
<circle cx="150.0" cy="103.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="150.0" cy="103.0" r="12" tabindex="0" data-tip="0% human|Rewritten once, run 1" />
<text class="t" x="136" y="162.0" text-anchor="end">Five rounds</text>
<rect x="141.0" y="148.0" width="340.4" height="18" rx="9" fill="#2a78d6" opacity=".14" />
<line x1="359.3" y1="142.0" x2="359.3" y2="172.0" stroke="var(--ink)" stroke-width="2.5" stroke-linecap="round" />
<text class="v" x="640" y="162.0" text-anchor="end" font-size="15">53%</text>
<circle cx="424.6" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="424.6" cy="157.0" r="12" tabindex="0" data-tip="69% human|Five rounds, run 1" />
<circle cx="472.4" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="472.4" cy="157.0" r="12" tabindex="0" data-tip="81% human|Five rounds, run 2" />
<circle cx="321.1" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="321.1" cy="157.0" r="12" tabindex="0" data-tip="43% human|Five rounds, run 3" />
<circle cx="150.0" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="150.0" cy="157.0" r="12" tabindex="0" data-tip="0% human|Five rounds, run 4" />
<circle cx="428.6" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="428.6" cy="157.0" r="12" tabindex="0" data-tip="70% human|Five rounds, run 5" />
<text class="t" x="136" y="216.0" text-anchor="end">Ten rounds</text>
<rect x="141.0" y="202.0" width="400.1" height="18" rx="9" fill="#2a78d6" opacity=".14" />
<line x1="420.6" y1="196.0" x2="420.6" y2="226.0" stroke="var(--ink)" stroke-width="2.5" stroke-linecap="round" />
<text class="v" x="640" y="216.0" text-anchor="end" font-size="15">68%</text>
<circle cx="504.2" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="504.2" cy="211.0" r="12" tabindex="0" data-tip="89% human|Ten rounds, run 1" />
<circle cx="444.5" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="444.5" cy="211.0" r="12" tabindex="0" data-tip="74% human|Ten rounds, run 2" />
<circle cx="150.0" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="150.0" cy="211.0" r="12" tabindex="0" data-tip="0% human|Ten rounds, run 3" />
<circle cx="472.4" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="472.4" cy="211.0" r="12" tabindex="0" data-tip="81% human|Ten rounds, run 4" />
<circle cx="532.1" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="532.1" cy="211.0" r="12" tabindex="0" data-tip="96% human|Ten rounds, run 5" />
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th>Stage</th>
      <th>Runs scanned</th>
      <th>Human score of each</th>
      <th>Words shared with the plain version</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Plain AI</td>
      <td>1</td>
      <td>0%</td>
      <td>1.000</td>
    </tr>
    <tr>
      <td>Rewritten once</td>
      <td>1</td>
      <td>0%</td>
      <td>0.774</td>
    </tr>
    <tr>
      <td>Five rounds</td>
      <td>5</td>
      <td>69%, 81%, 43%, 0%, 70%</td>
      <td>0.653</td>
    </tr>
    <tr>
      <td>Ten rounds</td>
      <td>5</td>
      <td>89%, 74%, 0%, 81%, 96%</td>
      <td>0.631</td>
    </tr>
  </tbody>
</table>

<h2 id="what-goes-wrong">What goes wrong</h2>

<p class="v-plain">Ten rounds of rewriting damage a text in three different ways. Each one is shown below with an example from the runs.</p>
<p class="v-tuned">Let us see how the text is damaged in three ways by rewriting the text in ten rounds. Here is an illustration (taken from the runs).</p>
<p class="v-prompt">Ten rounds of rewriting damage a text in three different ways. Let's go through each one below with an example from the runs.</p>

<p class="v-plain"><strong>It changes facts.</strong> The model does not know which words carry the meaning, so it rewords them as freely as the rest. One paragraph of the test text says that extra training passes make the model memorise the posts instead of learning from them. After ten rounds, one run had it saying that further passes will result in the model learning from the posts rather than simply memorising them. The sentence reads well and says the opposite.</p>
<p class="v-tuned"><strong>It changes facts.</strong> The model does not know which words carry the meaning. It rewords them as freely as the rest. In one of the paragraphs in the text it states that more training passes will result in the model starting to memorise the posts rather than learning from the posts. After ten rounds, one run gave this sentence and states that the additional passes will make the model learn from the posts rather than memorise the posts. The sentence flows nicely and says the opposite.</p>
<p class="v-prompt"><strong>It changes facts.</strong> Here is the catch - the model has no idea which words carry the meaning, so it rewords them as freely as everything else. One paragraph of the test text says that extra training passes make the model memorise the posts instead of learning from them. After ten rounds, one run had it saying that further passes will result in the model learning from the posts rather than simply memorising them. Read it again, the sentence reads really well and says the exact opposite! Ouch.</p>

<p class="v-plain"><strong>It invents.</strong> One run added that the GPU was faster than the CPU, which nobody had said. Another began a paragraph with Observing Figure 50, when the plain version speaks of 50 held-back pairs and there is no figure. A third defined a base model as one that is first trained to continue text and then trained to follow instructions. That is the definition of an instruction-tuned model, which is exactly what a base model is not.</p>
<p class="v-tuned"><strong>It invents.</strong> One run added that the GPU was faster than the CPU; this nobody has stated. Another started a paragraph with Observing Figure 50, when the plain version mentions 50 held-back pairs and there is no figure. A third defined a base model as one which is first trained to continue text and then trained to follow instructions. This is the definition of an instruction-tuned model, which is exactly what a base model is not.</p>
<p class="v-prompt"><strong>It invents.</strong> It gets better. One run added that the GPU was faster than the CPU, which nobody had said. Another began a paragraph with Observing Figure 50, when the plain version speaks of 50 held-back pairs and there is no figure to observe. A third defined a base model as one that is first trained to continue text and then trained to follow instructions. That is the definition of an instruction-tuned model, which is exactly what a base model is not (my tongue hurts just reading it!).</p>

<p class="v-plain"><strong>It drops words.</strong> In earlier experiments with the first, smaller attempt at the model, nine wrong paragraphs out of ten were sentences with a hole in them, such as I will be using a of 0.00005 with a cosine. The words learning rate and schedule had simply gone. These are easy for a reader to spot. A reversed meaning in a smooth sentence is not.</p>
<p class="v-tuned"><strong>It drops words.</strong> So when we tried this with the first, smaller attempt at the model early on, nine out of ten wrong paragraphs were a sentence with a hole in them such as I will be using a of 0.00005 with a cosine. The words learning rate and schedule had simply gone. These are easy for a reader to spot. A reversed meaning in a smooth sentence is not.</p>
<p class="v-prompt"><strong>It drops words.</strong> In earlier experiments with the first, smaller attempt at the model, nine wrong paragraphs out of ten were sentences with a hole in them, such as I will be using a of 0.00005 with a cosine. The words learning rate and schedule had simply gone. These are easy for a reader to spot - you stumble on them straight away. A reversed meaning in a smooth sentence is a whole different beast.</p>

<h2 id="the-whole-pipeline">The whole pipeline</h2>

<div class="v-plain"><p>Left alone, ten rounds of rewriting get past the detector only some of the time, and they damage the facts on the way. So the rewriting was wrapped in a pipeline: a fixed sequence of five steps that runs from one command.</p><ul><li>What goes in is a list of plain paragraphs.</li><li>What comes out is the same paragraphs in the author's voice, each with a short report that says which round it came from and whether anything had to be repaired.</li></ul></div>
<div class="v-tuned"><p>When we run the ten rounds of rewriting left alone it is interesting to note that only sometimes a rewriting gets by the detector. And it hurts the facts on the way.</p><ul><li>So what we did was to place rewriting behind a pipeline; a fixed sequence of five steps which can be run from one command.</li><li>Given a list of plain paragraphs as input the pipeline outputs the same paragraphs in the author’s voice - each with a short report indicating which round it came from, and whether or not anything had to be fixed.</li></ul></div>
<p class="v-prompt">So what happens if we leave it alone? Ten rounds of rewriting get past the detector only some of the time, and they damage the facts on the way. Let's fix this by wrapping the rewriting in a pipeline: a fixed sequence of five steps that runs from one command. What goes in is a list of plain paragraphs. What comes out is the same paragraphs in the author's voice, each with a short report that tells us which round it came from and whether anything had to be repaired.</p>

<p class="v-plain">Two models take part, and they have very different jobs. The voice model, the one trained in the <a href="/80000-Words-Of-Me/">second post</a>, writes all of the prose. A chat model never writes prose. It lists the key terms of each paragraph before the rewriting starts, and it checks each finished paragraph against the plain version afterwards. There is one exception: if a paragraph is still wrong after everything else has been tried, the chat model may change a few words in it.</p>
<p class="v-tuned">We will have two models. They will have very different roles. The voice model (the one we trained in the <a href="/80000-Words-Of-Me/">second post</a>) will write all the prose. The chat model will never write prose. The chat model will list the key terms of each paragraph prior to rewriting and will check each rewritten paragraph against the plain version afterwards. One exception - if a paragraph is still wrong after all else is done, a chat model can change a few words in it.</p>
<p class="v-prompt">Two models take part and they have very different jobs. The voice model, the one we trained in the <a href="/80000-Words-Of-Me/">second post</a>, writes all of the prose. A chat model never writes prose. It lists the key terms of each paragraph before the rewriting starts and checks each finished paragraph against the plain version afterwards. There is one exception: if a paragraph is still wrong after everything else has been tried, the chat model is allowed to change a few words in it.</p>

<figure class="chart flow" role="group" aria-label="The five steps of the pipeline in order">
<figcaption><strong>One command, five steps</strong><span>Blue steps write prose. Orange steps only read it, except the last.</span></figcaption>

<ol><li><h4>List the key terms <span class="who" style="background:#eb6834">chat model</span><span class="loop">once per paragraph</span></h4><p>Four to eight words that carry the facts of the paragraph. A rewrite that loses them no longer says the same thing.</p></li><li><h4>Rewrite <span class="who" style="background:#2a78d6">voice model</span><span class="loop">10 rounds × 5 candidates</span></h4><p>The model rewrites the paragraph, then rewrites its own output. A candidate must pass every guard. Among those that pass, the least machine-like one is kept.</p><ul><li>same numbers</li><li>similar length</li><li>no broken sentences</li><li>key terms present</li></ul></li><li><h4>Judge <span class="who" style="background:#eb6834">chat model</span><span class="loop">newest round first</span></h4><p>Each paragraph is read against the plain version and marked correct, blurred or wrong. Only the facts count, not the style.</p></li><li><h4>Roll back <span class="who" style="background:#6b6f8c">no model</span></h4><p>A paragraph marked wrong is replaced by its newest earlier round that was not wrong. Every word still comes from the voice model.</p></li><li><h4>Patch <span class="who" style="background:#eb6834">chat model</span><span class="loop">last resort</span></h4><p>If every round was wrong, a few words are changed to repair the fact. If that fails too, the plain paragraph is used.</p></li></ol>
</figure>

<h2 id="step-2-the-guards">Step 2: the guards</h2>

<p class="v-plain">Each round the voice model writes five candidates for every paragraph. A candidate is kept only if it passes every one of the checks below. None of them uses a model. They are plain comparisons of the candidate with the original paragraph.</p>
<p class="v-tuned">The voice model will write five candidates for each paragraph for each round. We will only save a candidate if it passes all the following check. Note that none of these will use a model. These are simply a comparison between the candidate and paragraph.</p>
<p class="v-prompt">Each round the voice model writes five candidates for every paragraph. A candidate is only kept if it passes every one of the checks below. Note that none of them uses a model - they are plain comparisons of the candidate with the original paragraph.</p>

<p class="v-plain"><strong>Same numbers.</strong> Every number in the original must appear in the candidate, the same number of times, and the candidate must contain no other number. If the original says 22 posts and 26,282 words, a candidate that says 23 posts is thrown out, and so is one that adds a year.</p>
<p class="v-tuned"><strong>Same numbers.</strong> The candidate must have the same numbers as the original, the same number of times. It cannot have other numbers. If our original has 22 posts and 26,282 words we would discard a candidate with 23 posts and we would also discard a candidate which adds a year.</p>
<p class="v-prompt"><strong>Same numbers.</strong> Numbers first. Every number in the original must appear in the candidate, the same number of times, and the candidate must contain no other number. If the original says 22 posts and 26,282 words, a candidate that says 23 posts is thrown out, and so is one that sneaks in a year.</p>

<p class="v-plain"><strong>Similar length.</strong> The candidate must have between 75% and 135% as many words as the original. This stops the model from quietly dropping a sentence, and from padding the paragraph with new ones.</p>
<p class="v-tuned"><strong>Similar length.</strong> The candidate should have 75% to 135% of the words of the original. This will prevent our model from silenty dropping a sentence and also prevent from padding the paragraph with new ones.</p>
<p class="v-prompt"><strong>Similar length.</strong> Next comes length. The candidate must have between 75% and 135% as many words as the original. This stops the model from quietly dropping a sentence, and also from padding the paragraph with new ones.</p>

<p class="v-plain"><strong>Same questions.</strong> The candidate must have as many question marks as the original, so that a statement cannot turn into a question.</p>
<p class="v-tuned"><strong>Same questions.</strong> NB Note that the candidate must have as many question marks as the original statement (so a statement cannot become a question).</p>
<p class="v-prompt"><strong>Same questions.</strong> Question marks are next. The candidate must have as many question marks as the original, so that a statement cannot magically turn into a question.</p>

<p class="v-plain"><strong>No holes.</strong> A pattern looks for the marks that a dropped word leaves behind: a small word followed directly by a full stop, two small words that cannot sit together, or a space before a comma. A candidate containing with a cosine followed by a full stop, or a of 0.00005, is thrown out.</p>
<p class="v-tuned"><strong>No holes.</strong> The pattern searches for the traces of a dropped word: small word followed by a full stop, two small words which cannot be sitting together, or a space before a comma. A candidate containing with a cosine followed by a full stop or a of 0.00005 is thrown out.</p>
<p class="v-prompt"><strong>No holes.</strong> Now for the holes. A pattern looks for the marks that a dropped word leaves behind: a small word followed directly by a full stop, two small words that cannot sit together, or a space before a comma. A candidate containing with a cosine followed by a full stop, or a of 0.00005, is thrown out.</p>

<p class="v-plain"><strong>A proper opening.</strong> The candidate must start with a capital letter and a full first sentence. This check was added after reading the output, because the model sometimes dropped the first word of a paragraph, or opened with a note of two words.</p>
<p class="v-tuned"><strong>A proper opening.</strong> The candidate must begin with a capital letter and a full first sentence. This was added after I have read the output from the model due to the fact that the model sometimes drops the first word from the paragraph or begins with a note of two words.</p>
<p class="v-prompt"><strong>A proper opening.</strong> The candidate must also start with a capital letter and a full first sentence. I added this check after reading the output, since the model sometimes dropped the first word of a paragraph, or opened with a little note of two words.</p>

<p class="v-plain"><strong>Key terms present.</strong> The words that carry the facts of the paragraph must still be there. Where these words come from is explained next.</p>
<p class="v-tuned"><strong>Key terms present.</strong> Note that the words which bear the facts of the paragraph must still be there. Where these words are coming from will be explained next.</p>
<p class="v-prompt"><strong>Key terms present.</strong> Finally, the words that carry the facts of the paragraph must still be there. Where do these words come from? Read on!</p>

<p class="v-plain">The key terms come from step 1. A chat model reads each plain paragraph once and lists four to eight single words that carry its facts, such as cosine, adapter or GPTZero. It is told to prefer words that have no synonym, because the voice model is supposed to change the others. One term may be missing from a list of five or more, and only the first five letters are compared, so that vocab still counts as vocabulary.</p>
<p class="v-tuned">The key terms are from step 1. Use a chat model to read each of the plain paragraphs and list four to eight single words which contains your facts (e.g. cosine, adapter, GPTZero). Tell the model to prefer words which have no synonyms since we expect the voice model to make the others change. One word might be missing from a list of five or more words and we only compare the first five letters - vocab still counts as vocabulary.</p>
<p class="v-prompt">The key terms come from step 1. A chat model reads each plain paragraph once and lists four to eight single words that carry its facts, such as cosine, adapter or GPTZero. It is told to prefer words that have no synonym, since the voice model is supposed to change the others. One term may be missing from a list of five or more, and only the first five letters are compared, so that vocab still counts as vocabulary.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">BROKEN</span> <span class="o">=</span> <span class="n">re</span><span class="p">.</span><span class="nb">compile</span><span class="p">(</span><span class="sa">r</span><span class="s">"\b(a|an|the|of|with|between|using|and|to|in|for|by|from|called|named|was|is)\s*[.,;:!?](\s|$)"</span>   <span class="c1"># "with a cosine ."
</span>                    <span class="sa">r</span><span class="s">"|\b(a|an|the|of|with|between|using|and|to|was|is|in|for|by|from|called|named)\s+(of|and|or|with)\b"</span>   <span class="c1"># "a of 0.00005"
</span>                    <span class="sa">r</span><span class="s">"|\s[.,;:](\s|$)|\(\s*\)|\bbetween and\b"</span><span class="p">,</span> <span class="n">re</span><span class="p">.</span><span class="n">I</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">has_terms</span><span class="p">(</span><span class="n">terms</span><span class="p">,</span> <span class="n">cand</span><span class="p">):</span>
    <span class="n">low</span> <span class="o">=</span> <span class="n">cand</span><span class="p">.</span><span class="n">lower</span><span class="p">()</span>                                   <span class="c1"># first five letters, so that "vocab" still counts as "vocabulary"
</span>    <span class="n">missing</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="mi">1</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">terms</span> <span class="k">if</span> <span class="n">w</span><span class="p">.</span><span class="n">lower</span><span class="p">()[:</span><span class="mi">5</span><span class="p">]</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">low</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">missing</span> <span class="o">&lt;=</span> <span class="p">(</span><span class="mi">1</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">terms</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="mi">5</span> <span class="k">else</span> <span class="mi">0</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">ok</span><span class="p">(</span><span class="n">orig</span><span class="p">,</span> <span class="n">terms</span><span class="p">,</span> <span class="n">cur</span><span class="p">,</span> <span class="n">cand</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">cand</span> <span class="ow">or</span> <span class="n">cand</span> <span class="o">==</span> <span class="n">cur</span> <span class="ow">or</span> <span class="s">'</span><span class="se">\n</span><span class="s">'</span> <span class="ow">in</span> <span class="n">cand</span><span class="p">:</span> <span class="k">return</span> <span class="bp">False</span>
    <span class="n">r</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">cand</span><span class="p">.</span><span class="n">split</span><span class="p">())</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">orig</span><span class="p">.</span><span class="n">split</span><span class="p">())</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">nums</span><span class="p">(</span><span class="n">orig</span><span class="p">)</span> <span class="o">==</span> <span class="n">nums</span><span class="p">(</span><span class="n">cand</span><span class="p">)</span>                     <span class="c1"># every number, and nothing but those numbers
</span>            <span class="ow">and</span> <span class="mf">0.75</span> <span class="o">&lt;=</span> <span class="n">r</span> <span class="o">&lt;=</span> <span class="mf">1.35</span>                        <span class="c1"># not much shorter or longer
</span>            <span class="ow">and</span> <span class="n">orig</span><span class="p">.</span><span class="n">count</span><span class="p">(</span><span class="s">'?'</span><span class="p">)</span> <span class="o">==</span> <span class="n">cand</span><span class="p">.</span><span class="n">count</span><span class="p">(</span><span class="s">'?'</span><span class="p">)</span>
            <span class="ow">and</span> <span class="ow">not</span> <span class="n">BROKEN</span><span class="p">.</span><span class="n">search</span><span class="p">(</span><span class="n">cand</span><span class="p">)</span>                  <span class="c1"># no hole where a word dropped out
</span>            <span class="ow">and</span> <span class="n">has_terms</span><span class="p">(</span><span class="n">terms</span><span class="p">,</span> <span class="n">cand</span><span class="p">))</span>                  <span class="c1"># the words that carry the facts
</span></code></pre></div></div>

<p class="v-plain">Two details matter. The candidate is always compared with the original plain paragraph, never with the previous round, so small losses cannot add up over ten rounds. And the checks are deliberately crude. They cannot tell whether a sentence means the same thing. They only catch damage that leaves a mark. A candidate that fails is thrown away, and if all five fail the paragraph stays as it was until the next round.</p>
<p class="v-tuned">Two things matter. Always compare the candidate to the plain paragraph (not to the previous round) so small losses cannot add up over ten rounds. These checks are crude on purpose. They cannot tell if a sentence is conveying the same meaning. All they can catch is the damage which leaves a mark. If any candidate fails we simply throw it away. If all five candidates fail then the paragraph stays as it was until the next round.</p>
<p class="v-prompt">Two details are worth stressing. The candidate is always compared with the original plain paragraph, never with the previous round, so small losses cannot add up over ten rounds. And the checks are deliberately crude. They cannot tell whether a sentence means the same thing, they only catch damage that leaves a mark. A candidate that fails is thrown away, and if all five fail the paragraph simply stays as it was until the next round.</p>

<h2 id="choosing-among-the-survivors">Choosing among the survivors</h2>

<p class="v-plain">Often several candidates pass. The papers that do best against detectors let a detector choose. In <a href="https://arxiv.org/abs/2506.07001">Adversarial Paraphrasing</a> by Cheng and colleagues, a detector scores the candidate next words at every step of the writing, and the least machine-like one is kept. This pipeline does something similar with whole candidates, using what is already loaded. The plain base model, with the adapter switched off, acts as the detector: machine text is the text a language model finds most predictable, so the candidate it finds most surprising is preferred. This is the loss from the <a href="/80000-Words-Of-Me/">second post</a>, used the other way round.</p>
<p class="v-tuned">Note that we can have more than one candidate which passes. The papers which performs best on the detectors gives the option to the detector. In <a href="https://arxiv.org/abs/2506.07001">Adversarial Paraphrasing</a> by Cheng and colleagues a detector is used which scores the candidate next words at every step of the writing and the least machine like one is kept. The pipeline will do something similar on whole candidates with whatever is already loaded. The plain base model (with the adapter switched off) will act as the detector: machine text is the text which the language model finds most predictable so we prefer the candidate which the language model finds most surprising. This is the loss from the <a href="/80000-Words-Of-Me/">second post</a> (used the other way round).</p>
<p class="v-prompt">Often several candidates pass, so how do we pick one? The papers that do best against detectors let a detector choose. In <a href="https://arxiv.org/abs/2506.07001">Adversarial Paraphrasing</a> by Cheng and colleagues, a detector scores the candidate next words at every step of the writing, and the least machine-like one is kept. Our pipeline does something similar with whole candidates, using what is already loaded. The plain base model, with the adapter switched off, acts as the detector: machine text is the text a language model finds most predictable, so we prefer the candidate it finds most surprising. This is the loss from the <a href="/80000-Words-Of-Me/">second post</a>, just used the other way round.</p>

<div class="v-plain"><p>Two more signals are ranked with it.</p><ul><li>One is how few words the candidate shares with the plain version.</li><li>The other is how uneven its sentence lengths are, because people mix short and long sentences more than chat models do.</li></ul><p>The candidate with the best three ranks together is kept.</p></div>
<div class="v-tuned"><p>Two other signals are ranked together with it.</p><ul><li>How few words does the candidate share with the plain version.</li><li>How uneven are the sentence lengths of the candidate, because people use a mix of short and long sentences more than chat models do.</li></ul><p>The candidate with the best three ranks together is kept.</p></div>
<div class="v-prompt"><p>Two more signals are ranked alongside it.</p><ul><li>One is how few words the candidate shares with the plain version.</li><li>The other is how uneven its sentence lengths are, since people mix short and long sentences more than chat models do.</li></ul><p>We add the three ranks together and the candidate with the best result is the one we keep.</p></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">surprise</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
    <span class="c1"># mean loss per token under the base model with the adapter switched off: a zero-shot detector
</span>    <span class="n">e</span> <span class="o">=</span> <span class="n">tok</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="n">return_tensors</span><span class="o">=</span><span class="s">'pt'</span><span class="p">).</span><span class="n">to</span><span class="p">(</span><span class="s">'mps'</span><span class="p">)</span>
    <span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="n">no_grad</span><span class="p">(),</span> <span class="n">model</span><span class="p">.</span><span class="n">disable_adapter</span><span class="p">():</span>
        <span class="k">return</span> <span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">e</span><span class="p">,</span> <span class="n">labels</span><span class="o">=</span><span class="n">e</span><span class="p">[</span><span class="s">'input_ids'</span><span class="p">]).</span><span class="n">loss</span><span class="p">.</span><span class="n">item</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">burst</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
    <span class="n">n</span> <span class="o">=</span> <span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">.</span><span class="n">split</span><span class="p">())</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">re</span><span class="p">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s">'(?&lt;=[.!?])\s+'</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span> <span class="k">if</span> <span class="n">s</span><span class="p">.</span><span class="n">strip</span><span class="p">()]</span>
    <span class="n">m</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">(</span><span class="nb">sum</span><span class="p">((</span><span class="n">x</span> <span class="o">-</span> <span class="n">m</span><span class="p">)</span> <span class="o">**</span> <span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">n</span><span class="p">)</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">n</span><span class="p">))</span> <span class="o">**</span> <span class="mf">0.5</span> <span class="o">/</span> <span class="n">m</span>          <span class="c1"># spread of sentence lengths
</span>
<span class="k">def</span> <span class="nf">choose</span><span class="p">(</span><span class="n">orig</span><span class="p">,</span> <span class="n">good</span><span class="p">):</span>
    <span class="n">keys</span> <span class="o">=</span> <span class="p">[[</span><span class="n">overlap</span><span class="p">(</span><span class="n">orig</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">good</span><span class="p">],</span>            <span class="c1"># fewer words shared with the plain version
</span>            <span class="p">[</span><span class="o">-</span><span class="n">surprise</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">good</span><span class="p">],</span>                <span class="c1"># less predictable to a language model
</span>            <span class="p">[</span><span class="o">-</span><span class="n">burst</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">good</span><span class="p">]]</span>                   <span class="c1"># more uneven sentences
</span>    <span class="n">rank</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">v</span><span class="p">:</span> <span class="p">[</span><span class="nb">sorted</span><span class="p">(</span><span class="n">v</span><span class="p">).</span><span class="n">index</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">v</span><span class="p">]</span>
    <span class="n">total</span> <span class="o">=</span> <span class="p">[</span><span class="nb">sum</span><span class="p">(</span><span class="n">r</span><span class="p">)</span> <span class="k">for</span> <span class="n">r</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="p">(</span><span class="n">rank</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">))]</span>
    <span class="k">return</span> <span class="n">good</span><span class="p">[</span><span class="n">total</span><span class="p">.</span><span class="n">index</span><span class="p">(</span><span class="nb">min</span><span class="p">(</span><span class="n">total</span><span class="p">))]</span>
</code></pre></div></div>

<h2 id="steps-3-to-5-judge-roll-back-patch">Steps 3 to 5: judge, roll back, patch</h2>

<p class="v-plain">The guards cannot see a changed meaning. A sentence that says the model learns when it should say memorises has all its numbers and all its terms. So after the last round a chat model reads every paragraph against the plain version and marks it correct, blurred or wrong. Blurred means a small qualifier was lost and a reader would not be misled. This idea comes from <a href="https://arxiv.org/abs/2606.00392">DEPO</a> by Wang and colleagues, where the rewriter is trained to keep its rewrites, on average, above a fixed level of similarity to the original.</p>
<p class="v-tuned">Guards are unable to see a change in meaning. A sentence which states that the model learns instead of memorises will contain all the numbers and all the terms. After the final round a chat model will go through all the paragraphs and read the paragraphs to the plain one and mark each paragraph as correct, blurred or wrong. Blurred means that a small qualifier was lost but the reader would not be mislead. This idea was initially proposed by Wang et al in <a href="https://arxiv.org/abs/2606.00392">DEPO</a> where the rewriter is trained to keep its rewrites, on average, above a fixed level of similarity to the original.</p>
<p class="v-prompt">The guards cannot see a changed meaning. A sentence that says the model learns when it should say memorises still has all its numbers and all its terms, so everything looks fine! To catch this, after the last round a chat model reads every paragraph against the plain version and marks it correct, blurred or wrong. Blurred means a small qualifier was lost and a reader would not be misled. This idea comes from <a href="https://arxiv.org/abs/2606.00392">DEPO</a> by Wang and colleagues, where the rewriter is trained to keep its rewrites, on average, above a fixed level of similarity to the original.</p>

<p class="v-plain">A paragraph marked wrong is not rewritten by the chat model, because that would bring the chat voice back. It is rolled back to its newest earlier round that was not wrong. All ten rounds are kept, so nothing has to be generated again. Only if every round is wrong does the chat model change a few words, and if that fails the plain paragraph is used.</p>
<p class="v-tuned">When a paragraph is wrong we do not want to use the chat model because this will restore the chat model voice. When we detect a wrong paragraph we will roll back to the most recent paragraph from an earlier round which is not wrong. All ten rounds are saved so we do not have to regenerate anything. We only use the chat model as a fallback when all rounds are wrong in order to rewrite a few words - if this fails we fallback to the plain paragraph.</p>
<p class="v-prompt">A paragraph marked wrong is not rewritten by the chat model - that would bring the chat voice right back. Instead it is rolled back to its newest earlier round that was not wrong. Since all ten rounds are kept, nothing has to be generated again. Only if every round is wrong does the chat model change a few words, and if that fails we simply use the plain paragraph.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">orig</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">original</span><span class="p">):</span>
    <span class="n">pick</span> <span class="o">=</span> <span class="bp">None</span>
    <span class="k">for</span> <span class="n">r</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">rounds</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">):</span>             <span class="c1"># newest round first
</span>        <span class="n">verdict</span><span class="p">,</span> <span class="n">why</span> <span class="o">=</span> <span class="n">judge</span><span class="p">(</span><span class="n">orig</span><span class="p">,</span> <span class="n">rounds</span><span class="p">[</span><span class="n">r</span><span class="p">][</span><span class="n">k</span><span class="p">])</span>         <span class="c1"># chat model: "ok", "minor" or "wrong", with one sentence of reason
</span>        <span class="k">if</span> <span class="n">verdict</span> <span class="o">!=</span> <span class="s">'wrong'</span><span class="p">:</span>
            <span class="n">pick</span> <span class="o">=</span> <span class="n">rounds</span><span class="p">[</span><span class="n">r</span><span class="p">][</span><span class="n">k</span><span class="p">];</span> <span class="k">break</span>                   <span class="c1"># round ten if it is fine, else the newest round that is
</span>    <span class="k">if</span> <span class="n">pick</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">pick</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="n">orig</span><span class="p">,</span> <span class="n">rounds</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">][</span><span class="n">k</span><span class="p">],</span> <span class="n">why</span><span class="p">)</span>           <span class="c1"># change as few words as possible
</span>        <span class="k">if</span> <span class="n">judge</span><span class="p">(</span><span class="n">orig</span><span class="p">,</span> <span class="n">pick</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="s">'wrong'</span><span class="p">:</span> <span class="n">pick</span> <span class="o">=</span> <span class="n">orig</span>  <span class="c1"># give up: the plain paragraph
</span>    <span class="n">final</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">pick</span><span class="p">)</span>
</code></pre></div></div>

<p class="v-plain">Here is one paragraph going through it. After ten rounds the model had reversed the point about memorising. The judge caught it, and the paragraph was rolled back to round five, which still reads like the author and says the right thing.</p>
<p class="v-tuned">So this is one paragraph going through it. After ten rounds the model has flipped the point about memorising. The judge caught it and the paragraph has been reverted to round five which still reads like the author and says the right thing.</p>
<p class="v-prompt">Let us look at one paragraph going through the process. After ten rounds the model had reversed the point about memorising. The judge caught it and the paragraph was rolled back to round five, which still reads like the author and says the right thing. Pretty neat huh?</p>

<div class="pipe-example">
<div><b>Plain version</b>The 50 held-back pairs show when to stop. Before training, the loss on them was 1.006. After the first pass it fell to 0.808. After the second pass it rose to 0.834, and after the third to 0.991, while the loss on the training pairs kept falling to 0.259. With only 328 examples, extra passes make the model memorise the posts instead of learning from them. The adapter saved after the first pass was used for everything that follows.</div>
<div class="bad"><b>Round ten · judged wrong</b>The 50 pairs which we have withheld will help us to understand when we should stop. Before we started training on the pairs our loss was 1.006 after the first pass this dropped to 0.808 and after the second pass we were at 0.834 and after the third pass we were at 0.991 on the held back pairs and on the training pairs we had a loss of 0.259. Our training set only consists of 328 examples so <mark>further passes will result in the model learning from the posts rather than simply memorising them</mark>. We will continue to use the adapter saved after the first pass.</div>
<div class="good"><b>Rolled back to round five · judged correct</b>The 50 pairs we have withheld will give us some indication on when to stop. Before we started training on the pairs our loss was 1.006, after the first pass this dropped to 0.808 and after the second pass we were at 0.834 and after the third pass we were at 0.991 on the held back pairs and on the training pairs we had a loss of 0.259. Given that our training set only has 328 examples further passes will result in the model memorising the posts rather than learning from them. We will use the adapter saved after the first pass for everything which follows.</div>
</div>

<p><em>The paragraph is from an earlier draft, so its figures are not the ones in the second post.</em></p>

<h2 id="what-the-pipeline-scores">What the pipeline scores</h2>

<p class="v-plain">The five runs were then passed through the judge. Each run is a rewrite of the same twelve test paragraphs, so five runs make 60 rewritten paragraphs in all. Of those 60, 47 were kept as they were after round ten, 12 were rolled back to an earlier round and 1 needed a few words changed. None fell back to the plain version. Afterwards the judge marked 28 paragraphs correct, 32 blurred and none wrong.</p>
<p class="v-tuned">So now we can run the five runs through the judge. Each run is a rewrite of the same twelve test paragraphs and so five runs make 60 rewritten paragraphs in all. Of these 60, 47 were kept as they were after round ten, 12 were rolled back to an earlier round and 1 needed a few words changed. None fell back to the plain version. Afterwards the judge marked 28 paragraphs correct, 32 blurred and none wrong.</p>
<p class="v-prompt">Now we passed the five runs through the judge. Each run is a rewrite of the same twelve test paragraphs, so five runs make 60 rewritten paragraphs in all. Of those 60, 47 were kept as they were after round ten, 12 were rolled back to an earlier round and 1 needed a few words changed. None fell back to the plain version. Afterwards the judge marked 28 paragraphs correct, 32 blurred and none wrong.</p>

<figure class="chart " role="group" aria-label="Stacked bars of paragraphs kept, rolled back and patched for five runs">
<figcaption><strong>Four paragraphs in five survive ten rounds untouched</strong><span>What the judge did with the twelve paragraphs of each run after ten rounds.</span></figcaption>
<ul class="legend"><li><i style="background:#2a78d6"></i>Kept at round ten</li><li><i style="background:#b9b8b3"></i>Rolled back to an earlier round</li><li><i style="background:#eb6834"></i>Patched</li></ul>
<svg viewBox="0 0 640 184" role="img" aria-label="Stacked bars of paragraphs kept, rolled back and patched for five runs">
<clipPath id="c29"><rect x="80" y="10.0" width="552" height="20" rx="7" /></clipPath>
<text class="t" x="66" y="25.0" text-anchor="end">Run 1</text><g clip-path="url(#c29)">
<rect x="80.0" y="10.0" width="552.0" height="20" fill="#2a78d6" tabindex="0" data-tip="12 kept at round ten|Run 1" />
<text x="89.0" y="24.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">12</text>
</g>
<clipPath id="c30"><rect x="80" y="46.0" width="552" height="20" rx="7" /></clipPath>
<text class="t" x="66" y="61.0" text-anchor="end">Run 2</text><g clip-path="url(#c30)">
<rect x="80.0" y="46.0" width="458.0" height="20" fill="#2a78d6" tabindex="0" data-tip="10 kept at round ten|Run 2" />
<text x="89.0" y="60.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">10</text>
<rect x="540.0" y="46.0" width="92.0" height="20" fill="#b9b8b3" tabindex="0" data-tip="2 rolled back|Run 2" />
<text x="549.0" y="60.5" fill="#1c1f3a" font-size="12.5" font-weight="600" pointer-events="none">2</text>
</g>
<clipPath id="c31"><rect x="80" y="82.0" width="552" height="20" rx="7" /></clipPath>
<text class="t" x="66" y="97.0" text-anchor="end">Run 3</text><g clip-path="url(#c31)">
<rect x="80.0" y="82.0" width="320.0" height="20" fill="#2a78d6" tabindex="0" data-tip="7 kept at round ten|Run 3" />
<text x="89.0" y="96.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">7</text>
<rect x="402.0" y="82.0" width="182.0" height="20" fill="#b9b8b3" tabindex="0" data-tip="4 rolled back|Run 3" />
<text x="411.0" y="96.5" fill="#1c1f3a" font-size="12.5" font-weight="600" pointer-events="none">4</text>
<rect x="586.0" y="82.0" width="46.0" height="20" fill="#eb6834" tabindex="0" data-tip="1 patched|Run 3" />
<text x="595.0" y="96.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">1</text>
</g>
<clipPath id="c32"><rect x="80" y="118.0" width="552" height="20" rx="7" /></clipPath>
<text class="t" x="66" y="133.0" text-anchor="end">Run 4</text><g clip-path="url(#c32)">
<rect x="80.0" y="118.0" width="458.0" height="20" fill="#2a78d6" tabindex="0" data-tip="10 kept at round ten|Run 4" />
<text x="89.0" y="132.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">10</text>
<rect x="540.0" y="118.0" width="92.0" height="20" fill="#b9b8b3" tabindex="0" data-tip="2 rolled back|Run 4" />
<text x="549.0" y="132.5" fill="#1c1f3a" font-size="12.5" font-weight="600" pointer-events="none">2</text>
</g>
<clipPath id="c33"><rect x="80" y="154.0" width="552" height="20" rx="7" /></clipPath>
<text class="t" x="66" y="169.0" text-anchor="end">Run 5</text><g clip-path="url(#c33)">
<rect x="80.0" y="154.0" width="366.0" height="20" fill="#2a78d6" tabindex="0" data-tip="8 kept at round ten|Run 5" />
<text x="89.0" y="168.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">8</text>
<rect x="448.0" y="154.0" width="184.0" height="20" fill="#b9b8b3" tabindex="0" data-tip="4 rolled back|Run 5" />
<text x="457.0" y="168.5" fill="#1c1f3a" font-size="12.5" font-weight="600" pointer-events="none">4</text>
</g>
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th>Twelve paragraphs per run</th>
      <th>Run 1</th>
      <th>Run 2</th>
      <th>Run 3</th>
      <th>Run 4</th>
      <th>Run 5</th>
      <th>All</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Kept at round ten</td>
      <td>12</td>
      <td>10</td>
      <td>7</td>
      <td>10</td>
      <td>8</td>
      <td>47</td>
    </tr>
    <tr>
      <td>Rolled back to an earlier round</td>
      <td>0</td>
      <td>2</td>
      <td>4</td>
      <td>2</td>
      <td>4</td>
      <td>12</td>
    </tr>
    <tr>
      <td>Patched</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
    </tr>
    <tr>
      <td>Plain version used</td>
      <td>0</td>
      <td>0</td>
      <td>0</td>
      <td>0</td>
      <td>0</td>
      <td>0</td>
    </tr>
  </tbody>
</table>

<p class="v-plain">Then the cleaned texts were scanned. The five runs scored 89%, 80%, 66%, 81% and 97% human: 83% on average, with every run rated human. The plain version of the same text scored 0%.</p>
<p class="v-tuned">Step three we cleaned the text and scanned it. The five runs scored 89%, 80%, 66%, 81% and 97% human: 83% on average with every run scored human. The plain version of the same text scored 0%.</p>
<p class="v-prompt">Next, we scanned the cleaned texts. The five runs scored 89%, 80%, 66%, 81% and 97% human: 83% on average, with every run rated human. The plain version of the same text scored 0%.</p>

<figure class="chart " role="group" aria-label="Dot chart of GPTZero human scores at each stage including the full pipeline">
<figcaption><strong>With the check, all five runs are rated human</strong><span>GPTZero human score at each stage, with the full pipeline in the last row. Each dot is one scanned run.</span></figcaption>

<svg viewBox="0 0 640 322" role="img" aria-label="Dot chart of GPTZero human scores at each stage including the full pipeline">
<line class="grid" x1="210.0" y1="0" x2="210.0" y2="294" /><text class="s" x="210.0" y="312" text-anchor="middle">0%</text>
<line class="dash" x1="294.5" y1="0" x2="294.5" y2="294" /><text class="s" x="294.5" y="312" text-anchor="middle">25%</text>
<line class="dash" x1="379.0" y1="0" x2="379.0" y2="294" /><text class="s" x="379.0" y="312" text-anchor="middle">50%</text>
<line class="dash" x1="463.5" y1="0" x2="463.5" y2="294" /><text class="s" x="463.5" y="312" text-anchor="middle">75%</text>
<line class="grid" x1="548.0" y1="0" x2="548.0" y2="294" /><text class="s" x="548.0" y="312" text-anchor="middle">100%</text>
<rect x="379.0" y="0" width="169.0" height="294" fill="#2a78d6" opacity=".045" />
<text class="s" x="463.5" y="11" text-anchor="middle">rated human</text>
<text class="s" x="640" y="11" text-anchor="end">mean</text>
<text class="t" x="196" y="54.0" text-anchor="end">Plain AI</text>
<rect x="201.0" y="40.0" width="18.0" height="18" rx="9" fill="#2a78d6" opacity=".14" />
<line x1="210.0" y1="34.0" x2="210.0" y2="64.0" stroke="var(--ink)" stroke-width="2.5" stroke-linecap="round" />
<text class="v" x="640" y="54.0" text-anchor="end" font-size="15">0%</text>
<circle cx="210.0" cy="49.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="210.0" cy="49.0" r="12" tabindex="0" data-tip="0% human|Plain AI, run 1" />
<text class="t" x="196" y="108.0" text-anchor="end">Rewritten once</text>
<rect x="201.0" y="94.0" width="18.0" height="18" rx="9" fill="#2a78d6" opacity=".14" />
<line x1="210.0" y1="88.0" x2="210.0" y2="118.0" stroke="var(--ink)" stroke-width="2.5" stroke-linecap="round" />
<text class="v" x="640" y="108.0" text-anchor="end" font-size="15">0%</text>
<circle cx="210.0" cy="103.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="210.0" cy="103.0" r="12" tabindex="0" data-tip="0% human|Rewritten once, run 1" />
<text class="t" x="196" y="162.0" text-anchor="end">Five rounds</text>
<rect x="201.0" y="148.0" width="291.8" height="18" rx="9" fill="#2a78d6" opacity=".14" />
<line x1="387.8" y1="142.0" x2="387.8" y2="172.0" stroke="var(--ink)" stroke-width="2.5" stroke-linecap="round" />
<text class="v" x="640" y="162.0" text-anchor="end" font-size="15">53%</text>
<circle cx="443.2" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="443.2" cy="157.0" r="12" tabindex="0" data-tip="69% human|Five rounds, run 1" />
<circle cx="483.8" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="483.8" cy="157.0" r="12" tabindex="0" data-tip="81% human|Five rounds, run 2" />
<circle cx="355.3" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="355.3" cy="157.0" r="12" tabindex="0" data-tip="43% human|Five rounds, run 3" />
<circle cx="210.0" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="210.0" cy="157.0" r="12" tabindex="0" data-tip="0% human|Five rounds, run 4" />
<circle cx="446.6" cy="157.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="446.6" cy="157.0" r="12" tabindex="0" data-tip="70% human|Five rounds, run 5" />
<text class="t" x="196" y="216.0" text-anchor="end">Ten rounds</text>
<rect x="201.0" y="202.0" width="342.5" height="18" rx="9" fill="#2a78d6" opacity=".14" />
<line x1="439.8" y1="196.0" x2="439.8" y2="226.0" stroke="var(--ink)" stroke-width="2.5" stroke-linecap="round" />
<text class="v" x="640" y="216.0" text-anchor="end" font-size="15">68%</text>
<circle cx="510.8" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="510.8" cy="211.0" r="12" tabindex="0" data-tip="89% human|Ten rounds, run 1" />
<circle cx="460.1" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="460.1" cy="211.0" r="12" tabindex="0" data-tip="74% human|Ten rounds, run 2" />
<circle cx="210.0" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="210.0" cy="211.0" r="12" tabindex="0" data-tip="0% human|Ten rounds, run 3" />
<circle cx="483.8" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="483.8" cy="211.0" r="12" tabindex="0" data-tip="81% human|Ten rounds, run 4" />
<circle cx="534.5" cy="211.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="534.5" cy="211.0" r="12" tabindex="0" data-tip="96% human|Ten rounds, run 5" />
<text class="t" x="196" y="270.0" text-anchor="end">Ten rounds, then the check</text>
<rect x="424.1" y="256.0" width="122.8" height="18" rx="9" fill="#2a78d6" opacity=".14" />
<line x1="489.2" y1="250.0" x2="489.2" y2="280.0" stroke="var(--ink)" stroke-width="2.5" stroke-linecap="round" />
<text class="v" x="640" y="270.0" text-anchor="end" font-size="15">83%</text>
<circle cx="510.8" cy="265.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="510.8" cy="265.0" r="12" tabindex="0" data-tip="89% human|Ten rounds, then the check, run 1" />
<circle cx="480.4" cy="265.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="480.4" cy="265.0" r="12" tabindex="0" data-tip="80% human|Ten rounds, then the check, run 2" />
<circle cx="433.1" cy="265.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="433.1" cy="265.0" r="12" tabindex="0" data-tip="66% human|Ten rounds, then the check, run 3" />
<circle cx="483.8" cy="265.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="483.8" cy="265.0" r="12" tabindex="0" data-tip="81% human|Ten rounds, then the check, run 4" />
<circle cx="537.9" cy="265.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="537.9" cy="265.0" r="12" tabindex="0" data-tip="97% human|Ten rounds, then the check, run 5" />
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th>GPTZero human score, twelve paragraphs</th>
      <th>Run 1</th>
      <th>Run 2</th>
      <th>Run 3</th>
      <th>Run 4</th>
      <th>Run 5</th>
      <th>Mean</th>
      <th>Spread (s.d.)</th>
      <th>Rated human</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Five rounds</td>
      <td>69%</td>
      <td>81%</td>
      <td>43%</td>
      <td>0%</td>
      <td>70%</td>
      <td>53%</td>
      <td>32.5</td>
      <td>3 of 5</td>
    </tr>
    <tr>
      <td>Ten rounds, before the check</td>
      <td>89%</td>
      <td>74%</td>
      <td>0%</td>
      <td>81%</td>
      <td>96%</td>
      <td>68%</td>
      <td>38.9</td>
      <td>4 of 5</td>
    </tr>
    <tr>
      <td>Ten rounds, after the check</td>
      <td>89%</td>
      <td>80%</td>
      <td>66%</td>
      <td>81%</td>
      <td>97%</td>
      <td>83%</td>
      <td>11.5</td>
      <td>5 of 5</td>
    </tr>
    <tr>
      <td>Words shared with the plain version</td>
      <td>0.658</td>
      <td>0.653</td>
      <td>0.611</td>
      <td>0.642</td>
      <td>0.648</td>
      <td>0.642</td>
      <td> </td>
      <td> </td>
    </tr>
  </tbody>
</table>

<div class="v-plain"><p>The surprise is what the check does to the score. Rolling a paragraph back puts it closer to the plain wording, so the check was expected to cost something. It never did.</p><ul><li>The run with no wrong paragraphs kept its 89%, and another stayed at 81%.</li><li>Two others went from 74% to 80% and from 96% to 97%.</li><li>And the run that had scored 0% after ten rounds scored 66% once its five wrong paragraphs were replaced.</li></ul><p>Text that is wrong is not thereby more human.</p></div>
<div class="v-tuned"><p>What is surprising is what the check did to the score. Rolling back a paragraph puts it close to plain wording and thus we thought that the check would have cost something. It never did.</p><ul><li>The run with no wrong paragraphs managed to keep its 89%, another run managed to keep its 81%.</li><li>Two others managed to score from 74% to 80% and from 96% to 97%.</li><li>The run which has managed to score 0% after ten rounds managed to score 66% after its five wrong paragraphs were replaced.</li></ul><p>Wrong paragraphs do not make it more human.</p></div>
<div class="v-prompt"><p>Here is the surprise: what does the check do to the score? Rolling a paragraph back puts it closer to the plain wording, so we expected the check to cost us something. It never did.</p><ul><li>The run with no wrong paragraphs kept its 89%, and another stayed at 81%.</li><li>Two others went from 74% to 80% and from 96% to 97%.</li><li>And the run that had scored 0% after ten rounds scored 66% once its five wrong paragraphs were replaced.</li></ul><p>Text that is wrong is not thereby more human.</p></div>

<figure class="chart " role="group" aria-label="Chart of GPTZero human scores before and after the check for five runs">
<figcaption><strong>The check never lowered a score, and rescued one run</strong><span>GPTZero human score of the same run after ten rounds, before and after the check replaced its wrong paragraphs.</span></figcaption>
<ul class="legend"><li><i style="background:#b9b8b3"></i>Ten rounds, before the check</li><li><i style="background:#2a78d6"></i>After the check</li></ul>
<svg viewBox="0 0 640 216" role="img" aria-label="Chart of GPTZero human scores before and after the check for five runs">
<line class="grid" x1="110.0" y1="0" x2="110.0" y2="188" /><text class="s" x="110.0" y="206" text-anchor="middle">0%</text>
<line class="dash" x1="228.5" y1="0" x2="228.5" y2="188" /><text class="s" x="228.5" y="206" text-anchor="middle">25%</text>
<line class="dash" x1="347.0" y1="0" x2="347.0" y2="188" /><text class="s" x="347.0" y="206" text-anchor="middle">50%</text>
<line class="dash" x1="465.5" y1="0" x2="465.5" y2="188" /><text class="s" x="465.5" y="206" text-anchor="middle">75%</text>
<line class="grid" x1="584.0" y1="0" x2="584.0" y2="188" /><text class="s" x="584.0" y="206" text-anchor="middle">100%</text>
<rect x="347.0" y="0" width="237.0" height="188" fill="#2a78d6" opacity=".045" />
<text class="s" x="465.5" y="11" text-anchor="middle">rated human</text>
<text class="g" x="0" y="41.0">The five runs</text>
<text class="s" x="96" y="69.0" text-anchor="end">Run 1</text>
<circle cx="531.9" cy="65.0" r="5.5" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle cx="531.9" cy="65.0" r="6.5" fill="#2a78d6" stroke="#fff" stroke-width="2" /><text class="v" x="544.9" y="69.5">89%</text><rect class="hit" x="110" y="52" width="474" height="26" tabindex="0" data-tip="89% → 89% human|The five runs, run 1" />
<text class="s" x="96" y="95.0" text-anchor="end">Run 2</text>
<line x1="460.8" y1="91.0" x2="489.2" y2="91.0" stroke="#2a78d6" stroke-opacity=".3" stroke-width="5" stroke-linecap="round" />
<circle cx="460.8" cy="91.0" r="5.5" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle cx="489.2" cy="91.0" r="6.5" fill="#2a78d6" stroke="#fff" stroke-width="2" /><text class="v" x="502.2" y="95.5">80%</text><rect class="hit" x="110" y="78" width="474" height="26" tabindex="0" data-tip="74% → 80% human|The five runs, run 2" />
<text class="s" x="96" y="121.0" text-anchor="end">Run 3</text>
<line x1="110.0" y1="117.0" x2="422.8" y2="117.0" stroke="#2a78d6" stroke-opacity=".3" stroke-width="5" stroke-linecap="round" />
<circle cx="110.0" cy="117.0" r="5.5" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle cx="422.8" cy="117.0" r="6.5" fill="#2a78d6" stroke="#fff" stroke-width="2" /><text class="v" x="435.8" y="121.5">66%</text><rect class="hit" x="110" y="104" width="474" height="26" tabindex="0" data-tip="0% → 66% human|The five runs, run 3" />
<text class="s" x="96" y="147.0" text-anchor="end">Run 4</text>
<circle cx="493.9" cy="143.0" r="5.5" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle cx="493.9" cy="143.0" r="6.5" fill="#2a78d6" stroke="#fff" stroke-width="2" /><text class="v" x="506.9" y="147.5">81%</text><rect class="hit" x="110" y="130" width="474" height="26" tabindex="0" data-tip="81% → 81% human|The five runs, run 4" />
<text class="s" x="96" y="173.0" text-anchor="end">Run 5</text>
<line x1="565.0" y1="169.0" x2="569.8" y2="169.0" stroke="#2a78d6" stroke-opacity=".3" stroke-width="5" stroke-linecap="round" />
<circle cx="565.0" cy="169.0" r="5.5" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle cx="569.8" cy="169.0" r="6.5" fill="#2a78d6" stroke="#fff" stroke-width="2" /><text class="v" x="582.8" y="173.5">97%</text><rect class="hit" x="110" y="156" width="474" height="26" tabindex="0" data-tip="96% → 97% human|The five runs, run 5" />
</svg>
</figure>

<h2 id="the-three-techniques-compared">The three techniques compared</h2>

<p class="v-plain">The <a href="/I-Did-Not-Write-This-Post/">first post</a> tried a much simpler technique: the author's old posts in the prompt of a chat model, and no training. It matched the habits of the author well, and it was scored 100% AI. The two techniques can now be set side by side.</p>
<p class="v-tuned">The <a href="/I-Did-Not-Write-This-Post/">first post</a> tried a much simpler technique; the authors previous posts in the prompt of the chat model and no training. This technique was able to emulate the authors habits quite well and received a score of 100% AI. Let us compare the two techniques.</p>
<p class="v-prompt">The <a href="/I-Did-Not-Write-This-Post/">first post</a> tried a much simpler technique: the author's old posts in the prompt of a chat model, and no training at all. It matched the habits of the author really well, and it was scored 100% AI. Now we can finally set the two techniques side by side.</p>

<p><strong>The three versions side by side</strong></p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>Plain AI</th>
      <th>Posts in the prompt</th>
      <th>Trained model, whole pipeline</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>What it needs</td>
      <td>Nothing</td>
      <td>My old posts, pasted into the prompt</td>
      <td>My old writing, one training run, a large GPU</td>
    </tr>
    <tr>
      <td>Time for one paragraph</td>
      <td>Seconds</td>
      <td>Seconds</td>
      <td>About a minute</td>
    </tr>
    <tr>
      <td>Words kept from the plain version</td>
      <td>100%</td>
      <td>94%</td>
      <td>64%</td>
    </tr>
    <tr>
      <td>“we” per 1,000 words (mine: 29.5)</td>
      <td>5.1</td>
      <td>20.7 to 28.4</td>
      <td>21.8</td>
    </tr>
    <tr>
      <td>Common-word distance (mine: 11.0)</td>
      <td>27.8</td>
      <td>11.6 to 13.9</td>
      <td>10.8</td>
    </tr>
    <tr>
      <td>GPTZero human score</td>
      <td>0%</td>
      <td>0%, all three models</td>
      <td>83% on average, five runs</td>
    </tr>
    <tr>
      <td>Facts</td>
      <td>The reference</td>
      <td>Every number kept; small asides added</td>
      <td>Checked against the plain version; still needs a read</td>
    </tr>
  </tbody>
</table>

<figure class="chart " role="group" aria-label="Bar chart of the share of plain words kept by each technique">
<figcaption><strong>The prompt decorates the text; the rounds rewrite it</strong><span>How much of the plain wording each technique leaves in place, on the twelve test paragraphs. The first three rows were all scored 100% AI.</span></figcaption>

<svg viewBox="0 0 640 226" role="img" aria-label="Bar chart of the share of plain words kept by each technique">
<text class="t" x="236" y="31.0" text-anchor="end">Plain AI</text>
<rect class="track" x="250" y="15.0" width="330" height="22" rx="6" />
<path d="M250,15.0 h324.0 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-324.0 z" fill="#2a78d6" tabindex="0" data-tip="100 % of the plain words kept|Plain AI — no rewriting" />
<text class="v" x="589.0" y="31.0">100</text>
<text class="t" x="236" y="75.0" text-anchor="end">Posts in the prompt (three models)</text>
<rect class="track" x="250" y="59.0" width="330" height="22" rx="6" />
<path d="M250,59.0 h304.2 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-304.2 z" fill="#2a78d6" tabindex="0" data-tip="94 % of the plain words kept|Posts in the prompt (three models) — Qwen 4 Max 94%, Claude Sonnet 5.5 94%, GPT-5.6 Luna 94%" />
<text class="v" x="569.2" y="75.0">94</text>
<text class="t" x="236" y="119.0" text-anchor="end">Trained model, one round</text>
<rect class="track" x="250" y="103.0" width="330" height="22" rx="6" />
<path d="M250,103.0 h248.1 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-248.1 z" fill="#2a78d6" tabindex="0" data-tip="77 % of the plain words kept|Trained model, one round" />
<text class="v" x="513.1" y="119.0">77</text>
<text class="t" x="236" y="163.0" text-anchor="end">Trained model, ten rounds</text>
<rect class="track" x="250" y="147.0" width="330" height="22" rx="6" />
<path d="M250,147.0 h201.9 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-201.9 z" fill="#2a78d6" tabindex="0" data-tip="63 % of the plain words kept|Trained model, ten rounds" />
<text class="v" x="466.9" y="163.0">63</text>
<text class="t" x="236" y="207.0" text-anchor="end">Ten rounds, after the check</text>
<rect class="track" x="250" y="191.0" width="330" height="22" rx="6" />
<path d="M250,191.0 h205.2 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-205.2 z" fill="#2a78d6" tabindex="0" data-tip="64 % of the plain words kept|Ten rounds, after the check" />
<text class="v" x="470.2" y="207.0">64</text>
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th>Twelve test paragraphs</th>
      <th>Words kept from the plain version</th>
      <th>GPTZero human score</th>
      <th>Numbers intact</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Qwen 4 Max, posts in prompt</td>
      <td>0.943</td>
      <td>0%</td>
      <td>12 of 12</td>
    </tr>
    <tr>
      <td>Claude Sonnet 5.5, posts in prompt</td>
      <td>0.941</td>
      <td>0%</td>
      <td>12 of 12</td>
    </tr>
    <tr>
      <td>GPT-5.6 Luna, posts in prompt</td>
      <td>0.936</td>
      <td>0%</td>
      <td>12 of 12</td>
    </tr>
    <tr>
      <td>Trained model, ten rounds and the check (five runs)</td>
      <td>0.642</td>
      <td>83% on average</td>
      <td>12 of 12, enforced by the guards</td>
    </tr>
  </tbody>
</table>

<p class="v-plain">The simple technique has two real advantages. It takes seconds and costs a few cents, where the pipeline takes minutes on a large GPU. And because it changes so little, it breaks very little: all three models kept every number in all twelve paragraphs, with no guards at all. So the two techniques answer different questions. To make a text read like the author to a person, the prompt is nearly enough. To make it read to a detector as written by a person, it does nothing.</p>
<p class="v-tuned">The simple technique has two real advantages. It takes seconds and costs a few cents where the pipeline takes minutes on a large GPU. And because it changes so little it breaks very little - all three models kept every number in all twelve paragraphs with no guards at all. So the two techniques answer different questions. To make a text read like the author to a person the prompt is nearly enough. To make it read to a detector as written by a person it does nothing.</p>
<p class="v-prompt">The simple technique has two real advantages. It takes seconds and costs a few cents, whereas the pipeline takes minutes on a large GPU. And because it changes so little, it breaks very little: all three models kept every number in all twelve paragraphs, with no guards at all. So the two techniques answer different questions. If you want a text to read like the author to a person, the prompt is nearly enough. If you want it to read to a detector as written by a person, it does nothing.</p>

<div class="pipe-example">
<div><b>Plain AI</b>Text produced by chat models has a recognisable voice. The sentences are balanced, the vocabulary is polished, and nothing is ever slightly wrong. Readers notice this, and so do AI detectors. The question behind this experiment was simple: can a model learn the voice of one specific person, given only a modest amount of that person's writing?</div>
<div class="good"><b>In my voice · trained model, ten rounds and the check</b>The text from the Chat models has a recognisable voice. The text is well balanced, the vocabulary is polished and nothing is ever a little bit wrong. Readers can tell and so can AI detectors. The question which I am trying to answer through this experiment is simple; Can a model learn the voice of a particular person just by observing some text written by that person?</div>
<div class="bad"><b>Posts in the prompt · Claude Sonnet 5.5, no training</b>Text produced by chat models has a recognisable voice. The sentences are balanced, the vocabulary is polished, and nothing is ever slightly wrong. Readers notice this and so do AI detectors. The question behind this experiment was simple: can a model learn the voice of one specific person, given only a modest amount of that person's writing?</div>
</div>

<p><em>The same paragraph three ways. It is the opening of the section “Why bother” in the first post.</em></p>

<table>
  <thead>
    <tr>
      <th>On 50 held-back paragraphs, per 1,000 words</th>
      <th>Bland paraphrase</th>
      <th>Trained model</th>
      <th>Qwen 4 Max, posts in prompt</th>
      <th>Claude Sonnet 5.5, posts in prompt</th>
      <th>GPT-5.6 Luna, posts in prompt</th>
      <th>What I really wrote</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>“we”</td>
      <td>5.1</td>
      <td>21.8</td>
      <td>28.4</td>
      <td>25.5</td>
      <td>20.7</td>
      <td>29.5</td>
    </tr>
    <tr>
      <td>“I”</td>
      <td>0.4</td>
      <td>0.8</td>
      <td>1.9</td>
      <td>1.1</td>
      <td>0.7</td>
      <td>2.6</td>
    </tr>
    <tr>
      <td>Contractions</td>
      <td>0.4</td>
      <td>1.5</td>
      <td>1.5</td>
      <td>3.0</td>
      <td>0.4</td>
      <td>3.4</td>
    </tr>
    <tr>
      <td>Exclamation marks</td>
      <td>0.0</td>
      <td>0.4</td>
      <td>3.0</td>
      <td>1.9</td>
      <td>0.0</td>
      <td>0.7</td>
    </tr>
    <tr>
      <td>Sentences of 6 words or fewer</td>
      <td>5%</td>
      <td>11%</td>
      <td>4%</td>
      <td>6%</td>
      <td>4%</td>
      <td>6%</td>
    </tr>
    <tr>
      <td>Common-word profile, distance from my other writing</td>
      <td>27.8</td>
      <td>10.8</td>
      <td>12.8</td>
      <td>11.6</td>
      <td>13.9</td>
      <td>11.0</td>
    </tr>
    <tr>
      <td>Words shared with the real paragraph</td>
      <td>0.600</td>
      <td>0.634</td>
      <td>0.716</td>
      <td>0.728</td>
      <td>0.695</td>
      <td>1.000</td>
    </tr>
  </tbody>
</table>

<h2 id="what-this-does-not-show">What this does not show</h2>

<div class="v-plain"><p><strong>The numbers are small.</strong> There are five runs of one text of twelve paragraphs, on one detector. The scores before the check range from 0% to 96%, so one more run could move any of the averages. The single rewrite was scanned only once.</p></div>
<div class="v-tuned"><p><strong>The numbers are small.</strong> Five runs of one text of twelve paragraphs, on one detector. The scores before the check varies between 0% and 96% hence one more run can influence the average in any way. The rewrite was scanned only once.</p></div>
<div class="v-prompt"><p><strong>Before we conclude, a word of caution - the numbers are small.</strong> There are five runs of one text of twelve paragraphs, on one detector. The scores before the check range from 0% to 96%, so one more run could move any of the averages. The single rewrite was scanned only once.</p></div>

<div class="v-plain"><p><strong>The judge is a model.</strong> None wrong means none that it could find, and 32 paragraphs of 60 lost some small detail on the way. A person who knows what the text should say still has to read it. The pipeline makes that read short. It does not replace it.</p></div>
<div class="v-tuned"><p><strong>Judge is a model.</strong> None wrong means none that it could find and 32 paragraphs of 60 lost some small detail on the way. A person who knows what the text should say still has to read it. The pipeline makes that read short. It does not replace it.</p></div>
<div class="v-prompt"><p><strong>The judge is a model too.</strong> None wrong means none that it could find, and 32 paragraphs of 60 lost some small detail on the way. A person who knows what the text should say still has to read it. The pipeline makes that read short. It does not replace it.</p></div>

<div class="v-plain"><p><strong>And none of the papers borrowed from here tested this setting.</strong> <a href="https://arxiv.org/abs/2606.00392">DEPO</a> was measured against five open detectors and <a href="https://arxiv.org/abs/2505.15337">CoPA</a> against eight, on texts from standard detection benchmarks, and neither used GPTZero. Two of their ideas are used here in a simpler form, and two papers are not used at all.</p></div>
<div class="v-tuned"><p><strong>And none of the papers which were borrowed from here tested this setting.</strong> <a href="https://arxiv.org/abs/2606.00392">DEPO</a> was tested against five open detectors and <a href="https://arxiv.org/abs/2505.15337">CoPA</a> against eight on texts from standard detection benchmarks and neither used GPTZero. Two of their ideas are used here in a simpler form and two papers are not used at all.</p></div>
<div class="v-prompt"><p><strong>And none of the papers borrowed from here tested this setting.</strong> <a href="https://arxiv.org/abs/2606.00392">DEPO</a> was measured against five open detectors and <a href="https://arxiv.org/abs/2505.15337">CoPA</a> against eight, on texts from standard detection benchmarks, and neither used GPTZero. Two of their ideas are used here in a simpler form, and two papers are not used at all.</p></div>

<table>
  <thead>
    <tr>
      <th>Paper</th>
      <th>Its idea</th>
      <th>In this pipeline</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><a href="https://arxiv.org/abs/2605.19516">Xu et al., Base Models Look Human To AI Detectors</a> (2026)</td>
      <td>A base model with an adapter, run again and again on its own output</td>
      <td>Used as it is, with the adapter tuned on my own writing</td>
    </tr>
    <tr>
      <td><a href="https://arxiv.org/abs/2506.07001">Cheng et al., Adversarial Paraphrasing</a> (2025)</td>
      <td>At every step of the writing, a detector picks the least machine-like next word</td>
      <td>The idea only: the base model’s surprise stands in for the detector</td>
    </tr>
    <tr>
      <td><a href="https://arxiv.org/abs/2606.00392">Wang et al., DEPO</a> (2026)</td>
      <td>The rewriter is trained to keep its rewrites, on average, above a fixed similarity to the original</td>
      <td>The idea only: a judge reads each rewrite against the original afterwards, and nothing is trained</td>
    </tr>
    <tr>
      <td>Factual error correction with minimal edits (<a href="https://arxiv.org/abs/2312.07049">LIFE</a>, <a href="https://arxiv.org/abs/2402.12566">GenAudit</a>)</td>
      <td>Find the error against the source and change as few words as possible</td>
      <td>The patch step, through a prompt</td>
    </tr>
    <tr>
      <td><a href="https://arxiv.org/abs/2505.15337">CoPA</a> (2025)</td>
      <td>Push each word away from what a chat model would write</td>
      <td>Not used</td>
    </tr>
    <tr>
      <td><a href="https://arxiv.org/abs/2602.08934">StealthRL</a> (2026)</td>
      <td>Train the rewriter against detectors with reinforcement learning</td>
      <td>Not used</td>
    </tr>
  </tbody>
</table>

<h2 id="running-it-on-exo">Running it on exo</h2>

<p class="v-plain">The adapter needs a base model of 28 GB underneath it. To serve it from exo on a Mac, the two were folded into one model and converted to MLX at 8 bits per weight, which gives 16 GB. That copy is published as <a href="https://huggingface.co/cloudmark/cloudmark-voice-qwen3-14b-mlx"><code>cloudmark/cloudmark-voice-qwen3-14b-mlx</code></a>.</p>
<p class="v-tuned">This adapter will expect the 28GB model under the hood. I wanted to serve from exo on my Mac so I have fused these two models together into one model converting to MLX at 8 bits per weight - results in 16 GB. It is available on <a href="https://huggingface.co/cloudmark/cloudmark-voice-qwen3-14b-mlx"><code>cloudmark/cloudmark-voice-qwen3-14b-mlx</code></a>.</p>
<p class="v-prompt">Let us now talk about serving. The adapter needs a base model of 28 GB underneath it. To serve it from exo on a Mac, I folded the two into one model and converted it to MLX at 8 bits per weight, which gives 16 GB. That copy is published as <a href="https://huggingface.co/cloudmark/cloudmark-voice-qwen3-14b-mlx"><code>cloudmark/cloudmark-voice-qwen3-14b-mlx</code></a>.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># 1. fold the adapter into the base model (28 GB, 16-bit floats)
</span><span class="n">base</span> <span class="o">=</span> <span class="n">AutoModelForCausalLM</span><span class="p">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="s">'Qwen/Qwen3-14B-Base'</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="p">.</span><span class="n">float16</span><span class="p">)</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">PeftModel</span><span class="p">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="n">base</span><span class="p">,</span> <span class="s">'voice-adapter/epoch-1'</span><span class="p">).</span><span class="n">merge_and_unload</span><span class="p">()</span>
<span class="n">model</span><span class="p">.</span><span class="n">save_pretrained</span><span class="p">(</span><span class="s">'merged'</span><span class="p">)</span>
<span class="n">AutoTokenizer</span><span class="p">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="s">'Qwen/Qwen3-14B-Base'</span><span class="p">).</span><span class="n">save_pretrained</span><span class="p">(</span><span class="s">'merged'</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># 2. convert to MLX at 8 bits per weight (16 GB) and publish</span>
python <span class="nt">-m</span> mlx_lm convert <span class="nt">--hf-path</span> merged <span class="nt">--mlx-path</span> voice-mlx-8bit <span class="nt">-q</span> <span class="nt">--q-bits</span> 8
hf upload cloudmark/cloudmark-voice-qwen3-14b-mlx ./voice-mlx-8bit <span class="nb">.</span> <span class="nt">--repo-type</span> model
</code></pre></div></div>

<p class="v-plain">exo keeps a list of the models it knows. A model that is not on the list has to be added by its Hugging Face name first, and then exo is asked to load it. Two calls to exo do this.</p>
<p class="v-tuned">exo knows which models it knows. If the model is not one of the models that exo knows we will add the model to the list of known models (provide the model Hugging Face model name) and then we will ask exo to load it. Two calls to exo will do that.</p>
<p class="v-prompt">exo keeps a list of the models it knows. A model that is not on the list has to be added by its Hugging Face name first, and then we ask exo to load it. Two calls to exo do this.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># 1. tell exo about the model</span>
curl <span class="nt">-X</span> POST http://localhost:52415/models/add <span class="nt">-H</span> <span class="s1">'Content-Type: application/json'</span> <span class="se">\</span>
  <span class="nt">-d</span> <span class="s1">'{"model_id": "cloudmark/cloudmark-voice-qwen3-14b-mlx"}'</span>

<span class="c"># 2. ask exo to load it</span>
curl <span class="nt">-X</span> POST http://localhost:52415/place_instance <span class="nt">-H</span> <span class="s1">'Content-Type: application/json'</span> <span class="se">\</span>
  <span class="nt">-d</span> <span class="s1">'{"model_id": "cloudmark/cloudmark-voice-qwen3-14b-mlx"}'</span>
</code></pre></div></div>

<p class="v-plain">The first attempt to load it failed with the error below. The setting it names, <code>rope_theta</code>, is a single number that tells the model how to mark the position of each word in the text. For this model the value is 1,000,000.</p>
<p class="v-tuned">So the first time we try to load it the model fails with the following error. So what the error refers to is a setting called <code>rope_theta</code> which is a single number which tells the model how to mark the position of each word in the text. For this model the value is 1,000,000.</p>
<p class="v-prompt">Our first attempt to load the model failed with the error below. The setting it complains about, <code>rope_theta</code>, is just a single number which tells the model how to mark the position of each word in the text (for this model the value is 1,000,000).</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>RunnerFailed: ModelArgs.__init__() missing 1 required positional argument: 'rope_theta'
</code></pre></div></div>

<p class="v-plain">The number was in the configuration file of the model, but not where exo looked for it. The library that saved the merged model writes it inside a group called <code>rope_parameters</code>. The loader in exo reads it from the top level of the file, found nothing there, and stopped. The fix was to write the same value in both places. That is one extra line in <code>config.json</code>, in the published copy and in the copy exo had already downloaded.</p>
<p class="v-tuned">The number was in the config of the model but not in the place that exo looks for it. The library that saved the merged model writes it inside a group called <code>rope_parameters</code>. The loader in exo looks for it at the top level of the file, finds nothing there and stops. We fixed it by writing the same value in both places. One extra line in <code>config.json</code> both in the published copy and in the copy exo has already downloaded.</p>
<p class="v-prompt">So the number was in the configuration file of the model, just not where exo expected to find it. The library which saved the merged model writes it inside a group called <code>rope_parameters</code> whilst the loader in exo reads it from the top level of the file, finds nothing there and gives up. The fix is simple - write the same value in both places. That is one extra line in <code>config.json</code>, in the published copy and also in the copy which exo had already downloaded.</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">"rope_parameters"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"rope_theta"</span><span class="p">:</span><span class="w"> </span><span class="mi">1000000</span><span class="p">,</span><span class="w"> </span><span class="nl">"rope_type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"default"</span><span class="w"> </span><span class="p">}</span><span class="err">,</span><span class="w">
</span><span class="nl">"rope_theta"</span><span class="p">:</span><span class="w"> </span><span class="mi">1000000</span><span class="err">,</span><span class="w">
</span></code></pre></div></div>

<p><em>The first line is what the file already had. The second line is the one that was added.</em></p>

<p class="v-plain">One more thing is different from an ordinary chat model. A base model has no chat format, so sending it a chat message does nothing useful. It has to be called through the raw completion endpoint, with the source and target tags written out by hand, exactly as they were in training.</p>
<p class="v-tuned">One thing which differs from a normal chat model is that a base model has no chat format. If we send a chat message to a base model then the model doesn’t do anything useful. We need to call the model by using the raw completion endpoint. We need to include the source and target tags in the input exactly as they are in the training as shown below:</p>
<p class="v-prompt">There is one more thing which is different from an ordinary chat model. A base model has no chat format and hence sending it a chat message does nothing useful. What we need to do is call it through the raw completion endpoint and write out the source and target tags by hand, exactly as they were used in training.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl http://localhost:52415/ollama/api/generate <span class="nt">-H</span> <span class="s1">'Content-Type: application/json'</span> <span class="nt">-d</span> <span class="s1">'{
  "model": "cloudmark/cloudmark-voice-qwen3-14b-mlx",
  "raw": true, "stream": false,
  "prompt": "&lt;source_text&gt;\nKubernetes treats applications running within pods as black boxes, lacking visibility into their internal operations.\n&lt;/source_text&gt;\n\n&lt;target_text&gt;\n",
  "options": { "temperature": 1.0, "top_p": 0.95, "num_predict": 120, "stop": ["&lt;/target_text&gt;"] }
}'</span>
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Kubernetes treat the application running inside pods as black boxes; they do not have any
insight as to what is happening inside these applications.
</code></pre></div></div>

<h2 id="closing">Closing</h2>

<p class="v-plain">A small model can learn to sound like one person from about 80,000 words of their writing. Sounding like them is not enough to be taken for them. Rewriting ten times over is enough, some of the time, and it breaks the facts on the way. With guards during the rewriting and a check afterwards, the same text was rated human in five runs out of five, with nothing left that the check could call wrong.</p>
<p class="v-tuned">With around 80,000 words of their writing a small model can be trained which can sound like one person. Sounding like them is not enough to be taken for them. Rewriting ten times over is enough, some of the time and it breaks the facts on the way. If there are guards during the rewriting and a check after the same text was judged human in five out of five attempts and nothing was left that the check could label as wrong.</p>
<p class="v-prompt">A small model can learn to sound like one person from about 80,000 words of their writing. Sounding like them, however, is not enough to be taken for them. Rewriting ten times over is enough, some of the time, but it breaks the facts on the way! With guards during the rewriting and a check afterwards, the same text was rated human in five runs out of five, and there was nothing left which the check could call wrong.</p>

<p><strong>In short</strong></p>

<ul>
  <li>One rewrite by the trained model still scores 100% AI. Ten rewrites in a row score anywhere from 0% to 96% human.</li>
  <li>Rewriting ten times breaks facts: it reverses meanings, invents details and drops words.</li>
  <li>Guards on every round and a check at the end remove the wrong paragraphs. With them, five runs out of five were rated human, 83% on average.</li>
  <li>The check never lowered a score.</li>
  <li>Posts in the prompt is cheap and sounds like me, and scores 0% human. The trained model with the pipeline is slow and scores 83%.</li>
  <li>A person still has to read the result.</li>
</ul>

<h2 id="references">References</h2>

<ol>
  <li><a href="https://arxiv.org/abs/2605.19516">Xu et al., Base Models Look Human To AI Detectors, 2026</a></li>
  <li><a href="https://arxiv.org/abs/2506.07001">Cheng et al., Adversarial Paraphrasing: A Universal Attack for Humanizing AI-Generated Text, 2025</a></li>
  <li><a href="https://arxiv.org/abs/2606.00392">Wang, Shen, Bu and Zou, Detector-Evasive LLM Paraphrasing via Constrained Policy Optimization (DEPO), 2026</a></li>
  <li><a href="https://arxiv.org/abs/2312.07049">Improving Factual Error Correction by Learning to Inject Factual Errors (LIFE), 2023</a></li>
  <li><a href="https://arxiv.org/abs/2402.12566">GenAudit, 2024</a></li>
  <li><a href="https://arxiv.org/abs/2505.15337">Your Language Model Can Secretly Write Like Humans: Contrastive Paraphrase Attacks on LLM-Generated Text Detectors (CoPA), 2025</a></li>
  <li><a href="https://arxiv.org/abs/2602.08934">Ranganath and Ramesh, StealthRL, 2026</a></li>
  <li><a href="https://github.com/cloudmark/in-my-voice">The code: cloudmark/in-my-voice</a></li>
</ol>

<p>As always, stay safe, keep hacking!</p>

<p><em>This was the last of three. Start again at <a href="/I-Did-Not-Write-This-Post/">I Didn’t Write This Post</a>.</em></p>

<script>
  (function () {
    var prose = document.querySelector('.prose'), buttons = document.querySelectorAll('.voice-switch button');
    function show(voice) {
      prose.setAttribute('data-voice', voice);
      buttons.forEach(function (b) { b.setAttribute('aria-pressed', String(b.dataset.voice === voice)); });
    }
    buttons.forEach(function (b) { b.addEventListener('click', function () { show(b.dataset.voice); }); });
    show('tuned');
  })();
</script>

<script>
  (function () {
    var tip = document.createElement('div'); tip.className = 'chart-tip'; tip.setAttribute('role', 'status');
    var value = document.createElement('b'), label = document.createElement('span'); tip.appendChild(value); tip.appendChild(label);
    document.body.appendChild(tip);
    function show(el, x, y) {
      var parts = el.getAttribute('data-tip').split('|');
      value.textContent = parts[0]; label.textContent = parts[1] || '';
      tip.style.opacity = 1; tip.style.transform = 'none';
      var w = tip.offsetWidth, left = Math.min(Math.max(8, x + 14), window.innerWidth - w - 8);
      tip.style.left = left + 'px'; tip.style.top = Math.max(8, y - tip.offsetHeight - 12) + 'px';
    }
    function hide() { tip.style.opacity = 0; tip.style.transform = ''; }
    document.querySelectorAll('.chart [data-tip]').forEach(function (el) {
      el.addEventListener('pointermove', function (e) { show(el, e.clientX, e.clientY); });
      el.addEventListener('pointerleave', hide);
      el.addEventListener('focus', function () { var r = el.getBoundingClientRect(); show(el, r.left + r.width / 2, r.top); });
      el.addEventListener('blur', hide);
    });
  })();
</script>]]></content><author><name>Mark Galea</name></author><category term="fine-tuning" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">80,000 Words of Me</title><link href="https://cloudmark.me/80000-Words-Of-Me/" rel="alternate" type="text/html" title="80,000 Words of Me" /><published>2026-11-27T08:20:00+01:00</published><updated>2026-11-27T08:20:00+01:00</updated><id>https://cloudmark.me/80000-Words-Of-Me</id><content type="html" xml:base="https://cloudmark.me/80000-Words-Of-Me/"><![CDATA[<style>
  .chart { margin: 2.2em 0 1.6em; padding: 22px 24px 18px; background: var(--paper, #fff) var(--grain-img, none); border: 1px solid var(--line); border-radius: 14px; }
  .chart figcaption { margin: 0 0 14px; }
  .chart figcaption strong { display: block; color: var(--ink); font: 600 18px/1.3 var(--ui); letter-spacing: -.01em; }
  .chart figcaption span { display: block; margin-top: 4px; color: var(--grey); font: 14px/1.45 var(--ui); }
  .chart .legend { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 0 0 10px; padding: 0; list-style: none; font: 13px var(--ui); color: var(--soft); }
  .chart .legend li { display: inline-flex; align-items: center; gap: 7px; margin: 0; }
  .chart .legend i { width: 11px; height: 11px; border-radius: 4px; display: inline-block; }
  .chart svg { display: block; width: 100%; height: auto; overflow: visible; font-family: var(--ui); }
  .chart .t { fill: var(--ink); font-size: 14px; }
  .chart .g { fill: var(--ink); font-size: 13px; font-weight: 600; letter-spacing: .02em; }
  .chart .s { fill: var(--grey); font-size: 12.5px; }
  .chart .v { fill: var(--ink); font-size: 13.5px; font-weight: 600; font-variant-numeric: tabular-nums; }
  .chart .grid { stroke: var(--line); stroke-width: 1; }
  .chart .dash { stroke: var(--line); stroke-width: 1; stroke-dasharray: 2 4; }
  .chart .track { fill: var(--line); opacity: .55; }
  .chart [data-tip] { cursor: default; outline: none; transition: filter .15s; }
  .chart [data-tip]:hover, .chart [data-tip]:focus-visible { filter: brightness(1.1) saturate(1.1); }
  .chart .hit { fill: transparent; }
  .chart-tip { position: fixed; z-index: 20; pointer-events: none; padding: 7px 11px; border-radius: 10px; background: var(--ink); color: var(--bg, #fff); font: 13px/1.35 var(--ui); max-width: 260px; opacity: 0; transform: translateY(4px); transition: opacity .12s, transform .12s; box-shadow: 0 8px 24px -8px rgba(var(--shadow, 28, 31, 58),.5); }
  .chart-tip b { display: block; font-size: 15px; font-variant-numeric: tabular-nums; }
  .flow ol { list-style: none; margin: 0; padding: 0; counter-reset: step; }
  .flow li { position: relative; margin: 0; padding: 0 0 18px 52px; counter-increment: step; }
  .flow li::before { content: counter(step); position: absolute; left: 0; top: 0; width: 34px; height: 34px; border-radius: 50%; background: var(--ink); color: var(--bg, #fff); font: 600 15px/34px var(--ui); text-align: center; }
  .flow li::after { content: ''; position: absolute; left: 16px; top: 40px; bottom: 4px; width: 2px; border-radius: 2px; background: var(--line); }
  .flow li:last-child { padding-bottom: 0; } .flow li:last-child::after { display: none; }
  .flow h4 { margin: 0; padding-top: 5px; font: 600 16px/1.3 var(--ui); color: var(--ink); display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
  .flow .who { font: 600 11.5px/1 var(--ui); letter-spacing: .03em; padding: 5px 9px; border-radius: 999px; color: #fff; }
  .flow .loop { font: 600 11.5px/1 var(--ui); padding: 5px 9px; border-radius: 999px; border: 1px solid var(--line); color: var(--soft); background: var(--paper, #fff); }
  .flow p { margin: 5px 0 0; font: 14.5px/1.5 var(--ui); color: var(--soft); }
  .flow ul { margin: 8px 0 0; padding: 0; list-style: none; display: flex; flex-wrap: wrap; gap: 6px; }
  .flow ul li { padding: 5px 10px; border-radius: 8px; background: var(--paper, #fff); border: 1px solid var(--line); font: 13px var(--ui); color: var(--ink); counter-increment: none; }
  .flow ul li::before, .flow ul li::after { display: none; }
  .chart circle[stroke="#fff"] { stroke: var(--paper, #fff); }
  .chart text[fill="#1c1f3a"] { fill: #1f1e1b; }
  /* At night the series colours take brighter steps, on fills, strokes and gradient stops alike. */
  :root[data-theme="dark"] .chart :is([fill="#2a78d6"], [style*="#2a78d6"]) { fill: #3987e5; background-color: #3987e5 !important; } :root[data-theme="dark"] .chart [stroke="#2a78d6"] { stroke: #3987e5; } :root[data-theme="dark"] .chart [stop-color="#2a78d6"] { stop-color: #3987e5; }
  :root[data-theme="dark"] .chart :is([fill="#eb6834"], [style*="#eb6834"]) { fill: #d95926; background-color: #d95926 !important; } :root[data-theme="dark"] .chart [stroke="#eb6834"] { stroke: #d95926; } :root[data-theme="dark"] .chart [stop-color="#eb6834"] { stop-color: #d95926; }
  :root[data-theme="dark"] .chart :is([fill="#1baf7a"], [style*="#1baf7a"]) { fill: #199e70; background-color: #199e70 !important; } :root[data-theme="dark"] .chart [stroke="#1baf7a"] { stroke: #199e70; } :root[data-theme="dark"] .chart [stop-color="#1baf7a"] { stop-color: #199e70; }
  :root[data-theme="dark"] .chart :is([fill="#b9b8b3"], [style*="#b9b8b3"]) { fill: #8d8b84; background-color: #8d8b84 !important; } :root[data-theme="dark"] .chart [stroke="#b9b8b3"] { stroke: #8d8b84; } :root[data-theme="dark"] .chart [stop-color="#b9b8b3"] { stop-color: #8d8b84; }
  @media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) .chart :is([fill="#2a78d6"], [style*="#2a78d6"]) { fill: #3987e5; background-color: #3987e5 !important; } :root:not([data-theme="light"]) .chart [stroke="#2a78d6"] { stroke: #3987e5; } :root:not([data-theme="light"]) .chart [stop-color="#2a78d6"] { stop-color: #3987e5; }
  :root:not([data-theme="light"]) .chart :is([fill="#eb6834"], [style*="#eb6834"]) { fill: #d95926; background-color: #d95926 !important; } :root:not([data-theme="light"]) .chart [stroke="#eb6834"] { stroke: #d95926; } :root:not([data-theme="light"]) .chart [stop-color="#eb6834"] { stop-color: #d95926; }
  :root:not([data-theme="light"]) .chart :is([fill="#1baf7a"], [style*="#1baf7a"]) { fill: #199e70; background-color: #199e70 !important; } :root:not([data-theme="light"]) .chart [stroke="#1baf7a"] { stroke: #199e70; } :root:not([data-theme="light"]) .chart [stop-color="#1baf7a"] { stop-color: #199e70; }
  :root:not([data-theme="light"]) .chart :is([fill="#b9b8b3"], [style*="#b9b8b3"]) { fill: #8d8b84; background-color: #8d8b84 !important; } :root:not([data-theme="light"]) .chart [stroke="#b9b8b3"] { stroke: #8d8b84; } :root:not([data-theme="light"]) .chart [stop-color="#b9b8b3"] { stop-color: #8d8b84; }
  }
</style>

<div class="view-switch voice-switch" role="group" aria-label="Which version to read">
  <button type="button" data-voice="plain" aria-pressed="false"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2.5h10A1.5 1.5 0 0 1 14.5 4v5.5A1.5 1.5 0 0 1 13 11H8l-3 2.5V11H3a1.5 1.5 0 0 1-1.5-1.5V4A1.5 1.5 0 0 1 3 2.5z" /></svg>Plain AI</button>
  <button type="button" data-voice="prompt" aria-pressed="false"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4.5" width="8.5" height="10" rx="1.5" /><path d="M5.5 4.5V3A1.5 1.5 0 0 1 7 1.5h5.5A1.5 1.5 0 0 1 14 3v7a1.5 1.5 0 0 1-1.5 1.5h-2M4.5 8h3.5M4.5 10.5h3.5" /></svg>Posts in the prompt</button>
  <button type="button" data-voice="tuned" aria-pressed="true"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.5 2.5l3 3-8 8-3.5.5.5-3.5zM9 4l3 3" /></svg>In my voice</button>
</div>
<style>
  .voice-switch { display: inline-flex; flex-wrap: wrap; gap: 4px; padding: 4px; margin: 0 0 1.6em; border-radius: 14px; background: var(--wash); }
  .voice-switch button { display: inline-flex; align-items: center; gap: 8px; }
  .voice-switch svg { flex: none; }
  .prose[data-voice="plain"] :is(.v-tuned, .v-prompt), .prose[data-voice="tuned"] :is(.v-plain, .v-prompt), .prose[data-voice="prompt"] :is(.v-plain, .v-tuned) { display: none; }
  .voice-note { color: var(--grey); font-size: 15px; margin-top: -1em; }
  .pipe-example { margin: 1.4em 0; display: grid; gap: 10px; }
  .pipe-example div { padding: 14px 16px; border-radius: 14px; border: 1px solid var(--line); background: var(--paper, #fff); font-size: 15.5px; line-height: 1.55; }
  .pipe-example b { display: block; margin-bottom: 4px; font: 600 12px var(--ui); letter-spacing: .04em; text-transform: uppercase; color: var(--grey); }
  .pipe-example .bad { border-color: color-mix(in srgb, #eb6834 45%, var(--line)); background: color-mix(in srgb, #eb6834 7%, var(--paper, #fff)); } .pipe-example .good { border-color: color-mix(in srgb, #2a78d6 45%, var(--line)); background: color-mix(in srgb, #2a78d6 7%, var(--paper, #fff)); }
  .pipe-example mark { color: inherit; background: color-mix(in srgb, #eb6834 30%, var(--paper, #fff)); padding: 0 3px; border-radius: 4px; }
</style>

<p class="voice-note"><span class="v-plain">You are reading the version a chat model wrote, with no tuning.</span><span class="v-tuned">You are reading the version written by the model trained on my own writing: ten guarded rounds, then a check of every paragraph against the plain version. In a last read, 27 small slips in 24 of the 109 paragraphs were fixed by hand, mostly dropped words and typos. For 37 paragraphs an earlier round was chosen by hand, because the last round read badly. In 11 paragraphs a word or two changed when two posts became three. The opening sentence of the second and third posts was shortened by hand. A fact check then corrected 12 paragraphs in all three versions, and in this version a further 31 sentences in 26 paragraphs where the meaning had drifted from the plain text.</span><span class="v-prompt">You are reading the version a chat model wrote with 22 of my old posts in its system prompt, and no training at all. It is the second technique, described in the first post. It was not checked against the plain version, so its asides and small additions are the model's own. Twelve paragraphs rewritten this way scored 100% AI.</span></p>

<p class="v-plain">This is the second of three posts. The <a href="/I-Did-Not-Write-This-Post/">first post</a> tried the simplest way to borrow a voice, which is to put the author's old posts in the prompt of a chat model. The result sounded like the author, and a detector scored it 100% AI.</p>
<p class="v-tuned">This is the second of three posts. The <a href="/I-Did-Not-Write-This-Post/">first post</a> tried the simplest way to borrow a voice which is to put the author's old posts in the prompt of a chat model. The result sounded like the author, a detector scored it 100% AI.</p>
<p class="v-prompt">This is the second of three posts. In the <a href="/I-Did-Not-Write-This-Post/">first post</a> we tried the simplest way to borrow a voice, which is to put the author's old posts in the prompt of a chat model. The result sounded like the author, and a detector scored it 100% AI.</p>

<p class="v-plain">This post takes the harder road. It trains a small model on the author's own writing, and then measures, in two different ways, whether what the model writes sounds like the author. The <a href="/The-Detector-Was-Not-Impressed/">third post</a> puts that model in front of the detector.</p>
<p class="v-tuned">This post takes the hard road. We train a small model on the authors own writing, and then measure in two ways whether what the model writes sounds like the author. In the <a href="/The-Detector-Was-Not-Impressed/">third post</a> we present that model to the detector.</p>
<p class="v-prompt">In this post we take the harder road. We will train a small model on the author's own writing, and then measure, in two different ways, whether what the model writes sounds like the author. In the <a href="/The-Detector-Was-Not-Impressed/">third post</a> we will put that model in front of the detector.</p>

<p><em>This is part 2 of three.</em></p>

<ol>
  <li><a href="/I-Did-Not-Write-This-Post/">I Didn’t Write This Post</a>: the idea, and the easy way</li>
  <li><strong>80,000 Words of Me</strong>: training a model on my own writing (this post)</li>
  <li><a href="/The-Detector-Was-Not-Impressed/">The Detector Was Not Impressed</a>: the detector and the pipeline</li>
</ol>

<p><em>The code for all three posts is on GitHub: <a href="https://github.com/cloudmark/in-my-voice">cloudmark/in-my-voice</a>.</em></p>

<h2 id="base-models-are-different">Base models are different</h2>

<p class="v-plain">A paper from 2026, <a href="https://arxiv.org/abs/2605.19516">Base Models Look Human To AI Detectors</a> by Xu and colleagues, reports a useful observation. A base model is a language model that has only been trained to continue text, before it is taught to follow instructions. When a base model continues a human-written opening, GPTZero rates the result as 96.7% human. The instruction-tuned version of the same model gets 30.3%.</p>
<p class="v-tuned">Xu and co in 2026 presented a paper <a href="https://arxiv.org/abs/2605.19516">Base Models Look Human To AI Detectors</a>. In their paper the authors discuss the following interesting insight. Base model refers to a language model which is only trained to continue text - it is not trained to follow instructions yet. When a base model continues a human written opening GPTZero will rate this result as 96.7% human. The instruction-tuned version of the same model will be rated as 30.3% human.</p>
<p class="v-prompt">A paper from 2026, <a href="https://arxiv.org/abs/2605.19516">Base Models Look Human To AI Detectors</a> by Xu and colleagues, reports a rather useful observation. A base model is a language model that has only been trained to continue text, before it is taught to follow instructions. When a base model continues a human-written opening, GPTZero rates the result as 96.7% human. The instruction-tuned version of the same model gets 30.3%.</p>

<p class="v-plain">The authors turn this into a method called <a href="https://arxiv.org/abs/2605.19516">Humanization by Iterative Paraphrasing</a>. They take a base model and train a small add-on, a LoRA adapter, on pairs of text. Each pair has an AI-style paraphrase as the input and the original human paragraph as the output. They published the code and the adapters. The experiment in this post starts from their adapter and continues the training on a single author.</p>
<p class="v-tuned">So how did the authors "convert" this idea and what have they proposed. They proposed a technique name <a href="https://arxiv.org/abs/2605.19516">Humanisation by Iterative Paraphrasing</a>. Given a model they train a small add on (LoRA adapter) on a pairs of text. One text being an AI style paraphrase and the other being the human paragraph. They have published the code and adapters. In this experiment we will start from this adapter and train further on a single author.</p>
<p class="v-prompt">The authors turn this into a method called <a href="https://arxiv.org/abs/2605.19516">Humanization by Iterative Paraphrasing</a>. They take a base model and train a small add-on, a LoRA adapter, on pairs of text. Each pair has an AI-style paraphrase as the input and the original human paragraph as the output. They published the code and the adapters (thank you!). The experiment in this post starts from their adapter and continues the training on a single author.</p>

<h2 id="the-training-set">The training set</h2>

<div class="v-plain"><p>The source material is documents the author wrote before chat models existed, so every word in them is known to be human-written. They were cut into paragraphs.</p><ul><li>Paragraphs between 25 and 160 words were kept, and longer ones were split at sentence boundaries.</li><li>Paragraphs made mostly of formulas, references, captions or links were removed.</li><li>Near-copies, such as a draft and the final version of the same text, were counted once.</li></ul></div>
<div class="v-tuned"><p>The source material is documents the author wrote before chat models existed, so every word in them is known to be human written. They were cut into paragraphs.</p><ul><li>Paragraphs between 25 and 160 words were kept, and longer paragraphs were split at sentence boundaries.</li><li>Paragraphs made mostly of formulas, references, captions or links were removed.</li><li>Near-copies, such as a draft and the final version of the same text, were counted once.</li></ul></div>
<div class="v-prompt"><p>The source material is documents the author wrote before chat models existed, so every word in them is known to be human-written. We cut them into paragraphs.</p><ul><li>Paragraphs between 25 and 160 words were kept, and longer ones were split at sentence boundaries.</li><li>Paragraphs made mostly of formulas, references, captions or links were removed.</li><li>Near-copies, such as a draft and the final version of the same text, were counted once.</li></ul></div>

<p class="v-plain">For each remaining paragraph, a chat model wrote a bland paraphrase. The model was Qwen 3.5 with 122 billion parameters, running on a Mac Studio through exo, so none of the text left the machine. The instruction was to paraphrase the paragraph in neutral, polished, textbook-style English while keeping every fact, name and term. Pairs where the paraphrase was much shorter or much longer than the original were dropped.</p>
<p class="v-tuned">For each remaining paragraph a chat model wrote a bland paraphrase. The chat model used was Qwen 3.5 with 122 billion parameters on a Mac Studio machine via exo, thus no text left the machine. The instruction was to paraphrase the paragraph in neutral, polished, textbook-style English but keeping every fact, name and term. We dropped pairs where the paraphrase was much shorter than the original or vice-versa.</p>
<p class="v-prompt">For each remaining paragraph, a chat model wrote a bland paraphrase. The model was Qwen 3.5 with 122 billion parameters, running on a Mac Studio through exo, so none of the text left the machine. The instruction was to paraphrase the paragraph in neutral, polished, textbook-style English while keeping every fact, name and term. Pairs where the paraphrase was much shorter or much longer than the original were dropped.</p>

<p class="v-plain">This left 1,418 pairs. Before any training they were split into two groups, and the two groups have different jobs.</p>
<p class="v-tuned">This leaves 1,418 pairs. Before we train let us divide the pairs in two groups and let the two groups do different jobs.</p>
<p class="v-prompt">This left us with 1,418 pairs. Before any training they were split into two groups, and the two groups have different jobs.</p>

<p class="v-plain">The larger group is the training set, with 1,259 pairs. These are the examples the model learns from. It is shown each one, it is told what the author really wrote, and it is adjusted a little. Together they hold 79,367 words of the author's writing.</p>
<p class="v-tuned">So the big guy here is our training set - we have 1,259 pairs. These are the examples which the model will learn from. In each of these examples the model is given the example, is told what the author wrote and the model is slightly tweaked. Combined these give us 79,367 words of the authors writing.</p>
<p class="v-prompt">The larger group is the training set, with 1,259 pairs. These are the examples the model learns from. It is shown each one, it is told what the author really wrote, and it is adjusted a little. Together they hold 79,367 words of the author's writing.</p>

<p class="v-plain">The smaller group is the test set, with 159 pairs. It is also called the held-back set, because the model never sees these pairs during training. They work like exam questions that were not in the textbook. If the model does well on them, it has learned how the author writes, and has not just memorised the examples it was shown. Roughly one pair in nine was held back, chosen at random, with every kind of document represented.</p>
<p class="v-tuned">The smaller set is the test set (159 pairs). The test set is also referred to as the held back set. The test set should never be used in training. It is similar to the questions we encountered on the exam which were not in the textbook. If the model does well on the test set this indicates that it must have learnt how the author writes rather than memorised the examples. We held back roughly one pair of each nine. This was done randomly and all document types were represented.</p>
<p class="v-prompt">The smaller group is the test set, with 159 pairs. It is also called the held-back set, because the model never sees these pairs during training. Think of them as exam questions which were not in the textbook. If the model does well on them, it has learned how the author writes and has not just memorised the examples it was shown. Roughly one pair in nine was held back, chosen at random, with every kind of document represented.</p>

<figure class="chart " role="group" aria-label="Diagram of the pairs split into a training set and a held-back set, with the held-back set split again">
<figcaption><strong>Nine pairs in ten train the model; the rest test it</strong><span>How the 1,418 pairs are divided, drawn to scale. The lower bar is the held-back set again, enlarged to show its two uses.</span></figcaption>

<svg viewBox="0 0 640 216" role="img" aria-label="Diagram of the pairs split into a training set and a held-back set, with the held-back set split again">
<rect x="0.0" y="34" width="565.2" height="52" rx="10" fill="#2a78d6" tabindex="0" data-tip="1,259 pairs|Training set: the model learns from these" />
<text class="g" x="0.0" y="22" text-anchor="start">Training set</text>
<text x="18.0" y="57" fill="#fff" font-size="17" font-weight="600" pointer-events="none">1,259 pairs</text><text x="18.0" y="75" fill="#fff" fill-opacity=".9" font-size="13" pointer-events="none">the model learns from these</text>
<rect x="568.2" y="34" width="71.8" height="52" rx="10" fill="#eb6834" tabindex="0" data-tip="159 pairs|Held-back set: the model never sees these" />
<text class="g" x="640.0" y="22" text-anchor="end">Held-back set</text>
<text x="604.1" y="66.0" fill="#fff" font-size="16" font-weight="600" text-anchor="middle" pointer-events="none">159</text>
<path d="M568.2,89 L640.0,89 L640,134 L0,134 Z" fill="#eb6834" opacity=".10" />
<text class="s" x="0" y="151">The same 159 pairs, drawn larger: the model never sees these</text>
<rect x="0.0" y="160" width="198.3" height="52" rx="10" fill="#1c1f3a" tabindex="0" data-tip="50 pairs|loss, and the voice test" />
<text x="18.0" y="183" fill="#fff" font-size="17" font-weight="600" pointer-events="none">50 pairs</text><text x="18.0" y="201" fill="#fff" fill-opacity=".9" font-size="13" pointer-events="none">loss, and the voice test</text>
<rect x="201.3" y="160" width="438.7" height="52" rx="10" fill="#eb6834" tabindex="0" data-tip="109 pairs|loss only" />
<text x="219.3" y="183" fill="#fff" font-size="17" font-weight="600" pointer-events="none">109 pairs</text><text x="219.3" y="201" fill="#fff" fill-opacity=".9" font-size="13" pointer-events="none">loss only</text>
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th>Set</th>
      <th>Pairs</th>
      <th>What it is used for</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>All pairs</td>
      <td>1,418</td>
      <td> </td>
    </tr>
    <tr>
      <td>Training set</td>
      <td>1,259</td>
      <td>The model learns from these</td>
    </tr>
    <tr>
      <td>Held-back set (test set)</td>
      <td>159</td>
      <td>Scoring the loss on paragraphs the model has never seen</td>
    </tr>
    <tr>
      <td>Part of the held-back set</td>
      <td>50</td>
      <td>Counting habits in what the model writes, later in this post</td>
    </tr>
  </tbody>
</table>

<p>One pair from the training set, with the chat model’s version first:</p>

<blockquote>
  <p><strong>Bland input.</strong> Following the viral success of our game lobby, we are prepared to enter a new market: Sweden. To ensure local relevance, we intend to adapt our application to support both Swedish and English. Our initial step involves creating a parent state designed to capture the relevant segment of the URL.</p>
</blockquote>

<blockquote>
  <p><strong>What I wrote in 2017.</strong> Our game lobby has gone viral and we are ready to take on a new market. Next stop Sweden! In order to be local we would like to convert our application to support both Swedish and English. We will first create a parent state which will capture the part of the URL.</p>
</blockquote>

<h2 id="the-training-recipe">The training recipe</h2>

<p class="v-plain">The base model is <a href="https://huggingface.co/Qwen/Qwen3-14B-Base"><code>Qwen3-14B-Base</code></a>. On top of it sits the published adapter, which has rank 128 and adds 514 million trainable values to a model of 14 billion. Each example is written as plain text with the paraphrase between source tags and the original paragraph between target tags. The loss is computed only on the target, so the model is never rewarded for copying the bland input.</p>
<p class="v-tuned">Base model is <a href="https://huggingface.co/Qwen/Qwen3-14B-Base"><code>Qwen3-14B-Base</code></a>. There is a published adapter on top of the base model. Rank of the adapter is 128. The adapter adds 514M trainable values on top of the 14B model. Each example is written in plain text. Paraphrases are written between the source tags and the original paragraph is written between the target tags. The loss is computed only on the target (model never rewarded for copying the bland input).</p>
<p class="v-prompt">The base model is <a href="https://huggingface.co/Qwen/Qwen3-14B-Base"><code>Qwen3-14B-Base</code></a>. On top of it sits the published adapter, which has rank 128 and adds 514 million trainable values to a model of 14 billion. Each example is written as plain text with the paraphrase between source tags and the original paragraph between target tags. Note that the loss is computed only on the target, so the model is never rewarded for copying the bland input.</p>

<p class="v-plain">The settings follow the paper and its published code, with one change: a learning rate of 0.00005 with a cosine schedule, and a warm-up over the first 3% of steps. The change is the batch, which is 4 examples here and 16 in the paper. The training ran on the Mac Studio's GPU in 32-bit floating point. One example took about 1 second and one pass over the 1,259 pairs took 22 minutes.</p>
<p class="v-tuned">We will make use of the following setting (as in the paper and its published code) lr = 0.00005 cosine schedule with warm-up for the first 3% of steps. One thing is different - our effective batch = 4 examples while the paper uses 16. We have trained on the Mac Studio's GPU in 32-bit floating point. One example takes 1 second and one pass over the 1,259 pairs takes 22 minutes.</p>
<p class="v-prompt">The settings follow the paper and its published code, with one change: a learning rate of 0.00005 with a cosine schedule, and a warm-up over the first 3% of steps. The change is the batch, which is 4 examples here and 16 in the paper. The training ran on the Mac Studio's GPU in 32-bit floating point. One example took about 1 second and one pass over the 1,259 pairs took 22 minutes.</p>

<p class="v-plain">Training goes through the 1,259 pairs one at a time. For each pair the model predicts the author's paragraph, a number called the loss says how far off it was, and the 514 million values are nudged so that the loss would be a little smaller next time. Going through every training pair once is called a pass. The next section explains the loss, and the one after it shows what happens when there is more than one pass.</p>
<p class="v-tuned">Training works by iterating over the 1,259 pairs one by one. For each pair the model predicts the authors paragraph, a number (the loss) tells us how off we are and the 514 million values are nudged slightly so that the loss is smaller next time. Iterating through each pair once is called one pass. In the next section we will explain the loss and in the one after what happens when we have more than one pass.</p>
<p class="v-prompt">Training goes through the 1,259 pairs one at a time. For each pair the model predicts the author's paragraph, a number called the loss says how far off it was, and the 514 million values are nudged so that the loss would be a little smaller next time. Going through every training pair once is called a pass. The next section explains the loss, and the one after it shows what happens when we do more than one pass.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">encode</span><span class="p">(</span><span class="n">pair</span><span class="p">):</span>
    <span class="c1"># the loss counts only the author's paragraph and the closing tag
</span>    <span class="n">prompt</span> <span class="o">=</span> <span class="s">'&lt;source_text&gt;</span><span class="se">\n</span><span class="s">'</span> <span class="o">+</span> <span class="n">pair</span><span class="p">[</span><span class="s">'source'</span><span class="p">]</span> <span class="o">+</span> <span class="s">'</span><span class="se">\n</span><span class="s">&lt;/source_text&gt;</span><span class="se">\n\n</span><span class="s">&lt;target_text&gt;</span><span class="se">\n</span><span class="s">'</span>
    <span class="n">a</span> <span class="o">=</span> <span class="n">tok</span><span class="p">(</span><span class="n">prompt</span><span class="p">)[</span><span class="s">'input_ids'</span><span class="p">]</span>
    <span class="n">b</span> <span class="o">=</span> <span class="n">tok</span><span class="p">(</span><span class="n">pair</span><span class="p">[</span><span class="s">'target'</span><span class="p">]</span> <span class="o">+</span> <span class="s">'</span><span class="se">\n</span><span class="s">&lt;/target_text&gt;'</span><span class="p">)[</span><span class="s">'input_ids'</span><span class="p">]</span> <span class="o">+</span> <span class="p">[</span><span class="n">tok</span><span class="p">.</span><span class="n">eos_token_id</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">torch</span><span class="p">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="p">]),</span> <span class="n">torch</span><span class="p">.</span><span class="n">tensor</span><span class="p">([[</span><span class="o">-</span><span class="mi">100</span><span class="p">]</span> <span class="o">*</span> <span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="o">+</span> <span class="n">b</span><span class="p">])</span>

<span class="n">model</span> <span class="o">=</span> <span class="n">AutoModelForCausalLM</span><span class="p">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="s">'Qwen/Qwen3-14B-Base'</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="p">.</span><span class="n">float32</span><span class="p">)</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">PeftModel</span><span class="p">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="s">'YixuanEvenXu/Qwen3-14B-Base-HIP-adapter'</span><span class="p">,</span> <span class="n">is_trainable</span><span class="o">=</span><span class="bp">True</span><span class="p">).</span><span class="n">to</span><span class="p">(</span><span class="s">'mps'</span><span class="p">)</span>
<span class="n">opt</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">optim</span><span class="p">.</span><span class="n">AdamW</span><span class="p">([</span><span class="n">p</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">model</span><span class="p">.</span><span class="n">parameters</span><span class="p">()</span> <span class="k">if</span> <span class="n">p</span><span class="p">.</span><span class="n">requires_grad</span><span class="p">],</span> <span class="n">lr</span><span class="o">=</span><span class="mf">5e-5</span><span class="p">)</span>

<span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">order</span><span class="p">,</span> <span class="mi">1</span><span class="p">):</span>                 <span class="c1"># one pass over the 1,259 pairs
</span>    <span class="n">ids</span><span class="p">,</span> <span class="n">labels</span> <span class="o">=</span> <span class="n">train</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
    <span class="n">loss</span> <span class="o">=</span> <span class="n">model</span><span class="p">(</span><span class="n">input_ids</span><span class="o">=</span><span class="n">ids</span><span class="p">,</span> <span class="n">labels</span><span class="o">=</span><span class="n">labels</span><span class="p">).</span><span class="n">loss</span>
    <span class="p">(</span><span class="n">loss</span> <span class="o">/</span> <span class="mi">4</span><span class="p">).</span><span class="n">backward</span><span class="p">()</span>                        <span class="c1"># four examples per update
</span>    <span class="k">if</span> <span class="n">k</span> <span class="o">%</span> <span class="mi">4</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">torch</span><span class="p">.</span><span class="n">nn</span><span class="p">.</span><span class="n">utils</span><span class="p">.</span><span class="n">clip_grad_norm_</span><span class="p">(</span><span class="n">params</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">)</span>
        <span class="n">opt</span><span class="p">.</span><span class="n">step</span><span class="p">();</span> <span class="n">sched</span><span class="p">.</span><span class="n">step</span><span class="p">();</span> <span class="n">opt</span><span class="p">.</span><span class="n">zero_grad</span><span class="p">()</span>
</code></pre></div></div>

<h2 id="how-the-model-is-scored-the-loss">How the model is scored: the loss</h2>

<p class="v-plain">A language model does not write a word. It gives every possible next word a probability, and one is drawn. The loss measures how much probability the model gave to the words the author really wrote. Nothing is generated during this test.</p>
<p class="v-tuned">Language models do not write a word. They give the next possible words with probabilities and one is drawn. The loss is how much probability the model has given to the words which the author has really written. No generation is performed in this test.</p>
<p class="v-prompt">A language model does not write a word. What it does is give every possible next word a probability, and then one is drawn. The loss measures how much probability the model gave to the words the author really wrote. Nothing is generated during this test.</p>

<p class="v-plain">Take one held-back pair. It has two halves: the bland paraphrase, and the paragraph the author really wrote. Suppose the author's paragraph begins with the words The settings follow the paper. The test walks through that paragraph one word at a time and asks the model the same question at every step: given everything so far, how likely is the word that really comes next?</p>
<p class="v-tuned">Pick a held back pair. A pair has two parts - a bland paraphrase and the paragraph which the author actually wrote. Say that the authors paragraph starts with The settings follow the paper. The test will go through the paragraph one word at a time and will ask the model: Given all that we have seen thus far, what is the probability that the word which really comes next comes? And so on for each word.</p>
<p class="v-prompt">Let's take one held-back pair. It has two halves: the bland paraphrase, and the paragraph the author really wrote. Suppose the author's paragraph begins with the words The settings follow the paper. The test walks through that paragraph one word at a time and asks the model the same question at every step: given everything so far, how likely is the word that really comes next?</p>

<div class="v-plain"><ol><li>At the first step the model is shown the bland paraphrase and the word The, and it is asked for the probability of settings.</li><li>At the second step it is shown the bland paraphrase and The settings, and it is asked for the probability of follow.</li><li>At the third step it is shown The settings follow, and it is asked for the probability of the.</li></ol><p>Each step adds one more real word to what the model can see.</p></div>
<div class="v-tuned"><ol><li>In step one we present the model with the bland paraphrase and The and ask for the probability of settings.</li><li>In step two we show the model the bland paraphrase and The settings and ask for the probability of follow.</li><li>In step three we show the model the settings follow and ask for the probability of the.</li></ol><p>In each step an additional word is revealed.</p></div>
<div class="v-prompt"><ol><li>At the first step the model is shown the bland paraphrase and the word The, and we ask it for the probability of settings.</li><li>At the second step it is shown the bland paraphrase and The settings, and we ask it for the probability of follow.</li><li>At the third step it is shown The settings follow, and we ask for the probability of the.</li></ol><p>Observe that each step adds one more real word to what the model can see.</p></div>

<p class="v-plain">The words the model is shown are always the words the author wrote, never the words it would have guessed. If it thought the second word should be parameters, it is still shown settings before the third question is asked. This matters for two reasons. One wrong guess cannot spoil every answer that comes after it. And every answer measures the same thing: how well the model knows this author at this point in this paragraph.</p>
<p class="v-tuned">Always display the words of the author rather than the model words. If the model guesses that the second word would have been parameters but the author actually wrote setting - then always show the authors words when the model is being asked the third question. This is important for two reasons. One wrong guess should not spoil all the subsequent answers. Every answer is a measurement of the same thing - how well does the model know this author at this point in this paragraph.</p>
<p class="v-prompt">Note that the words the model is shown are always the words the author wrote, never the words it would have guessed. If it thought the second word should be parameters, it is still shown settings before we ask the third question. This matters for two reasons. One wrong guess cannot spoil every answer that comes after it. And every answer measures the same thing - how well the model knows this author at this point in this paragraph.</p>

<div class="v-plain"><p>Each answer is turned into a penalty. The penalty is the negative logarithm of the probability that the model gave to the real word. The logarithm is used because of how it behaves at the two ends.</p><ul><li>A probability of 0.9 gives a penalty of 0.11.</li><li>A probability of 0.5 gives 0.69.</li><li>A probability of 0.01 gives 4.6.</li></ul><p>A model that is confident and right pays almost nothing. A model that is confident and wrong pays a great deal, far more than it saved by being right somewhere else.</p></div>
<p class="v-tuned">So let’s convert each answer to a penalty. We could define the penalty as the negative log of the probability of the model assigned to the real word. We take the log because log is very nice at both ends. 0.9 becomes 0.11. 0.5 becomes 0.69. 0.01 becomes 4.6. The model which is confident and right pays almost nothing. The model which is confident and wrong pays a great deal. Far more than it saved by being right somewhere else.</p>
<p class="v-prompt">Each answer is then turned into a penalty. The penalty is the negative logarithm of the probability that the model gave to the real word. Why a logarithm? Because of how it behaves at the two ends. A probability of 0.9 gives a penalty of 0.11. A probability of 0.5 gives 0.69. A probability of 0.01 gives 4.6. A model that is confident and right pays almost nothing, but a model that is confident and wrong pays a great deal - far more than it saved by being right somewhere else. Ouch!</p>

<p class="v-plain">The table below shows the four steps for the opening of that paragraph. The model found the word settings hard to predict, so the first penalty is large. It found the word the easy, so the third penalty is small.</p>
<p class="v-tuned">The table below shows the four steps when we open the paragraph. Note in this case the model has a hard time guessing the word settings thus the high first penalty. The model was able to easily guess the word the hence the low penalty.</p>
<p class="v-prompt">The table below shows the four steps for the opening of that paragraph. The model found the word settings hard to predict so the first penalty is large. It found the word the easy, so the third penalty is small.</p>

<table>
  <thead>
    <tr>
      <th>What the model has been shown</th>
      <th>The real next word</th>
      <th>Probability it gave that word</th>
      <th>Penalty</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>The bland paragraph, then “The”</td>
      <td>settings</td>
      <td>0.20</td>
      <td>1.61</td>
    </tr>
    <tr>
      <td>… “The settings”</td>
      <td>follow</td>
      <td>0.45</td>
      <td>0.80</td>
    </tr>
    <tr>
      <td>… “The settings follow”</td>
      <td>the</td>
      <td>0.90</td>
      <td>0.11</td>
    </tr>
    <tr>
      <td>… “The settings follow the”</td>
      <td>paper</td>
      <td>0.60</td>
      <td>0.51</td>
    </tr>
    <tr>
      <td><strong>Average over these four</strong></td>
      <td> </td>
      <td> </td>
      <td><strong>0.76</strong></td>
    </tr>
  </tbody>
</table>

<p><em>The probabilities in this table are made up to show the arithmetic. The penalties are the real negative logarithms of them.</em></p>

<p class="v-plain">The loss of a paragraph is the average penalty over all its pieces. The loss of the model is the average over all the held-back paragraphs. The pieces are tokens, not words: a token is a short word or a part of a longer one, and this kind of text has about 1.2 tokens per word. The bland paraphrase is never scored, only the author's paragraph.</p>
<p class="v-tuned">Loss of a paragraph is the average of the pieces penalties. Loss of our model is the average of the losses of the held back paragraphs. Pieces are tokens not words. A token is a short word or a part of a longer word. Our text has about 1.2 tokens per word. The bland paraphrase is never scored: only the authors paragraph.</p>
<p class="v-prompt">The loss of a paragraph is the average penalty over all its pieces, and the loss of the model is the average over all the held-back paragraphs. Note that the pieces are tokens and not words; a token is a short word or a part of a longer one, and this kind of text has about 1.2 tokens per word. The bland paraphrase is never scored, only the author's paragraph.</p>

<div class="v-plain"><p>The number has a plain reading. Raise e to the loss and you get the number of equally likely choices the model was hesitating between, on average, at each token.</p><ul><li>A loss of 1.014 is about 2.8 choices.</li><li>A loss of 0.807 is about 2.2.</li></ul><p>Training narrows down what the author's next word is.</p></div>
<div class="v-tuned"><p>The number has a plain reading. Raise e to the loss and you get the number of equally likely choices that the model was hesitating between on average at each token.</p><ul><li>A loss of 1.014 is about 2.8 choices.</li><li>A loss of 0.807 is about 2.2.</li></ul><p>Training narrows down what the authors next word is.</p></div>
<div class="v-prompt"><p>The number has a plain reading. Raise e to the loss and you get the number of equally likely choices the model was hesitating between, on average, at each token.</p><ul><li>A loss of 1.014 is about 2.8 choices.</li><li>A loss of 0.807 is about 2.2.</li></ul><p>In other words, training narrows down what the author's next word is.</p></div>

<p class="v-plain">The loss must be measured on held-back pairs. On the training pairs it keeps falling for as long as the training runs, because the model starts to memorise them. On pairs it has never seen it falls and then rises again. The turning point is where learning the voice ends and memorising begins.</p>
<p class="v-tuned">So let us try and track the loss of the held back pairs. The loss on the training pairs will continue to fall for as long as the training is running due to the fact that the model will start memorising the pairs. The loss on the never seen pairs will fall and rise again. The turning point will illustrate when the learning of the voice ends and memorising begins.</p>
<p class="v-prompt">The loss must be measured on held-back pairs. On the training pairs it keeps falling for as long as the training runs, because the model starts to memorise them. On pairs it has never seen it falls and then rises again. The turning point is where learning the voice ends and memorising begins - think of it as the point where the model stops reading and starts cramming!</p>

<h2 id="one-pass-is-enough">One pass is enough</h2>

<p class="v-plain">Before training, the loss on the 159 held-back pairs was 1.014. After the first pass it fell to 0.807. After the second pass it rose to 0.823, and after the third to 0.968, while the loss on the training pairs kept falling to 0.279. Even with 1,259 examples, extra passes make the model memorise the paragraphs instead of learning from them. The adapter saved after the first pass was used for everything that follows.</p>
<p class="v-tuned">Initially before we run the loss for the 159 held back pairs was 1.014. After the first pass the loss has decreased to 0.807. After the second pass the loss has increased to 0.823 and after the third pass the loss has increased further to 0.968 while the loss on the training pairs continues decreasing to 0.279. With 1,259 examples the model starts memorising the paragraph rather than learning from the examples with additional passes. I have used the adapter saved after the first pass for all subsequent tasks.</p>
<p class="v-prompt">Before training, the loss on the 159 held-back pairs was 1.014. After the first pass it fell to 0.807. After the second pass it rose to 0.823, and after the third to 0.968, while the loss on the training pairs kept falling to 0.279. Even with 1,259 examples, extra passes make the model memorise the paragraphs instead of learning from them. The adapter saved after the first pass is the one we will use for everything that follows.</p>

<figure class="chart " role="group" aria-label="Line chart of training and held-back loss per pass">
<figcaption><strong>One pass is the best the model gets</strong><span>Loss after each pass. The training loss keeps falling while the held-back loss turns upwards after pass 1: the model has started to memorise.</span></figcaption>

<svg viewBox="0 0 640 270" role="img" aria-label="Line chart of training and held-back loss per pass">
<defs>
<linearGradient id="g18" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#2a78d6" stop-opacity=".16" /><stop offset="1" stop-color="#2a78d6" stop-opacity="0" /></linearGradient>
<linearGradient id="g19" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#eb6834" stop-opacity=".16" /><stop offset="1" stop-color="#eb6834" stop-opacity="0" /></linearGradient>
</defs>
<line class="grid" x1="40" y1="238.0" x2="490" y2="238.0" /><text class="s" x="31" y="242.0" text-anchor="end">0.0</text>
<line class="dash" x1="40" y1="163.3" x2="490" y2="163.3" /><text class="s" x="31" y="167.3" text-anchor="end">0.4</text>
<line class="dash" x1="40" y1="88.7" x2="490" y2="88.7" /><text class="s" x="31" y="92.7" text-anchor="end">0.8</text>
<line class="dash" x1="40" y1="14.0" x2="490" y2="14.0" /><text class="s" x="31" y="18.0" text-anchor="end">1.2</text>
<text class="s" x="40.0" y="262" text-anchor="middle">Before</text>
<text class="s" x="190.0" y="262" text-anchor="middle">Pass 1</text>
<text class="s" x="340.0" y="262" text-anchor="middle">Pass 2</text>
<text class="s" x="490.0" y="262" text-anchor="middle">Pass 3</text>
<line x1="190.0" y1="34" x2="190.0" y2="238" stroke="var(--ink)" stroke-width="1" stroke-dasharray="3 3" /><rect x="165.0" y="12" width="50" height="22" rx="11" fill="var(--ink)" /><text x="190.0" y="27" text-anchor="middle" style="fill:var(--bg, #fff)" font-size="12" font-weight="600">used</text>
<polygon fill="url(#g18)" points="40.0,238 40.0,48.7 190.0,87.4 340.0,84.4 490.0,57.3 490.0,238" />
<polyline fill="none" stroke="#2a78d6" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round" points="40.0,48.7 190.0,87.4 340.0,84.4 490.0,57.3" />
<circle cx="40.0" cy="48.7" r="5.5" fill="#2a78d6" stroke="#fff" stroke-width="2.5" /><circle class="hit" cx="40.0" cy="48.7" r="15" tabindex="0" data-tip="1.014|Held-back pairs, before" />
<circle cx="190.0" cy="87.4" r="5.5" fill="#2a78d6" stroke="#fff" stroke-width="2.5" /><circle class="hit" cx="190.0" cy="87.4" r="15" tabindex="0" data-tip="0.807|Held-back pairs, pass 1" />
<circle cx="340.0" cy="84.4" r="5.5" fill="#2a78d6" stroke="#fff" stroke-width="2.5" /><circle class="hit" cx="340.0" cy="84.4" r="15" tabindex="0" data-tip="0.823|Held-back pairs, pass 2" />
<circle cx="490.0" cy="57.3" r="5.5" fill="#2a78d6" stroke="#fff" stroke-width="2.5" /><circle class="hit" cx="490.0" cy="57.3" r="15" tabindex="0" data-tip="0.968|Held-back pairs, pass 3" />
<rect x="506.0" y="48.3" width="10" height="10" rx="3" fill="#2a78d6" /><text class="t" x="522.0" y="58.3" font-weight="600">Held-back pairs</text><text class="v" x="522.0" y="75.3">0.968</text>
<polygon fill="url(#g19)" points="190.0,238 190.0,84.6 340.0,133.3 490.0,185.9 490.0,238" />
<polyline fill="none" stroke="#eb6834" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round" points="190.0,84.6 340.0,133.3 490.0,185.9" />
<circle cx="190.0" cy="84.6" r="5.5" fill="#eb6834" stroke="#fff" stroke-width="2.5" /><circle class="hit" cx="190.0" cy="84.6" r="15" tabindex="0" data-tip="0.822|Training pairs, pass 1" />
<circle cx="340.0" cy="133.3" r="5.5" fill="#eb6834" stroke="#fff" stroke-width="2.5" /><circle class="hit" cx="340.0" cy="133.3" r="15" tabindex="0" data-tip="0.561|Training pairs, pass 2" />
<circle cx="490.0" cy="185.9" r="5.5" fill="#eb6834" stroke="#fff" stroke-width="2.5" /><circle class="hit" cx="490.0" cy="185.9" r="15" tabindex="0" data-tip="0.279|Training pairs, pass 3" />
<rect x="506.0" y="176.9" width="10" height="10" rx="3" fill="#eb6834" /><text class="t" x="522.0" y="186.9" font-weight="600">Training pairs</text><text class="v" x="522.0" y="203.9">0.279</text>
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>Loss on the 1,259 training pairs</th>
      <th>Loss on the 159 held-back pairs</th>
      <th>Choices per token (e to the loss)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Before training</td>
      <td> </td>
      <td>1.014</td>
      <td>2.8</td>
    </tr>
    <tr>
      <td>After pass 1</td>
      <td>0.822</td>
      <td><strong>0.807</strong></td>
      <td>2.2</td>
    </tr>
    <tr>
      <td>After pass 2</td>
      <td>0.561</td>
      <td>0.823</td>
      <td>2.3</td>
    </tr>
    <tr>
      <td>After pass 3</td>
      <td>0.279</td>
      <td>0.968</td>
      <td>2.6</td>
    </tr>
  </tbody>
</table>

<p class="v-plain">From here on there are two adapters to tell apart. The published adapter is the one that Xu and colleagues released, which learned from the writing of many people. The tuned adapter is the same adapter after one more pass of training on the pairs of the author. It is the model this post set out to make, and the next section tests whether the extra pass made a difference.</p>
<p class="v-tuned">From here on there are two adapters to tell apart. Published Adapter is the adapter which Xu et al published which learnt from writings of many people. Tuned adapter is the same adapter after one more pass of training on the pairs of the author. This is the model which this post will attempt to create. In the next section we will see whether this extra pass made any difference.</p>
<p class="v-prompt">From here on we have two adapters to tell apart. The published adapter is the one that Xu and colleagues released - it learned from the writing of many people. The tuned adapter is the very same adapter after one more pass of training on the pairs of the author. This is the model this post set out to make, and in the next section we will test whether the extra pass made a difference. Let's see!</p>

<h2 id="does-it-sound-like-the-author">Does it sound like the author</h2>

<p class="v-plain">The loss says how well the model predicts the author. It does not say what the model writes when it is left to write. So the second test lets it write. Writing takes much longer than scoring, so this test used 50 of the 159 held-back paragraphs. For each of the 50 there are four texts with the same content: the bland paraphrase, the rewrite by the published adapter, the rewrite by the tuned adapter, and the paragraph the author really wrote. Habits can be counted in each.</p>
<p class="v-tuned">The loss represents how close can the model predict the author. The loss does not represent what the model writes when we let it write. This is why the second test let the model write. Writing is significantly slower than scoring. To make the test faster we will use 50 paragraphs from the 159 paragraphs we kept for testing. For each of the 50 paragraphs we have four texts which contain the same content; the bland paraphrase, the rewrite by the published adapter, the rewrite by the tuned adapter and the paragraph the author really wrote. Habits can be counted in each.</p>
<p class="v-prompt">The loss tells us how well the model predicts the author, but it does not tell us what the model writes when it is left to write on its own. So for the second test we let it write. Writing takes much longer than scoring so this test used 50 of the 159 held-back paragraphs. For each of the 50 we have four texts with the same content: the bland paraphrase, the rewrite by the published adapter, the rewrite by the tuned adapter, and the paragraph the author really wrote. Now we can count habits in each.</p>

<p class="v-plain">The simplest habit is one word. The real paragraphs use we 29.5 times per 1,000 words. The bland paraphrases use it 5.1 times. The published adapter raises this to 14.1 and the tuned adapter to 21.8. The tuning has not copied the author, but it has moved the text most of the way.</p>
<p class="v-tuned">We is the simplest habit. The real paragraphs use we 29.5 times per 1,000 words. The bland paraphrases use it 5.1 times. The published adapter raises this to 14.1 and the tuned adapter to 21.8. The tuning has not copied the author but it has moved the text most of the way.</p>
<p class="v-prompt">The simplest habit is one word. The real paragraphs use we 29.5 times per 1,000 words. The bland paraphrases use it 5.1 times. The published adapter raises this to 14.1 and the tuned adapter to 21.8. The tuning has not copied the author but it has moved the text most of the way. Not bad!</p>

<figure class="chart " role="group" aria-label="Bar chart of how often the word we appears in four versions of the same paragraphs">
<figcaption><strong>Tuning moves the voice most of the way to mine</strong><span>How often &quot;we&quot; appears per 1,000 words, in four versions of the same 50 held-back paragraphs.</span></figcaption>

<svg viewBox="0 0 640 182" role="img" aria-label="Bar chart of how often the word we appears in four versions of the same paragraphs">
<text class="t" x="196" y="31.0" text-anchor="end">Bland paraphrase</text>
<rect class="track" x="210" y="15.0" width="370" height="22" rx="6" />
<path d="M210,15.0 h53.0 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-53.0 z" fill="#2a78d6" tabindex="0" data-tip="5.1 per 1,000 words|Bland paraphrase — chat model" />
<text class="v" x="278.0" y="31.0">5.1</text>
<text class="t" x="196" y="75.0" text-anchor="end">Published adapter</text>
<rect class="track" x="210" y="59.0" width="370" height="22" rx="6" />
<path d="M210,59.0 h157.0 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-157.0 z" fill="#2a78d6" tabindex="0" data-tip="14.1 per 1,000 words|Published adapter — before tuning" />
<text class="v" x="382.0" y="75.0">14.1</text>
<text class="t" x="196" y="119.0" text-anchor="end">Tuned adapter</text>
<rect class="track" x="210" y="103.0" width="370" height="22" rx="6" />
<path d="M210,103.0 h246.1 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-246.1 z" fill="#2a78d6" tabindex="0" data-tip="21.8 per 1,000 words|Tuned adapter — after one pass on my writing" />
<text class="v" x="471.1" y="119.0">21.8</text>
<text class="t" x="196" y="163.0" text-anchor="end" font-weight="600">What I really wrote</text>
<rect class="track" x="210" y="147.0" width="370" height="22" rx="6" />
<path d="M210,147.0 h335.1 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-335.1 z" fill="var(--ink)" tabindex="0" data-tip="29.5 per 1,000 words|What I really wrote" />
<text class="v" x="560.1" y="163.0">29.5</text>
</svg>
</figure>

<p class="v-plain">One word is a narrow test, so more habits were counted in the same way. Each row of the table below is a count per 1,000 words, or a share of sentences. They are small things nobody chooses on purpose: how often a writer says I or you, how often two words are joined into one with an apostrophe, how often a sentence runs past 30 words.</p>
<p class="v-tuned">So one word is a narrow test; I counted more habits in the same way. Rows in the table below are counts per 1,000 words or shares of sentences. They are little things nobody chooses on purpose; how often a writer says I or you, how often two words are joined into one with an apostrophe, how often a sentence runs past 30 words.</p>
<p class="v-prompt">One word is a narrow test, so let us count more habits in the same way. Each row of the table below is a count per 1,000 words, or a share of sentences. These are small things nobody chooses on purpose: how often a writer says I or you, how often two words are joined into one with an apostrophe, how often a sentence runs past 30 words.</p>

<figure class="chart " role="group" aria-label="Dot chart of eleven writing habits in the bland paraphrase, the published adapter and the tuned adapter, against the author&#x27;s own figures">
<figcaption><strong>Tuning pulls most habits towards mine, and misses a few</strong><span>Eleven habits in three versions of the same 50 paragraphs, as a multiple of my own figure. A dot on the line at 1 matches what I really wrote. The exact numbers are in the table underneath.</span></figcaption>
<ul class="legend"><li><i style="background:#b9b8b3"></i>Bland paraphrase</li><li><i style="background:#eb6834"></i>Published adapter</li><li><i style="background:#2a78d6"></i>Tuned adapter</li></ul>
<svg viewBox="0 0 640 386" role="img" aria-label="Dot chart of eleven writing habits in the bland paraphrase, the published adapter and the tuned adapter, against the author&#x27;s own figures">
<line class="grid" x1="220.0" y1="20" x2="220.0" y2="358" /><text class="s" x="220.0" y="376" text-anchor="middle">0×</text>
<line class="dash" x1="286.0" y1="20" x2="286.0" y2="358" /><text class="s" x="286.0" y="376" text-anchor="middle">0.5×</text>
<line class="dash" x1="352.0" y1="20" x2="352.0" y2="358" /><text class="s" x="352.0" y="376" text-anchor="middle">1×</text>
<line class="dash" x1="418.0" y1="20" x2="418.0" y2="358" /><text class="s" x="418.0" y="376" text-anchor="middle">1.5×</text>
<line class="dash" x1="484.0" y1="20" x2="484.0" y2="358" /><text class="s" x="484.0" y="376" text-anchor="middle">2×</text>
<line class="dash" x1="550.0" y1="20" x2="550.0" y2="358" /><text class="s" x="550.0" y="376" text-anchor="middle">2.5×</text>
<line class="dash" x1="616.0" y1="20" x2="616.0" y2="358" /><text class="s" x="616.0" y="376" text-anchor="middle">3×</text>
<line x1="352.0" y1="20" x2="352.0" y2="358" stroke="var(--ink)" stroke-width="2" /><text class="v" x="359.0" y="14">what I really wrote</text>
<text class="t" x="206" y="46.0" text-anchor="end" font-weight="600">&quot;we&quot;</text>
<line x1="242.8" y1="41.0" x2="352.0" y2="41.0" stroke="var(--line)" stroke-width="2" />
<circle cx="242.8" cy="41.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="242.8" cy="41.0" r="11" tabindex="0" data-tip="0.17× what I really wrote|“&quot;we&quot;” in bland paraphrase — mine: 29.5 times per 1,000 words" />
<circle cx="283.1" cy="41.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="283.1" cy="41.0" r="11" tabindex="0" data-tip="0.48× what I really wrote|“&quot;we&quot;” in published adapter — mine: 29.5 times per 1,000 words" />
<circle cx="317.5" cy="41.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="317.5" cy="41.0" r="11" tabindex="0" data-tip="0.74× what I really wrote|“&quot;we&quot;” in tuned adapter — mine: 29.5 times per 1,000 words" />
<text class="t" x="206" y="76.0" text-anchor="end" font-weight="600">&quot;you&quot;</text>
<line x1="220.0" y1="71.0" x2="412.9" y2="71.0" stroke="var(--line)" stroke-width="2" />
<circle cx="220.0" cy="71.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="220.0" cy="71.0" r="11" tabindex="0" data-tip="0.00× what I really wrote|“&quot;you&quot;” in bland paraphrase — mine: 2.6 times per 1,000 words" />
<circle cx="387.5" cy="71.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="387.5" cy="71.0" r="11" tabindex="0" data-tip="1.27× what I really wrote|“&quot;you&quot;” in published adapter — mine: 2.6 times per 1,000 words" />
<circle cx="412.9" cy="71.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="412.9" cy="71.0" r="11" tabindex="0" data-tip="1.46× what I really wrote|“&quot;you&quot;” in tuned adapter — mine: 2.6 times per 1,000 words" />
<text class="t" x="206" y="106.0" text-anchor="end" font-weight="600">&quot;I&quot;</text>
<line x1="240.3" y1="101.0" x2="352.0" y2="101.0" stroke="var(--line)" stroke-width="2" />
<circle cx="240.3" cy="101.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="240.3" cy="101.0" r="11" tabindex="0" data-tip="0.15× what I really wrote|“&quot;I&quot;” in bland paraphrase — mine: 2.6 times per 1,000 words" />
<circle cx="275.8" cy="101.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="275.8" cy="101.0" r="11" tabindex="0" data-tip="0.42× what I really wrote|“&quot;I&quot;” in published adapter — mine: 2.6 times per 1,000 words" />
<circle cx="260.6" cy="101.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="260.6" cy="101.0" r="11" tabindex="0" data-tip="0.31× what I really wrote|“&quot;I&quot;” in tuned adapter — mine: 2.6 times per 1,000 words" />
<text class="t" x="206" y="136.0" text-anchor="end" font-weight="600">&quot;so&quot;, &quot;hence&quot;, &quot;thus&quot;</text>
<line x1="248.5" y1="131.0" x2="355.6" y2="131.0" stroke="var(--line)" stroke-width="2" />
<circle cx="248.5" cy="131.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="248.5" cy="131.0" r="11" tabindex="0" data-tip="0.22× what I really wrote|“&quot;so&quot;, &quot;hence&quot;, &quot;thus&quot;” in bland paraphrase — mine: 3.7 times per 1,000 words" />
<circle cx="298.5" cy="131.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="298.5" cy="131.0" r="11" tabindex="0" data-tip="0.59× what I really wrote|“&quot;so&quot;, &quot;hence&quot;, &quot;thus&quot;” in published adapter — mine: 3.7 times per 1,000 words" />
<circle cx="355.6" cy="131.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="355.6" cy="131.0" r="11" tabindex="0" data-tip="1.03× what I really wrote|“&quot;so&quot;, &quot;hence&quot;, &quot;thus&quot;” in tuned adapter — mine: 3.7 times per 1,000 words" />
<text class="t" x="206" y="166.0" text-anchor="end" font-weight="600">Contractions</text>
<line x1="235.5" y1="161.0" x2="445.2" y2="161.0" stroke="var(--line)" stroke-width="2" />
<circle cx="235.5" cy="161.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="235.5" cy="161.0" r="11" tabindex="0" data-tip="0.12× what I really wrote|“Contractions” in bland paraphrase — mine: 3.4 per 1,000 words" />
<circle cx="445.2" cy="161.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="445.2" cy="161.0" r="11" tabindex="0" data-tip="1.71× what I really wrote|“Contractions” in published adapter — mine: 3.4 per 1,000 words" />
<circle cx="278.2" cy="161.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="278.2" cy="161.0" r="11" tabindex="0" data-tip="0.44× what I really wrote|“Contractions” in tuned adapter — mine: 3.4 per 1,000 words" />
<text class="t" x="206" y="196.0" text-anchor="end" font-weight="600">Exclamation marks</text>
<line x1="220.0" y1="191.0" x2="352.0" y2="191.0" stroke="var(--line)" stroke-width="2" />
<circle cx="220.0" cy="191.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="220.0" cy="191.0" r="11" tabindex="0" data-tip="0.00× what I really wrote|“Exclamation marks” in bland paraphrase — mine: 0.7 per 1,000 words" />
<circle cx="295.4" cy="191.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="295.4" cy="191.0" r="11" tabindex="0" data-tip="0.57× what I really wrote|“Exclamation marks” in published adapter — mine: 0.7 per 1,000 words" />
<circle cx="295.4" cy="191.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="295.4" cy="191.0" r="11" tabindex="0" data-tip="0.57× what I really wrote|“Exclamation marks” in tuned adapter — mine: 0.7 per 1,000 words" />
<text class="t" x="206" y="226.0" text-anchor="end" font-weight="600">Semicolons</text>
<line x1="352.0" y1="221.0" x2="616.0" y2="221.0" stroke="var(--line)" stroke-width="2" />
<text class="s" x="606.0" y="212.0" text-anchor="end">off the scale: 3.9×</text>
<circle cx="616.0" cy="221.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="616.0" cy="221.0" r="11" tabindex="0" data-tip="3.91× what I really wrote|“Semicolons” in bland paraphrase — mine: 1.1 per 1,000 words" />
<circle cx="352.0" cy="221.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="352.0" cy="221.0" r="11" tabindex="0" data-tip="1.00× what I really wrote|“Semicolons” in published adapter — mine: 1.1 per 1,000 words" />
<circle cx="496.0" cy="221.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="496.0" cy="221.0" r="11" tabindex="0" data-tip="2.09× what I really wrote|“Semicolons” in tuned adapter — mine: 1.1 per 1,000 words" />
<text class="t" x="206" y="256.0" text-anchor="end" font-weight="600">Brackets</text>
<line x1="280.8" y1="251.0" x2="352.0" y2="251.0" stroke="var(--line)" stroke-width="2" />
<circle cx="326.9" cy="251.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="326.9" cy="251.0" r="11" tabindex="0" data-tip="0.81× what I really wrote|“Brackets” in bland paraphrase — mine: 6.3 per 1,000 words" />
<circle cx="280.8" cy="251.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="280.8" cy="251.0" r="11" tabindex="0" data-tip="0.46× what I really wrote|“Brackets” in published adapter — mine: 6.3 per 1,000 words" />
<circle cx="299.6" cy="251.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="299.6" cy="251.0" r="11" tabindex="0" data-tip="0.60× what I really wrote|“Brackets” in tuned adapter — mine: 6.3 per 1,000 words" />
<text class="t" x="206" y="286.0" text-anchor="end" font-weight="600">Average sentence length</text>
<line x1="342.2" y1="281.0" x2="352.0" y2="281.0" stroke="var(--line)" stroke-width="2" />
<circle cx="342.9" cy="281.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="342.9" cy="281.0" r="11" tabindex="0" data-tip="0.93× what I really wrote|“Average sentence length” in bland paraphrase — mine: 20.2 words" />
<circle cx="346.8" cy="281.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="346.8" cy="281.0" r="11" tabindex="0" data-tip="0.96× what I really wrote|“Average sentence length” in published adapter — mine: 20.2 words" />
<circle cx="342.2" cy="281.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="342.2" cy="281.0" r="11" tabindex="0" data-tip="0.93× what I really wrote|“Average sentence length” in tuned adapter — mine: 20.2 words" />
<text class="t" x="206" y="316.0" text-anchor="end" font-weight="600">Sentences of 30 words or more</text>
<line x1="299.2" y1="311.0" x2="352.0" y2="311.0" stroke="var(--line)" stroke-width="2" />
<circle cx="299.2" cy="311.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="299.2" cy="311.0" r="11" tabindex="0" data-tip="0.60× what I really wrote|“Sentences of 30 words or more” in bland paraphrase — mine: 15 % of sentences" />
<circle cx="308.0" cy="311.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="308.0" cy="311.0" r="11" tabindex="0" data-tip="0.67× what I really wrote|“Sentences of 30 words or more” in published adapter — mine: 15 % of sentences" />
<circle cx="308.0" cy="311.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="308.0" cy="311.0" r="11" tabindex="0" data-tip="0.67× what I really wrote|“Sentences of 30 words or more” in tuned adapter — mine: 15 % of sentences" />
<text class="t" x="206" y="346.0" text-anchor="end" font-weight="600">Sentences of 6 words or fewer</text>
<line x1="330.0" y1="341.0" x2="462.0" y2="341.0" stroke="var(--line)" stroke-width="2" />
<circle cx="330.0" cy="341.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="330.0" cy="341.0" r="11" tabindex="0" data-tip="0.83× what I really wrote|“Sentences of 6 words or fewer” in bland paraphrase — mine: 6 % of sentences" />
<circle cx="330.0" cy="341.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="330.0" cy="341.0" r="11" tabindex="0" data-tip="0.83× what I really wrote|“Sentences of 6 words or fewer” in published adapter — mine: 6 % of sentences" />
<circle cx="462.0" cy="341.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="462.0" cy="341.0" r="11" tabindex="0" data-tip="1.83× what I really wrote|“Sentences of 6 words or fewer” in tuned adapter — mine: 6 % of sentences" />
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th>On 50 held-back paragraphs</th>
      <th>Bland paraphrase</th>
      <th>Published adapter</th>
      <th>Tuned adapter</th>
      <th>What I really wrote</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>“we” per 1,000 words</td>
      <td>5.1</td>
      <td>14.1</td>
      <td>21.8</td>
      <td>29.5</td>
    </tr>
    <tr>
      <td>“you” per 1,000 words</td>
      <td>0.0</td>
      <td>3.3</td>
      <td>3.8</td>
      <td>2.6</td>
    </tr>
    <tr>
      <td>“I” per 1,000 words</td>
      <td>0.4</td>
      <td>1.1</td>
      <td>0.8</td>
      <td>2.6</td>
    </tr>
    <tr>
      <td>“so”, “hence”, “thus” per 1,000 words</td>
      <td>0.8</td>
      <td>2.2</td>
      <td>3.8</td>
      <td>3.7</td>
    </tr>
    <tr>
      <td>Contractions per 1,000 words</td>
      <td>0.4</td>
      <td>5.8</td>
      <td>1.5</td>
      <td>3.4</td>
    </tr>
    <tr>
      <td>Exclamation marks per 1,000 words</td>
      <td>0.0</td>
      <td>0.4</td>
      <td>0.4</td>
      <td>0.7</td>
    </tr>
    <tr>
      <td>Semicolons per 1,000 words</td>
      <td>4.3</td>
      <td>1.1</td>
      <td>2.3</td>
      <td>1.1</td>
    </tr>
    <tr>
      <td>Brackets per 1,000 words</td>
      <td>5.1</td>
      <td>2.9</td>
      <td>3.8</td>
      <td>6.3</td>
    </tr>
    <tr>
      <td>Average sentence, in words</td>
      <td>18.8</td>
      <td>19.4</td>
      <td>18.7</td>
      <td>20.2</td>
    </tr>
    <tr>
      <td>Sentences of 30 words or more</td>
      <td>9%</td>
      <td>10%</td>
      <td>10%</td>
      <td>15%</td>
    </tr>
    <tr>
      <td>Sentences of 6 words or fewer</td>
      <td>5%</td>
      <td>5%</td>
      <td>11%</td>
      <td>6%</td>
    </tr>
    <tr>
      <td>Words shared with the real paragraph</td>
      <td>0.600</td>
      <td>0.576</td>
      <td>0.634</td>
      <td>1.000</td>
    </tr>
    <tr>
      <td>Common-word profile, distance from my other writing</td>
      <td>27.8</td>
      <td>17.0</td>
      <td>10.8</td>
      <td>11.0</td>
    </tr>
  </tbody>
</table>

<p class="v-plain">The last two rows need explaining. Words shared with the real paragraph compares the rewrite with what the author wrote, word by word, and gives 1 if every word matches and 0 if none does. The bland paraphrase scores 0.600, because it has the same facts and so many of the same words. The tuned rewrite scores 0.634.</p>
<p class="v-tuned">Ok, let’s try to understand the last two rows. Words shared with real paragraph compares the rewrite with the paragraph the author wrote word by word and gives 1 if all the words match and 0 if none match. The bland paraphrase scores 0.600 due to the same facts and thus most words match. The tuned rewrite scores 0.634.</p>
<p class="v-prompt">The last two rows need some explaining. Words shared with the real paragraph compares the rewrite with what the author wrote, word by word, and gives 1 if every word matches and 0 if none does. The bland paraphrase scores 0.600, since it has the same facts and hence so many of the same words. The tuned rewrite scores 0.634.</p>

<p class="v-plain">The last row is the common-word profile, an old method for deciding who wrote an anonymous text. Every writer uses the small common words, such as the, of, which and so, at rates of their own. Nobody chooses these rates, and they do not depend on the subject, so they work like a fingerprint.</p>
<p class="v-tuned">Last row is the common word profile. It is an old technique - to find out who wrote an anonymous text. Every writer uses small common words - the, of, which and so - at rates of their own. Nobody chooses these rates and these rates do not depend on the subject - so they work like a fingerprint.</p>
<p class="v-prompt">The last row is the common-word profile, an old method for deciding who wrote an anonymous text. Every writer uses the small common words, such as the, of, which and so, at rates of their own. Nobody chooses these rates and they do not depend on the subject, so you can think of them as a fingerprint.</p>

<p class="v-plain">To build the fingerprint, take a large sample of the author's writing and find the 150 words used most often. For each word, work out what share of all the words it takes up. The result is a list of 150 numbers. A list like this is called a vector, and it can be made for any text: count the same 150 words in it and write down their shares.</p>
<p class="v-tuned">So now let us try and make the fingerprint. Making the fingerprint is as follows: We take a big sample of the authors writing and try to work out the 150 most used words. Then we compute the share of each word with respect to the total number of words used. In the end we are left with a list of 150 numbers. We will call this list a vector. We can create a vector from any text. For our vector we will also count the same 150 words and write down the shares.</p>
<p class="v-prompt">To build the fingerprint, we take a large sample of the author's writing and find the 150 words used most often. For each word we work out what share of all the words it takes up. The result is a list of 150 numbers. A list like this is called a vector, and it can be made for any text - just count the same 150 words in it and write down their shares.</p>

<p class="v-plain">Two texts by the same writer give two lists that are nearly the same. Two texts by different writers give lists that disagree on many words. The chart below shows this for twelve of the 150 words. For each word, the author's usual rate is set to 1. A dot at 2 means that the text uses the word twice as often as the author usually does, and a dot at 0.5 means half as often.</p>
<p class="v-tuned">When we compare two texts written by the same author we have two lists which are almost identical. When we compare two texts written by different writers we have two lists which disagree on many words. In the following diagram the words are illustrated for the twelve out of the 150 words. The authors usual rate is set to 1. A dot at 2 represents that the text uses the word twice as often as the author usually does and half as often at 0.5.</p>
<p class="v-prompt">Two texts by the same writer give two lists which are nearly the same. Two texts by different writers give lists which disagree on many words. The chart below shows this for twelve of the 150 words. For each word, the author's usual rate is set to 1. A dot at 2 means that the text uses the word twice as often as the author usually does, and a dot at 0.5 means half as often.</p>

<figure class="chart " role="group" aria-label="Dot chart of twelve common words in three texts against the author&#x27;s usual rate">
<figcaption><strong>The bland text scatters; the tuned text sits where I do</strong><span>How often each text uses twelve common words, as a multiple of my usual rate. Dots near the line at 1 use the word as I do.</span></figcaption>
<ul class="legend"><li><i style="background:#b9b8b3"></i>My own held-back paragraphs</li><li><i style="background:#eb6834"></i>Bland paraphrase</li><li><i style="background:#2a78d6"></i>Tuned adapter</li></ul>
<svg viewBox="0 0 640 416" role="img" aria-label="Dot chart of twelve common words in three texts against the author&#x27;s usual rate">
<line class="grid" x1="90.0" y1="20" x2="90.0" y2="388" /><text class="s" x="90.0" y="406" text-anchor="middle">0×</text>
<line class="dash" x1="195.2" y1="20" x2="195.2" y2="388" /><text class="s" x="195.2" y="406" text-anchor="middle">0.5×</text>
<line class="dash" x1="300.4" y1="20" x2="300.4" y2="388" /><text class="s" x="300.4" y="406" text-anchor="middle">1×</text>
<line class="dash" x1="405.6" y1="20" x2="405.6" y2="388" /><text class="s" x="405.6" y="406" text-anchor="middle">1.5×</text>
<line class="dash" x1="510.8" y1="20" x2="510.8" y2="388" /><text class="s" x="510.8" y="406" text-anchor="middle">2×</text>
<line class="dash" x1="616.0" y1="20" x2="616.0" y2="388" /><text class="s" x="616.0" y="406" text-anchor="middle">2.5×</text>
<line x1="300.4" y1="20" x2="300.4" y2="388" stroke="var(--ink)" stroke-width="2" /><text class="v" x="307.4" y="14">my usual rate</text>
<text class="t" x="76" y="46.0" text-anchor="end" font-weight="600">the</text>
<line x1="264.6" y1="41.0" x2="300.4" y2="41.0" stroke="var(--line)" stroke-width="2" />
<circle cx="264.6" cy="41.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="264.6" cy="41.0" r="11" tabindex="0" data-tip="0.83× my usual rate|“the” in my own held-back paragraphs — 7.2% of my words" />
<circle cx="283.6" cy="41.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="283.6" cy="41.0" r="11" tabindex="0" data-tip="0.92× my usual rate|“the” in bland paraphrase — 7.2% of my words" />
<circle cx="289.9" cy="41.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="289.9" cy="41.0" r="11" tabindex="0" data-tip="0.95× my usual rate|“the” in tuned adapter — 7.2% of my words" />
<text class="t" x="76" y="76.0" text-anchor="end" font-weight="600">to</text>
<line x1="292.0" y1="71.0" x2="300.4" y2="71.0" stroke="var(--line)" stroke-width="2" />
<circle cx="292.0" cy="71.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="292.0" cy="71.0" r="11" tabindex="0" data-tip="0.96× my usual rate|“to” in my own held-back paragraphs — 3.19% of my words" />
<circle cx="296.2" cy="71.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="296.2" cy="71.0" r="11" tabindex="0" data-tip="0.98× my usual rate|“to” in bland paraphrase — 3.19% of my words" />
<circle cx="298.3" cy="71.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="298.3" cy="71.0" r="11" tabindex="0" data-tip="0.99× my usual rate|“to” in tuned adapter — 3.19% of my words" />
<text class="t" x="76" y="106.0" text-anchor="end" font-weight="600">is</text>
<line x1="289.9" y1="101.0" x2="300.4" y2="101.0" stroke="var(--line)" stroke-width="2" />
<circle cx="296.2" cy="101.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="296.2" cy="101.0" r="11" tabindex="0" data-tip="0.98× my usual rate|“is” in my own held-back paragraphs — 2.06% of my words" />
<circle cx="289.9" cy="101.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="289.9" cy="101.0" r="11" tabindex="0" data-tip="0.95× my usual rate|“is” in bland paraphrase — 2.06% of my words" />
<circle cx="300.4" cy="101.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="300.4" cy="101.0" r="11" tabindex="0" data-tip="1.00× my usual rate|“is” in tuned adapter — 2.06% of my words" />
<text class="t" x="76" y="136.0" text-anchor="end" font-weight="600">we</text>
<line x1="136.3" y1="131.0" x2="357.2" y2="131.0" stroke="var(--line)" stroke-width="2" />
<circle cx="357.2" cy="131.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="357.2" cy="131.0" r="11" tabindex="0" data-tip="1.27× my usual rate|“we” in my own held-back paragraphs — 2.32% of my words" />
<circle cx="136.3" cy="131.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="136.3" cy="131.0" r="11" tabindex="0" data-tip="0.22× my usual rate|“we” in bland paraphrase — 2.32% of my words" />
<circle cx="287.8" cy="131.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="287.8" cy="131.0" r="11" tabindex="0" data-tip="0.94× my usual rate|“we” in tuned adapter — 2.32% of my words" />
<text class="t" x="76" y="166.0" text-anchor="end" font-weight="600">in</text>
<line x1="199.4" y1="161.0" x2="300.4" y2="161.0" stroke="var(--line)" stroke-width="2" />
<circle cx="273.0" cy="161.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="273.0" cy="161.0" r="11" tabindex="0" data-tip="0.87× my usual rate|“in” in my own held-back paragraphs — 1.96% of my words" />
<circle cx="199.4" cy="161.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="199.4" cy="161.0" r="11" tabindex="0" data-tip="0.52× my usual rate|“in” in bland paraphrase — 1.96% of my words" />
<circle cx="239.4" cy="161.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="239.4" cy="161.0" r="11" tabindex="0" data-tip="0.71× my usual rate|“in” in tuned adapter — 1.96% of my words" />
<text class="t" x="76" y="196.0" text-anchor="end" font-weight="600">will</text>
<line x1="201.5" y1="191.0" x2="365.6" y2="191.0" stroke="var(--line)" stroke-width="2" />
<circle cx="315.1" cy="191.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="315.1" cy="191.0" r="11" tabindex="0" data-tip="1.07× my usual rate|“will” in my own held-back paragraphs — 1.26% of my words" />
<circle cx="201.5" cy="191.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="201.5" cy="191.0" r="11" tabindex="0" data-tip="0.53× my usual rate|“will” in bland paraphrase — 1.26% of my words" />
<circle cx="365.6" cy="191.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="365.6" cy="191.0" r="11" tabindex="0" data-tip="1.31× my usual rate|“will” in tuned adapter — 1.26% of my words" />
<text class="t" x="76" y="226.0" text-anchor="end" font-weight="600">which</text>
<line x1="123.7" y1="221.0" x2="344.6" y2="221.0" stroke="var(--line)" stroke-width="2" />
<circle cx="300.4" cy="221.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="300.4" cy="221.0" r="11" tabindex="0" data-tip="1.00× my usual rate|“which” in my own held-back paragraphs — 0.74% of my words" />
<circle cx="123.7" cy="221.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="123.7" cy="221.0" r="11" tabindex="0" data-tip="0.16× my usual rate|“which” in bland paraphrase — 0.74% of my words" />
<circle cx="344.6" cy="221.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="344.6" cy="221.0" r="11" tabindex="0" data-tip="1.21× my usual rate|“which” in tuned adapter — 0.74% of my words" />
<text class="t" x="76" y="256.0" text-anchor="end" font-weight="600">be</text>
<line x1="300.4" y1="251.0" x2="470.8" y2="251.0" stroke="var(--line)" stroke-width="2" />
<circle cx="334.1" cy="251.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="334.1" cy="251.0" r="11" tabindex="0" data-tip="1.16× my usual rate|“be” in my own held-back paragraphs — 0.64% of my words" />
<circle cx="424.5" cy="251.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="424.5" cy="251.0" r="11" tabindex="0" data-tip="1.59× my usual rate|“be” in bland paraphrase — 0.64% of my words" />
<circle cx="470.8" cy="251.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="470.8" cy="251.0" r="11" tabindex="0" data-tip="1.81× my usual rate|“be” in tuned adapter — 0.64% of my words" />
<text class="t" x="76" y="286.0" text-anchor="end" font-weight="600">have</text>
<line x1="102.6" y1="281.0" x2="310.9" y2="281.0" stroke="var(--line)" stroke-width="2" />
<circle cx="270.9" cy="281.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="270.9" cy="281.0" r="11" tabindex="0" data-tip="0.86× my usual rate|“have” in my own held-back paragraphs — 0.61% of my words" />
<circle cx="102.6" cy="281.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="102.6" cy="281.0" r="11" tabindex="0" data-tip="0.06× my usual rate|“have” in bland paraphrase — 0.61% of my words" />
<circle cx="310.9" cy="281.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="310.9" cy="281.0" r="11" tabindex="0" data-tip="1.05× my usual rate|“have” in tuned adapter — 0.61% of my words" />
<text class="t" x="76" y="316.0" text-anchor="end" font-weight="600">our</text>
<line x1="180.5" y1="311.0" x2="332.0" y2="311.0" stroke="var(--line)" stroke-width="2" />
<circle cx="332.0" cy="311.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="332.0" cy="311.0" r="11" tabindex="0" data-tip="1.15× my usual rate|“our” in my own held-back paragraphs — 0.55% of my words" />
<circle cx="180.5" cy="311.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="180.5" cy="311.0" r="11" tabindex="0" data-tip="0.43× my usual rate|“our” in bland paraphrase — 0.55% of my words" />
<circle cx="292.0" cy="311.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="292.0" cy="311.0" r="11" tabindex="0" data-tip="0.96× my usual rate|“our” in tuned adapter — 0.55% of my words" />
<text class="t" x="76" y="346.0" text-anchor="end" font-weight="600">from</text>
<line x1="195.2" y1="341.0" x2="321.4" y2="341.0" stroke="var(--line)" stroke-width="2" />
<circle cx="321.4" cy="341.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="321.4" cy="341.0" r="11" tabindex="0" data-tip="1.10× my usual rate|“from” in my own held-back paragraphs — 0.47% of my words" />
<circle cx="195.2" cy="341.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="195.2" cy="341.0" r="11" tabindex="0" data-tip="0.50× my usual rate|“from” in bland paraphrase — 0.47% of my words" />
<circle cx="205.7" cy="341.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="205.7" cy="341.0" r="11" tabindex="0" data-tip="0.55× my usual rate|“from” in tuned adapter — 0.47% of my words" />
<text class="t" x="76" y="376.0" text-anchor="end" font-weight="600">it</text>
<line x1="300.4" y1="371.0" x2="578.1" y2="371.0" stroke="var(--line)" stroke-width="2" />
<circle cx="468.7" cy="371.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="468.7" cy="371.0" r="11" tabindex="0" data-tip="1.80× my usual rate|“it” in my own held-back paragraphs — 0.46% of my words" />
<circle cx="578.1" cy="371.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="578.1" cy="371.0" r="11" tabindex="0" data-tip="2.32× my usual rate|“it” in bland paraphrase — 0.46% of my words" />
<circle cx="401.4" cy="371.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="401.4" cy="371.0" r="11" tabindex="0" data-tip="1.48× my usual rate|“it” in tuned adapter — 0.46% of my words" />
</svg>
</figure>

<p class="v-plain">The orange dots are the bland paraphrase, and they are scattered. It uses we about a fifth as often as the author, which about a sixth as often, and have almost never. The blue dots are the tuned rewrite. On those three words it sits at 0.94, 1.21 and 1.05, next to the grey dots of the author's own paragraphs. It is not perfect: it uses be nearly twice as often as the author, and from about half as often.</p>
<p class="v-tuned">We have some orange dots which are the bland paraphrase. It is scattered. It uses we about a fifth as often as the author, which about a sixth as often and have almost never. The blue dots are the tuned rewrite. On those three words it sits at 0.94, 1.21 and 1.05, next to the grey dots of the author’s own paragraphs. It is not perfect: it uses be nearly twice as often as the author, and from about half as often.</p>
<p class="v-prompt">The orange dots are the bland paraphrase, and as you can see they are scattered. It uses we about a fifth as often as the author, which about a sixth as often, and have almost never. The blue dots are the tuned rewrite. On those three words it sits at 0.94, 1.21 and 1.05, right next to the grey dots of the author's own paragraphs. It is not perfect though: it uses be nearly twice as often as the author, and from about half as often.</p>

<table>
  <thead>
    <tr>
      <th>Word</th>
      <th>Share of my words</th>
      <th>My own held-back paragraphs</th>
      <th>Bland paraphrase</th>
      <th>Published adapter</th>
      <th>Tuned adapter</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>“the”</td>
      <td>7.20%</td>
      <td>0.83×</td>
      <td>0.92×</td>
      <td>0.88×</td>
      <td>0.95×</td>
    </tr>
    <tr>
      <td>“to”</td>
      <td>3.19%</td>
      <td>0.96×</td>
      <td>0.98×</td>
      <td>1.15×</td>
      <td>0.99×</td>
    </tr>
    <tr>
      <td>“is”</td>
      <td>2.06%</td>
      <td>0.98×</td>
      <td>0.95×</td>
      <td>1.32×</td>
      <td>1.00×</td>
    </tr>
    <tr>
      <td>“we”</td>
      <td>2.32%</td>
      <td>1.27×</td>
      <td>0.22×</td>
      <td>0.56×</td>
      <td>0.94×</td>
    </tr>
    <tr>
      <td>“in”</td>
      <td>1.96%</td>
      <td>0.87×</td>
      <td>0.52×</td>
      <td>0.70×</td>
      <td>0.71×</td>
    </tr>
    <tr>
      <td>“will”</td>
      <td>1.26%</td>
      <td>1.07×</td>
      <td>0.53×</td>
      <td>0.66×</td>
      <td>1.31×</td>
    </tr>
    <tr>
      <td>“which”</td>
      <td>0.74%</td>
      <td>1.00×</td>
      <td>0.16×</td>
      <td>0.29×</td>
      <td>1.21×</td>
    </tr>
    <tr>
      <td>“be”</td>
      <td>0.64%</td>
      <td>1.16×</td>
      <td>1.59×</td>
      <td>1.92×</td>
      <td>1.81×</td>
    </tr>
    <tr>
      <td>“have”</td>
      <td>0.61%</td>
      <td>0.86×</td>
      <td>0.06×</td>
      <td>0.71×</td>
      <td>1.05×</td>
    </tr>
    <tr>
      <td>“our”</td>
      <td>0.55%</td>
      <td>1.15×</td>
      <td>0.43×</td>
      <td>0.46×</td>
      <td>0.96×</td>
    </tr>
    <tr>
      <td>“from”</td>
      <td>0.47%</td>
      <td>1.10×</td>
      <td>0.50×</td>
      <td>0.54×</td>
      <td>0.55×</td>
    </tr>
    <tr>
      <td>“it”</td>
      <td>0.46%</td>
      <td>1.80×</td>
      <td>2.32×</td>
      <td>2.46×</td>
      <td>1.48×</td>
    </tr>
  </tbody>
</table>

<p><em>Each figure is the word’s rate in that text divided by its rate in the rest of my writing. The texts are the 50 held-back paragraphs, about 2,600 words each, so single words wobble.</em></p>

<p class="v-plain">The chart shows twelve words. To compare all 150 at once, the gaps are added up into a single distance. The sum used here is called the Jensen-Shannon divergence, which is a way of adding the gaps so that very rare words do not count for too much. Zero means that the two texts use all 150 words at exactly the same rates, and a bigger number means they are further apart.</p>
<p class="v-tuned">So let us count these words that we find in the chart. There are twelve words. To compare all 150 at once we will add up the gaps into one distance. The sum that we use here is called the Jensen-Shannon divergence and is one of the ways of adding up the gaps so that very rare words don't count for too much. Zero means that the two texts use all 150 words at exactly the same rate and a bigger number means they are further apart.</p>
<p class="v-prompt">The chart only shows twelve words, but we want to compare all 150 at once, so the gaps are added up into a single distance. The sum we will use is called the Jensen-Shannon divergence - think of it as a way of adding up the gaps so that very rare words do not count for too much. Zero means that the two texts use all 150 words at exactly the same rates and a bigger number means they are further apart.</p>

<div class="v-plain"><p>No two samples of one person match exactly. The 50 real paragraphs, compared with the rest of the author's writing, are at a distance of 11.0. That is the natural difference between the author and the author, and no model can be expected to do better.</p><ul><li>The bland paraphrases are at 27.8.</li><li>The published adapter brings that down to 17.0, and the tuned adapter to 10.8.</li></ul><p>On this measure the tuned model is as close to the author as the author is.</p></div>
<div class="v-tuned"><p>There is no two samples from one person which matches perfectly. The distance between the 50 real paragraphs and the rest of the authors work is 11.0. This is what we should expect from two samples from the same author and it is unreasonable to expect a model to do better.</p><ul><li>The bland paraphrases are at 27.8.</li><li>The published adapter reduces this to 17.0 while the tuned adapter reduces it to 10.8.</li></ul><p>On this measure the tuned model is as close to the author as the author himself.</p></div>
<p class="v-prompt">Here is the thing, no two samples of one person ever match exactly. The 50 real paragraphs, compared with the rest of the author's writing, sit at a distance of 11.0. That is the natural difference between the author and the author (my head hurts!) so no model can be expected to do better than that. The bland paraphrases sit at 27.8. The published adapter brings that down to 17.0 and the tuned adapter to 10.8. On this measure the tuned model is as close to the author as the author is. Pretty neat huh?!</p>

<figure class="chart " role="group" aria-label="Bar chart of common-word distance for four texts">
<figcaption><strong>On common words the tuned model is as close to me as I am</strong><span>Distance between each text and the rest of my writing, over my 150 most used words. Lower is closer; my own paragraphs mark the best a model can do.</span></figcaption>

<svg viewBox="0 0 640 182" role="img" aria-label="Bar chart of common-word distance for four texts">
<text class="t" x="216" y="31.0" text-anchor="end">Bland paraphrase</text>
<rect class="track" x="230" y="15.0" width="350" height="22" rx="6" />
<path d="M230,15.0 h318.3 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-318.3 z" fill="#2a78d6" tabindex="0" data-tip="27.8 (distance over 150 words)|Bland paraphrase — chat model" />
<text class="v" x="563.3" y="31.0">27.8</text>
<text class="t" x="216" y="75.0" text-anchor="end">Published adapter</text>
<rect class="track" x="230" y="59.0" width="350" height="22" rx="6" />
<path d="M230,59.0 h192.3 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-192.3 z" fill="#2a78d6" tabindex="0" data-tip="17 (distance over 150 words)|Published adapter — before tuning" />
<text class="v" x="437.3" y="75.0">17</text>
<text class="t" x="216" y="119.0" text-anchor="end">Tuned adapter</text>
<rect class="track" x="230" y="103.0" width="350" height="22" rx="6" />
<path d="M230,103.0 h120.0 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-120.0 z" fill="#2a78d6" tabindex="0" data-tip="10.8 (distance over 150 words)|Tuned adapter — after one pass on my writing" />
<text class="v" x="365.0" y="119.0">10.8</text>
<text class="t" x="216" y="163.0" text-anchor="end" font-weight="600">My own held-back paragraphs</text>
<rect class="track" x="230" y="147.0" width="350" height="22" rx="6" />
<path d="M230,147.0 h122.3 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-122.3 z" fill="var(--ink)" tabindex="0" data-tip="11 (distance over 150 words)|My own held-back paragraphs — the author against the author" />
<text class="v" x="367.3" y="163.0">11</text>
</svg>
</figure>

<p class="v-plain">It is not a perfect copy. The tuned model is more formal than the author: it uses fewer contractions, says I less often, and writes too few long sentences. It also writes more very short sentences than the author does. These counts come from one rewrite of each paragraph, so small differences mean little, but those four are large enough to be real.</p>
<p class="v-tuned">Not a perfect copy. The tuned model is more formal than the author - uses less contractions, says I less often and writes too few long sentences. Writes more very short sentences than the author. These counts come from one rewrite of each paragraph - small differences mean little - but those four are large enough to be real.</p>
<p class="v-prompt">It is not a perfect copy though. The tuned model is more formal than the author: it uses fewer contractions, says I less often and writes too few long sentences. It also writes more very short sentences than the author does. Note that these counts come from one rewrite of each paragraph, so small differences mean very little, but those four are large enough to be real.</p>

<h2 id="publishing-the-model">Publishing the model</h2>

<p class="v-plain">The result of all this is one file of about 2 GB: a LoRA adapter that sits on top of <a href="https://huggingface.co/Qwen/Qwen3-14B-Base"><code>Qwen3-14B-Base</code></a>. In a narrow sense it is a model of how the author writes. It is published on Hugging Face as <a href="https://huggingface.co/cloudmark/cloudmark-voice-qwen3-14b"><code>cloudmark/cloudmark-voice-qwen3-14b</code></a>, so that the experiment can be repeated and so that anyone can try it on their own text.</p>
<p class="v-tuned">So what we end up with after all of this is one file - a 2 GB - LoRA adapter on top of <a href="https://huggingface.co/Qwen/Qwen3-14B-Base"><code>Qwen3-14B-Base</code></a>. In a narrow sense this is a model of how I write. It is published on Hugging Face - <a href="https://huggingface.co/cloudmark/cloudmark-voice-qwen3-14b"><code>cloudmark/cloudmark-voice-qwen3-14b</code></a> - so that others can reproduce this experiment and anyone can have a play around with their own text.</p>
<p class="v-prompt">The end result of all this is one file of about 2 GB - a LoRA adapter which sits on top of <a href="https://huggingface.co/Qwen/Qwen3-14B-Base"><code>Qwen3-14B-Base</code></a>. In a narrow sense it is a model of how the author writes. It is published on Hugging Face as <a href="https://huggingface.co/cloudmark/cloudmark-voice-qwen3-14b"><code>cloudmark/cloudmark-voice-qwen3-14b</code></a> so that you can repeat the experiment and try it out on your own text.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>hf auth login
hf repo create cloudmark/cloudmark-voice-qwen3-14b <span class="nt">--repo-type</span> model
hf upload cloudmark/cloudmark-voice-qwen3-14b ./voice-adapter/epoch-1 <span class="nb">.</span> <span class="nt">--repo-type</span> model
</code></pre></div></div>

<p class="v-plain">Using it takes a few lines. The text to rewrite goes between the source tags, the prompt ends with an open target tag, and the model continues from there. Sampling several candidates matters, for reasons the <a href="/The-Detector-Was-Not-Impressed/">third post</a> makes painfully clear.</p>
<p class="v-tuned">So making a call with it is really quite easy. It takes couple of lines of code. The text which we will re-write goes between the source tags, prompt ends with an open target tag and model continues from there. Sampling several candidates does matter and the <a href="/The-Detector-Was-Not-Impressed/">third post</a> makes it really clear why.</p>
<p class="v-prompt">Using it is easy - just a few lines. The text to rewrite goes between the source tags, the prompt ends with an open target tag and the model simply continues from there. Note that we sample several candidates, and the <a href="/The-Detector-Was-Not-Impressed/">third post</a> makes painfully clear why.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">peft</span> <span class="kn">import</span> <span class="n">PeftModel</span>
<span class="kn">from</span> <span class="nn">transformers</span> <span class="kn">import</span> <span class="n">AutoModelForCausalLM</span><span class="p">,</span> <span class="n">AutoTokenizer</span>

<span class="n">base</span> <span class="o">=</span> <span class="n">AutoModelForCausalLM</span><span class="p">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="s">'Qwen/Qwen3-14B-Base'</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float16'</span><span class="p">)</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">PeftModel</span><span class="p">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="n">base</span><span class="p">,</span> <span class="s">'cloudmark/cloudmark-voice-qwen3-14b'</span><span class="p">).</span><span class="n">to</span><span class="p">(</span><span class="s">'mps'</span><span class="p">)</span>    <span class="c1"># or 'cuda'
</span><span class="n">tok</span> <span class="o">=</span> <span class="n">AutoTokenizer</span><span class="p">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="s">'cloudmark/cloudmark-voice-qwen3-14b'</span><span class="p">)</span>

<span class="n">text</span> <span class="o">=</span> <span class="s">'Kubernetes restarts a pod when its process fails. It cannot see inside the application.'</span>
<span class="n">prompt</span> <span class="o">=</span> <span class="s">'&lt;source_text&gt;</span><span class="se">\n</span><span class="s">'</span> <span class="o">+</span> <span class="n">text</span> <span class="o">+</span> <span class="s">'</span><span class="se">\n</span><span class="s">&lt;/source_text&gt;</span><span class="se">\n\n</span><span class="s">&lt;target_text&gt;</span><span class="se">\n</span><span class="s">'</span>
<span class="n">ids</span> <span class="o">=</span> <span class="n">tok</span><span class="p">(</span><span class="n">prompt</span><span class="p">,</span> <span class="n">return_tensors</span><span class="o">=</span><span class="s">'pt'</span><span class="p">).</span><span class="n">to</span><span class="p">(</span><span class="n">model</span><span class="p">.</span><span class="n">device</span><span class="p">)</span>
<span class="n">out</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="n">generate</span><span class="p">(</span><span class="o">**</span><span class="n">ids</span><span class="p">,</span> <span class="n">max_new_tokens</span><span class="o">=</span><span class="mi">120</span><span class="p">,</span> <span class="n">do_sample</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">temperature</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span> <span class="n">top_p</span><span class="o">=</span><span class="mf">0.95</span><span class="p">,</span> <span class="n">num_return_sequences</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="k">for</span> <span class="n">o</span> <span class="ow">in</span> <span class="n">out</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">tok</span><span class="p">.</span><span class="n">decode</span><span class="p">(</span><span class="n">o</span><span class="p">[</span><span class="n">ids</span><span class="p">[</span><span class="s">'input_ids'</span><span class="p">].</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]:],</span> <span class="n">skip_special_tokens</span><span class="o">=</span><span class="bp">True</span><span class="p">).</span><span class="n">split</span><span class="p">(</span><span class="s">'&lt;/target_text&gt;'</span><span class="p">)[</span><span class="mi">0</span><span class="p">].</span><span class="n">strip</span><span class="p">())</span>
</code></pre></div></div>

<h2 id="what-this-does-not-tell-us">What this does not tell us</h2>

<p class="v-plain">Both tests in this post are about voice. Neither says whether a detector would take the rewrite for human writing, and neither says whether the facts survived the rewrite. A model can predict the author's words well and still change a number when it writes freely. Those two questions are the subject of the <a href="/The-Detector-Was-Not-Impressed/">third post</a>, and the answers were not the ones expected.</p>
<p class="v-tuned">So both test presented in this post answers neither question. Voice is the theme of the tests however both tests will not indicate whether the detector would consider the rewrite as a human writing and neither would indicate whether facts survived the rewrite. It could be that a model predicts the authors words well but still changes a number when it writes freely. In the <a href="/The-Detector-Was-Not-Impressed/">third post</a> we will address those two questions and the answers were not the ones we anticipated.</p>
<p class="v-prompt">Both tests in this post are about voice. Neither of them tells us whether a detector would take the rewrite for human writing, and neither tells us whether the facts survived the rewrite. A model can predict the author's words really well and still change a number when it writes freely. Those two questions are the subject of the <a href="/The-Detector-Was-Not-Impressed/">third post</a> and, spoiler alert, the answers were not the ones I expected.</p>

<p><strong>In short</strong></p>

<ul>
  <li>The training set is 1,418 pairs: a bland version of a paragraph, and the paragraph I really wrote. 1,259 train the model and 159 test it.</li>
  <li>The loss measures how much probability the model gave to the words I really wrote. Lower is better, and it must be measured on pairs the model never saw.</li>
  <li>One pass over the data was the best. After that the model memorises.</li>
  <li>On habits and on the common-word profile, what the model writes is close to what I write.</li>
  <li>None of this says what a detector thinks, or whether the facts survive. That is the third post.</li>
</ul>

<h2 id="references">References</h2>

<ol>
  <li><a href="https://arxiv.org/abs/2605.19516">Xu et al., Base Models Look Human To AI Detectors, 2026</a></li>
  <li><a href="https://github.com/cloudmark/in-my-voice">The code: cloudmark/in-my-voice</a></li>
</ol>

<p>As always, stay safe, keep hacking!</p>

<p><em>Next: <a href="/The-Detector-Was-Not-Impressed/">The Detector Was Not Impressed</a>, on the detector and the pipeline.</em></p>

<script>
  (function () {
    var prose = document.querySelector('.prose'), buttons = document.querySelectorAll('.voice-switch button');
    function show(voice) {
      prose.setAttribute('data-voice', voice);
      buttons.forEach(function (b) { b.setAttribute('aria-pressed', String(b.dataset.voice === voice)); });
    }
    buttons.forEach(function (b) { b.addEventListener('click', function () { show(b.dataset.voice); }); });
    show('tuned');
  })();
</script>

<script>
  (function () {
    var tip = document.createElement('div'); tip.className = 'chart-tip'; tip.setAttribute('role', 'status');
    var value = document.createElement('b'), label = document.createElement('span'); tip.appendChild(value); tip.appendChild(label);
    document.body.appendChild(tip);
    function show(el, x, y) {
      var parts = el.getAttribute('data-tip').split('|');
      value.textContent = parts[0]; label.textContent = parts[1] || '';
      tip.style.opacity = 1; tip.style.transform = 'none';
      var w = tip.offsetWidth, left = Math.min(Math.max(8, x + 14), window.innerWidth - w - 8);
      tip.style.left = left + 'px'; tip.style.top = Math.max(8, y - tip.offsetHeight - 12) + 'px';
    }
    function hide() { tip.style.opacity = 0; tip.style.transform = ''; }
    document.querySelectorAll('.chart [data-tip]').forEach(function (el) {
      el.addEventListener('pointermove', function (e) { show(el, e.clientX, e.clientY); });
      el.addEventListener('pointerleave', hide);
      el.addEventListener('focus', function () { var r = el.getBoundingClientRect(); show(el, r.left + r.width / 2, r.top); });
      el.addEventListener('blur', hide);
    });
  })();
</script>]]></content><author><name>Mark Galea</name></author><category term="fine-tuning" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">I Didn’t Write This Post</title><link href="https://cloudmark.me/I-Did-Not-Write-This-Post/" rel="alternate" type="text/html" title="I Didn’t Write This Post" /><published>2026-11-27T08:10:00+01:00</published><updated>2026-11-27T08:10:00+01:00</updated><id>https://cloudmark.me/I-Did-Not-Write-This-Post</id><content type="html" xml:base="https://cloudmark.me/I-Did-Not-Write-This-Post/"><![CDATA[<style>
  .chart { margin: 2.2em 0 1.6em; padding: 22px 24px 18px; background: var(--paper, #fff) var(--grain-img, none); border: 1px solid var(--line); border-radius: 14px; }
  .chart figcaption { margin: 0 0 14px; }
  .chart figcaption strong { display: block; color: var(--ink); font: 600 18px/1.3 var(--ui); letter-spacing: -.01em; }
  .chart figcaption span { display: block; margin-top: 4px; color: var(--grey); font: 14px/1.45 var(--ui); }
  .chart .legend { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 0 0 10px; padding: 0; list-style: none; font: 13px var(--ui); color: var(--soft); }
  .chart .legend li { display: inline-flex; align-items: center; gap: 7px; margin: 0; }
  .chart .legend i { width: 11px; height: 11px; border-radius: 4px; display: inline-block; }
  .chart svg { display: block; width: 100%; height: auto; overflow: visible; font-family: var(--ui); }
  .chart .t { fill: var(--ink); font-size: 14px; }
  .chart .g { fill: var(--ink); font-size: 13px; font-weight: 600; letter-spacing: .02em; }
  .chart .s { fill: var(--grey); font-size: 12.5px; }
  .chart .v { fill: var(--ink); font-size: 13.5px; font-weight: 600; font-variant-numeric: tabular-nums; }
  .chart .grid { stroke: var(--line); stroke-width: 1; }
  .chart .dash { stroke: var(--line); stroke-width: 1; stroke-dasharray: 2 4; }
  .chart .track { fill: var(--line); opacity: .55; }
  .chart [data-tip] { cursor: default; outline: none; transition: filter .15s; }
  .chart [data-tip]:hover, .chart [data-tip]:focus-visible { filter: brightness(1.1) saturate(1.1); }
  .chart .hit { fill: transparent; }
  .chart-tip { position: fixed; z-index: 20; pointer-events: none; padding: 7px 11px; border-radius: 10px; background: var(--ink); color: var(--bg, #fff); font: 13px/1.35 var(--ui); max-width: 260px; opacity: 0; transform: translateY(4px); transition: opacity .12s, transform .12s; box-shadow: 0 8px 24px -8px rgba(var(--shadow, 28, 31, 58),.5); }
  .chart-tip b { display: block; font-size: 15px; font-variant-numeric: tabular-nums; }
  .flow ol { list-style: none; margin: 0; padding: 0; counter-reset: step; }
  .flow li { position: relative; margin: 0; padding: 0 0 18px 52px; counter-increment: step; }
  .flow li::before { content: counter(step); position: absolute; left: 0; top: 0; width: 34px; height: 34px; border-radius: 50%; background: var(--ink); color: var(--bg, #fff); font: 600 15px/34px var(--ui); text-align: center; }
  .flow li::after { content: ''; position: absolute; left: 16px; top: 40px; bottom: 4px; width: 2px; border-radius: 2px; background: var(--line); }
  .flow li:last-child { padding-bottom: 0; } .flow li:last-child::after { display: none; }
  .flow h4 { margin: 0; padding-top: 5px; font: 600 16px/1.3 var(--ui); color: var(--ink); display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
  .flow .who { font: 600 11.5px/1 var(--ui); letter-spacing: .03em; padding: 5px 9px; border-radius: 999px; color: #fff; }
  .flow .loop { font: 600 11.5px/1 var(--ui); padding: 5px 9px; border-radius: 999px; border: 1px solid var(--line); color: var(--soft); background: var(--paper, #fff); }
  .flow p { margin: 5px 0 0; font: 14.5px/1.5 var(--ui); color: var(--soft); }
  .flow ul { margin: 8px 0 0; padding: 0; list-style: none; display: flex; flex-wrap: wrap; gap: 6px; }
  .flow ul li { padding: 5px 10px; border-radius: 8px; background: var(--paper, #fff); border: 1px solid var(--line); font: 13px var(--ui); color: var(--ink); counter-increment: none; }
  .flow ul li::before, .flow ul li::after { display: none; }
  .chart circle[stroke="#fff"] { stroke: var(--paper, #fff); }
  .chart text[fill="#1c1f3a"] { fill: #1f1e1b; }
  /* At night the series colours take brighter steps, on fills, strokes and gradient stops alike. */
  :root[data-theme="dark"] .chart :is([fill="#2a78d6"], [style*="#2a78d6"]) { fill: #3987e5; background-color: #3987e5 !important; } :root[data-theme="dark"] .chart [stroke="#2a78d6"] { stroke: #3987e5; } :root[data-theme="dark"] .chart [stop-color="#2a78d6"] { stop-color: #3987e5; }
  :root[data-theme="dark"] .chart :is([fill="#eb6834"], [style*="#eb6834"]) { fill: #d95926; background-color: #d95926 !important; } :root[data-theme="dark"] .chart [stroke="#eb6834"] { stroke: #d95926; } :root[data-theme="dark"] .chart [stop-color="#eb6834"] { stop-color: #d95926; }
  :root[data-theme="dark"] .chart :is([fill="#1baf7a"], [style*="#1baf7a"]) { fill: #199e70; background-color: #199e70 !important; } :root[data-theme="dark"] .chart [stroke="#1baf7a"] { stroke: #199e70; } :root[data-theme="dark"] .chart [stop-color="#1baf7a"] { stop-color: #199e70; }
  :root[data-theme="dark"] .chart :is([fill="#b9b8b3"], [style*="#b9b8b3"]) { fill: #8d8b84; background-color: #8d8b84 !important; } :root[data-theme="dark"] .chart [stroke="#b9b8b3"] { stroke: #8d8b84; } :root[data-theme="dark"] .chart [stop-color="#b9b8b3"] { stop-color: #8d8b84; }
  @media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) .chart :is([fill="#2a78d6"], [style*="#2a78d6"]) { fill: #3987e5; background-color: #3987e5 !important; } :root:not([data-theme="light"]) .chart [stroke="#2a78d6"] { stroke: #3987e5; } :root:not([data-theme="light"]) .chart [stop-color="#2a78d6"] { stop-color: #3987e5; }
  :root:not([data-theme="light"]) .chart :is([fill="#eb6834"], [style*="#eb6834"]) { fill: #d95926; background-color: #d95926 !important; } :root:not([data-theme="light"]) .chart [stroke="#eb6834"] { stroke: #d95926; } :root:not([data-theme="light"]) .chart [stop-color="#eb6834"] { stop-color: #d95926; }
  :root:not([data-theme="light"]) .chart :is([fill="#1baf7a"], [style*="#1baf7a"]) { fill: #199e70; background-color: #199e70 !important; } :root:not([data-theme="light"]) .chart [stroke="#1baf7a"] { stroke: #199e70; } :root:not([data-theme="light"]) .chart [stop-color="#1baf7a"] { stop-color: #199e70; }
  :root:not([data-theme="light"]) .chart :is([fill="#b9b8b3"], [style*="#b9b8b3"]) { fill: #8d8b84; background-color: #8d8b84 !important; } :root:not([data-theme="light"]) .chart [stroke="#b9b8b3"] { stroke: #8d8b84; } :root:not([data-theme="light"]) .chart [stop-color="#b9b8b3"] { stop-color: #8d8b84; }
  }
</style>

<div class="view-switch voice-switch" role="group" aria-label="Which version to read">
  <button type="button" data-voice="plain" aria-pressed="false"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2.5h10A1.5 1.5 0 0 1 14.5 4v5.5A1.5 1.5 0 0 1 13 11H8l-3 2.5V11H3a1.5 1.5 0 0 1-1.5-1.5V4A1.5 1.5 0 0 1 3 2.5z" /></svg>Plain AI</button>
  <button type="button" data-voice="prompt" aria-pressed="false"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4.5" width="8.5" height="10" rx="1.5" /><path d="M5.5 4.5V3A1.5 1.5 0 0 1 7 1.5h5.5A1.5 1.5 0 0 1 14 3v7a1.5 1.5 0 0 1-1.5 1.5h-2M4.5 8h3.5M4.5 10.5h3.5" /></svg>Posts in the prompt</button>
  <button type="button" data-voice="tuned" aria-pressed="true"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.5 2.5l3 3-8 8-3.5.5.5-3.5zM9 4l3 3" /></svg>In my voice</button>
</div>
<style>
  .voice-switch { display: inline-flex; flex-wrap: wrap; gap: 4px; padding: 4px; margin: 0 0 1.6em; border-radius: 14px; background: var(--wash); }
  .voice-switch button { display: inline-flex; align-items: center; gap: 8px; }
  .voice-switch svg { flex: none; }
  .prose[data-voice="plain"] :is(.v-tuned, .v-prompt), .prose[data-voice="tuned"] :is(.v-plain, .v-prompt), .prose[data-voice="prompt"] :is(.v-plain, .v-tuned) { display: none; }
  .voice-note { color: var(--grey); font-size: 15px; margin-top: -1em; }
  .pipe-example { margin: 1.4em 0; display: grid; gap: 10px; }
  .pipe-example div { padding: 14px 16px; border-radius: 14px; border: 1px solid var(--line); background: var(--paper, #fff); font-size: 15.5px; line-height: 1.55; }
  .pipe-example b { display: block; margin-bottom: 4px; font: 600 12px var(--ui); letter-spacing: .04em; text-transform: uppercase; color: var(--grey); }
  .pipe-example .bad { border-color: color-mix(in srgb, #eb6834 45%, var(--line)); background: color-mix(in srgb, #eb6834 7%, var(--paper, #fff)); } .pipe-example .good { border-color: color-mix(in srgb, #2a78d6 45%, var(--line)); background: color-mix(in srgb, #2a78d6 7%, var(--paper, #fff)); }
  .pipe-example mark { color: inherit; background: color-mix(in srgb, #eb6834 30%, var(--paper, #fff)); padding: 0 3px; border-radius: 4px; }
</style>

<p class="voice-note"><span class="v-plain">You are reading the version a chat model wrote, with no tuning.</span><span class="v-tuned">You are reading the version written by the model trained on my own writing: ten guarded rounds, then a check of every paragraph against the plain version. In a last read, 27 small slips in 24 of the 109 paragraphs were fixed by hand, mostly dropped words and typos. For 37 paragraphs an earlier round was chosen by hand, because the last round read badly. In 11 paragraphs a word or two changed when two posts became three. The opening sentence of the second and third posts was shortened by hand. A fact check then corrected 12 paragraphs in all three versions, and in this version a further 31 sentences in 26 paragraphs where the meaning had drifted from the plain text.</span><span class="v-prompt">You are reading the version a chat model wrote with 22 of my old posts in its system prompt, and no training at all. It is the second technique, described in the first post. It was not checked against the plain version, so its asides and small additions are the model's own. Twelve paragraphs rewritten this way scored 100% AI.</span></p>

<p class="v-plain">This post was written with AI. A chat model produced a plain version of every paragraph, and then a second, much smaller model rewrote each paragraph so that it sounds like the author. That second model was trained on things the author wrote years ago. The switch at the top of the page changes the whole text between the versions, so each can be read in full.</p>
<p class="v-tuned">This post was written with AI. I first got a chat model to output a plain version of each paragraph, and then got another - much smaller - model to rewrite each paragraph to sound like me. The second model was trained on things I wrote years ago. The switch at the top of the page swaps the whole text between the versions, allowing you to read each fully.</p>
<p class="v-prompt">This post was written with AI. A chat model produced a plain version of every paragraph, and then a second, much smaller model rewrote each paragraph so that it sounds like the author (that's me!). That second model was trained on things the author wrote years ago. The switch at the top of the page changes the whole text between the versions, so each can be read in full.</p>

<p class="v-plain">This is the first of three posts. This one sets out the idea and tries the simplest technique, which needs no training at all. The <a href="/80000-Words-Of-Me/">second post</a> trains a small model on the author's writing and measures how close it gets. The <a href="/The-Detector-Was-Not-Impressed/">third post</a> puts both in front of an AI detector, and builds the pipeline that was needed to keep the facts straight.</p>
<p class="v-tuned">This is the first of three posts. In this one I will try out the simplest technique, which requires no training at all. In the <a href="/80000-Words-Of-Me/">second post</a> I will train a small model on my own writing and measure how close it gets. In the <a href="/The-Detector-Was-Not-Impressed/">third post</a> I will put both in front of an AI detector and I will build the pipeline that I needed to keep the facts straight.</p>
<p class="v-prompt">This is the first of three posts. In this one I will set out the idea and try the simplest technique, which needs no training at all. In the <a href="/80000-Words-Of-Me/">second post</a> we will train a small model on the author's writing and measure how close it gets. In the <a href="/The-Detector-Was-Not-Impressed/">third post</a> we will put both in front of an AI detector, and I will show you the pipeline we needed to keep the facts straight.</p>

<p><em>This is part 1 of three.</em></p>

<ol>
  <li><strong>I Didn’t Write This Post</strong>: the idea, and the easy way (this post)</li>
  <li><a href="/80000-Words-Of-Me/">80,000 Words of Me</a>: training a model on my own writing</li>
  <li><a href="/The-Detector-Was-Not-Impressed/">The Detector Was Not Impressed</a>: the detector and the pipeline</li>
</ol>

<p><em>The code for all three posts is on GitHub: <a href="https://github.com/cloudmark/in-my-voice">cloudmark/in-my-voice</a>.</em></p>

<h2 id="three-techniques">Three techniques</h2>

<p class="v-plain">These three posts compare three ways of producing text in the voice of one person. Each one sits behind a position of the switch at the top, so the same paragraph can be read all three ways.</p>
<p class="v-tuned">These three posts compare the three methods of producing text in the voice of one person. Each of the three methods is situated behind one position of the switch at the top and thus we can read the same paragraph through all three.</p>
<p class="v-prompt">These three posts compare three ways of producing text in the voice of one person. Each one sits behind a position of the switch at the top, so the same paragraph can be read all three ways. Pretty neat huh?!</p>

<p class="v-plain"><strong>Plain AI.</strong> A chat model writes the text, with no attempt at a voice. This is the starting point, and it is what the other two are measured against. Every paragraph of all three posts began this way.</p>
<p class="v-tuned"><strong>Plain AI.</strong> A chat model will write the text, no attempt at a voice. This is where it starts, and this is what the other two are measured against. Every paragraph of all three posts started this way.</p>
<p class="v-prompt"><strong>Plain AI.</strong> A chat model writes the text, with no attempt at a voice. This is our starting point, and it is what the other two are measured against. Every paragraph of all three posts began this way.</p>

<p class="v-plain"><strong>Posts in the prompt.</strong> The same kind of chat model is first shown 22 of the author's old posts, about 24,000 words, in its system prompt. It is then asked to rewrite each plain paragraph in that voice while keeping every fact. Nothing is trained, and it takes seconds.</p>
<p class="v-tuned"><strong>Posts in the prompt.</strong> First we show 22 of the author's old posts, about 24,000 words, in the model's system prompt. We ask the same kind of chat model to rewrite each plain paragraph in that voice while keeping every fact. Nothing is trained, and it takes seconds.</p>
<p class="v-prompt"><strong>Posts in the prompt.</strong> The same kind of chat model is first shown 22 of the author's old posts - about 24,000 words - in its system prompt. It is then asked to rewrite each plain paragraph in that voice whilst keeping every fact. Nothing is trained and it takes seconds.</p>

<p class="v-plain"><strong>In my voice.</strong> A small base model is trained on pairs of text, so that it turns a bland paragraph into one the author might have written. It then rewrites each plain paragraph ten times over, with guards on every round and a check against the plain version at the end. This is the technique that most of these three posts are about.</p>
<p class="v-tuned"><strong>In my voice.</strong> A small base model is trained on text pairs, so that it can turn a bland paragraph into something the author might have written. Once trained it rewrites each plain paragraph ten times (with guards on each round and checks against the plain version at the end). This is the technique that most of these three posts are about.</p>
<p class="v-prompt"><strong>In my voice.</strong> A small base model is trained on pairs of text, so that it turns a bland paragraph into one the author might have written. It then rewrites each plain paragraph ten times over, with guards on every round and a check against the plain version at the end. This is the technique that most of these three posts are about.</p>

<p class="v-plain">This post covers the second technique, because it is the easiest one to try. The <a href="/80000-Words-Of-Me/">second post</a> covers the training behind the third technique. The <a href="/The-Detector-Was-Not-Impressed/">third post</a> covers the detector, the pipeline around the trained model, and the comparison between all three.</p>
<p class="v-tuned">In this post we will cover the second technique, this one is the easiest to attempt. The <a href="/80000-Words-Of-Me/">second post</a> will discuss the training required for the third technique. Finally, in the <a href="/The-Detector-Was-Not-Impressed/">third post</a> we will cover the detector, the pipeline around the trained model and a comparison of all three.</p>
<p class="v-prompt">In this post we will cover the second technique, because it is the easiest one to try. The <a href="/80000-Words-Of-Me/">second post</a> covers the training behind the third technique. The <a href="/The-Detector-Was-Not-Impressed/">third post</a> covers the detector, the pipeline around the trained model, and the comparison between all three.</p>

<h2 id="why-bother">Why bother</h2>

<p class="v-plain">Text produced by chat models has a recognisable voice. The sentences are balanced, the vocabulary is polished, and nothing is ever slightly wrong. Readers notice this, and so do AI detectors. The question behind this experiment was simple: can a model learn the voice of one specific person, given only a modest amount of that person's writing?</p>
<p class="v-tuned">The text from the Chat models has a recognisable voice. The text is well balanced, the vocabulary is polished and nothing is ever a little bit wrong. Readers can tell and so can AI detectors. The question which I am trying to answer through this experiment is simple; Can a model learn the voice of a particular person just by observing some text written by that person?</p>
<p class="v-prompt">Text produced by chat models has a recognisable voice. The sentences are balanced, the vocabulary is polished, and nothing is ever slightly wrong. Readers notice this and so do AI detectors. The question behind this experiment was simple: can a model learn the voice of one specific person, given only a modest amount of that person's writing?</p>

<p class="v-plain">The first attempts used prompts. A chat model was asked to rewrite a passage so that it read as if a person had written it, with light rewrites, heavy rewrites and a spoken style. Three models were tried, including a 397 billion parameter model running locally. The wording changed but the voice did not, and GPTZero scored every one of these rewrites as 100% AI.</p>
<p class="v-tuned">First attempts - we tried prompts. We asked a chat model to rewrite a passage in such a way that it is as if a person wrote it. We tried out light, heavy and spoken style. We tried out three different models - one of the three was a 397 billion parameter model running locally. The wording changed but the voice did not, and GPTZero scored all these rewrites as 100% AI.</p>
<p class="v-prompt">My first attempts used prompts. I asked a chat model to rewrite a passage so that it read as if a person had written it - light rewrites, heavy rewrites and a spoken style. I tried three models, including a 397 billion parameter model running locally. The wording changed but the voice did not, and GPTZero scored every one of these rewrites as 100% AI. Ouch!</p>

<h2 id="the-easy-way-posts-in-the-prompt">The easy way: posts in the prompt</h2>

<p class="v-plain">The first serious attempt needs no training. A chat model can be given a lot of the author's writing to read before it is asked to do anything. So 22 of the author's old posts, about 24,000 words, were placed in the system prompt. That is the part of a conversation which the model reads first and treats as standing instructions. All of these posts were written before chat models existed, so every word in them is the author's own.</p>
<p class="v-tuned">The first serious attempt needs no training. A chat model can be provided with a lot of the authors writing to read and then it can be asked to do something. So 22 of the authors old posts (about 24,000 words) were provided in the system prompt. System prompt is part of a conversation which the model reads first and treats as standing instructions. All of these posts were written before chat models existed, so every word in them is the authors own.</p>
<p class="v-prompt">The first serious attempt needs no training. A chat model can be given a lot of the author's writing to read before it is asked to do anything. So we took 22 of the author's old posts, about 24,000 words, and placed them in the system prompt. This is the part of a conversation which the model reads first and treats as standing instructions. All of these posts were written before chat models existed, so every word in them is the author's own.</p>

<p class="v-plain">After the posts came one instruction, shown below. The model was then given plain paragraphs and asked to rewrite each one. Three chat models were tried in exactly the same way: Qwen 4 Max, Claude Sonnet 5.5 and GPT-5.6 Luna.</p>
<p class="v-tuned">After the posts came one instruction, presented below. Then the plain paragraphs are given to the model and it is asked to rewrite each of these. Three chat models were attempted in the same manner: Qwen 4 Max, Claude Sonnet 5.5 and GPT-5.6 Luna.</p>
<p class="v-prompt">After the posts came one instruction, shown below. We then gave the model plain paragraphs and asked it to rewrite each one. We tried three chat models in exactly the same way: Qwen 4 Max, Claude Sonnet 5.5 and GPT-5.6 Luna.</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Below are blog posts written by one author. Study how this author writes: word choice,
sentence rhythm, how they address the reader, their small habits and imperfections.

You will then be given numbered paragraphs written in a neutral style. Rewrite each one so
that it reads as if this author had written it. Keep every fact, number, name and technical
term exactly. Keep one output paragraph per input paragraph, of similar length.

=== THE AUTHOR'S POSTS ===

(22 posts, about 24,000 words)
</code></pre></div></div>

<h2 id="does-it-sound-like-me">Does it sound like me</h2>

<p class="v-plain">To judge a voice, two texts are needed that say the same thing: one by the model and one by the author. So 50 paragraphs from the old posts were set aside and left out of the prompt. A chat model wrote a bland version of each of them, with the same facts and none of the style. Each of the three models was then asked to rewrite the bland versions, and the results were compared with what the author had really written.</p>
<p class="v-tuned">To judge a voice we need two text which convey the same information - one authored by the model and the other by the author. 50 paragraphs from the old posts were set aside and excluded from the prompt. Then a chat model was asked to write a bland version of each of them - the same facts but none of the style. Each of the three models was asked to rewrite the bland versions. The results were then compared with what the author had really written.</p>
<p class="v-prompt">To judge a voice we need two texts that say the same thing: one by the model and one by the author. So I set aside 50 paragraphs from the old posts and left them out of the prompt. A chat model wrote a bland version of each of them, with the same facts and none of the style. We then asked each of the three models to rewrite the bland versions and compared the results with what the author had really written.</p>

<p class="v-plain">A voice is partly made of small habits, and habits can be counted. The author says we constantly: 29.5 times in every 1,000 words. The bland versions use it 5.1 times. With the posts in the prompt, the three models use it 28.4, 25.5 and 20.7 times. Two of the models also move towards the author on I, and on contractions, which are short forms such as don't and it's, though not as far. The third, GPT-5.6 Luna, hardly moves on either.</p>
<p class="v-tuned">A voice is partly made of small habits. And habits can be counted. The author says we constantly: 29.5 times in every 1,000 words. The bland versions use it 5.1 times. With the posts in the prompt the three models use it 28.4, 25.5 and 20.7 times. Two of the models also move towards the author on I and on contractions such as don't and it's, though not as far. The third, GPT-5.6 Luna, hardly moves on either.</p>
<p class="v-prompt">A voice is partly made of small habits, and habits can be counted. The author says we constantly: 29.5 times in every 1,000 words. The bland versions use it 5.1 times. With the posts in the prompt, the three models use it 28.4, 25.5 and 20.7 times. Two of the models also move towards the author on I, and on contractions, which are short forms such as don't and it's, though not as far. The third, GPT-5.6 Luna, hardly moves on either.</p>

<figure class="chart " role="group" aria-label="Dot chart of five writing habits in the bland version and in three chat models with the posts in the prompt, against the author&#x27;s own rate">
<figcaption><strong>With my posts in the prompt the models move towards me, and two overdo the exclamation marks</strong><span>Five habits in four versions of the same 50 paragraphs, as a multiple of my own rate. A dot on the line at 1 uses the habit exactly as often as I do. The models all read my posts first; the bland version did not.</span></figcaption>
<ul class="legend"><li><i style="background:#b9b8b3"></i>Bland version</li><li><i style="background:#2a78d6"></i>Qwen 4 Max</li><li><i style="background:#eb6834"></i>Claude Sonnet 5.5</li><li><i style="background:#1baf7a"></i>GPT-5.6 Luna</li></ul>
<svg viewBox="0 0 640 206" role="img" aria-label="Dot chart of five writing habits in the bland version and in three chat models with the posts in the prompt, against the author&#x27;s own rate">
<line class="grid" x1="170.0" y1="20" x2="170.0" y2="178" /><text class="s" x="170.0" y="196" text-anchor="middle">0×</text>
<line class="dash" x1="244.3" y1="20" x2="244.3" y2="178" /><text class="s" x="244.3" y="196" text-anchor="middle">0.5×</text>
<line class="dash" x1="318.7" y1="20" x2="318.7" y2="178" /><text class="s" x="318.7" y="196" text-anchor="middle">1×</text>
<line class="dash" x1="393.0" y1="20" x2="393.0" y2="178" /><text class="s" x="393.0" y="196" text-anchor="middle">1.5×</text>
<line class="dash" x1="467.3" y1="20" x2="467.3" y2="178" /><text class="s" x="467.3" y="196" text-anchor="middle">2×</text>
<line class="dash" x1="541.7" y1="20" x2="541.7" y2="178" /><text class="s" x="541.7" y="196" text-anchor="middle">2.5×</text>
<line class="dash" x1="616.0" y1="20" x2="616.0" y2="178" /><text class="s" x="616.0" y="196" text-anchor="middle">3×</text>
<line x1="318.7" y1="20" x2="318.7" y2="178" stroke="var(--ink)" stroke-width="2" /><text class="v" x="325.7" y="14">my own rate</text>
<text class="t" x="156" y="46.0" text-anchor="end" font-weight="600">&quot;we&quot;</text>
<line x1="195.7" y1="41.0" x2="318.7" y2="41.0" stroke="var(--line)" stroke-width="2" />
<circle cx="195.7" cy="41.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="195.7" cy="41.0" r="11" tabindex="0" data-tip="0.17× my own rate|“&quot;we&quot;” in bland version — I use it 29.5 times per 1,000 words" />
<circle cx="313.1" cy="41.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="313.1" cy="41.0" r="11" tabindex="0" data-tip="0.96× my own rate|“&quot;we&quot;” in qwen 4 max — I use it 29.5 times per 1,000 words" />
<circle cx="298.5" cy="41.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="298.5" cy="41.0" r="11" tabindex="0" data-tip="0.86× my own rate|“&quot;we&quot;” in claude sonnet 5.5 — I use it 29.5 times per 1,000 words" />
<circle cx="274.3" cy="41.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="274.3" cy="41.0" r="11" tabindex="0" data-tip="0.70× my own rate|“&quot;we&quot;” in gpt-5.6 luna — I use it 29.5 times per 1,000 words" />
<text class="t" x="156" y="76.0" text-anchor="end" font-weight="600">&quot;I&quot;</text>
<line x1="192.9" y1="71.0" x2="318.7" y2="71.0" stroke="var(--line)" stroke-width="2" />
<circle cx="192.9" cy="71.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="192.9" cy="71.0" r="11" tabindex="0" data-tip="0.15× my own rate|“&quot;I&quot;” in bland version — I use it 2.6 times per 1,000 words" />
<circle cx="278.6" cy="71.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="278.6" cy="71.0" r="11" tabindex="0" data-tip="0.73× my own rate|“&quot;I&quot;” in qwen 4 max — I use it 2.6 times per 1,000 words" />
<circle cx="232.9" cy="71.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="232.9" cy="71.0" r="11" tabindex="0" data-tip="0.42× my own rate|“&quot;I&quot;” in claude sonnet 5.5 — I use it 2.6 times per 1,000 words" />
<circle cx="210.0" cy="71.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="210.0" cy="71.0" r="11" tabindex="0" data-tip="0.27× my own rate|“&quot;I&quot;” in gpt-5.6 luna — I use it 2.6 times per 1,000 words" />
<text class="t" x="156" y="106.0" text-anchor="end" font-weight="600">Contractions</text>
<line x1="187.5" y1="101.0" x2="318.7" y2="101.0" stroke="var(--line)" stroke-width="2" />
<circle cx="187.5" cy="101.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="187.5" cy="101.0" r="11" tabindex="0" data-tip="0.12× my own rate|“Contractions” in bland version — I use it 3.4 times per 1,000 words" />
<circle cx="235.6" cy="101.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="235.6" cy="101.0" r="11" tabindex="0" data-tip="0.44× my own rate|“Contractions” in qwen 4 max — I use it 3.4 times per 1,000 words" />
<circle cx="301.2" cy="101.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="301.2" cy="101.0" r="11" tabindex="0" data-tip="0.88× my own rate|“Contractions” in claude sonnet 5.5 — I use it 3.4 times per 1,000 words" />
<circle cx="187.5" cy="101.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="187.5" cy="101.0" r="11" tabindex="0" data-tip="0.12× my own rate|“Contractions” in gpt-5.6 luna — I use it 3.4 times per 1,000 words" />
<text class="t" x="156" y="136.0" text-anchor="end" font-weight="600">&quot;so&quot;, &quot;hence&quot;, &quot;thus&quot;</text>
<line x1="202.1" y1="131.0" x2="383.0" y2="131.0" stroke="var(--line)" stroke-width="2" />
<circle cx="202.1" cy="131.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="202.1" cy="131.0" r="11" tabindex="0" data-tip="0.22× my own rate|“&quot;so&quot;, &quot;hence&quot;, &quot;thus&quot;” in bland version — I use it 3.7 times per 1,000 words" />
<circle cx="383.0" cy="131.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="383.0" cy="131.0" r="11" tabindex="0" data-tip="1.43× my own rate|“&quot;so&quot;, &quot;hence&quot;, &quot;thus&quot;” in qwen 4 max — I use it 3.7 times per 1,000 words" />
<circle cx="334.7" cy="131.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="334.7" cy="131.0" r="11" tabindex="0" data-tip="1.11× my own rate|“&quot;so&quot;, &quot;hence&quot;, &quot;thus&quot;” in claude sonnet 5.5 — I use it 3.7 times per 1,000 words" />
<circle cx="318.7" cy="131.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="318.7" cy="131.0" r="11" tabindex="0" data-tip="1.00× my own rate|“&quot;so&quot;, &quot;hence&quot;, &quot;thus&quot;” in gpt-5.6 luna — I use it 3.7 times per 1,000 words" />
<text class="t" x="156" y="166.0" text-anchor="end" font-weight="600">Exclamation marks</text>
<line x1="170.0" y1="161.0" x2="616.0" y2="161.0" stroke="var(--line)" stroke-width="2" />
<circle cx="170.0" cy="161.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="170.0" cy="161.0" r="11" tabindex="0" data-tip="0.00× my own rate|“Exclamation marks” in bland version — I use it 0.7 times per 1,000 words" />
<text class="s" x="606.0" y="152.0" text-anchor="end">off the scale: 4.3×</text>
<circle cx="616.0" cy="161.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="616.0" cy="161.0" r="11" tabindex="0" data-tip="4.29× my own rate|“Exclamation marks” in qwen 4 max — I use it 0.7 times per 1,000 words" />
<circle cx="573.5" cy="161.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="573.5" cy="161.0" r="11" tabindex="0" data-tip="2.71× my own rate|“Exclamation marks” in claude sonnet 5.5 — I use it 0.7 times per 1,000 words" />
<circle cx="170.0" cy="161.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="170.0" cy="161.0" r="11" tabindex="0" data-tip="0.00× my own rate|“Exclamation marks” in gpt-5.6 luna — I use it 0.7 times per 1,000 words" />
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th>On the 50 paragraphs set aside, per 1,000 words</th>
      <th>Bland version</th>
      <th>Qwen 4 Max</th>
      <th>Claude Sonnet 5.5</th>
      <th>GPT-5.6 Luna</th>
      <th>What I really wrote</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>“we”</td>
      <td>5.1</td>
      <td>28.4</td>
      <td>25.5</td>
      <td>20.7</td>
      <td>29.5</td>
    </tr>
    <tr>
      <td>“I”</td>
      <td>0.4</td>
      <td>1.9</td>
      <td>1.1</td>
      <td>0.7</td>
      <td>2.6</td>
    </tr>
    <tr>
      <td>Contractions</td>
      <td>0.4</td>
      <td>1.5</td>
      <td>3.0</td>
      <td>0.4</td>
      <td>3.4</td>
    </tr>
    <tr>
      <td>“so”, “hence”, “thus”</td>
      <td>0.8</td>
      <td>5.3</td>
      <td>4.1</td>
      <td>3.7</td>
      <td>3.7</td>
    </tr>
    <tr>
      <td>Exclamation marks</td>
      <td>0.0</td>
      <td>3.0</td>
      <td>1.9</td>
      <td>0.0</td>
      <td>0.7</td>
    </tr>
  </tbody>
</table>

<p class="v-plain">It is not perfect. Two of the models use exclamation marks three to four times as often as the author does, and they add little asides that the author never wrote. But on the habits a reader would notice, the simple technique works.</p>
<p class="v-tuned">It is not perfect. Two of the models use the exclamation mark three to four times as much as the author does and add little asides which the author never wrote. But on the habits a reader would notice, this simple technique works.</p>
<p class="v-prompt">It is not perfect. Two of the models use exclamation marks three to four times as often as the author does, and they add little asides that the author never wrote. But on the habits a reader would notice, the simple technique works.</p>

<h2 id="a-stricter-test-the-common-words">A stricter test: the common words</h2>

<p class="v-plain">Counting we and I is a narrow test, because those are habits a model can copy on purpose. A stricter test looks at words nobody thinks about. Every writer uses the small common words, such as the, of, which and so, at rates of their own. Nobody chooses these rates, and they do not depend on the subject, so they work like a fingerprint.</p>
<p class="v-tuned">Counting we and I is a narrow test - we and I are habits which a model can reproduce on purpose. A stricter test includes words which no-one really thinks about. Every writer uses small common words such as the, of, which and so on at their own rates. No one chooses these rates and they do not depend on the subject. They work as a fingerprint.</p>
<p class="v-prompt">Counting we and I is a narrow test, because those are habits a model can pick up on purpose. A stricter test looks at the words nobody thinks about. Every writer uses the small common words - the, of, which, so - at rates of their own. Nobody chooses these rates and they do not depend on the subject, so they work like a fingerprint.</p>

<p class="v-plain">To build the fingerprint, take the old posts and find the 150 words the author uses most often. For each word, work out what share of all the words it takes up. The most common one is the, which is 7.2% of everything the author wrote, and we is 2.3%. The result is a list of 150 shares. The same list can be made for any other text, by counting the same 150 words in it.</p>
<p class="v-tuned">To build the fingerprint, take the old posts and find the 150 words the author uses most often. For each word, work out what share of all the words it takes up. The most common one is the - it’s 7.2% of everything the author wrote and we is 2.3%. The result is a list of 150 shares. The same list can be made for any other text, by counting the same 150 words in it.</p>
<p class="v-prompt">To build the fingerprint we take the old posts and find the 150 words the author uses most often. For each word we work out what share of all the words it takes up. The most common one is the, which is 7.2% of everything the author wrote, and we is 2.3%. What we end up with is a list of 150 shares. The same list can be made for any other text by counting the same 150 words in it.</p>

<p class="v-plain">The chart below shows twelve of the 150 words. For each word, the usual share of the author is set to 1. A dot at 2 means that the text uses the word twice as often as the author usually does, and a dot at 0.5 means half as often.</p>
<p class="v-tuned">The chart below contains twelve of the 150 words. Each word will have the usual share set to 1. A dot at 2 means that the text uses the word twice as much as usual, and a dot at 0.5 means that the text uses the word half as much as usual.</p>
<p class="v-prompt">The chart below shows twelve of the 150 words. For each word the usual share of the author is set to 1. A dot at 2 means the text uses the word twice as often as the author usually does, and a dot at 0.5 means half as often.</p>

<figure class="chart " role="group" aria-label="Dot chart of twelve common words in the bland version and in three chat models with the posts in the prompt, against the author&#x27;s usual rate">
<figcaption><strong>The bland text scatters; with my posts in the prompt the models close in</strong><span>How often each text uses twelve common words, as a multiple of my usual rate. Dots near the line at 1 use the word as I do.</span></figcaption>
<ul class="legend"><li><i style="background:#b9b8b3"></i>Bland version</li><li><i style="background:#2a78d6"></i>Qwen 4 Max</li><li><i style="background:#eb6834"></i>Claude Sonnet 5.5</li><li><i style="background:#1baf7a"></i>GPT-5.6 Luna</li></ul>
<svg viewBox="0 0 640 416" role="img" aria-label="Dot chart of twelve common words in the bland version and in three chat models with the posts in the prompt, against the author&#x27;s usual rate">
<line class="grid" x1="90.0" y1="20" x2="90.0" y2="388" /><text class="s" x="90.0" y="406" text-anchor="middle">0×</text>
<line class="dash" x1="195.2" y1="20" x2="195.2" y2="388" /><text class="s" x="195.2" y="406" text-anchor="middle">0.5×</text>
<line class="dash" x1="300.4" y1="20" x2="300.4" y2="388" /><text class="s" x="300.4" y="406" text-anchor="middle">1×</text>
<line class="dash" x1="405.6" y1="20" x2="405.6" y2="388" /><text class="s" x="405.6" y="406" text-anchor="middle">1.5×</text>
<line class="dash" x1="510.8" y1="20" x2="510.8" y2="388" /><text class="s" x="510.8" y="406" text-anchor="middle">2×</text>
<line class="dash" x1="616.0" y1="20" x2="616.0" y2="388" /><text class="s" x="616.0" y="406" text-anchor="middle">2.5×</text>
<line x1="300.4" y1="20" x2="300.4" y2="388" stroke="var(--ink)" stroke-width="2" /><text class="v" x="307.4" y="14">my usual rate</text>
<text class="t" x="76" y="46.0" text-anchor="end" font-weight="600">the</text>
<line x1="273.0" y1="41.0" x2="300.4" y2="41.0" stroke="var(--line)" stroke-width="2" />
<circle cx="283.6" cy="41.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="283.6" cy="41.0" r="11" tabindex="0" data-tip="0.92× my usual rate|“the” in bland version — 7.2% of my words" />
<circle cx="273.0" cy="41.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="273.0" cy="41.0" r="11" tabindex="0" data-tip="0.87× my usual rate|“the” in qwen 4 max — 7.2% of my words" />
<circle cx="275.2" cy="41.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="275.2" cy="41.0" r="11" tabindex="0" data-tip="0.88× my usual rate|“the” in claude sonnet 5.5 — 7.2% of my words" />
<circle cx="273.0" cy="41.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="273.0" cy="41.0" r="11" tabindex="0" data-tip="0.87× my usual rate|“the” in gpt-5.6 luna — 7.2% of my words" />
<text class="t" x="76" y="76.0" text-anchor="end" font-weight="600">to</text>
<line x1="270.9" y1="71.0" x2="321.4" y2="71.0" stroke="var(--line)" stroke-width="2" />
<circle cx="296.2" cy="71.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="296.2" cy="71.0" r="11" tabindex="0" data-tip="0.98× my usual rate|“to” in bland version — 3.19% of my words" />
<circle cx="270.9" cy="71.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="270.9" cy="71.0" r="11" tabindex="0" data-tip="0.86× my usual rate|“to” in qwen 4 max — 3.19% of my words" />
<circle cx="287.8" cy="71.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="287.8" cy="71.0" r="11" tabindex="0" data-tip="0.94× my usual rate|“to” in claude sonnet 5.5 — 3.19% of my words" />
<circle cx="321.4" cy="71.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="321.4" cy="71.0" r="11" tabindex="0" data-tip="1.10× my usual rate|“to” in gpt-5.6 luna — 3.19% of my words" />
<text class="t" x="76" y="106.0" text-anchor="end" font-weight="600">is</text>
<line x1="283.6" y1="101.0" x2="315.1" y2="101.0" stroke="var(--line)" stroke-width="2" />
<circle cx="289.9" cy="101.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="289.9" cy="101.0" r="11" tabindex="0" data-tip="0.95× my usual rate|“is” in bland version — 2.06% of my words" />
<circle cx="294.1" cy="101.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="294.1" cy="101.0" r="11" tabindex="0" data-tip="0.97× my usual rate|“is” in qwen 4 max — 2.06% of my words" />
<circle cx="315.1" cy="101.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="315.1" cy="101.0" r="11" tabindex="0" data-tip="1.07× my usual rate|“is” in claude sonnet 5.5 — 2.06% of my words" />
<circle cx="283.6" cy="101.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="283.6" cy="101.0" r="11" tabindex="0" data-tip="0.92× my usual rate|“is” in gpt-5.6 luna — 2.06% of my words" />
<text class="t" x="76" y="136.0" text-anchor="end" font-weight="600">we</text>
<line x1="136.3" y1="131.0" x2="348.8" y2="131.0" stroke="var(--line)" stroke-width="2" />
<circle cx="136.3" cy="131.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="136.3" cy="131.0" r="11" tabindex="0" data-tip="0.22× my usual rate|“we” in bland version — 2.32% of my words" />
<circle cx="348.8" cy="131.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="348.8" cy="131.0" r="11" tabindex="0" data-tip="1.23× my usual rate|“we” in qwen 4 max — 2.32% of my words" />
<circle cx="321.4" cy="131.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="321.4" cy="131.0" r="11" tabindex="0" data-tip="1.10× my usual rate|“we” in claude sonnet 5.5 — 2.32% of my words" />
<circle cx="279.4" cy="131.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="279.4" cy="131.0" r="11" tabindex="0" data-tip="0.90× my usual rate|“we” in gpt-5.6 luna — 2.32% of my words" />
<text class="t" x="76" y="166.0" text-anchor="end" font-weight="600">in</text>
<line x1="199.4" y1="161.0" x2="300.4" y2="161.0" stroke="var(--line)" stroke-width="2" />
<circle cx="199.4" cy="161.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="199.4" cy="161.0" r="11" tabindex="0" data-tip="0.52× my usual rate|“in” in bland version — 1.96% of my words" />
<circle cx="239.4" cy="161.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="239.4" cy="161.0" r="11" tabindex="0" data-tip="0.71× my usual rate|“in” in qwen 4 max — 1.96% of my words" />
<circle cx="254.1" cy="161.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="254.1" cy="161.0" r="11" tabindex="0" data-tip="0.78× my usual rate|“in” in claude sonnet 5.5 — 1.96% of my words" />
<circle cx="245.7" cy="161.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="245.7" cy="161.0" r="11" tabindex="0" data-tip="0.74× my usual rate|“in” in gpt-5.6 luna — 1.96% of my words" />
<text class="t" x="76" y="196.0" text-anchor="end" font-weight="600">will</text>
<line x1="201.5" y1="191.0" x2="300.4" y2="191.0" stroke="var(--line)" stroke-width="2" />
<circle cx="201.5" cy="191.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="201.5" cy="191.0" r="11" tabindex="0" data-tip="0.53× my usual rate|“will” in bland version — 1.26% of my words" />
<circle cx="216.2" cy="191.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="216.2" cy="191.0" r="11" tabindex="0" data-tip="0.60× my usual rate|“will” in qwen 4 max — 1.26% of my words" />
<circle cx="233.1" cy="191.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="233.1" cy="191.0" r="11" tabindex="0" data-tip="0.68× my usual rate|“will” in claude sonnet 5.5 — 1.26% of my words" />
<circle cx="275.2" cy="191.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="275.2" cy="191.0" r="11" tabindex="0" data-tip="0.88× my usual rate|“will” in gpt-5.6 luna — 1.26% of my words" />
<text class="t" x="76" y="226.0" text-anchor="end" font-weight="600">which</text>
<line x1="123.7" y1="221.0" x2="428.7" y2="221.0" stroke="var(--line)" stroke-width="2" />
<circle cx="123.7" cy="221.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="123.7" cy="221.0" r="11" tabindex="0" data-tip="0.16× my usual rate|“which” in bland version — 0.74% of my words" />
<circle cx="388.8" cy="221.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="388.8" cy="221.0" r="11" tabindex="0" data-tip="1.42× my usual rate|“which” in qwen 4 max — 0.74% of my words" />
<circle cx="428.7" cy="221.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="428.7" cy="221.0" r="11" tabindex="0" data-tip="1.61× my usual rate|“which” in claude sonnet 5.5 — 0.74% of my words" />
<circle cx="424.5" cy="221.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="424.5" cy="221.0" r="11" tabindex="0" data-tip="1.59× my usual rate|“which” in gpt-5.6 luna — 0.74% of my words" />
<text class="t" x="76" y="256.0" text-anchor="end" font-weight="600">be</text>
<line x1="226.8" y1="251.0" x2="424.5" y2="251.0" stroke="var(--line)" stroke-width="2" />
<circle cx="424.5" cy="251.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="424.5" cy="251.0" r="11" tabindex="0" data-tip="1.59× my usual rate|“be” in bland version — 0.64% of my words" />
<circle cx="226.8" cy="251.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="226.8" cy="251.0" r="11" tabindex="0" data-tip="0.65× my usual rate|“be” in qwen 4 max — 0.64% of my words" />
<circle cx="275.2" cy="251.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="275.2" cy="251.0" r="11" tabindex="0" data-tip="0.88× my usual rate|“be” in claude sonnet 5.5 — 0.64% of my words" />
<circle cx="380.4" cy="251.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="380.4" cy="251.0" r="11" tabindex="0" data-tip="1.38× my usual rate|“be” in gpt-5.6 luna — 0.64% of my words" />
<text class="t" x="76" y="286.0" text-anchor="end" font-weight="600">have</text>
<line x1="102.6" y1="281.0" x2="300.4" y2="281.0" stroke="var(--line)" stroke-width="2" />
<circle cx="102.6" cy="281.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="102.6" cy="281.0" r="11" tabindex="0" data-tip="0.06× my usual rate|“have” in bland version — 0.61% of my words" />
<circle cx="273.0" cy="281.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="273.0" cy="281.0" r="11" tabindex="0" data-tip="0.87× my usual rate|“have” in qwen 4 max — 0.61% of my words" />
<circle cx="245.7" cy="281.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="245.7" cy="281.0" r="11" tabindex="0" data-tip="0.74× my usual rate|“have” in claude sonnet 5.5 — 0.61% of my words" />
<circle cx="153.1" cy="281.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="153.1" cy="281.0" r="11" tabindex="0" data-tip="0.30× my usual rate|“have” in gpt-5.6 luna — 0.61% of my words" />
<text class="t" x="76" y="316.0" text-anchor="end" font-weight="600">our</text>
<line x1="180.5" y1="311.0" x2="350.9" y2="311.0" stroke="var(--line)" stroke-width="2" />
<circle cx="180.5" cy="311.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="180.5" cy="311.0" r="11" tabindex="0" data-tip="0.43× my usual rate|“our” in bland version — 0.55% of my words" />
<circle cx="350.9" cy="311.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="350.9" cy="311.0" r="11" tabindex="0" data-tip="1.24× my usual rate|“our” in qwen 4 max — 0.55% of my words" />
<circle cx="218.3" cy="311.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="218.3" cy="311.0" r="11" tabindex="0" data-tip="0.61× my usual rate|“our” in claude sonnet 5.5 — 0.55% of my words" />
<circle cx="203.6" cy="311.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="203.6" cy="311.0" r="11" tabindex="0" data-tip="0.54× my usual rate|“our” in gpt-5.6 luna — 0.55% of my words" />
<text class="t" x="76" y="346.0" text-anchor="end" font-weight="600">from</text>
<line x1="188.9" y1="341.0" x2="300.4" y2="341.0" stroke="var(--line)" stroke-width="2" />
<circle cx="195.2" cy="341.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="195.2" cy="341.0" r="11" tabindex="0" data-tip="0.50× my usual rate|“from” in bland version — 0.47% of my words" />
<circle cx="241.5" cy="341.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="241.5" cy="341.0" r="11" tabindex="0" data-tip="0.72× my usual rate|“from” in qwen 4 max — 0.47% of my words" />
<circle cx="239.4" cy="341.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="239.4" cy="341.0" r="11" tabindex="0" data-tip="0.71× my usual rate|“from” in claude sonnet 5.5 — 0.47% of my words" />
<circle cx="188.9" cy="341.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="188.9" cy="341.0" r="11" tabindex="0" data-tip="0.47× my usual rate|“from” in gpt-5.6 luna — 0.47% of my words" />
<text class="t" x="76" y="376.0" text-anchor="end" font-weight="600">it</text>
<line x1="300.4" y1="371.0" x2="607.6" y2="371.0" stroke="var(--line)" stroke-width="2" />
<circle cx="578.1" cy="371.0" r="6" fill="#b9b8b3" stroke="#fff" stroke-width="2" /><circle class="hit" cx="578.1" cy="371.0" r="11" tabindex="0" data-tip="2.32× my usual rate|“it” in bland version — 0.46% of my words" />
<circle cx="472.9" cy="371.0" r="6" fill="#2a78d6" stroke="#fff" stroke-width="2" /><circle class="hit" cx="472.9" cy="371.0" r="11" tabindex="0" data-tip="1.82× my usual rate|“it” in qwen 4 max — 0.46% of my words" />
<circle cx="607.6" cy="371.0" r="6" fill="#eb6834" stroke="#fff" stroke-width="2" /><circle class="hit" cx="607.6" cy="371.0" r="11" tabindex="0" data-tip="2.46× my usual rate|“it” in claude sonnet 5.5 — 0.46% of my words" />
<circle cx="500.3" cy="371.0" r="6" fill="#1baf7a" stroke="#fff" stroke-width="2" /><circle class="hit" cx="500.3" cy="371.0" r="11" tabindex="0" data-tip="1.95× my usual rate|“it” in gpt-5.6 luna — 0.46% of my words" />
</svg>
</figure>

<p class="v-plain">The grey dots are the bland versions, and they are scattered. They use we about a fifth as often as the author, which about a sixth as often, and have almost never. The coloured dots are the three models with the posts in the prompt. On we they sit at 1.23, 1.10 and 0.90, next to the line. They are not perfect here either: all three use which about one and a half times as often as the author does.</p>
<p class="v-tuned">The grey dots are the bland versions and they are scattered. These use we about a fifth as often as the author does, which about a sixth as often and have almost never. The coloured dots are the three models with the posts in the prompt. On we they sit at 1.23, 1.10 and 0.90, next to the line. Note that these are not perfect either here: all three use which about one and a half times as often as the author does.</p>
<p class="v-prompt">The grey dots are the bland versions and they are all over the place. They use we about a fifth as often as the author, which about a sixth as often, and have almost never. The coloured dots are the three models with the posts in the prompt. On we they sit at 1.23, 1.10 and 0.90, right next to the line. They are not perfect here either: all three use which about one and a half times as often as the author does.</p>

<table>
  <thead>
    <tr>
      <th>Word</th>
      <th>Share of my words</th>
      <th>My own 50 paragraphs</th>
      <th>Bland version</th>
      <th>Qwen 4 Max</th>
      <th>Claude Sonnet 5.5</th>
      <th>GPT-5.6 Luna</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>“the”</td>
      <td>7.20%</td>
      <td>0.83×</td>
      <td>0.92×</td>
      <td>0.87×</td>
      <td>0.88×</td>
      <td>0.87×</td>
    </tr>
    <tr>
      <td>“to”</td>
      <td>3.19%</td>
      <td>0.96×</td>
      <td>0.98×</td>
      <td>0.86×</td>
      <td>0.94×</td>
      <td>1.10×</td>
    </tr>
    <tr>
      <td>“is”</td>
      <td>2.06%</td>
      <td>0.98×</td>
      <td>0.95×</td>
      <td>0.97×</td>
      <td>1.07×</td>
      <td>0.92×</td>
    </tr>
    <tr>
      <td>“we”</td>
      <td>2.32%</td>
      <td>1.27×</td>
      <td>0.22×</td>
      <td>1.23×</td>
      <td>1.10×</td>
      <td>0.90×</td>
    </tr>
    <tr>
      <td>“in”</td>
      <td>1.96%</td>
      <td>0.87×</td>
      <td>0.52×</td>
      <td>0.71×</td>
      <td>0.78×</td>
      <td>0.74×</td>
    </tr>
    <tr>
      <td>“will”</td>
      <td>1.26%</td>
      <td>1.07×</td>
      <td>0.53×</td>
      <td>0.60×</td>
      <td>0.68×</td>
      <td>0.88×</td>
    </tr>
    <tr>
      <td>“which”</td>
      <td>0.74%</td>
      <td>1.00×</td>
      <td>0.16×</td>
      <td>1.42×</td>
      <td>1.61×</td>
      <td>1.59×</td>
    </tr>
    <tr>
      <td>“be”</td>
      <td>0.64%</td>
      <td>1.16×</td>
      <td>1.59×</td>
      <td>0.65×</td>
      <td>0.88×</td>
      <td>1.38×</td>
    </tr>
    <tr>
      <td>“have”</td>
      <td>0.61%</td>
      <td>0.86×</td>
      <td>0.06×</td>
      <td>0.87×</td>
      <td>0.74×</td>
      <td>0.30×</td>
    </tr>
    <tr>
      <td>“our”</td>
      <td>0.55%</td>
      <td>1.15×</td>
      <td>0.43×</td>
      <td>1.24×</td>
      <td>0.61×</td>
      <td>0.54×</td>
    </tr>
    <tr>
      <td>“from”</td>
      <td>0.47%</td>
      <td>1.10×</td>
      <td>0.50×</td>
      <td>0.72×</td>
      <td>0.71×</td>
      <td>0.47×</td>
    </tr>
    <tr>
      <td>“it”</td>
      <td>0.46%</td>
      <td>1.80×</td>
      <td>2.32×</td>
      <td>1.82×</td>
      <td>2.46×</td>
      <td>1.95×</td>
    </tr>
  </tbody>
</table>

<p><em>Each figure is the word’s rate in that text divided by its rate in the rest of my old posts. Each text is about 2,600 words, so single words wobble: my own paragraphs are not at 1 either.</em></p>

<p class="v-plain">To compare all 150 words at once, the gaps are added up into one distance. Zero means that a text uses all 150 words at exactly the rates of the author, and a bigger number means it is further away. No two samples of one person match exactly, so the 50 real paragraphs were measured too: they are at a distance of 11.0 from the rest of the old posts. The bland versions are at 27.8. The three models are at 11.6, 12.8 and 13.9. Even on words that nobody chooses, a chat model that has read the posts lands almost as close to the author as the author does. The <a href="/80000-Words-Of-Me/">second post</a> explains how the distance is calculated.</p>
<p class="v-tuned">So in order to compare all 150 words at once we will sum all the gaps together into one distance. Zero implies that the text uses all 150 words at the same rate as the author while larger numbers imply that the text is further away. Note that two samples of the same person never match. We have also measured the 50 real paragraphs, they have a distance of 11.0 from the rest of the old posts. The bland versions are at 27.8. The three models are at 11.6, 12.8 and 13.9. Note that even on words that nobody has chosen a chat model which has read the posts lands almost as close to the author as the author. The <a href="/80000-Words-Of-Me/">second post</a> explains how the distance is calculated.</p>
<p class="v-prompt">To compare all 150 words at once, the gaps are added up into one distance. Zero means a text uses all 150 words at exactly the rates of the author, and a bigger number means it is further away. No two samples of one person match exactly, so the 50 real paragraphs were measured too: they are at a distance of 11.0 from the rest of the old posts. The bland versions are at 27.8. The three models are at 11.6, 12.8 and 13.9. Even on words that nobody chooses, a chat model that has read the posts lands almost as close to the author as the author does. The <a href="/80000-Words-Of-Me/">second post</a> explains how the distance is calculated.</p>

<figure class="chart " role="group" aria-label="Bar chart of common-word distance for the bland version, three chat models and the author">
<figcaption><strong>On common words, the models land almost as close to me as I do</strong><span>Distance between each text and the rest of my old posts, over my 150 most used words. Lower is closer; my own paragraphs mark the best a model can do.</span></figcaption>

<svg viewBox="0 0 640 226" role="img" aria-label="Bar chart of common-word distance for the bland version, three chat models and the author">
<text class="t" x="236" y="31.0" text-anchor="end">Bland version</text>
<rect class="track" x="250" y="15.0" width="330" height="22" rx="6" />
<path d="M250,15.0 h299.8 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-299.8 z" fill="#2a78d6" tabindex="0" data-tip="27.8 (distance over 150 words)|Bland version — chat model, no posts" />
<text class="v" x="564.8" y="31.0">27.8</text>
<text class="t" x="236" y="75.0" text-anchor="end">GPT-5.6 Luna, posts in prompt</text>
<rect class="track" x="250" y="59.0" width="330" height="22" rx="6" />
<path d="M250,59.0 h146.9 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-146.9 z" fill="#2a78d6" tabindex="0" data-tip="13.9 (distance over 150 words)|GPT-5.6 Luna, posts in prompt" />
<text class="v" x="411.9" y="75.0">13.9</text>
<text class="t" x="236" y="119.0" text-anchor="end">Qwen 4 Max, posts in prompt</text>
<rect class="track" x="250" y="103.0" width="330" height="22" rx="6" />
<path d="M250,103.0 h134.8 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-134.8 z" fill="#2a78d6" tabindex="0" data-tip="12.8 (distance over 150 words)|Qwen 4 Max, posts in prompt" />
<text class="v" x="399.8" y="119.0">12.8</text>
<text class="t" x="236" y="163.0" text-anchor="end">Claude Sonnet 5.5, posts in prompt</text>
<rect class="track" x="250" y="147.0" width="330" height="22" rx="6" />
<path d="M250,147.0 h121.6 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-121.6 z" fill="#2a78d6" tabindex="0" data-tip="11.6 (distance over 150 words)|Claude Sonnet 5.5, posts in prompt" />
<text class="v" x="386.6" y="163.0">11.6</text>
<text class="t" x="236" y="207.0" text-anchor="end" font-weight="600">My own 50 paragraphs</text>
<rect class="track" x="250" y="191.0" width="330" height="22" rx="6" />
<path d="M250,191.0 h115.0 a6,6 0 0 1 6,6 v10 a6,6 0 0 1 -6,6 h-115.0 z" fill="var(--ink)" tabindex="0" data-tip="11 (distance over 150 words)|My own 50 paragraphs — the author against the author" />
<text class="v" x="380.0" y="207.0">11</text>
</svg>
</figure>

<h2 id="what-a-detector-says">What a detector says</h2>

<p class="v-plain">An AI detector is a service that reads a text and estimates how likely it is that a machine wrote it. The one used throughout these posts is GPTZero. It gives three numbers that add up to 100%: the share it thinks was written by AI, the share written by a person, and a mixed share.</p>
<p class="v-tuned">An AI detector is a service that takes a piece of text and estimates how likely it is that a machine wrote it. The one we are going to use throughout these posts is GPTZero. It provides three numbers which sum up to 100%, the share it thinks was written by AI, the share written by a person and a mixed share.</p>
<p class="v-prompt">An AI detector is a service that reads a text and estimates how likely it is that a machine wrote it. The one we will use throughout these posts is GPTZero. It gives three numbers that add up to 100%: the share it thinks was written by AI, the share written by a person, and a mixed share.</p>

<p class="v-plain">First, a check that the detector is worth listening to. Seven samples of the author's real writing, from 2011 to 2021, were scanned. Six of them scored 100% human and one scored 99% human. So the detector does not simply call everything AI.</p>
<p class="v-tuned">So first let us check whether the detector is worth listening to. I took seven samples of my real writing from 2011-2021 and scanned them through the detector. Six of them scored 100% human and one scored 99% human. The detector does not just detect everything as AI.</p>
<p class="v-prompt">First, let us check that the detector is worth listening to. I scanned seven samples of the author's real writing, from 2011 to 2021. Six of them scored 100% human and one scored 99% human. So the detector does not simply call everything AI. Good!</p>

<p class="v-plain">Then twelve plain paragraphs, about 800 words, were rewritten by each of the three models with the posts in the prompt, and scanned. All three scored 100% AI and 0% human. The plain draft that these paragraphs come from, with no rewriting at all, scored the same. For the detector, nothing had changed.</p>
<p class="v-tuned">Then twelve plain paragraphs, about 800 words, were rewritten by each of the three models with the posts in the prompt and were scanned. All three scored 100% AI and 0% human. The plain draft that these paragraphs come from, with no rewriting at all, scored the same. For the detector, nothing had changed.</p>
<p class="v-prompt">Then we took twelve plain paragraphs, about 800 words, had each of the three models rewrite them with the posts in the prompt, and scanned the results. All three scored 100% AI and 0% human. The plain draft that these paragraphs come from, with no rewriting at all, scored the same. For the detector, nothing had changed.</p>

<figure class="chart " role="group" aria-label="Stacked bars of GPTZero scores for plain text, three rewrites and real writing">
<figcaption><strong>The detector knows my real writing from all three rewrites</strong><span>GPTZero verdict for each text, as shares of human, mixed and AI.</span></figcaption>
<ul class="legend"><li><i style="background:#2a78d6"></i>Human</li><li><i style="background:#b9b8b3"></i>Mixed</li><li><i style="background:#eb6834"></i>AI</li></ul>
<svg viewBox="0 0 640 400" role="img" aria-label="Stacked bars of GPTZero scores for plain text, three rewrites and real writing">
<clipPath id="c34"><rect x="230" y="10.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="25.0" text-anchor="end">Plain AI draft</text><g clip-path="url(#c34)">
<rect x="230.0" y="10.0" width="402.0" height="20" fill="#eb6834" tabindex="0" data-tip="100% AI|Plain AI draft" />
<text x="239.0" y="24.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c35"><rect x="230" y="46.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="61.0" text-anchor="end">Rewritten by Qwen 4 Max</text><g clip-path="url(#c35)">
<rect x="230.0" y="46.0" width="402.0" height="20" fill="#eb6834" tabindex="0" data-tip="100% AI|Rewritten by Qwen 4 Max" />
<text x="239.0" y="60.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c36"><rect x="230" y="82.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="97.0" text-anchor="end">Rewritten by Claude Sonnet 5.5</text><g clip-path="url(#c36)">
<rect x="230.0" y="82.0" width="402.0" height="20" fill="#eb6834" tabindex="0" data-tip="100% AI|Rewritten by Claude Sonnet 5.5" />
<text x="239.0" y="96.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c37"><rect x="230" y="118.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="133.0" text-anchor="end">Rewritten by GPT-5.6 Luna</text><g clip-path="url(#c37)">
<rect x="230.0" y="118.0" width="402.0" height="20" fill="#eb6834" tabindex="0" data-tip="100% AI|Rewritten by GPT-5.6 Luna" />
<text x="239.0" y="132.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c38"><rect x="230" y="154.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="169.0" text-anchor="end">My writing, 2011</text><g clip-path="url(#c38)">
<rect x="230.0" y="154.0" width="402.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2011" />
<text x="239.0" y="168.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c39"><rect x="230" y="190.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="205.0" text-anchor="end">My writing, 2016 (a)</text><g clip-path="url(#c39)">
<rect x="230.0" y="190.0" width="402.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2016 (a)" />
<text x="239.0" y="204.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c40"><rect x="230" y="226.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="241.0" text-anchor="end">My writing, 2016 (b)</text><g clip-path="url(#c40)">
<rect x="230.0" y="226.0" width="396.0" height="20" fill="#2a78d6" tabindex="0" data-tip="99% human|My writing, 2016 (b)" />
<text x="239.0" y="240.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">99%</text>
<rect x="628.0" y="226.0" width="4.0" height="20" fill="#eb6834" tabindex="0" data-tip="1% AI|My writing, 2016 (b)" />
</g>
<clipPath id="c41"><rect x="230" y="262.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="277.0" text-anchor="end">My writing, 2016 (c)</text><g clip-path="url(#c41)">
<rect x="230.0" y="262.0" width="402.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2016 (c)" />
<text x="239.0" y="276.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c42"><rect x="230" y="298.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="313.0" text-anchor="end">My writing, 2017</text><g clip-path="url(#c42)">
<rect x="230.0" y="298.0" width="402.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2017" />
<text x="239.0" y="312.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c43"><rect x="230" y="334.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="349.0" text-anchor="end">My writing, 2019</text><g clip-path="url(#c43)">
<rect x="230.0" y="334.0" width="402.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2019" />
<text x="239.0" y="348.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
<clipPath id="c44"><rect x="230" y="370.0" width="402" height="20" rx="7" /></clipPath>
<text class="t" x="216" y="385.0" text-anchor="end">My writing, 2021</text><g clip-path="url(#c44)">
<rect x="230.0" y="370.0" width="402.0" height="20" fill="#2a78d6" tabindex="0" data-tip="100% human|My writing, 2021" />
<text x="239.0" y="384.5" fill="#fff" font-size="12.5" font-weight="600" pointer-events="none">100%</text>
</g>
</svg>
</figure>

<table>
  <thead>
    <tr>
      <th>Text scanned with GPTZero</th>
      <th>Words</th>
      <th>AI</th>
      <th>Mixed</th>
      <th>Human</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Earlier draft, plain AI version</td>
      <td>1,080</td>
      <td>100%</td>
      <td>0%</td>
      <td>0%</td>
    </tr>
    <tr>
      <td>Twelve paragraphs, Qwen 4 Max with my posts</td>
      <td>801</td>
      <td>100%</td>
      <td>0%</td>
      <td>0%</td>
    </tr>
    <tr>
      <td>Twelve paragraphs, Claude Sonnet 5.5 with my posts</td>
      <td>815</td>
      <td>100%</td>
      <td>0%</td>
      <td>0%</td>
    </tr>
    <tr>
      <td>Twelve paragraphs, GPT-5.6 Luna with my posts</td>
      <td>796</td>
      <td>100%</td>
      <td>0%</td>
      <td>0%</td>
    </tr>
    <tr>
      <td>My writing, 2011</td>
      <td>270</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2016 (a)</td>
      <td>260</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2016 (b)</td>
      <td>260</td>
      <td>1%</td>
      <td>0%</td>
      <td>99%</td>
    </tr>
    <tr>
      <td>My writing, 2016 (c)</td>
      <td>300</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2017</td>
      <td>260</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2019</td>
      <td>260</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>My writing, 2021</td>
      <td>260</td>
      <td>0%</td>
      <td>0%</td>
      <td>100%</td>
    </tr>
  </tbody>
</table>

<p><em>The plain version was scanned as a whole draft of 1,080 words. The twelve test paragraphs are about 800 of those words.</em></p>

<h2 id="why-it-fails">Why it fails</h2>

<p class="v-plain">Why does the detector see no difference? One more measurement answers that. Take a rewritten paragraph and the plain paragraph it started from, and count how many of their words the two have in common. The result is a share. At 100% the rewrite uses exactly the words of the plain version, and at 0% it uses none of them.</p>
<p class="v-tuned">Ok but how come the detector thinks there is no difference? Let’s do another measurement. Starting from the rewritten paragraph and the plain paragraph it was rewritten from let’s count how many of the words of these paragraphs are present in the two. The result is a share. 100% means that the rewrite contains exactly the same words of the plain paragraph and 0% means that the rewrite contains none of the words from the plain paragraph.</p>
<p class="v-prompt">So why does the detector see no difference? One more measurement should answer that. Let us take a rewritten paragraph and the plain paragraph it started from, and count how many of their words the two have in common. The result is a share. At 100% the rewrite uses exactly the words of the plain version, and at 0% it uses none of them - pretty simple huh?</p>

<p class="v-plain">For the three models with the posts in the prompt, that share is 94%. Almost every word of the plain version is still there. The models add a we, a so and an exclamation mark, and leave the sentences underneath exactly as they were. Here is one paragraph before and after.</p>
<p class="v-tuned">So now for the three models with the posts in the prompt the share is 94%. Almost every word of the plain version is still there. The models add a we, a so and an exclamation mark, and leave the sentences underneath exactly as they were. Here is one paragraph before and after.</p>
<p class="v-prompt">For the three models with the posts in the prompt, that share is 94%. Yes, you read that right! Almost every word of the plain version is still there. The models sprinkle in a we, a so and an exclamation mark, but the sentences underneath are left exactly as they were. Below you can see one paragraph before and after.</p>

<div class="pipe-example">
<div><b>Plain AI</b>The first attempts used prompts. A chat model was asked to rewrite a passage so that it read as if a person had written it, with light rewrites, heavy rewrites and a spoken style. Three models were tried, including a 397 billion parameter model running locally. The wording changed but the voice did not, and GPTZero scored every one of these rewrites as 100% AI.</div>
<div class="bad"><b>Claude Sonnet 5.5 with my posts in the prompt</b>My first attempts used prompts. I asked a chat model to rewrite a passage so that it read as if a person had written it - light rewrites, heavy rewrites and a spoken style. I tried three models, including a 397 billion parameter model running locally. The wording changed but the voice did not, and GPTZero scored every one of these rewrites as 100% AI. Ouch!</div>
</div>

<p class="v-plain">A detector does not count how often a text says we. It looks at the sentences themselves, and at how predictable each word is, given the words before it. Text from a chat model is very predictable, and a few borrowed habits on top do not change that. To move the detector, the sentences have to be written differently, not decorated.</p>
<p class="v-tuned">The detector does not count how often we is said in the text. It looks at the sentences themselves and the predictability of each word given the words that come before it. A chat model text is very predictable, a few borrowed habits on top do not make the text any less predictable. In order to move the detector the sentences need to be written differently, not decorated.</p>
<p class="v-prompt">A detector does not count how often a text says we. It looks at the sentences themselves, and at how predictable each word is given the words before it. Text from a chat model is very predictable, and a few borrowed habits on top do not change that. To move the detector, the sentences have to be written differently, not decorated.</p>

<h2 id="where-this-leaves-us">Where this leaves us</h2>

<p class="v-plain">The simple technique has real strengths. It takes seconds and costs a few cents. It needs no special hardware. And because it changes so little, it breaks very little: all three models kept every number in all twelve paragraphs. If the goal is a text that reads like the author to a person, it is nearly enough.</p>
<p class="v-tuned">The simple technique has real strengths. It takes seconds and costs a few cents. It needs no special hardware. And because it changes so little, it breaks very little: all three models kept every number in all twelve paragraphs. If your aim is to get a text which reads like the author to a person, simple is nearly enough.</p>
<p class="v-prompt">The simple technique has real strengths. It takes seconds and costs a few cents. It needs no special hardware. And because it changes so little, it breaks very little: all three models kept every number in all twelve paragraphs. If the goal is a text that reads like the author to a person, it is nearly enough.</p>

<p class="v-plain">If the goal is a text that a detector takes for human writing, it does nothing. That needs a different kind of model, one that was never taught to write like a chat model in the first place. The <a href="/80000-Words-Of-Me/">second post</a> trains one.</p>
<p class="v-tuned">If you want a text that the detector takes for human writing, it will do nothing. That needs a different type of model; one that was never taught to write like a chat model in the first place. The <a href="/80000-Words-Of-Me/">second post</a> trains one.</p>
<p class="v-prompt">If the goal is a text that a detector takes for human writing, it does nothing. For that we need a different kind of model, one that was never taught to write like a chat model in the first place. In the <a href="/80000-Words-Of-Me/">second post</a> we will train one.</p>

<p><strong>In short</strong></p>

<ul>
  <li>Putting my old posts in the prompt of a chat model takes seconds and needs no training.</li>
  <li>The result picks up my habits: the three models say <em>we</em> 20.7 to 28.4 times per 1,000 words, against my 29.5.</li>
  <li>On the 150 common words nobody chooses, the models are at a distance of 11.6 to 13.9 from my writing. My own paragraphs are at 11.0 and the bland text at 27.8.</li>
  <li>It keeps 94% of the plain wording, so the sentences underneath are unchanged.</li>
  <li>GPTZero scored all three models 100% AI, and scored my real writing 99% to 100% human.</li>
</ul>

<h2 id="references">References</h2>

<ol>
  <li><a href="https://github.com/cloudmark/in-my-voice">The code: cloudmark/in-my-voice</a></li>
</ol>

<p>As always, stay safe, keep hacking!</p>

<p><em>Next: <a href="/80000-Words-Of-Me/">80,000 Words of Me</a>, on training a model on my own writing.</em></p>

<script>
  (function () {
    var prose = document.querySelector('.prose'), buttons = document.querySelectorAll('.voice-switch button');
    function show(voice) {
      prose.setAttribute('data-voice', voice);
      buttons.forEach(function (b) { b.setAttribute('aria-pressed', String(b.dataset.voice === voice)); });
    }
    buttons.forEach(function (b) { b.addEventListener('click', function () { show(b.dataset.voice); }); });
    show('tuned');
  })();
</script>

<script>
  (function () {
    var tip = document.createElement('div'); tip.className = 'chart-tip'; tip.setAttribute('role', 'status');
    var value = document.createElement('b'), label = document.createElement('span'); tip.appendChild(value); tip.appendChild(label);
    document.body.appendChild(tip);
    function show(el, x, y) {
      var parts = el.getAttribute('data-tip').split('|');
      value.textContent = parts[0]; label.textContent = parts[1] || '';
      tip.style.opacity = 1; tip.style.transform = 'none';
      var w = tip.offsetWidth, left = Math.min(Math.max(8, x + 14), window.innerWidth - w - 8);
      tip.style.left = left + 'px'; tip.style.top = Math.max(8, y - tip.offsetHeight - 12) + 'px';
    }
    function hide() { tip.style.opacity = 0; tip.style.transform = ''; }
    document.querySelectorAll('.chart [data-tip]').forEach(function (el) {
      el.addEventListener('pointermove', function (e) { show(el, e.clientX, e.clientY); });
      el.addEventListener('pointerleave', hide);
      el.addEventListener('focus', function () { var r = el.getBoundingClientRect(); show(el, r.left + r.width / 2, r.top); });
      el.addEventListener('blur', hide);
    });
  })();
</script>]]></content><author><name>Mark Galea</name></author><category term="fine-tuning" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">EventStore: From Log to State, and Into Production</title><link href="https://cloudmark.me/EventStore-Projections-And-Production/" rel="alternate" type="text/html" title="EventStore: From Log to State, and Into Production" /><published>2026-11-18T00:01:00+01:00</published><updated>2026-11-18T00:01:00+01:00</updated><id>https://cloudmark.me/EventStore-Projections-And-Production</id><content type="html" xml:base="https://cloudmark.me/EventStore-Projections-And-Production/"><![CDATA[<p><img class="title" src="/images/eventstore/logo-small.png" />
In the <a href="/EventStore-Introducing/">first post</a> we built a single ordered log, and in the <a href="/EventStore-Reading/">second</a> we read it every way we could. Sooner or later, though, somebody asks a question about <em>all</em> the messages at once. ACME’s sales team wants a dashboard showing, for every customer, how many orders they placed, how many they cancelled and how much they actually spent (Wile E. Coyote is, unsurprisingly, top of the chart). Nobody stores that number; it is <em>derived</em> from the log. In this final post we will build a projection that folds the log into exactly that state, crash it with <code class="language-plaintext highlighter-rouge">kill -9</code> and check it lands on the right numbers, serve it to every dashboard that asks, and then cover what it takes to run the whole thing in production.</p>

<blockquote>
  <p>For a complete listing of all code samples and to clone the project, visit the <a href="https://github.com/fifteen02/eventstore/tree/main/samples/07-projection">GitHub repository</a>.</p>
</blockquote>

<h2 id="a-fold-is-a-tally-sheet">A Fold Is a Tally Sheet</h2>
<p>Think of a bank statement. Nobody stores your balance as a fact of nature; the bank starts from zero, goes through every transaction in order, and keeps a running total. That is a <strong>fold</strong>: a starting state, plus a step that takes “the state so far and the next event” and returns “the new state”. Our projection keeps one row per customer, and the step is three small rules:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">switch</span> <span class="o">(</span><span class="n">type</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">case</span> <span class="s">"OrderPlaced"</span> <span class="o">-&gt;</span> <span class="o">{</span>
        <span class="kt">long</span> <span class="n">total</span> <span class="o">=</span> <span class="n">body</span><span class="o">.</span><span class="na">path</span><span class="o">(</span><span class="s">"total"</span><span class="o">).</span><span class="na">asLong</span><span class="o">();</span>
        <span class="n">openOrders</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">orderId</span><span class="o">,</span> <span class="k">new</span> <span class="nc">OpenOrder</span><span class="o">(</span><span class="n">customer</span><span class="o">,</span> <span class="n">total</span><span class="o">));</span>
        <span class="n">s</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Stats</span><span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">placed</span><span class="o">()</span> <span class="o">+</span> <span class="mi">1</span><span class="o">,</span> <span class="n">s</span><span class="o">.</span><span class="na">shipped</span><span class="o">(),</span> <span class="n">s</span><span class="o">.</span><span class="na">cancelled</span><span class="o">(),</span> <span class="n">s</span><span class="o">.</span><span class="na">spent</span><span class="o">()</span> <span class="o">+</span> <span class="n">total</span><span class="o">);</span>
    <span class="o">}</span>
    <span class="k">case</span> <span class="s">"OrderShipped"</span> <span class="o">-&gt;</span> <span class="n">s</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Stats</span><span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">placed</span><span class="o">(),</span> <span class="n">s</span><span class="o">.</span><span class="na">shipped</span><span class="o">()</span> <span class="o">+</span> <span class="mi">1</span><span class="o">,</span> <span class="n">s</span><span class="o">.</span><span class="na">cancelled</span><span class="o">(),</span> <span class="n">s</span><span class="o">.</span><span class="na">spent</span><span class="o">());</span>
    <span class="k">case</span> <span class="s">"OrderCancelled"</span> <span class="o">-&gt;</span> <span class="o">{</span>
        <span class="c1">// Order-sensitive: a cancellation refunds a total we learned from an earlier event.</span>
        <span class="nc">OpenOrder</span> <span class="n">order</span> <span class="o">=</span> <span class="n">openOrders</span><span class="o">.</span><span class="na">remove</span><span class="o">(</span><span class="n">orderId</span><span class="o">);</span>
        <span class="kt">long</span> <span class="n">refund</span> <span class="o">=</span> <span class="n">order</span> <span class="o">==</span> <span class="kc">null</span> <span class="o">?</span> <span class="mi">0</span> <span class="o">:</span> <span class="n">order</span><span class="o">.</span><span class="na">total</span><span class="o">();</span>
        <span class="n">s</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Stats</span><span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">placed</span><span class="o">(),</span> <span class="n">s</span><span class="o">.</span><span class="na">shipped</span><span class="o">(),</span> <span class="n">s</span><span class="o">.</span><span class="na">cancelled</span><span class="o">()</span> <span class="o">+</span> <span class="mi">1</span><span class="o">,</span> <span class="n">s</span><span class="o">.</span><span class="na">spent</span><span class="o">()</span> <span class="o">-</span> <span class="n">refund</span><span class="o">);</span>
    <span class="o">}</span>
    <span class="k">default</span> <span class="o">-&gt;</span> <span class="o">{</span> <span class="k">return</span> <span class="kc">null</span><span class="o">;</span> <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Look closely, because those rules come in two flavours. Counting orders does not care about order: three rockets are three rockets in any sequence. The cancellation rule does: it refunds a total it learned from an <em>earlier</em> <code class="language-plaintext highlighter-rouge">OrderPlaced</code>, so feed it the cancellation first and the refund is zero. Most interesting business logic looks like this, and this is where the single index from the first post pays for itself. EventStore’s log has one order, the same for every reader and every replay, so an order-sensitive fold lands on the same state every single time. Over a partitioned log you would first have to agree how to interleave the partitions, forever.</p>

<h2 id="snapshots-dont-re-read-the-whole-statement">Snapshots: Don’t Re-Read the Whole Statement</h2>
<p>Folding the whole log works, but after a crash you would start again from index 1, and with a few million messages that is a long coffee break :coffee:. The fix is the one your bank uses: a monthly statement with a closing balance. A <strong>snapshot</strong> is the pair <em>(index, state)</em>, “this is the state after folding events 1 to index”, and the important word is <em>pair</em>: index and state are saved together, atomically, or they will eventually disagree:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">save</span><span class="o">(</span><span class="nc">Path</span> <span class="n">file</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">Exception</span> <span class="o">{</span>
    <span class="nc">ObjectNode</span> <span class="n">snapshot</span> <span class="o">=</span> <span class="no">JSON</span><span class="o">.</span><span class="na">createObjectNode</span><span class="o">();</span>
    <span class="n">snapshot</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">"index"</span><span class="o">,</span> <span class="n">index</span><span class="o">);</span>
    <span class="n">snapshot</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">"customers"</span><span class="o">,</span> <span class="no">JSON</span><span class="o">.</span><span class="na">valueToTree</span><span class="o">(</span><span class="n">customers</span><span class="o">));</span>
    <span class="n">snapshot</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">"openOrders"</span><span class="o">,</span> <span class="no">JSON</span><span class="o">.</span><span class="na">valueToTree</span><span class="o">(</span><span class="n">openOrders</span><span class="o">));</span>
    <span class="nc">Path</span> <span class="n">tmp</span> <span class="o">=</span> <span class="n">file</span><span class="o">.</span><span class="na">resolveSibling</span><span class="o">(</span><span class="n">file</span><span class="o">.</span><span class="na">getFileName</span><span class="o">()</span> <span class="o">+</span> <span class="s">".tmp"</span><span class="o">);</span>
    <span class="nc">Files</span><span class="o">.</span><span class="na">writeString</span><span class="o">(</span><span class="n">tmp</span><span class="o">,</span> <span class="no">JSON</span><span class="o">.</span><span class="na">writeValueAsString</span><span class="o">(</span><span class="n">snapshot</span><span class="o">));</span>
    <span class="nc">Files</span><span class="o">.</span><span class="na">move</span><span class="o">(</span><span class="n">tmp</span><span class="o">,</span> <span class="n">file</span><span class="o">,</span> <span class="nc">StandardCopyOption</span><span class="o">.</span><span class="na">REPLACE_EXISTING</span><span class="o">,</span> <span class="nc">StandardCopyOption</span><span class="o">.</span><span class="na">ATOMIC_MOVE</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>On restart the projection loads the snapshot and asks EventStore for <code class="language-plaintext highlighter-rouge">startIndex = index + 1</code>, so it folds only what happened since, and as a belt-and-braces measure the fold ignores anything at or below its own index. Save the state without the index and you do not know where to resume; save them separately and a crash in between leaves them disagreeing; both mean double counting or skipping. How often to snapshot is the <code class="language-plaintext highlighter-rouge">ack.batch</code> question from the last post wearing a different hat: often means fast recovery and lots of writes, rarely means the opposite.</p>

<p>Let’s give the projection some history and start it:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">CUSTOMERS</span><span class="o">=</span>4 samples/bin/publish-orders.sh 12
mvn <span class="nt">-q</span> <span class="nt">-f</span> samples/07-projection compile <span class="nb">exec</span>:java
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>projection: loaded snapshot at index 0 from …/projection.snapshot.json
projection: connected from 1, log is at 29
projection: snapshot at index 20
projection: caught up at index 29 (4 alerts suppressed during catch-up)
projection: snapshot at index 29
</code></pre></div></div>

<p>Line by line: no snapshot yet, so we start at 1; the log ends at 29, which is our “caught up” target; we snapshot after 20 events as configured; at 29 we have caught up, holding back 4 alerts (more on those in a moment), and snapshot again. A quick sanity check by hand: <code class="language-plaintext highlighter-rouge">customer-0</code> placed orders 4, 8 and 12 at 40, 80 and 120, and order 12 was cancelled, which leaves 120 spent, exactly what <code class="language-plaintext highlighter-rouge">GET /state</code> reports.</p>

<h3 id="the-crash-test">The Crash Test</h3>
<p>Talk is cheap, so let’s break it. I published 150 more orders and killed the projection with <code class="language-plaintext highlighter-rouge">kill -9</code> halfway through: no shutdown hooks, no last-minute snapshot. Then I started it again:</p>

<p><img class="center" style="width: 720px" alt="Snapshots at 29, 69 and 109; a kill -9 after 109; the restart loads 109 and folds 110 to 411" src="/images/eventstore/es-snapshots.png" /></p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>projection: loaded snapshot at index 109 from …/projection.snapshot.json
projection: connected from 110, log is at 411
…
projection: caught up at index 411 (8 alerts suppressed during catch-up)
</code></pre></div></div>

<p>To check the result, I ran a second instance with no snapshot at all, folding the entire log from index 1, and compared the two:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>resumed:    index 411 {'placed': 176, 'shipped': 176, 'cancelled': 58, 'spent': 75990}
recomputed: index 411 {'placed': 176, 'shipped': 176, 'cancelled': 58, 'spent': 75990}
identical customers: True
</code></pre></div></div>

<p>Same totals, every customer identical. No double counting, nothing skipped.</p>

<h3 id="holding-your-fire-and-its-catch">Holding Your Fire, and Its Catch</h3>
<p>The projection raises an alert when a customer becomes a VIP, that is, when their spend crosses 100. During catch-up it is replaying the past, and an alert about last month is noise, so it keeps quiet until it has caught up; after that, alerts fire as they should:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>projection: ALERT customer-1 is now a VIP (spent 150)
projection: ALERT customer-4 is now a VIP (spent 140)
</code></pre></div></div>

<p>Now look again at the crash test: <em>8 alerts suppressed during catch-up</em>. Those were customers who crossed 100 while the projection was dead, so on restart they are “the past” and nobody is ever told. Holding your fire is the right default, but it is not free. If every crossing must produce exactly one alert, either make “alerted” part of the snapshot and send the missing ones once caught up, or give alerts their own consumer with its own bookmark (a replayable interface from the last post).</p>

<h3 id="fold-once-serve-many">Fold Once, Serve Many</h3>
<p>Who should run this fold? There are two shapes:</p>

<p><img class="center" style="width: 720px" alt="Every client folding for itself versus one projection service folding once and serving views" src="/images/eventstore/es-fold.png" /></p>

<p><strong>Every client folds for itself</strong>: the dashboard streams from EventStore, folds in the browser and keeps its bookmark in <code class="language-plaintext highlighter-rouge">localStorage</code>. No service to deploy, perfect for one team and one view. But every new tab replays history, and when five teams build five dashboards on the same numbers, the same fold runs five times in five codebases that slowly drift apart.</p>

<p><strong>One service folds for everyone</strong>: that is the sample. The projection does the folding once, and its clients never replay anything; on connect they get the <strong>current state</strong>, then one update per change:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>event:snapshot
data:{"index":29,"customers":{…},"totals":{"placed":12,"shipped":12,"cancelled":4,"spent":480},"caughtUp":true}

event:update
data:{"index":30,"customer":"customer-1","stats":{"placed":4,"shipped":3,"cancelled":1,"spent":70},"totals":{…,"spent":490}}
</code></pre></div></div>

<p>There is no bookmark on this side: a dashboard that reconnects simply gets a fresh snapshot, and the <code class="language-plaintext highlighter-rouge">caughtUp</code> flag lets it say “still loading history” instead of presenting half the picture as the truth. Notice <code class="language-plaintext highlighter-rouge">totals</code>, too: it is not folded from events at all but added up from the per-customer rows, so coarser views come for free when the rule is “add things up”. Start with every client folding for itself, because it is the cheapest thing that works, and move the fold into a service when a view is shared, when catching up takes long enough that people notice, or when the logic matters enough to live in exactly one place. The price is simple: you now own a service.</p>

<h2 id="into-production">Into Production</h2>
<p>Running EventStore well is mostly a matter of respecting the single writer from the first post: one instance per database and <code class="language-plaintext highlighter-rouge">Recreate</code> deployments. The rest is hygiene.</p>

<p><strong>Watch the lag.</strong> Every 30 seconds EventStore compares each acknowledged interface’s bookmark with the newest index and logs an error when the gap exceeds <code class="language-plaintext highlighter-rouge">max(ack.lag-alert-min-messages, ceil(ack.batch × ack.lag-alert-batch-ratio))</code>, which is 1,500 messages with the defaults. A real one, from an interface with <code class="language-plaintext highlighter-rouge">batch: 5</code>:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ERROR c.f.e.monitor.InterfaceLagMonitor - [INTERFACE_BEHIND] Interface 'billing' is behind: lag=19501 messages (current=19501, lastAck=0, threshold=8, batch=5, ratio=1.5)
</code></pre></div></div>

<p>Alert on <code class="language-plaintext highlighter-rouge">[INTERFACE_BEHIND]</code>, with two caveats: the first check runs the moment EventStore starts, so an interface still catching up raises one alert before it has had a chance (that one caught up three seconds later), and a healthy interface can sit up to <code class="language-plaintext highlighter-rouge">batch - 1</code> behind. A steady stream of <code class="language-plaintext highlighter-rouge">Waiting for missing index</code> warnings is the other signal worth an alert: a consumer is dropping messages without acknowledging them. And as we saw last time, put “restart EventStore” in your broker-outage runbook until the interface restart fix ships.</p>

<p><strong>Archive the old stuff.</strong> By default every message stays in PostgreSQL forever. For large logs EventStore can archive to Google BigQuery and trim PostgreSQL, built from the same push machinery as billing: a <code class="language-plaintext highlighter-rouge">persister</code> interface named <code class="language-plaintext highlighter-rouge">google-big-query</code>, an archiver service of yours that writes each message to BigQuery and acknowledges it, and a retention job. The retention job is cautious by design:</p>

<p><img class="center" style="width: 680px" alt="The BigQuery archive covers 1 to 9,000; PostgreSQL rows 5,001 to 7,000 are trimmed because the archive covers them" src="/images/eventstore/es-archive.png" /></p>

<p>It deletes PostgreSQL rows older than the cutoff <strong>only if the archive covers that entire range</strong>; if the archiver is behind or has a gap, it logs a warning and deletes nothing. Replays then read old ranges from BigQuery and recent ones from PostgreSQL. Two edges to know: aggregate fields are not archived, so replays from the archive return them empty, and a row whose content is not valid JSON is skipped on replay, so validate in the archiver.</p>

<p><strong>Lock the doors.</strong> One bearer token protects publishing and streaming (there are no per-client scopes, so put a gateway in front if you need them); <code class="language-plaintext highlighter-rouge">/actuator/**</code> and the <code class="language-plaintext highlighter-rouge">/debug/events</code> page are unauthenticated and served in every profile, so block them at your ingress; TLS is terminated in front; and <code class="language-plaintext highlighter-rouge">changeme</code> is a password for your laptop. Outside Google Cloud, run the <code class="language-plaintext highlighter-rouge">dev</code> profile with overrides (<code class="language-plaintext highlighter-rouge">staging</code> and <code class="language-plaintext highlighter-rouge">live</code> assume Google Cloud Logging), and never invent a profile name: logging is only configured for the known ones, so <code class="language-plaintext highlighter-rouge">prod</code> starts in eerie silence :warning:.</p>

<p>Here is all of that on one card:</p>

<ul>
  <li>one instance, <code class="language-plaintext highlighter-rouge">Recreate</code> deployments, a grace period longer than 30 seconds;</li>
  <li>publisher confirms on AMQP producers and a dead-letter policy on the input queue;</li>
  <li>a real token and database password; <code class="language-plaintext highlighter-rouge">/actuator</code> and <code class="language-plaintext highlighter-rouge">/debug/events</code> blocked at the edge;</li>
  <li>alerts on <code class="language-plaintext highlighter-rouge">[INTERFACE_BEHIND]</code> and on bursts of <code class="language-plaintext highlighter-rouge">Waiting for missing index</code>;</li>
  <li>“restart EventStore” in the broker-outage runbook;</li>
  <li>idempotent consumers, always: restarts re-deliver, by design.</li>
</ul>

<h2 id="conclusion-tada">Conclusion :tada:</h2>
<p>In this blog post we turned the log into state and took it to production. In summary:</p>

<ul>
  <li><strong>Folds</strong>: state plus the next event gives the new state; order-sensitive folds are safe because EventStore’s log has exactly one order.</li>
  <li><strong>Snapshots</strong>: save index and state together, resume from index + 1, and a <code class="language-plaintext highlighter-rouge">kill -9</code> costs you only the events since the last snapshot.</li>
  <li><strong>Hold your fire</strong>: no side effects during catch-up, and if every alert matters, put “alerted” in the state or give alerts their own consumer.</li>
  <li><strong>Fold once, serve many</strong>: when a view is shared, one service folds and every client gets the current state on connect.</li>
  <li><strong>Run it with care</strong>: one writer, lag alerts, a cautious archive and locked doors.</li>
</ul>

<p>That wraps up the series :tada:. We started with one index and ended with snapshots, sharded readers and an archive, and along the way Wile has been charged exactly once for every rocket. The <a href="https://github.com/fifteen02/eventstore">repository</a> has all seven samples, the documentation and the known issues, which are great places to start contributing. Issues and pull requests are very welcome.</p>

<p>As always, stay safe, keep hacking!</p>]]></content><author><name>Mark Galea</name></author><category term="eventstore" /><summary type="html"><![CDATA[In the first post we built a single ordered log, and in the second we read it every way we could. Sooner or later, though, somebody asks a question about all the messages at once. ACME’s sales team wants a dashboard showing, for every customer, how many orders they placed, how many they cancelled and how much they actually spent (Wile E. Coyote is, unsurprisingly, top of the chart). Nobody stores that number; it is derived from the log. In this final post we will build a projection that folds the log into exactly that state, crash it with kill -9 and check it lands on the right numbers, serve it to every dashboard that asks, and then cover what it takes to run the whole thing in production.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://cloudmark.me/images/eventstore/logo-small.png" /><media:content medium="image" url="https://cloudmark.me/images/eventstore/logo-small.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">EventStore: Reading the Log by Pulling, Pushing and Sharding</title><link href="https://cloudmark.me/EventStore-Reading/" rel="alternate" type="text/html" title="EventStore: Reading the Log by Pulling, Pushing and Sharding" /><published>2026-11-10T00:01:00+01:00</published><updated>2026-11-10T00:01:00+01:00</updated><id>https://cloudmark.me/EventStore-Reading</id><content type="html" xml:base="https://cloudmark.me/EventStore-Reading/"><![CDATA[<p><img class="title" src="/images/eventstore/logo-small.png" />
In the <a href="/EventStore-Introducing/">first post</a> we got Wile’s orders into a single, ordered log. A log nobody reads is just an expensive diary, though :smirk:, so this post is all about getting messages <em>out</em>. There are two ways, and they differ in one question: who remembers how far a consumer has got? With <strong>pull</strong>, the consumer keeps its own bookmark and asks for the log from any point. With <strong>push</strong>, EventStore keeps the bookmark, delivers over AMQP and resumes after a restart. We will build a consumer for each, work out <em>exactly</em> when a message arrives twice, peek at the trick that joins history to live messages without a seam, and finish by splitting one log across several readers.</p>

<blockquote>
  <p>For a complete listing of all code samples and to clone the project, visit the <a href="https://github.com/fifteen02/eventstore/tree/main/samples">GitHub repository</a>.</p>
</blockquote>

<h2 id="pull-a-bookmark-not-a-memory">Pull: A Bookmark, Not a Memory</h2>
<p>Think about how you read a long book. You do not remember every page you have read; you keep a bookmark, and when you pick the book up again you open it on the page <em>after</em> the bookmark. Fall asleep mid-chapter and, worst case, you re-read a page.</p>

<p>A pull consumer works exactly like that. EventStore keeps <strong>no state for a stream</strong>: it does not know who you are or where you were last time. The consumer keeps one number, the index of the last message it processed, and the whole consumer is a loop around it:</p>

<ol>
  <li><strong>Read the bookmark</strong>: the last index processed, or 0 if there is none.</li>
  <li><strong>Open the book</strong>: <code class="language-plaintext highlighter-rouge">GET /api/events/stream?startIndex=&lt;bookmark + 1&gt;</code>.</li>
  <li><strong>Read a page</strong>: for each message, process it, <strong>then</strong> move the bookmark to its index.</li>
  <li><strong>Fell asleep?</strong>: when the connection ends, for any reason, wait a moment and go back to 1.</li>
</ol>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">while</span> <span class="o">(</span><span class="kc">true</span><span class="o">)</span> <span class="o">{</span>
    <span class="kt">long</span> <span class="n">startIndex</span> <span class="o">=</span> <span class="n">readCheckpoint</span><span class="o">()</span> <span class="o">+</span> <span class="mi">1</span><span class="o">;</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">consume</span><span class="o">(</span><span class="n">startIndex</span><span class="o">))</span> <span class="o">{</span>
            <span class="k">return</span><span class="o">;</span> <span class="c1">// the server ended the stream at END_INDEX</span>
        <span class="o">}</span>
    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"stream: "</span> <span class="o">+</span> <span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">()</span> <span class="o">+</span> <span class="s">", reconnecting in 2s"</span><span class="o">);</span>
    <span class="o">}</span>
    <span class="nc">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="mi">2_000</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Notice what is missing: there is no special case for “my process restarted”, “EventStore restarted” or “a proxy dropped the connection”. They are all the same event, so there is no separate recovery path that only runs twice a year and turns out to be broken when it finally does.</p>

<p>The stream itself is plain Server-Sent Events: lines of <code class="language-plaintext highlighter-rouge">event:</code> and <code class="language-plaintext highlighter-rouge">data:</code> with a blank line between events, which the JDK’s <code class="language-plaintext highlighter-rouge">HttpClient</code> and a <code class="language-plaintext highlighter-rouge">BufferedReader</code> handle in about twenty lines (no SSE library needed, see the sample). Four kinds of events arrive: <code class="language-plaintext highlighter-rouge">connected</code> (once, with where the log currently ends), <code class="language-plaintext highlighter-rouge">message</code> (one per log entry), <code class="language-plaintext highlighter-rouge">heartbeat</code> (every five seconds, so proxies don’t close a quiet connection) and <code class="language-plaintext highlighter-rouge">stream-ended</code> (only if you asked for an <code class="language-plaintext highlighter-rouge">endIndex</code>).</p>

<h3 id="move-the-bookmark-after-never-before">Move the Bookmark After, Never Before</h3>
<p>The order of two lines decides what kind of consumer you have built:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">case</span> <span class="s">"message"</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="kt">long</span> <span class="n">id</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="na">path</span><span class="o">(</span><span class="s">"message"</span><span class="o">).</span><span class="na">path</span><span class="o">(</span><span class="s">"id"</span><span class="o">).</span><span class="na">asLong</span><span class="o">();</span>
    <span class="n">process</span><span class="o">(</span><span class="n">data</span><span class="o">.</span><span class="na">path</span><span class="o">(</span><span class="s">"message"</span><span class="o">));</span>
    <span class="n">writeCheckpoint</span><span class="o">(</span><span class="n">id</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Crash between <code class="language-plaintext highlighter-rouge">process</code> and <code class="language-plaintext highlighter-rouge">writeCheckpoint</code> and the next run asks for that index again, so the message is processed twice. Swap the two lines and a crash in between skips it forever. Twice is recoverable; never is not. That is at-least-once in a nutshell, and it is why <code class="language-plaintext highlighter-rouge">process</code> must be idempotent, keyed by the index. When the effect lives in the same database as the bookmark, write both in <strong>one transaction</strong> and the duplicate disappears altogether. Keep that thought for the last post.</p>

<p>Let’s run it. Wile is <code class="language-plaintext highlighter-rouge">customer-1</code> in the samples:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>samples/bin/run-eventstore.sh
mvn <span class="nt">-q</span> <span class="nt">-f</span> samples/02-pull-stream compile <span class="nb">exec</span>:java
samples/bin/publish-orders.sh 2
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>stream: connected from 1, server is at 4
stream: #1 StartMarker    user=system     {}   (3 behind)
stream: #2 OrderPlaced    user=customer-1 {"total":49.9,"orderId":"order-1791800693-26411"}   (2 behind)
stream: #3 OrderShipped   user=customer-2 {"total":49.9,"orderId":"order-1791800693-19084"}   (1 behind)
stream: #4 OrderPlaced    user=           {"orderId":"same"}
stream: #5 OrderPlaced    user=customer-1 {"orderId":"order-1791800707-23589-1","total":10}
stream: #6 OrderShipped   user=customer-1 {"orderId":"order-1791800707-23589-1","carrier":"DHL"}
</code></pre></div></div>

<p>Line by line:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">connected from 1, server is at 4</code>: no bookmark yet, so we start at 1, and the log ends at 4.</li>
  <li><code class="language-plaintext highlighter-rouge">#1</code> to <code class="language-plaintext highlighter-rouge">#4</code> are history; the <code class="language-plaintext highlighter-rouge">(n behind)</code> counter counts down as we catch up.</li>
  <li><code class="language-plaintext highlighter-rouge">#5</code> and <code class="language-plaintext highlighter-rouge">#6</code> are live, arriving on the very same connection as <code class="language-plaintext highlighter-rouge">publish-orders</code> sends them.</li>
</ul>

<p>Stop the consumer, have Wile order another rocket while it is down, start it again, and it carries on exactly where it stopped: <code class="language-plaintext highlighter-rouge">connected from 11, server is at 12</code>. Restart EventStore instead and you get the same result.</p>

<h3 id="inside-eventstore-recorded-then-live">Inside EventStore: Recorded, Then Live</h3>
<p>Here is the tricky bit a pull API has to get right. Imagine you want to watch a football match that started an hour ago. Watch the recording first and then switch to live, and you miss whatever happened in between. Switch to live first and you see some goals twice. The trick is to start recording the live feed <em>before</em> you sit down with the recording, and skip what you have already seen. EventStore does exactly this for every stream:</p>

<p><img class="center" style="width: 720px" alt="The stream replays 1 to 5 from the database while live messages queue up; 4 and 5 are skipped from the queue" src="/images/eventstore/es-handoff.png" /></p>

<ol>
  <li>The router <strong>registers</strong> the stream first, so every newly committed message also lands in the stream’s mailbox.</li>
  <li>It then <strong>replays</strong> from <code class="language-plaintext highlighter-rouge">startIndex</code> up to the newest committed index, loading from the database in batches of 1,000.</li>
  <li>Finally it works through the mailbox, and one check throws away the overlap:</li>
</ol>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">private</span> <span class="kt">boolean</span> <span class="nf">hasAlreadySeen</span><span class="o">(</span><span class="nc">MessageTo</span> <span class="n">messageTo</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">return</span> <span class="n">messageTo</span><span class="o">.</span><span class="na">id</span><span class="o">()</span> <span class="o">&lt;=</span> <span class="n">lastObservedIndex</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Nothing can be missed, because registration comes before the replay plan; nothing can be sent twice, because anything at or below the replay’s last index is dropped. That holds for one connection; across reconnects, your bookmark takes over.</p>

<h3 id="hold-your-fire-while-catching-up">Hold Your Fire While Catching Up</h3>
<p>A mistake I have seen more than once: a consumer sends an email whenever an order is cancelled. It is redeployed with an empty bookmark, replays history, and sends Wile forty emails about rockets he cancelled last month :scream:. Replaying should rebuild state, not repeat side effects. The <code class="language-plaintext highlighter-rouge">connected</code> event tells you where the log ended when you connected, so a consumer knows when it has caught up; until then, update state but hold back emails, alerts and webhooks. The last post builds exactly this, including its subtle catch.</p>

<p>Because the bookmark belongs to the client, a replay is also just a stream with a different bookmark. Want every <code class="language-plaintext highlighter-rouge">OrderPlaced</code> up to index 4 without touching the main consumer?</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">CHECKPOINT_FILE</span><span class="o">=</span>/tmp/placed.cp <span class="nv">END_INDEX</span><span class="o">=</span>4 <span class="nv">STREAM_TYPES</span><span class="o">=</span>OrderPlaced mvn <span class="nt">-q</span> <span class="nt">-f</span> samples/02-pull-stream <span class="nb">exec</span>:java
</code></pre></div></div>

<p>Two sharp edges before you build one: EventStore ignores the SSE <code class="language-plaintext highlighter-rouge">Last-Event-ID</code> header (resume with <code class="language-plaintext highlighter-rouge">startIndex</code>), and browsers cannot use <code class="language-plaintext highlighter-rouge">EventSource</code> here because it cannot send an <code class="language-plaintext highlighter-rouge">Authorization</code> header, so use <code class="language-plaintext highlighter-rouge">fetch()</code> with a streaming body reader instead.</p>

<h2 id="push-let-eventstore-keep-the-bookmark">Push: Let EventStore Keep the Bookmark</h2>
<p>Pulling is perfect for dashboards and replays. For a fleet of backend services that already speak AMQP it means every team re-implements the same bookkeeping, so EventStore offers to keep the bookmark instead. A push consumer is called an <strong>interface</strong> and lives in configuration:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">eventstore</span><span class="pi">:</span>
  <span class="na">amqp</span><span class="pi">:</span>
    <span class="na">enabled</span><span class="pi">:</span> <span class="no">true</span>
  <span class="na">interfaces</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">billing</span>
      <span class="na">type</span><span class="pi">:</span> <span class="s">replayable</span>
      <span class="na">include-types</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">OrderPlaced</span><span class="pi">,</span> <span class="nv">OrderCancelled</span><span class="pi">]</span>
      <span class="na">sink</span><span class="pi">:</span> <span class="pi">{</span> <span class="nv">amqp</span><span class="pi">:</span> <span class="pi">{</span> <span class="nv">virtual-host</span><span class="pi">:</span> <span class="nv">/</span> <span class="pi">}</span> <span class="pi">}</span>
      <span class="na">ack</span><span class="pi">:</span>  <span class="pi">{</span> <span class="nv">amqp</span><span class="pi">:</span> <span class="pi">{</span> <span class="nv">virtual-host</span><span class="pi">:</span> <span class="nv">/</span> <span class="pi">},</span> <span class="nv">batch</span><span class="pi">:</span> <span class="nv">5</span> <span class="pi">}</span>
</code></pre></div></div>

<p>EventStore declares two queues named after the interface, <code class="language-plaintext highlighter-rouge">billing.sink</code> (EventStore publishes here) and <code class="language-plaintext highlighter-rouge">billing.ack</code> (billing answers here), and billing’s bookmark becomes a row in EventStore’s database. Messages billing does not care about are acknowledged on its behalf, so they never hold the bookmark back. Here is the round trip for one of Wile’s orders:</p>

<p><img class="center" style="width: 720px" alt="EventStore publishes #42 to billing.sink, billing processes it, acknowledges on billing.ack and signs for the delivery; EventStore moves its bookmark" src="/images/eventstore/es-acks.png" /></p>

<p>In code, steps 3 and 4:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// 3. Acknowledge to EventStore.</span>
<span class="kt">var</span> <span class="n">ackProperties</span> <span class="o">=</span> <span class="k">new</span> <span class="no">AMQP</span><span class="o">.</span><span class="na">BasicProperties</span><span class="o">.</span><span class="na">Builder</span><span class="o">()</span>
        <span class="o">.</span><span class="na">contentType</span><span class="o">(</span><span class="s">"application/json"</span><span class="o">)</span>
        <span class="o">.</span><span class="na">headers</span><span class="o">(</span><span class="nc">Map</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="nc">MessageHeaders</span><span class="o">.</span><span class="na">SERVER_CORRELATION_UUID</span><span class="o">,</span> <span class="n">serverCorrelationUuid</span><span class="o">))</span>
        <span class="o">.</span><span class="na">build</span><span class="o">();</span>
<span class="n">channel</span><span class="o">.</span><span class="na">basicPublish</span><span class="o">(</span><span class="s">""</span><span class="o">,</span> <span class="no">ACK_QUEUE</span><span class="o">,</span> <span class="n">ackProperties</span><span class="o">,</span>
        <span class="no">JSON</span><span class="o">.</span><span class="na">writeValueAsBytes</span><span class="o">(</span><span class="k">new</span> <span class="nc">AcknowledgeTo</span><span class="o">(</span><span class="n">index</span><span class="o">,</span> <span class="n">serverCorrelationUuid</span><span class="o">)));</span>

<span class="c1">// 4. Remove the delivery from billing.sink.</span>
<span class="n">channel</span><span class="o">.</span><span class="na">basicAck</span><span class="o">(</span><span class="n">delivery</span><span class="o">.</span><span class="na">getEnvelope</span><span class="o">().</span><span class="na">getDeliveryTag</span><span class="o">(),</span> <span class="kc">false</span><span class="o">);</span>
</code></pre></div></div>

<p>The two acknowledgements mean very different things. Think of a parcel courier: signing for the parcel at the door (“I have it, stop carrying it around”) is step 4; telling the shop you have actually <em>used</em> what was inside (“tick order 42 off”) is step 3. Forget step 4 and the queue fills with parcels you never signed for. Forget step 3 and the shop never ticks anything off, so every restart sends you everything again.</p>

<p>Why the <code class="language-plaintext highlighter-rouge">serverCorrelationUUID</code> header? Every EventStore run picks a fresh one, and acknowledgements whose header does not match the current run are dropped. After a restart EventStore decides where to resume from its own saved bookmark and re-sends everything after it, so an acknowledgement still in flight from the previous run refers to a delivery that has already been re-sent. One source of truth: the saved bookmark plus this run’s acknowledgements.</p>

<h3 id="from-acknowledgements-to-a-bookmark">From Acknowledgements to a Bookmark</h3>
<p>Acknowledgements can arrive in any order, especially with several consumers on one queue. EventStore keeps them in a sorted set and only moves the bookmark over a <strong>contiguous</strong> run of indices, and only in <strong>whole batches</strong>:</p>

<p><img class="center" style="width: 720px" alt="Indices 16 to 24 and 26 are acknowledged; the bookmark is saved at 20 and 26 waits for the missing 25" src="/images/eventstore/es-bookmark.png" /></p>

<p>If 7 is acknowledged before 6, the bookmark waits at 5; it can never jump over a message nobody processed. And with the default batch of 1,000, the database sees one write per thousand messages rather than a thousand writes. That second rule is a deliberate trade, and it is exactly where duplicates come from.</p>

<h3 id="exactly-when-wile-gets-charged-twice">Exactly When Wile Gets Charged Twice</h3>
<p>Start EventStore with that configuration on a log that already has some history:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Interface [replayable] 'billing' started and ready to receive messages
Interface billing catch-up completed: processed 6 messages, skipped 7 messages, reached message ID 13
</code></pre></div></div>

<p>A brand-new interface starts at the very beginning of the log: it pushed the 6 matching messages and acknowledged the 7 it does not care about. Adding a service later never needs a backfill job, and it is quick: catching up past 19,502 messages took about three seconds in a test.</p>

<p>Now have Wile order two more things, so billing processes 21 to 24 while its saved bookmark stays at 20, and restart EventStore while billing keeps running:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Interface billing catch-up completed: processed 2 messages, skipped 3 messages, reached message ID 25
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>billing: #21 duplicate, skipped
billing: #23 duplicate, skipped
</code></pre></div></div>

<p>EventStore resumed from 20 and re-sent the two orders above it. Without the duplicate check, Wile would have paid for those rockets twice. So after a restart, an interface is re-sent everything after its saved bookmark: up to <code class="language-plaintext highlighter-rouge">batch - 1</code> processed messages that did not complete a batch, anything stuck behind a gap, and everything still waiting in the queue, which is now in it <strong>twice</strong>. The re-sent copies join the back of the queue, so a slow consumer can see something like <code class="language-plaintext highlighter-rouge">#9, #11, #6, #8, #9, #11</code>. Rely on the index, never on arrival order, and let your database do the bookkeeping, in the same transaction as the charge:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">create</span> <span class="k">table</span> <span class="n">billing_processed</span> <span class="p">(</span><span class="n">event_index</span> <span class="nb">bigint</span> <span class="k">primary</span> <span class="k">key</span><span class="p">);</span>

<span class="c1">-- inside the transaction that records the charge</span>
<span class="k">insert</span> <span class="k">into</span> <span class="n">billing_processed</span> <span class="p">(</span><span class="n">event_index</span><span class="p">)</span> <span class="k">values</span> <span class="p">(:</span><span class="n">messageId</span><span class="p">)</span>
<span class="k">on</span> <span class="n">conflict</span> <span class="k">do</span> <span class="k">nothing</span><span class="p">;</span>   <span class="c1">-- 0 rows: already processed, roll back the charge and just acknowledge</span>
</code></pre></div></div>

<p>And acknowledge duplicates to EventStore too, otherwise the bookmark never moves past them.</p>

<h3 id="realtime-fire-and-forget">Realtime: Fire and Forget</h3>
<p>ACME’s notifications service tells Wile his rocket has shipped. Miss one and Wile finds out when the parcel lands on his head anyway. For that there is a <code class="language-plaintext highlighter-rouge">realtime</code> interface: no ack queue, no bookmark, no catch-up, each message published once as it is committed. “Fire and forget” is only a good choice if you know what gets forgotten:</p>

<table>
  <thead>
    <tr>
      <th>Situation</th>
      <th>realtime</th>
      <th>replayable</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Consumer is down</td>
      <td>messages wait in the queue</td>
      <td>messages wait in the queue</td>
    </tr>
    <tr>
      <td>Interface added later</td>
      <td>never sees history</td>
      <td>catches up from index 1</td>
    </tr>
    <tr>
      <td>EventStore restarts</td>
      <td>nothing is re-sent</td>
      <td>re-sends everything after the bookmark</td>
    </tr>
    <tr>
      <td>Broker unreachable when publishing</td>
      <td>lost</td>
      <td>re-sent after the next EventStore restart</td>
    </tr>
  </tbody>
</table>

<p>That last row hides a rough edge I found while testing :warning:. A failed publish stops the interface’s actor and nothing restarts it, so after a broker outage an interface stays silent until EventStore itself restarts. Replayable interfaces recover everything on that restart; realtime ones lose everything in between. It is a known issue with a clear fix, and until it ships, “broker outage” should be followed by “restart EventStore”.</p>

<h2 id="sharding-more-readers-one-rule">Sharding: More Readers, One Rule</h2>
<p>Sooner or later one pull consumer cannot keep up: the work per message gets heavier and ACME gets busier (Wile has discovered next-day delivery). The hard part of running more readers is splitting the work so that nothing is handled twice, nothing is dropped, and messages that belong together stay with the same reader, in order.</p>

<p>Picture a post office with three clerks: letters are shared out by surname, so every letter lands with exactly one clerk and all the Coyote family’s letters land with the same one. EventStore’s sharding is that rule, with the <code class="language-plaintext highlighter-rouge">userId</code> as the surname. Any stream can ask for its shard:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>GET /api/events/stream?startIndex=1&amp;shardCount=3&amp;shardIndex=0
</code></pre></div></div>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">return</span> <span class="nc">Math</span><span class="o">.</span><span class="na">floorMod</span><span class="o">(</span><span class="n">shardHash</span><span class="o">(</span><span class="n">messageTo</span><span class="o">),</span> <span class="n">shardCount</span><span class="o">)</span> <span class="o">==</span> <span class="n">shardIndex</span><span class="o">;</span>   <span class="c1">// murmur3 of the userId</span>
</code></pre></div></div>

<p><img class="center" style="width: 720px" alt="Six customers hashed onto three readers; each customer always lands with the same reader" src="/images/eventstore/es-shards.png" /></p>

<p>Each reader is otherwise exactly the pull consumer from above, with its own bookmark: no coordinator, no group membership, no rebalancing. Let’s prove it with fifty customers and three readers, each replaying the whole log for its shard:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">CUSTOMERS</span><span class="o">=</span>50 samples/bin/publish-orders.sh 100
mvn <span class="nt">-q</span> <span class="nt">-f</span> samples/05-sharded-readers compile <span class="nb">exec</span>:java
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>reading indices 1..292 with 3 shard readers

shard 0: 115 messages  {customer-0=..., customer-12=..., ...}
shard 1:  64 messages  {...}
shard 2: 113 messages  {...}

total 292 distinct of 292 stored, 0 delivered twice
</code></pre></div></div>

<p>Every one of the 292 messages was delivered exactly once, and every customer appears in exactly one shard. Notice, though, that 115, 64 and 113 are not equal: shards are balanced by <strong>users</strong>, not messages. With only three customers it gets silly, and one of three readers receives nothing at all. A single very busy user makes their shard busy however many shards you add.</p>

<p>How does this compare to Kafka partitions? Kafka sorts letters into bags <strong>at the door</strong>: the partition is chosen when a message is written, and the number of bags is fixed. EventStore sorts <strong>at the desk</strong>: there is one log, and each stream applies the hash as it reads. So you can pick any number of readers, change it whenever you like, and the split applies to history too. The cost is that every reader’s stream reads the whole log inside EventStore; sharding spreads the <em>processing</em>, not the reading. To change the number of readers safely, stop all the old ones, start the new layout from the <strong>lowest</strong> of their bookmarks, and let idempotency absorb the overlap.</p>

<h2 id="conclusion-tada">Conclusion :tada:</h2>
<p>In this blog post we read the log three ways. In summary:</p>

<ul>
  <li><strong>Pull</strong>: the client owns one number; move it after processing, reconnect to recover, and hold side effects until you have caught up.</li>
  <li><strong>No seam</strong>: EventStore registers a stream first, replays, then drops what it has already sent, so a connection never misses or repeats a message.</li>
  <li><strong>Push</strong>: two acknowledgements, a bookmark that moves over contiguous indices in whole batches, and duplicates whose size you can predict; realtime is cheap for a reason.</li>
  <li><strong>Shards</strong>: a pure function of the user, so readers need no coordination, at the price of shards that are only as even as your users.</li>
</ul>

<p>Grab samples <a href="https://github.com/fifteen02/eventstore/tree/main/samples/02-pull-stream">02</a>, <a href="https://github.com/fifteen02/eventstore/tree/main/samples/03-push-replayable">03</a> and <a href="https://github.com/fifteen02/eventstore/tree/main/samples/05-sharded-readers">05</a>, restart things at awkward moments, and watch nothing get lost. In the <a href="/EventStore-Projections-And-Production/">last post</a> we fold the log into state and take it to production.</p>

<p>As always, stay safe, keep hacking!</p>]]></content><author><name>Mark Galea</name></author><category term="eventstore" /><summary type="html"><![CDATA[In the first post we got Wile’s orders into a single, ordered log. A log nobody reads is just an expensive diary, though :smirk:, so this post is all about getting messages out. There are two ways, and they differ in one question: who remembers how far a consumer has got? With pull, the consumer keeps its own bookmark and asks for the log from any point. With push, EventStore keeps the bookmark, delivers over AMQP and resumes after a restart. We will build a consumer for each, work out exactly when a message arrives twice, peek at the trick that joins history to live messages without a seam, and finish by splitting one log across several readers.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://cloudmark.me/images/eventstore/logo-small.png" /><media:content medium="image" url="https://cloudmark.me/images/eventstore/logo-small.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">EventStore: One Ordered Log for Everything</title><link href="https://cloudmark.me/EventStore-Introducing/" rel="alternate" type="text/html" title="EventStore: One Ordered Log for Everything" /><published>2026-10-13T00:01:00+02:00</published><updated>2026-10-13T00:01:00+02:00</updated><id>https://cloudmark.me/EventStore-Introducing</id><content type="html" xml:base="https://cloudmark.me/EventStore-Introducing/"><![CDATA[<p><img class="title" src="/images/eventstore/logo-small.png" />
Every system I have worked on eventually grows the same bit of plumbing. Something happens, an order is placed or a payment clears, and three other services need to know about it. Version one is a queue per consumer. Version two adds a table so a consumer that was down can catch up. Version three adds an ordering column, a “last processed” pointer per consumer, and a script that someone runs when the pointer and the table disagree :grimacing:. After building that plumbing one time too many, I wanted it done once, properly, and today <a href="https://github.com/fifteen02/eventstore">EventStore</a> is open source :tada:! In this blog post I will introduce the idea behind it, show you how messages get in, what that costs, and be very precise about the guarantee you get. It is the first of three posts: the next one covers reading the log, and the last one turns the log into state and runs it in production.</p>

<blockquote>
  <p>For a complete listing of all code samples and to clone the project, visit the <a href="https://github.com/fifteen02/eventstore/tree/main/samples">GitHub repository</a>.</p>
</blockquote>

<h2 id="meet-acme">Meet ACME</h2>
<p>Throughout this series we will follow ACME Corporation, the company that sells rockets, anvils and giant magnets. Its best customer, by far, is Wile E. Coyote. Every time Wile orders something, three services need to know: <strong>billing</strong> has to charge him, <strong>notifications</strong> has to tell him his rocket has shipped (again), and a <strong>dashboard</strong> keeps a running tally of who is spending what.</p>

<p>Simple enough, until billing is down for five minutes. When it comes back, which orders did it miss? In what order did they happen? And how does it avoid charging Wile twice for the same rocket? Those three questions are what EventStore answers, and this is the shape of the answer:</p>

<p><img class="center" style="width: 720px" alt="Producers write into one ordered log; billing and notifications get messages pushed, the dashboard pulls" src="/images/eventstore/es-overview.png" /></p>

<p>Messages come in over REST or an AMQP queue, every one of them gets the next number in a single log, and consumers read that log either by having it <strong>pushed</strong> to them over AMQP or by <strong>pulling</strong> it over HTTP from any point in history.</p>

<h2 id="one-log-one-index">One Log, One Index</h2>
<p>That number is the <strong>global index</strong>: 1, 2, 3 and so on, across every type of message. Think of it as the ticket number at the deli counter. Everyone gets a number, the numbers only go up, and “where am I in the queue?” is answered by a single integer. That one number does three jobs at once:</p>

<ol>
  <li><strong>Identity</strong>: message 42 is message 42, forever.</li>
  <li><strong>Position</strong>: “I have processed everything up to 41” fully describes a consumer’s progress.</li>
  <li><strong>Idempotency key</strong>: “have I already charged for 42?” is a primary-key lookup.</li>
</ol>

<p>If you have used Kafka you might be wondering why there is only one counter. Kafka splits a topic into partitions and gives each partition its own offset, so a consumer’s position is really a <em>vector</em> of numbers, one per partition. That buys a lot of write parallelism, but it costs you a total order:</p>

<p><img class="center" style="width: 720px" alt="A partitioned topic has one offset per partition and no order across them; EventStore has one order for every reader" src="/images/eventstore/es-partitions.png" /></p>

<p>Offset 1 on partition 0 and offset 1 on partition 1 say nothing about which happened first, and two consumers can each be “ahead” of the other on different partitions. EventStore deliberately makes the opposite trade: one counter, so every consumer agrees on what happened before what, and progress is always a single number. The price is paid on the write path.</p>

<h2 id="getting-a-message-in">Getting a Message In</h2>
<p>Here is the heart of the ingestion code, trimmed slightly:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">synchronized</span> <span class="nc">MessageTo</span> <span class="nf">ingest</span><span class="o">(</span><span class="nc">MessageInput</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
    <span class="kt">var</span> <span class="n">contentHash</span> <span class="o">=</span> <span class="n">contentHash</span><span class="o">(</span><span class="n">input</span><span class="o">.</span><span class="na">content</span><span class="o">());</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">duplicateDetectionService</span><span class="o">.</span><span class="na">isDuplicate</span><span class="o">(</span><span class="n">contentHash</span><span class="o">))</span> <span class="o">{</span>
        <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>                                            <span class="c1">// -&gt; 202 Accepted</span>
    <span class="o">}</span>
    <span class="kt">var</span> <span class="n">messageTo</span> <span class="o">=</span> <span class="n">transactionOperations</span><span class="o">.</span><span class="na">execute</span><span class="o">(</span><span class="n">_</span> <span class="o">-&gt;</span> <span class="o">{</span>
        <span class="kt">var</span> <span class="n">message</span> <span class="o">=</span> <span class="n">buildMessage</span><span class="o">(</span><span class="n">input</span><span class="o">,</span> <span class="n">contentHash</span><span class="o">,</span> <span class="n">indexService</span><span class="o">.</span><span class="na">nextCandidate</span><span class="o">().</span><span class="na">value</span><span class="o">());</span>
        <span class="k">return</span> <span class="nc">MessageTo</span><span class="o">.</span><span class="na">from</span><span class="o">(</span><span class="n">messageRepository</span><span class="o">.</span><span class="na">save</span><span class="o">(</span><span class="n">message</span><span class="o">));</span>
    <span class="o">});</span>
    <span class="n">indexService</span><span class="o">.</span><span class="na">markCommitted</span><span class="o">(</span><span class="n">messageTo</span><span class="o">.</span><span class="na">id</span><span class="o">());</span>
    <span class="n">duplicateDetectionService</span><span class="o">.</span><span class="na">recordProcessedHash</span><span class="o">(</span><span class="n">contentHash</span><span class="o">);</span>
    <span class="n">actorRegistry</span><span class="o">.</span><span class="na">tellRouter</span><span class="o">(</span><span class="k">new</span> <span class="nc">RouterActor</span><span class="o">.</span><span class="na">Route</span><span class="o">(</span><span class="n">messageTo</span><span class="o">));</span>  <span class="c1">// hand it to the consumers</span>
    <span class="k">return</span> <span class="n">messageTo</span><span class="o">;</span>                                           <span class="c1">// -&gt; 201 Created</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Three properties fall out of these few lines, and they matter far more than any feature list:</p>

<ul>
  <li><strong>No gaps, ever</strong>: the next index is always “last committed + 1”, and an index only counts as committed after the database transaction succeeds. If a save fails, the next message reuses the number. If you have seen 42, then 1 to 41 exist.</li>
  <li><strong>Nothing is visible before it is durable</strong>: a message is handed to consumers only after its row is committed.</li>
  <li><strong>Order is paid for with serialization</strong>: notice the <code class="language-plaintext highlighter-rouge">synchronized</code>. One message at a time reserves its index, commits and is routed.</li>
</ul>

<p>How expensive is that last one? I measured it on my laptop (Apple M4 Max, PostgreSQL 16 in Docker), publishing 5,000 messages over REST from an in-process Java client:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>concurrency  1:   881 msg/s, 1.13 ms per message
concurrency  8:  1273 msg/s, 6.28 ms per message
concurrency 32:  1602 msg/s, 19.97 ms per message
</code></pre></div></div>

<p>Reading these line by line:</p>

<ul>
  <li>With one client, each publish takes about a millisecond, roughly one database commit.</li>
  <li>With eight clients, throughput goes up by less than half, while each client waits six times longer.</li>
  <li>With thirty-two clients, throughput is less than double the single-client figure.</li>
</ul>

<p>Adding clients mostly adds queueing, exactly as you would expect from a single writer. A database across a network will be slower, but the shape will not change. If you need tens of thousands of events per second in one stream, this is the wrong tool; if you need hundreds to a couple of thousand, with an order you never have to think about, it fits comfortably.</p>

<h3 id="one-instance-per-database">One Instance per Database</h3>
<p>The single writer has one more consequence. EventStore hands out indices from memory: on startup it reads the highest index into a counter and counts up from there. Picture two deli counters handing out tickets from two rolls that both start at 42: two customers get ticket 43, and one of them is going to be disappointed (the second insert fails on the primary key). So the rule is <strong>exactly one instance per database</strong>, and that includes deployments:</p>

<p><img class="center" style="width: 680px" alt="A rolling update briefly runs two writers; Recreate stops the old instance first" src="/images/eventstore/es-deploy.png" /></p>

<p>Use a <code class="language-plaintext highlighter-rouge">Recreate</code> deployment rather than a rolling update. During the short gap, REST producers retry, AMQP producers do not even notice (their messages wait in the queue), and readers reconnect from their bookmarks. One more thing to budget for: shutdown waits up to 30 seconds while streams are connected, because an open stream is a request that never finishes on its own. With a single stream connected I saw about 25 seconds. That is not a hang.</p>

<h2 id="your-first-message">Your First Message</h2>
<p>Let’s run it. You will need Docker, Java 25 and Maven:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose <span class="nt">-f</span> samples/docker-compose.yml up <span class="nt">-d</span> <span class="nt">--wait</span>
mvn <span class="nt">-q</span> <span class="nb">install</span> <span class="nt">-DskipTests</span>
samples/bin/run-eventstore.sh
</code></pre></div></div>

<p>That starts PostgreSQL and an AMQP broker, builds EventStore and runs it on port 8083 with a development token.</p>

<p>If you’d rather watch than read JSON, open the debug console at <a href="http://localhost:8083/debug/events">http://localhost:8083/debug/events</a>, paste <code class="language-plaintext highlighter-rouge">dev-eventstore-token</code> into the Token field, and keep it open while you follow along: every message below shows up there as it lands.</p>

<p><img class="center shot" alt="The EventStore debug console: the head of the log, each consumer's position on a ruler, and the log streaming in live" src="/images/eventstore/debug-console.png" /></p>

<p>Wile orders a rocket:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-X</span> PUT http://localhost:8083/api/events/message <span class="se">\</span>
  <span class="nt">-H</span> <span class="s1">'Authorization: Bearer dev-eventstore-token'</span> <span class="se">\</span>
  <span class="nt">-H</span> <span class="s1">'Content-Type: application/json'</span> <span class="se">\</span>
  <span class="nt">-d</span> <span class="s1">'{"messageType":"OrderPlaced","userId":"customer-1","content":{"orderId":"o-1001","total":49.90}}'</span>
</code></pre></div></div>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="nl">"id"</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span><span class="nl">"messageType"</span><span class="p">:</span><span class="s2">"OrderPlaced"</span><span class="p">,</span><span class="nl">"body"</span><span class="p">:{</span><span class="nl">"orderId"</span><span class="p">:</span><span class="s2">"o-1001"</span><span class="p">,</span><span class="nl">"total"</span><span class="p">:</span><span class="mf">49.9</span><span class="p">},</span><span class="nl">"userId"</span><span class="p">:</span><span class="s2">"customer-1"</span><span class="p">,</span><span class="nl">"contentHash"</span><span class="p">:</span><span class="s2">"3c5f5a66…"</span><span class="p">,</span><span class="w"> </span><span class="err">...</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>The response is the stored message, and <code class="language-plaintext highlighter-rouge">id</code> is its index. Why 2 and not 1? Every time EventStore starts it writes a <code class="language-plaintext highlighter-rouge">StartMarker</code> into the log, so restarts are recorded right there in the history. Reading it back is one request away, and the next post is all about that.</p>

<h3 id="publishing-over-amqp">Publishing Over AMQP</h3>
<p>Producers that already sit on a broker can publish to an input queue instead of calling REST. The body is the content as JSON and everything else travels as headers; <code class="language-plaintext highlighter-rouge">messageType</code> is the one that is required:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">headers</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="nc">MessageHeaders</span><span class="o">.</span><span class="na">MESSAGE_TYPE</span><span class="o">,</span> <span class="s">"OrderPlaced"</span><span class="o">);</span>    <span class="c1">// required</span>
<span class="n">headers</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="nc">MessageHeaders</span><span class="o">.</span><span class="na">USER_ID</span><span class="o">,</span> <span class="s">"customer-1"</span><span class="o">);</span>
<span class="n">headers</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="nc">MessageHeaders</span><span class="o">.</span><span class="na">METADATA</span><span class="o">,</span> <span class="s">"{\"source\":\"order-form\"}"</span><span class="o">);</span>

<span class="n">channel</span><span class="o">.</span><span class="na">confirmSelect</span><span class="o">();</span>
<span class="n">channel</span><span class="o">.</span><span class="na">basicPublish</span><span class="o">(</span><span class="s">""</span><span class="o">,</span> <span class="s">"eventstore.input"</span><span class="o">,</span> <span class="n">properties</span><span class="o">,</span> <span class="n">json</span><span class="o">.</span><span class="na">writeValueAsBytes</span><span class="o">(</span><span class="n">content</span><span class="o">));</span>
<span class="n">channel</span><span class="o">.</span><span class="na">waitForConfirmsOrDie</span><span class="o">(</span><span class="mi">5_000</span><span class="o">);</span>
</code></pre></div></div>

<p>Getting Wile’s order from the form into the log involves two hand-offs, and each deserves a guarantee:</p>

<ol>
  <li><strong>Producer to broker</strong>: use <strong>publisher confirms</strong> (<code class="language-plaintext highlighter-rouge">confirmSelect</code> and <code class="language-plaintext highlighter-rouge">waitForConfirmsOrDie</code>). Without them, a message lost on the way to the broker is lost silently.</li>
  <li><strong>Broker to EventStore</strong>: EventStore acknowledges an input message only <strong>after</strong> it is committed. If EventStore dies halfway, the broker re-delivers.</li>
</ol>

<p>What you give up is the reply: an AMQP producer never learns the index it was given. And a message without a <code class="language-plaintext highlighter-rouge">messageType</code> is rejected without being re-queued. If you want to keep those for a post-mortem, give the input queue a dead-letter policy. I tried it with one untyped message and one valid one:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>WARN c.f.e.amqp.EventstoreInputHandler - Rejecting AMQP input without a messageType header (delivery tag 3)
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>eventstore.input messages 0 consumers 1
eventstore.input.rejected messages 1 consumers 0
</code></pre></div></div>

<p>The bad message is parked in the dead-letter queue, the valid one was stored, and ingestion carried on.</p>

<h2 id="duplicates">Duplicates</h2>
<p>What happens if a producer sends the same thing twice? Let’s try:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for </span>i <span class="k">in </span>1 2<span class="p">;</span> <span class="k">do </span>curl <span class="nt">-s</span> <span class="nt">-o</span> /dev/null <span class="nt">-w</span> <span class="s1">'%{http_code}\n'</span> <span class="nt">-X</span> PUT localhost:8083/api/events/message <span class="se">\</span>
  <span class="nt">-H</span> <span class="s1">'Authorization: Bearer dev-eventstore-token'</span> <span class="nt">-H</span> <span class="s1">'Content-Type: application/json'</span> <span class="se">\</span>
  <span class="nt">-d</span> <span class="s1">'{"messageType":"OrderPlaced","content":{"orderId":"same"}}'</span><span class="p">;</span> <span class="k">done</span>
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>201
202
</code></pre></div></div>

<p>The second one was accepted but not stored. It is tempting to read too much into this, so here is exactly what happens. On startup EventStore loads the hashes of the most recent messages (2,000 by default). For the next 2,000 messages it ingests, any message whose body hashes the same as a remembered one is skipped. After that the check switches itself off until the next restart.</p>

<p>Why such a narrow window? Because it targets one specific accident: a producer sends a batch, EventStore restarts before the responses arrive, and the producer helpfully sends the whole batch again. It is a safety net, not a deduplication layer:</p>

<ul>
  <li>Only the body is hashed, so give every real event a unique body. Two genuine <code class="language-plaintext highlighter-rouge">OrderPlaced</code> events that both just say <code class="language-plaintext highlighter-rouge">{"orderId":"o-1"}</code> collapse into one while the window is open.</li>
  <li>Outside the window nothing is suppressed, so producers that need exactly-once writes bring their own idempotency key.</li>
</ul>

<h2 id="the-guarantee">The Guarantee</h2>
<p>Let’s be precise, because this one sentence shapes every consumer in this series. EventStore gives you <strong>at-least-once delivery over a gap-free, totally ordered log</strong>:</p>

<ul>
  <li>A committed message is never lost, and indices never repeat or skip.</li>
  <li>A single stream delivers indices in increasing order, each at most once per connection.</li>
  <li>A consumer <em>can</em> see the same message more than once, after a crash or a restart. The next post shows exactly when.</li>
</ul>

<p>So every consumer we write is idempotent, and the index makes that cheap: it is unique, it never changes, and it arrives with every message.</p>

<h2 id="conclusion-tada">Conclusion :tada:</h2>
<p>In this blog post we introduced EventStore and the decisions behind it. In summary:</p>

<ul>
  <li><strong>One index</strong>: one number is a message’s identity, a consumer’s position and your idempotency key, and it gives every consumer the same order.</li>
  <li><strong>One writer</strong>: gap-free ordering and “visible means durable” come from a single serialized write path, which caps throughput and means one instance per database, deployed with <code class="language-plaintext highlighter-rouge">Recreate</code>.</li>
  <li><strong>Two safe ways in</strong>: REST if you want the index back, AMQP with publisher confirms (and a dead-letter queue) if you don’t.</li>
  <li><strong>At least once</strong>: duplicate suppression covers producer retries after a restart; everything else is the consumer’s job, keyed by the index.</li>
</ul>

<p>Clone the <a href="https://github.com/fifteen02/eventstore">repository</a>, run sample 01, and send Wile a rocket of your own :rocket:. Next time, we read the log: pulling it, pushing it and sharding it.</p>

<p>As always, stay safe, keep hacking!</p>]]></content><author><name>Mark Galea</name></author><category term="eventstore" /><summary type="html"><![CDATA[Every system I have worked on eventually grows the same bit of plumbing. Something happens, an order is placed or a payment clears, and three other services need to know about it. Version one is a queue per consumer. Version two adds a table so a consumer that was down can catch up. Version three adds an ordering column, a “last processed” pointer per consumer, and a script that someone runs when the pointer and the table disagree :grimacing:. After building that plumbing one time too many, I wanted it done once, properly, and today EventStore is open source :tada:! In this blog post I will introduce the idea behind it, show you how messages get in, what that costs, and be very precise about the guarantee you get. It is the first of three posts: the next one covers reading the log, and the last one turns the log into state and runs it in production.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://cloudmark.me/images/eventstore/logo-small.png" /><media:content medium="image" url="https://cloudmark.me/images/eventstore/logo-small.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Cats-Actors 2.2.0: Taking Control of Time</title><link href="https://cloudmark.me/Cats-Actors-Controlling-Time/" rel="alternate" type="text/html" title="Cats-Actors 2.2.0: Taking Control of Time" /><published>2026-09-01T00:00:00+02:00</published><updated>2026-09-01T00:00:00+02:00</updated><id>https://cloudmark.me/Cats-Actors-Controlling-Time</id><content type="html" xml:base="https://cloudmark.me/Cats-Actors-Controlling-Time/"><![CDATA[<p><img class="title" src="/images/cats-actors/logo-small.png" />
Every actor test suite eventually grows a graveyard of sleeps. You schedule something for five seconds, so the test sleeps for six. You set a receive timeout of a minute, and quietly decide that particular branch is untestable. Then CI runs on a loaded machine, a sleep lands a few milliseconds early, and a test that was fine on your laptop goes red for reasons nobody can reproduce. Cats-Actors 2.2.0 fixes this by handing you the clock. Scheduled work, receive timeouts, supervision restart windows: all of it now runs in <em>simulated</em> time, which means an hour-long timeout can be tested in milliseconds and the result is the same every single run.</p>

<h2 id="the-problem-with-waiting">The Problem With Waiting</h2>

<p>Here is the test everyone writes at least once. An actor schedules some work for five seconds from now, and we want to prove it fires:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span> <span class="o">{</span>
  <span class="n">fired</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">(</span><span class="kc">false</span><span class="o">)</span>
  <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nf">schedulingActor</span><span class="o">(</span><span class="n">fired</span><span class="o">),</span> <span class="s">"scheduler-actor"</span><span class="o">)</span>
  <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">IO</span><span class="o">.</span><span class="py">sleep</span><span class="o">(</span><span class="mf">6.</span><span class="n">seconds</span><span class="o">)</span>   <span class="c1">// 😴 six real seconds of your life</span>
  <span class="n">result</span> <span class="k">&lt;-</span> <span class="nv">fired</span><span class="o">.</span><span class="py">get</span>
<span class="o">}</span> <span class="k">yield</span> <span class="n">result</span> <span class="n">shouldBe</span> <span class="kc">true</span>
</code></pre></div></div>

<p>It works. It also costs six seconds of wall-clock time, every run, forever. Multiply that by a suite of thirty timing tests and your feedback loop is measured in minutes. Worse, the six is a guess. It is “five plus a bit for luck”, and the amount of luck required depends on how busy the machine is.</p>

<p>Cats Effect has had the answer to this for a while in <code class="language-plaintext highlighter-rouge">TestControl</code>: a runtime where <code class="language-plaintext highlighter-rouge">IO.sleep</code> does not sleep, it simply advances a simulated clock. What was missing was the plumbing to run an entire actor system inside it.</p>

<h2 id="enter-controlledtestkit">Enter <code class="language-plaintext highlighter-rouge">ControlledTestKit</code></h2>

<p>2.2.0 ships <code class="language-plaintext highlighter-rouge">ControlledTestKit</code> in the companion testkit module:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">resolvers</span> <span class="o">+=</span> <span class="s">"jitpack"</span> <span class="n">at</span> <span class="s">"https://jitpack.io"</span>

<span class="n">libraryDependencies</span> <span class="o">+=</span> <span class="s">"com.github.cloudmark.cats-actors"</span> <span class="o">%%%</span> <span class="s">"cats-actors-testkit"</span> <span class="o">%</span> <span class="s">"2.2.0"</span> <span class="o">%</span> <span class="nc">Test</span>
</code></pre></div></div>

<p>Mix the trait into your spec and wrap the body in <code class="language-plaintext highlighter-rouge">withActorSystemIO</code>. It provisions an <code class="language-plaintext highlighter-rouge">ActorSystem[IO]</code>, runs your logic under <code class="language-plaintext highlighter-rouge">TestControl</code>, ticks the simulated clock, and hands back the result:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="nn">cats.effect.</span><span class="o">{</span><span class="nc">IO</span><span class="o">,</span> <span class="nc">Ref</span><span class="o">}</span>
<span class="k">import</span> <span class="nn">cats.effect.testing.scalatest.AsyncIOSpec</span>
<span class="k">import</span> <span class="nn">com.suprnation.actor.Actor.</span><span class="o">{</span><span class="nc">Actor</span><span class="o">,</span> <span class="nc">Receive</span><span class="o">}</span>
<span class="k">import</span> <span class="nn">com.suprnation.actor.test.ControlledTestKit</span>
<span class="k">import</span> <span class="nn">org.scalatest.matchers.should.Matchers</span>
<span class="k">import</span> <span class="nn">org.scalatest.wordspec.AsyncWordSpec</span>

<span class="k">import</span> <span class="nn">scala.concurrent.duration._</span>

<span class="k">class</span> <span class="nc">SchedulerSpec</span>
    <span class="k">extends</span> <span class="nc">AsyncWordSpec</span>
    <span class="k">with</span> <span class="nc">AsyncIOSpec</span>
    <span class="k">with</span> <span class="nc">Matchers</span>
    <span class="k">with</span> <span class="nc">ControlledTestKit</span> <span class="o">{</span>

  <span class="s">"An actor scheduling delayed work"</span> <span class="n">should</span> <span class="o">{</span>
    <span class="s">"observe the task firing without waiting in real time"</span> <span class="n">in</span>
      <span class="n">withActorSystemIO</span> <span class="o">{</span> <span class="n">system</span> <span class="k">=&gt;</span>
        <span class="k">for</span> <span class="o">{</span>
          <span class="n">fired</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">(</span><span class="kc">false</span><span class="o">)</span>
          <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span>
            <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">String</span><span class="o">]</span> <span class="o">{</span>
              <span class="k">override</span> <span class="k">def</span> <span class="nf">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span>
                <span class="c1">// scheduleOnce_ fires in the background (it `.start`s a fiber);</span>
                <span class="c1">// scheduleOnce would instead block preStart for the full delay.</span>
                <span class="nv">context</span><span class="o">.</span><span class="py">system</span><span class="o">.</span><span class="py">scheduler</span><span class="o">.</span><span class="py">scheduleOnce_</span><span class="o">(</span><span class="mf">5.</span><span class="n">seconds</span><span class="o">)(</span><span class="nv">fired</span><span class="o">.</span><span class="py">set</span><span class="o">(</span><span class="kc">true</span><span class="o">)).</span><span class="py">void</span>

              <span class="k">override</span> <span class="k">def</span> <span class="nf">receive</span><span class="k">:</span> <span class="kt">Receive</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">String</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span> <span class="k">case</span> <span class="k">_</span> <span class="k">=&gt;</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span> <span class="o">}</span>
            <span class="o">},</span>
            <span class="s">"scheduler-actor"</span>
          <span class="o">)</span>
          <span class="c1">// Written as a 6s wait, but ControlledTestKit advances simulated</span>
          <span class="c1">// time, so the test still completes instantly.</span>
          <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">IO</span><span class="o">.</span><span class="py">sleep</span><span class="o">(</span><span class="mf">6.</span><span class="n">seconds</span><span class="o">)</span>
          <span class="n">result</span> <span class="k">&lt;-</span> <span class="nv">fired</span><span class="o">.</span><span class="py">get</span>
        <span class="o">}</span> <span class="k">yield</span> <span class="n">result</span> <span class="n">shouldBe</span> <span class="kc">true</span>
      <span class="o">}</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Same test, same six-second sleep, except now it finishes in the time it takes to allocate a <code class="language-plaintext highlighter-rouge">Ref</code>. The sleep is not skipped, mind you. It is <em>honoured</em> against a clock that we advance ourselves, so ordering is preserved: work scheduled for five seconds still happens strictly before the six-second mark.</p>

<p>The signature is small on purpose:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">withActorSystemIO</span><span class="o">[</span><span class="kt">T</span><span class="o">](</span>
    <span class="n">testCode</span><span class="k">:</span> <span class="kt">ActorSystem</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=&gt;</span> <span class="nc">IO</span><span class="o">[</span><span class="kt">T</span><span class="o">],</span>
    <span class="n">testTimeWindow</span><span class="k">:</span> <span class="kt">FiniteDuration</span> <span class="o">=</span> <span class="nc">FiniteDuration</span><span class="o">(</span><span class="mi">90</span><span class="o">,</span> <span class="nv">TimeUnit</span><span class="o">.</span><span class="py">SECONDS</span><span class="o">)</span>
<span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">T</span><span class="o">]</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">testTimeWindow</code> is how much <em>simulated</em> time to tick through, not how long you are prepared to wait. Ninety simulated seconds cost nothing, so feel free to raise it. The returned <code class="language-plaintext highlighter-rouge">IO</code> succeeds with your value, or fails: errors propagate as themselves, while a cancelled or unfinished test surfaces as a <code class="language-plaintext highlighter-rouge">ControlledTestException.Canceled</code> or <code class="language-plaintext highlighter-rouge">ControlledTestException.TimedOut</code>. It is framework agnostic, so any runner that can execute an <code class="language-plaintext highlighter-rouge">IO</code> will do. If you would rather inspect a failure than propagate it, <code class="language-plaintext highlighter-rouge">.attempt</code> the result.</p>

<p><code class="language-plaintext highlighter-rouge">ControlledTestKit</code> extends <code class="language-plaintext highlighter-rouge">TestKit</code>, so every message assertion you already use (<code class="language-plaintext highlighter-rouge">expectMsgs</code>, <code class="language-plaintext highlighter-rouge">expectMsgType</code>, <code class="language-plaintext highlighter-rouge">awaitTerminated</code>, probes) works inside a controlled-time test.</p>

<h2 id="the-test-that-was-impossible-before">The Test That Was Impossible Before</h2>

<p>Here is my favourite consequence. Receive timeouts now honour simulated time too, which makes this a perfectly reasonable thing to write:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">replyingActorOf</span><span class="o">(</span><span class="nf">constantFlowActor</span><span class="o">(</span><span class="mf">1.</span><span class="n">hour</span><span class="o">,</span> <span class="n">counter</span><span class="o">,</span> <span class="n">buffer</span><span class="o">),</span> <span class="s">"long-timeout-actor"</span><span class="o">)</span>
<span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">IO</span><span class="o">.</span><span class="py">sleep</span><span class="o">(</span><span class="mf">65.</span><span class="n">minutes</span><span class="o">)</span>   <span class="c1">// an hour and five minutes, in about a millisecond</span>
<span class="n">timeouts</span> <span class="k">&lt;-</span> <span class="n">helloActor</span> <span class="o">?</span> <span class="nc">Get</span>
</code></pre></div></div>

<p>An hour-long receive timeout, verified in a unit test, deterministically. Before 2.2.0 the only way to check that branch was to actually wait an hour, which is another way of saying nobody ever checked it.</p>

<h2 id="why-it-did-not-work-before">Why It Did Not Work Before</h2>

<p>The reason receive timeouts ignored <code class="language-plaintext highlighter-rouge">TestControl</code> was mundane. <code class="language-plaintext highlighter-rouge">ReceiveTimeout</code> recorded when the last message arrived using <code class="language-plaintext highlighter-rouge">System.currentTimeMillis</code>. <code class="language-plaintext highlighter-rouge">TestControl</code> can advance an <code class="language-plaintext highlighter-rouge">IO.sleep</code>, but it has no power whatsoever over the system wall clock. So virtual time raced ahead an hour while the wall clock moved a fraction of a millisecond, the timeout never came due, and the test hung or silently proved nothing.</p>

<p>The fix was to read the clock through Cats Effect instead:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">private</span> <span class="k">def</span> <span class="nf">nowMillis</span><span class="k">:</span> <span class="kt">F</span><span class="o">[</span><span class="kt">Long</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Clock</span><span class="o">[</span><span class="kt">F</span><span class="o">].</span><span class="py">monotonic</span><span class="o">.</span><span class="py">map</span><span class="o">(</span><span class="nv">_</span><span class="o">.</span><span class="py">toMillis</span><span class="o">)</span>
</code></pre></div></div>

<p>Two details worth stealing if you are doing the same thing in your own codebase:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">Clock[F]</code>, not <code class="language-plaintext highlighter-rouge">Temporal[F]</code>.</strong> <code class="language-plaintext highlighter-rouge">Temporal</code> only adds <code class="language-plaintext highlighter-rouge">sleep</code> on top of <code class="language-plaintext highlighter-rouge">Clock</code>, so <code class="language-plaintext highlighter-rouge">Clock</code> is the weaker (and therefore better) constraint. More often than not it is already in scope: <code class="language-plaintext highlighter-rouge">Sync</code> extends <code class="language-plaintext highlighter-rouge">Clock</code>, so the change frequently costs you no new typeclass bound at all.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">monotonic</code> for elapsed time, <code class="language-plaintext highlighter-rouge">realTime</code> for timestamps.</strong> A timeout measures a <em>duration</em>, so it should be immune to the wall clock jumping under it (NTP corrections, someone changing the system time). <code class="language-plaintext highlighter-rouge">TestControl</code> advances both, so you lose nothing by picking the correct one.</li>
</ul>

<h2 id="supervision-windows-play-along-too">Supervision Windows Play Along Too</h2>

<p>The same treatment went to supervision, which is where simulated time earns its keep a second time. Every strategy can be given a retry budget over a window:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">OneForOneStrategy</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="n">maxNrOfRetries</span> <span class="k">=</span> <span class="mi">2</span><span class="o">,</span> <span class="n">withinTimeRange</span> <span class="k">=</span> <span class="mf">500.</span><span class="n">millis</span><span class="o">)</span> <span class="o">{</span> <span class="k">case</span> <span class="k">_</span> <span class="k">=&gt;</span> <span class="nc">Restart</span> <span class="o">}</span>
</code></pre></div></div>

<p>“Restart the child up to twice in any 500ms window.” Testing that honestly means arranging failures on either side of the window boundary, which used to mean sleeping through it for real. The window is now measured with the monotonic clock, so it moves with simulated time like everything else, and the test becomes something you would actually write: with <code class="language-plaintext highlighter-rouge">maxNrOfRetries = 2</code> and <code class="language-plaintext highlighter-rouge">withinTimeRange = 500.millis</code>, fire three failures a <em>virtual</em> second apart. Each one opens a fresh window, so all three children restart, and the whole thing runs in milliseconds.</p>

<p>Getting there without disturbing the public API took a small trick worth knowing. <code class="language-plaintext highlighter-rouge">ChildRestartStats</code> stays free of any effect type: the caller passes the timestamp in, and both strategies read the clock in <code class="language-plaintext highlighter-rouge">processFailure</code>, which already returns <code class="language-plaintext highlighter-rouge">F[Unit]</code>:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">context</span><span class="o">.</span><span class="py">system</span><span class="o">.</span><span class="py">temporalF</span><span class="o">.</span><span class="py">monotonic</span><span class="o">.</span><span class="py">flatMap</span> <span class="o">{</span> <span class="n">now</span> <span class="k">=&gt;</span>
  <span class="nf">if</span> <span class="o">(</span><span class="n">restart</span> <span class="o">&amp;&amp;</span> <span class="nv">stats</span><span class="o">.</span><span class="py">requestRestartPermission</span><span class="o">(</span><span class="n">retriesWindow</span><span class="o">,</span> <span class="nv">now</span><span class="o">.</span><span class="py">toNanos</span><span class="o">))</span>
    <span class="nf">restartChild</span><span class="o">(</span><span class="n">child</span><span class="o">,</span> <span class="n">cause</span><span class="o">,</span> <span class="n">suspendFirst</span> <span class="k">=</span> <span class="kc">false</span><span class="o">)</span>
  <span class="k">else</span>
    <span class="nv">context</span><span class="o">.</span><span class="py">stop</span><span class="o">(</span><span class="n">child</span><span class="o">)</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The actor system already exposes a <code class="language-plaintext highlighter-rouge">Temporal[F]</code>, so <code class="language-plaintext highlighter-rouge">OneForOneStrategy</code> and <code class="language-plaintext highlighter-rouge">AllForOneStrategy</code> gained no new constraint at all.</p>

<h2 id="also-in-this-release">Also In This Release</h2>

<p>A few smaller things came along for the ride:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">expectMsgTypeCountN</code> and <code class="language-plaintext highlighter-rouge">expectMsgTypeSingle</code></strong> in <code class="language-plaintext highlighter-rouge">TestKit</code>. These count messages of a given type in the buffer, and unlike <code class="language-plaintext highlighter-rouge">expectMsgType</code> they do not care <em>when</em> the message arrived relative to the call. <code class="language-plaintext highlighter-rouge">expectMsgType</code> snapshots the buffer on entry and requires exactly one new message after that snapshot, which makes it quietly unreliable when the message arrives quickly. It now carries a warning in its scaladoc, and <code class="language-plaintext highlighter-rouge">expectMsgTypeCountN</code> is the assertion you probably want.</li>
  <li><strong>Better failure output.</strong> <code class="language-plaintext highlighter-rouge">expectMsgs</code> now prints the queue state when it fails, so you can see what the actor <em>did</em> receive.</li>
  <li><strong>The dead-letter mailbox idle check</strong> moved to the monotonic clock as well.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ActorSystem.uptime</code> is now <code class="language-plaintext highlighter-rouge">F[Long]</code></strong> rather than <code class="language-plaintext highlighter-rouge">Long</code>, measured against the monotonic clock. This is a breaking change, though a small one: <code class="language-plaintext highlighter-rouge">system.uptime.flatMap(...)</code> instead of <code class="language-plaintext highlighter-rouge">system.uptime</code>.</li>
</ul>

<p>One deliberate omission: <code class="language-plaintext highlighter-rouge">LogEvent.timestamp</code> still reads the wall clock. It records <em>when an event was created</em>, which is a genuine timestamp rather than an elapsed measurement, so <code class="language-plaintext highlighter-rouge">realTime</code> semantics are the honest answer there and threading a clock through it would buy nothing in determinism.</p>

<h2 id="upgrading">Upgrading</h2>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">resolvers</span> <span class="o">+=</span> <span class="s">"jitpack"</span> <span class="n">at</span> <span class="s">"https://jitpack.io"</span>

<span class="n">libraryDependencies</span> <span class="o">+=</span> <span class="s">"com.github.cloudmark.cats-actors"</span> <span class="o">%%%</span> <span class="s">"cats-actors"</span> <span class="o">%</span> <span class="s">"2.2.0"</span>
<span class="n">libraryDependencies</span> <span class="o">+=</span> <span class="s">"com.github.cloudmark.cats-actors"</span> <span class="o">%%%</span> <span class="s">"cats-actors-testkit"</span> <span class="o">%</span> <span class="s">"2.2.0"</span> <span class="o">%</span> <span class="nc">Test</span>
</code></pre></div></div>

<p>Scala 2.13 and 3, on JVM, Scala.js and Scala Native, as always. The only source-level break is <code class="language-plaintext highlighter-rouge">uptime</code>, plus <code class="language-plaintext highlighter-rouge">ChildRestartStats.requestRestartPermission</code> if you happen to call it directly from a hand-rolled <code class="language-plaintext highlighter-rouge">SupervisionStrategy</code>. The built-in strategies are unchanged.</p>

<h2 id="conclusion-tada">Conclusion :tada:</h2>

<p>Deterministic tests are not a luxury feature for a concurrency library, they are the whole point. If you cannot test the timeout, the retry window, and the scheduled sweep without inserting real sleeps into your build, you end up not testing them at all, and those are precisely the paths that fail at three in the morning.</p>

<p>What I like most about this release is how it came about. Somebody read the source, noticed <code class="language-plaintext highlighter-rouge">System.currentTimeMillis</code> where a <code class="language-plaintext highlighter-rouge">Clock</code> belonged, and asked whether there was a reason for it. There was not, only inheritance from an older design. Following that thread turned a handful of untestable code paths into ordinary ones, and left the suite faster and steadier than it was last week. Good questions are worth more than good answers.</p>

<p>Grab <a href="https://github.com/cloudmark/cats-actors">Cats-Actors 2.2.0</a>, point <code class="language-plaintext highlighter-rouge">ControlledTestKit</code> at your slowest timing test, and enjoy watching an hour go by instantly.</p>

<p>As always, stay safe, keep hacking!</p>]]></content><author><name>Mark Galea</name></author><category term="cats-actors" /><summary type="html"><![CDATA[Every actor test suite eventually grows a graveyard of sleeps. You schedule something for five seconds, so the test sleeps for six. You set a receive timeout of a minute, and quietly decide that particular branch is untestable. Then CI runs on a loaded machine, a sleep lands a few milliseconds early, and a test that was fine on your laptop goes red for reasons nobody can reproduce. Cats-Actors 2.2.0 fixes this by handing you the clock. Scheduled work, receive timeouts, supervision restart windows: all of it now runs in simulated time, which means an hour-long timeout can be tested in milliseconds and the result is the same every single run.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://cloudmark.me/images/cats-actors/logo-small.png" /><media:content medium="image" url="https://cloudmark.me/images/cats-actors/logo-small.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Cats-Actors 2.1.0 Goes Cross-Platform</title><link href="https://cloudmark.me/Cats-Actors-Native-And-JS/" rel="alternate" type="text/html" title="Cats-Actors 2.1.0 Goes Cross-Platform" /><published>2026-04-03T00:00:00+02:00</published><updated>2026-04-03T00:00:00+02:00</updated><id>https://cloudmark.me/Cats-Actors-Native-And-JS</id><content type="html" xml:base="https://cloudmark.me/Cats-Actors-Native-And-JS/"><![CDATA[<p><img class="title" src="/images/cats-actors/logo-small.png" />
Imagine writing your actor logic once (typed messages, functional state, the <code class="language-plaintext highlighter-rouge">!</code> operator, supervision and all) and then deciding on a whim whether it runs as a JVM service, a self-contained native binary, or a live interactive app in your browser. No rewrites, no ports, no platform-specific glue. Just one codebase. Cats-Actors can do that now, and in this post we are going to have some fun with it. We will throw a token around a ring of actors on both JVM and Scala Native, and then (because why not) we will drop eight monkey actors into a banana-throwing arena right here inside this page. Real actors. Real messages. Running in your browser.</p>

<h2 id="setting-up-your-project">Setting Up Your Project</h2>

<p>To get started you will need to configure your project as a cross-project so sbt can compile to all three targets.</p>

<h3 id="adding-dependencies">Adding Dependencies</h3>

<p>Add JitPack to your resolvers and pull in cats-actors using the <code class="language-plaintext highlighter-rouge">%%%</code> triple-percent operator, which selects the right artifact for each platform automatically:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">resolvers</span> <span class="o">+=</span> <span class="s">"jitpack"</span> <span class="n">at</span> <span class="s">"https://jitpack.io"</span>

<span class="n">libraryDependencies</span> <span class="o">+=</span> <span class="s">"com.github.suprnation.cats-actors"</span> <span class="o">%%%</span> <span class="s">"cats-actors"</span> <span class="o">%</span> <span class="s">"2.1.0"</span>
</code></pre></div></div>

<p>Then declare a cross-project in your <code class="language-plaintext highlighter-rouge">build.sbt</code>:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="nn">org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._</span>
<span class="k">import</span> <span class="nn">scala.scalanative.build._</span>

<span class="nc">ThisBuild</span> <span class="o">/</span> <span class="n">scalaVersion</span> <span class="o">:=</span> <span class="s">"2.13.18"</span>

<span class="k">lazy</span> <span class="k">val</span> <span class="nv">myProject</span> <span class="k">=</span> <span class="nf">crossProject</span><span class="o">(</span><span class="nc">JVMPlatform</span><span class="o">,</span> <span class="nc">JSPlatform</span><span class="o">,</span> <span class="nc">NativePlatform</span><span class="o">)</span>
  <span class="o">.</span><span class="py">crossType</span><span class="o">(</span><span class="nv">CrossType</span><span class="o">.</span><span class="py">Full</span><span class="o">)</span>
  <span class="o">.</span><span class="py">settings</span><span class="o">(</span>
    <span class="n">libraryDependencies</span> <span class="o">++=</span> <span class="nc">Seq</span><span class="o">(</span>
      <span class="s">"com.github.suprnation.cats-actors"</span> <span class="o">%%%</span> <span class="s">"cats-actors"</span> <span class="o">%</span> <span class="s">"2.1.0"</span>
    <span class="o">)</span>
  <span class="o">)</span>
  <span class="o">.</span><span class="py">nativeSettings</span><span class="o">(</span>
    <span class="n">nativeConfig</span> <span class="o">~=</span> <span class="o">{</span>
      <span class="nv">_</span><span class="o">.</span><span class="py">withLTO</span><span class="o">(</span><span class="nv">LTO</span><span class="o">.</span><span class="py">none</span><span class="o">)</span>
        <span class="o">.</span><span class="py">withMode</span><span class="o">(</span><span class="nv">Mode</span><span class="o">.</span><span class="py">releaseFull</span><span class="o">)</span>
        <span class="o">.</span><span class="py">withGC</span><span class="o">(</span><span class="nv">GC</span><span class="o">.</span><span class="py">immix</span><span class="o">)</span>
    <span class="o">}</span>
  <span class="o">)</span>
</code></pre></div></div>

<p>With <code class="language-plaintext highlighter-rouge">CrossType.Full</code> you get separate <code class="language-plaintext highlighter-rouge">jvm/</code>, <code class="language-plaintext highlighter-rouge">js/</code>, and <code class="language-plaintext highlighter-rouge">native/</code> source trees alongside the shared one. Everything in <code class="language-plaintext highlighter-rouge">shared/</code> compiles everywhere. Platform-specific code lives in its own tree, and the build wires it in automatically.</p>

<p>From there, running on any platform is just a target name:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sbt <span class="s2">"myProjectJVM/run"</span>      <span class="c"># JVM</span>
sbt <span class="s2">"myProjectJS/run"</span>       <span class="c"># Node.js</span>
sbt <span class="s2">"myProjectNative/run"</span>   <span class="c"># Scala Native binary</span>
</code></pre></div></div>

<blockquote>
  <p>Note: to view and run all code samples discussed in this blog post, clone the <a href="https://github.com/cloudmark/cats-actor-sample">GitHub repository</a>.</p>
</blockquote>

<h2 id="racing-jvm-against-native">Racing JVM Against Native</h2>

<p>The actor ring benchmark is a classic. Popularised by Erlang, it has been used to compare actor systems for decades. Create a ring of <code class="language-plaintext highlighter-rouge">N</code> actors, inject a single token, and let it travel <code class="language-plaintext highlighter-rouge">totalHops</code> times around the ring. Each relay is one message send. Measure the total time. Same code, two platforms, see what happens.</p>

<p>The full code lives in <a href="https://github.com/cloudmark/cats-actor-sample/tree/main/sample7"><code class="language-plaintext highlighter-rouge">sample7</code></a> in the repository, but let’s walk through it.</p>

<div class="mermaid">
graph LR
    N0["RingNode 0 ●"] --&gt;|"RingToken(r-1)"| N1["RingNode 1"]
    N1 --&gt;|"RingToken(r-2)"| N2["RingNode 2"]
    N2 --&gt;|"..."| N3["RingNode N-1"]
    N3 --&gt;|"RingToken(0) → done!"| N0
</div>

<h3 id="the-ring-actor">The Ring Actor</h3>

<p>Each actor in the ring does exactly one thing: if the token still has hops remaining, pass it to the next actor. When the count hits zero, signal that the relay is done.</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">final</span> <span class="k">case</span> <span class="k">class</span> <span class="nc">RingToken</span><span class="o">(</span><span class="n">remaining</span><span class="k">:</span> <span class="kt">Long</span><span class="o">)</span>

<span class="k">final</span> <span class="k">class</span> <span class="nc">RingNode</span><span class="o">(</span>
    <span class="n">index</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span>
    <span class="n">ringSize</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span>
    <span class="n">slots</span><span class="k">:</span> <span class="kt">Ref</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Option</span><span class="o">[</span><span class="kt">Vector</span><span class="o">[</span><span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">RingToken</span><span class="o">]]]],</span>
    <span class="n">done</span><span class="k">:</span> <span class="kt">Deferred</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Unit</span><span class="o">]</span>
<span class="o">)</span> <span class="k">extends</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">RingToken</span><span class="o">]</span> <span class="o">{</span>

  <span class="k">override</span> <span class="k">def</span> <span class="nf">receive</span><span class="k">:</span> <span class="kt">Receive</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">RingToken</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
    <span class="k">case</span> <span class="nc">RingToken</span><span class="o">(</span><span class="mi">0L</span><span class="o">)</span> <span class="k">=&gt;</span>
      <span class="nv">done</span><span class="o">.</span><span class="py">complete</span><span class="o">(()).</span><span class="py">void</span>
    <span class="k">case</span> <span class="nc">RingToken</span><span class="o">(</span><span class="n">r</span><span class="o">)</span> <span class="k">if</span> <span class="n">r</span> <span class="o">&gt;</span> <span class="mi">0L</span> <span class="k">=&gt;</span>
      <span class="k">for</span> <span class="o">{</span>
        <span class="n">vecOpt</span> <span class="k">&lt;-</span> <span class="nv">slots</span><span class="o">.</span><span class="py">get</span>
        <span class="n">vec</span>    <span class="k">&lt;-</span> <span class="n">vecOpt</span> <span class="k">match</span> <span class="o">{</span>
          <span class="k">case</span> <span class="nc">Some</span><span class="o">(</span><span class="n">v</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">IO</span><span class="o">.</span><span class="py">pure</span><span class="o">(</span><span class="n">v</span><span class="o">)</span>
          <span class="k">case</span> <span class="nc">None</span>    <span class="k">=&gt;</span> <span class="nv">IO</span><span class="o">.</span><span class="py">raiseError</span><span class="o">(</span><span class="k">new</span> <span class="nc">IllegalStateException</span><span class="o">(</span><span class="s">"ring not wired"</span><span class="o">))</span>
        <span class="o">}</span>
        <span class="n">next</span> <span class="k">=</span> <span class="nf">vec</span><span class="o">((</span><span class="n">index</span> <span class="o">+</span> <span class="mi">1</span><span class="o">)</span> <span class="o">%</span> <span class="n">ringSize</span><span class="o">)</span>
        <span class="k">_</span>    <span class="k">&lt;-</span> <span class="n">next</span> <span class="o">!</span> <span class="nc">RingToken</span><span class="o">(</span><span class="n">r</span> <span class="o">-</span> <span class="mi">1L</span><span class="o">)</span>
      <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
    <span class="k">case</span> <span class="k">_</span> <span class="k">=&gt;</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h3 id="breaking-down-the-ringnode">Breaking Down the RingNode</h3>

<ol>
  <li>
    <p><strong>The token</strong>: <code class="language-plaintext highlighter-rouge">RingToken</code> carries a single field, <code class="language-plaintext highlighter-rouge">remaining</code>, counting down from <code class="language-plaintext highlighter-rouge">totalHops</code> to zero. That is all that ever travels on the wire.</p>
  </li>
  <li>
    <p><strong>The ring topology</strong>: The vector of actor refs is stored in a <code class="language-plaintext highlighter-rouge">Ref</code> because all nodes are spawned before any of them know about the others. The harness wires them up in a second pass by calling <code class="language-plaintext highlighter-rouge">slots.set(Some(refs))</code>.</p>
  </li>
  <li>
    <p><strong>The completion signal</strong>: <code class="language-plaintext highlighter-rouge">done</code> is a <code class="language-plaintext highlighter-rouge">Deferred[IO, Unit]</code>, a one-shot, semantically blocking signal. When the last hop arrives, <code class="language-plaintext highlighter-rouge">done.complete(())</code> fires and unblocks the harness that is waiting on <code class="language-plaintext highlighter-rouge">done.get</code>. No polling, no shared mutable variable.</p>
  </li>
  <li>
    <p><strong>The send</strong>: <code class="language-plaintext highlighter-rouge">next ! RingToken(r - 1L)</code> is the fire-and-forget send, pure functional IO, the same whether this code runs on the JVM or compiles to a native binary.</p>
  </li>
</ol>

<h3 id="wiring-and-firing">Wiring and Firing</h3>

<p>The benchmark harness spawns the ring, wires it, fires the first token, and waits:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">private</span> <span class="k">def</span> <span class="nf">runOnce</span><span class="o">(</span><span class="n">system</span><span class="k">:</span> <span class="kt">ActorSystem</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">runId</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">cfg</span><span class="k">:</span> <span class="kt">Config</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">FiniteDuration</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
  <span class="k">val</span> <span class="nv">n</span>    <span class="k">=</span> <span class="nv">cfg</span><span class="o">.</span><span class="py">ringSize</span>
  <span class="k">val</span> <span class="nv">hops</span> <span class="k">=</span> <span class="nv">cfg</span><span class="o">.</span><span class="py">totalHops</span>

  <span class="k">for</span> <span class="o">{</span>
    <span class="n">done</span>     <span class="k">&lt;-</span> <span class="nc">Deferred</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Unit</span><span class="o">]</span>
    <span class="n">slots</span>    <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">[</span><span class="kt">Option</span><span class="o">[</span><span class="kt">Vector</span><span class="o">[</span><span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">RingToken</span><span class="o">]]]](</span><span class="nc">None</span><span class="o">)</span>
    <span class="n">refsList</span> <span class="k">&lt;-</span> <span class="o">(</span><span class="mi">0</span> <span class="n">until</span> <span class="n">n</span><span class="o">).</span><span class="py">toList</span><span class="o">.</span><span class="py">traverse</span><span class="o">(</span><span class="n">i</span> <span class="k">=&gt;</span>
      <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="k">new</span> <span class="nc">RingNode</span><span class="o">(</span><span class="n">i</span><span class="o">,</span> <span class="n">n</span><span class="o">,</span> <span class="n">slots</span><span class="o">,</span> <span class="n">done</span><span class="o">),</span> <span class="n">s</span><span class="s">"ring-$runId-$i"</span><span class="o">)</span>
    <span class="o">)</span>
    <span class="n">refs</span> <span class="k">=</span> <span class="nv">refsList</span><span class="o">.</span><span class="py">toVector</span>
    <span class="k">_</span>    <span class="k">&lt;-</span> <span class="nv">slots</span><span class="o">.</span><span class="py">set</span><span class="o">(</span><span class="nc">Some</span><span class="o">(</span><span class="n">refs</span><span class="o">))</span>
    <span class="n">t0</span>   <span class="k">&lt;-</span> <span class="nc">Clock</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">monotonic</span>
    <span class="k">_</span>    <span class="k">&lt;-</span> <span class="nf">refs</span><span class="o">(</span><span class="mi">0</span><span class="o">)</span> <span class="o">!</span> <span class="nc">RingToken</span><span class="o">(</span><span class="n">hops</span><span class="o">)</span>
    <span class="k">_</span>    <span class="k">&lt;-</span> <span class="nv">done</span><span class="o">.</span><span class="py">get</span>
    <span class="n">t1</span>   <span class="k">&lt;-</span> <span class="nc">Clock</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">monotonic</span>
  <span class="o">}</span> <span class="k">yield</span> <span class="n">t1</span> <span class="o">-</span> <span class="n">t0</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Run it yourself:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># JVM</span>
sbt <span class="s2">"sample7JVM/run"</span>

<span class="c"># Scala Native (compile first, then run the binary directly)</span>
sbt <span class="s2">"sample7Native/nativeLink"</span>
./sample7/native/target/scala-2.13/native/com.suprnation.Sample7
</code></pre></div></div>

<p>You can tune things via environment variables (<code class="language-plaintext highlighter-rouge">SAMPLE7_RING_SIZE</code>, <code class="language-plaintext highlighter-rouge">SAMPLE7_TOTAL_HOPS</code>, <code class="language-plaintext highlighter-rouge">SAMPLE7_WARMUP_RUNS</code>, <code class="language-plaintext highlighter-rouge">SAMPLE7_MEASURED_RUNS</code>) or pass them as CLI flags. The same benchmark also runs on Node.js via <code class="language-plaintext highlighter-rouge">sample7JS/run</code> — useful for a quick sanity check, though the browser target is where Scala.js really comes into its own, as you will see in the next section.</p>

<h3 id="sample-output-log">Sample Output :log:</h3>

<p>Here is what the Native binary prints for ring size 64 with 1M hops:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">===</span> Sample 7: actor ring <span class="o">(</span>token relay<span class="o">)</span> <span class="o">===</span>
Startup <span class="o">(</span>entry → actor system ready<span class="o">)</span>: 0.21 ms
Ring size: 64, total hops: 1000000
Warmup: 1, measured: 3

<span class="o">[</span>warmup 1] elapsed: 11.612 s
<span class="o">[</span>run 1] elapsed: 11.498 s
<span class="o">[</span>run 2] elapsed: 11.541 s
<span class="o">[</span>run 3] elapsed: 11.573 s

Median elapsed: 11.541 s
Stddev elapsed: 0.033 s
CV <span class="o">(</span>consistency<span class="o">)</span>: 0.3%  <span class="o">(</span>lower <span class="o">=</span> steadier<span class="o">)</span>
Median throughput: 86696.41 messages/s
Median latency: 11541.000 ns per hop
</code></pre></div></div>

<p>0.21ms startup, 0.3% CV. Now run the same config on the JVM and the startup jumps to 127ms, CV climbs to 6.6%, but throughput reaches 111k msg/s and keeps climbing with ring size. Two different trade-offs, same actor code.</p>

<h3 id="the-numbers">The Numbers</h3>

<p>Results from a sweep across ring sizes of 32, 64, 128, and 256 with 1M total hops:</p>

<p><img src="/images/cats-actors/ring-benchmark.png" alt="Ring benchmark results" /></p>

<p>Native starts up in under 6ms across every ring size while the JVM costs over 120ms at startup. After warmup the JVM pulls ahead on throughput, reaching over 250k messages per second at ring size 128, because the JVM’s just-in-time compiler observes the hot loop at runtime and generates optimised machine code for it, something a statically compiled binary cannot do. Native compiles once ahead of time and runs at a fixed speed, which is why its throughput is steady but does not accelerate with load. The consistency column reflects exactly this: Native’s stddev stays flat and low throughout while the JVM varies more between runs. If you need a process that starts instantly and runs predictably, Native is the right choice. If you need maximum sustained throughput on a long-running service, the JVM takes it. Same actor code, both options open.</p>

<hr />

<h2 id="eight-monkeys-in-the-browser">Eight Monkeys in the Browser</h2>

<p>OK now we are having fun.</p>

<p>Meet Kong, Bonzo, Coco, Mango, Peaches, Bandit, Zippy, and Bubbles. Eight monkey actors spawned into an arena. Each round, every living monkey picks a random target and throws a banana at them. The target has a 25% chance to dodge. Take enough hits and you are out. Last monkey standing wins.</p>

<p>Every banana throw is a real actor message send using the <code class="language-plaintext highlighter-rouge">!</code> operator. The monkeys are making decisions, updating their own state, and communicating asynchronously, exactly as you would write production actor code. And on Scala.js, every event feeds a live React UI running right here in the page.</p>

<p>Go ahead, watch the battle unfold. :point_down:</p>

<iframe src="/banana-battle.html" width="100%" height="800" frameborder="0" style="border-radius:12px; display:block; margin: 1.5rem 0; min-height: 800px;"></iframe>

<p>Not a single line of JavaScript was written. Those are Scala actors, compiled to JS via Scala.js, rendering a React UI through the Slinky bindings. The full code is in <a href="https://github.com/cloudmark/cats-actor-sample/tree/main/sample8"><code class="language-plaintext highlighter-rouge">sample8</code></a> in the repository.</p>

<h3 id="the-monkeyactor">The MonkeyActor</h3>

<p>Each monkey holds its own state in a <code class="language-plaintext highlighter-rouge">Ref[IO, MonkeyState]</code> and receives three kinds of messages:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">sealed</span> <span class="k">trait</span> <span class="nc">ArenaMessage</span>
<span class="k">final</span> <span class="k">case</span> <span class="k">class</span> <span class="nc">Tick</span><span class="o">(</span><span class="n">round</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span>                              <span class="k">extends</span> <span class="nc">ArenaMessage</span>
<span class="k">final</span> <span class="k">case</span> <span class="k">class</span> <span class="nc">IncomingBanana</span><span class="o">(</span><span class="n">fromId</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">fromName</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">ArenaMessage</span>
<span class="k">final</span> <span class="k">case</span> <span class="k">class</span> <span class="nc">ThrowResult</span><span class="o">(</span><span class="n">targetId</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">hit</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span>      <span class="k">extends</span> <span class="nc">ArenaMessage</span>
</code></pre></div></div>

<p>On a <code class="language-plaintext highlighter-rouge">Tick</code>, a monkey picks a target and throws:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">case</span> <span class="nc">Tick</span><span class="o">(</span><span class="k">_</span><span class="o">)</span> <span class="k">=&gt;</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">me</span> <span class="k">&lt;-</span> <span class="nv">state</span><span class="o">.</span><span class="py">get</span>
    <span class="k">_</span>  <span class="k">&lt;-</span> <span class="nf">if</span> <span class="o">(</span><span class="nv">me</span><span class="o">.</span><span class="py">health</span> <span class="o">&lt;=</span> <span class="mi">0</span> <span class="o">||</span> <span class="nv">me</span><span class="o">.</span><span class="py">bananas</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="o">)</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span> <span class="k">else</span> <span class="nf">throwBanana</span><span class="o">(</span><span class="n">me</span><span class="o">)</span>
  <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">throwBanana</code> finds a living target, decrements the banana count, and sends an <code class="language-plaintext highlighter-rouge">IncomingBanana</code> to the target actor:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">private</span> <span class="k">def</span> <span class="nf">throwBanana</span><span class="o">(</span><span class="n">me</span><span class="k">:</span> <span class="kt">MonkeyState</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">targets</span> <span class="k">&lt;-</span> <span class="nv">allStates</span><span class="o">.</span><span class="py">traverse</span><span class="o">(</span><span class="nv">_</span><span class="o">.</span><span class="py">get</span><span class="o">).</span><span class="py">map</span><span class="o">(</span><span class="nv">_</span><span class="o">.</span><span class="py">filter</span><span class="o">(</span><span class="n">s</span> <span class="k">=&gt;</span> <span class="nv">s</span><span class="o">.</span><span class="py">health</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="o">&amp;&amp;</span> <span class="nv">s</span><span class="o">.</span><span class="py">id</span> <span class="o">!=</span> <span class="n">id</span><span class="o">))</span>
    <span class="k">_</span> <span class="k">&lt;-</span> <span class="nf">if</span> <span class="o">(</span><span class="nv">targets</span><span class="o">.</span><span class="py">isEmpty</span><span class="o">)</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span> <span class="k">else</span> <span class="o">{</span>
      <span class="k">val</span> <span class="nv">target</span> <span class="k">=</span> <span class="nf">targets</span><span class="o">(</span><span class="nv">rng</span><span class="o">.</span><span class="py">nextInt</span><span class="o">(</span><span class="nv">targets</span><span class="o">.</span><span class="py">size</span><span class="o">))</span>
      <span class="k">for</span> <span class="o">{</span>
        <span class="k">_</span>       <span class="k">&lt;-</span> <span class="nv">state</span><span class="o">.</span><span class="py">update</span><span class="o">(</span><span class="n">s</span> <span class="k">=&gt;</span> <span class="nv">s</span><span class="o">.</span><span class="py">copy</span><span class="o">(</span><span class="n">bananas</span> <span class="k">=</span> <span class="nv">s</span><span class="o">.</span><span class="py">bananas</span> <span class="o">-</span> <span class="mi">1</span><span class="o">,</span> <span class="n">throws</span> <span class="k">=</span> <span class="nv">s</span><span class="o">.</span><span class="py">throws</span> <span class="o">+</span> <span class="mi">1</span><span class="o">))</span>
        <span class="k">_</span>       <span class="k">&lt;-</span> <span class="nv">PlatformInterop</span><span class="o">.</span><span class="py">appendVisualLog</span><span class="o">(</span><span class="n">s</span><span class="s">"🍌 $name throws at ${target.name}!"</span><span class="o">)</span>
        <span class="k">_</span>       <span class="k">&lt;-</span> <span class="nv">PlatformInterop</span><span class="o">.</span><span class="py">onBananaThrown</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="nv">target</span><span class="o">.</span><span class="py">id</span><span class="o">)</span>
        <span class="n">monkeys</span> <span class="k">&lt;-</span> <span class="nv">registry</span><span class="o">.</span><span class="py">get</span>
        <span class="k">_</span>       <span class="k">&lt;-</span> <span class="nf">monkeys</span><span class="o">(</span><span class="nv">target</span><span class="o">.</span><span class="py">id</span><span class="o">)</span> <span class="o">!</span> <span class="nc">IncomingBanana</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="n">name</span><span class="o">)</span>
      <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
    <span class="o">}</span>
  <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
</code></pre></div></div>

<p>On the receiving end the target rolls the dice (25% dodge chance, otherwise take the hit):</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">private</span> <span class="k">def</span> <span class="nf">receiveBanana</span><span class="o">(</span><span class="n">me</span><span class="k">:</span> <span class="kt">MonkeyState</span><span class="o">,</span> <span class="n">fromId</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">fromName</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
  <span class="k">val</span> <span class="nv">dodged</span> <span class="k">=</span> <span class="nv">rng</span><span class="o">.</span><span class="py">nextInt</span><span class="o">(</span><span class="mi">100</span><span class="o">)</span> <span class="o">&lt;</span> <span class="mi">25</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">monkeys</span> <span class="k">&lt;-</span> <span class="nv">registry</span><span class="o">.</span><span class="py">get</span>
    <span class="k">_</span> <span class="k">&lt;-</span> <span class="nf">if</span> <span class="o">(</span><span class="n">dodged</span><span class="o">)</span> <span class="o">{</span>
      <span class="nv">PlatformInterop</span><span class="o">.</span><span class="py">appendVisualLog</span><span class="o">(</span><span class="n">s</span><span class="s">"💨 ${me.name} dodges!"</span><span class="o">)</span> <span class="o">*&gt;</span>
      <span class="o">(</span><span class="nf">monkeys</span><span class="o">(</span><span class="n">fromId</span><span class="o">)</span> <span class="o">!</span> <span class="nc">ThrowResult</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="n">hit</span> <span class="k">=</span> <span class="kc">false</span><span class="o">))</span>
    <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
      <span class="k">for</span> <span class="o">{</span>
        <span class="n">updated</span> <span class="k">&lt;-</span> <span class="nv">state</span><span class="o">.</span><span class="py">updateAndGet</span><span class="o">(</span><span class="n">s</span> <span class="k">=&gt;</span> <span class="nv">s</span><span class="o">.</span><span class="py">copy</span><span class="o">(</span><span class="n">health</span> <span class="k">=</span> <span class="nv">s</span><span class="o">.</span><span class="py">health</span> <span class="o">-</span> <span class="mi">1</span><span class="o">))</span>
        <span class="k">_</span>       <span class="k">&lt;-</span> <span class="nv">PlatformInterop</span><span class="o">.</span><span class="py">appendVisualLog</span><span class="o">(</span><span class="n">s</span><span class="s">"💥 ${me.name} hit! HP: ${updated.health}"</span><span class="o">)</span>
        <span class="k">_</span>       <span class="k">&lt;-</span> <span class="nf">monkeys</span><span class="o">(</span><span class="n">fromId</span><span class="o">)</span> <span class="o">!</span> <span class="nc">ThrowResult</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="n">hit</span> <span class="k">=</span> <span class="kc">true</span><span class="o">)</span>
        <span class="k">_</span>       <span class="k">&lt;-</span> <span class="nf">if</span> <span class="o">(</span><span class="nv">updated</span><span class="o">.</span><span class="py">health</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="o">)</span>
                     <span class="nv">PlatformInterop</span><span class="o">.</span><span class="py">appendVisualLog</span><span class="o">(</span><span class="n">s</span><span class="s">"☠️  ${me.name} is out!"</span><span class="o">)</span> <span class="o">*&gt;</span>
                     <span class="nv">PlatformInterop</span><span class="o">.</span><span class="py">onMonkeyEliminated</span><span class="o">(</span><span class="n">id</span><span class="o">)</span>
                   <span class="k">else</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span>
      <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
    <span class="o">}</span>
  <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Notice the thrower always gets a <code class="language-plaintext highlighter-rouge">ThrowResult</code> back. Actors closing the loop, idiomatic actor design.</p>

<h3 id="one-trait-three-platforms">One Trait, Three Platforms</h3>

<p>Here is the clever part. The shared actor code never touches any platform-specific API. Instead it calls through a single trait:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">trait</span> <span class="nc">PlatformInteropApi</span> <span class="o">{</span>
  <span class="k">def</span> <span class="nf">appendVisualLog</span><span class="o">(</span><span class="n">line</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">onBananaThrown</span><span class="o">(</span><span class="n">fromId</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">toId</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">onMonkeyEliminated</span><span class="o">(</span><span class="n">id</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">onScoreUpdate</span><span class="o">(</span><span class="n">scores</span><span class="k">:</span> <span class="kt">List</span><span class="o">[(</span><span class="kt">Int</span>, <span class="kt">String</span>, <span class="kt">Int</span>, <span class="kt">Int</span><span class="o">)])</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">checkRestart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Boolean</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">resetArena</span><span class="o">()</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>
<span class="o">}</span>
</code></pre></div></div>

<p>On JVM and Native it is minimal, just print to the console and move on:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// JVM and Native</span>
<span class="k">object</span> <span class="nc">PlatformInterop</span> <span class="k">extends</span> <span class="nc">PlatformInteropApi</span> <span class="o">{</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">appendVisualLog</span><span class="o">(</span><span class="n">line</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>         <span class="k">=</span> <span class="nv">IO</span><span class="o">.</span><span class="py">println</span><span class="o">(</span><span class="n">line</span><span class="o">)</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">onBananaThrown</span><span class="o">(</span><span class="n">fromId</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">toId</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">onMonkeyEliminated</span><span class="o">(</span><span class="n">id</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>           <span class="k">=</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span>
  <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<p>On Scala.js, every call feeds the live React arena above:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// JS (browser)</span>
<span class="k">object</span> <span class="nc">PlatformInterop</span> <span class="k">extends</span> <span class="nc">PlatformInteropApi</span> <span class="o">{</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">appendVisualLog</span><span class="o">(</span><span class="n">line</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>         <span class="k">=</span> <span class="nc">IO</span><span class="o">(</span><span class="nv">ReactShowcase</span><span class="o">.</span><span class="py">append</span><span class="o">(</span><span class="n">line</span><span class="o">))</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">onBananaThrown</span><span class="o">(</span><span class="n">fromId</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">toId</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="nc">IO</span><span class="o">(</span><span class="nv">ReactShowcase</span><span class="o">.</span><span class="py">addProjectile</span><span class="o">(</span><span class="n">fromId</span><span class="o">,</span> <span class="n">toId</span><span class="o">))</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">onMonkeyEliminated</span><span class="o">(</span><span class="n">id</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>           <span class="k">=</span> <span class="nc">IO</span><span class="o">(</span><span class="nv">ReactShowcase</span><span class="o">.</span><span class="py">eliminateMonkey</span><span class="o">(</span><span class="n">id</span><span class="o">))</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">checkRestart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Boolean</span><span class="o">]</span>                       <span class="k">=</span> <span class="nc">IO</span><span class="o">(</span><span class="nv">ReactShowcase</span><span class="o">.</span><span class="py">consumeRestart</span><span class="o">())</span>
  <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">ReactShowcase</code> manages state through an <code class="language-plaintext highlighter-rouge">AtomicReference</code> and runs a 50ms paint loop that re-renders the SVG arena. Click restart and the shared actor code picks it up automatically, same functional IO loop across all three platforms.</p>

<h3 id="running-locally">Running Locally</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cd </span>sample8
sbt <span class="s2">"starterJS/fastLinkJS"</span>
npm <span class="nb">install</span> <span class="o">&amp;&amp;</span> npm run dev
<span class="c"># open http://localhost:5173</span>
</code></pre></div></div>

<h2 id="conclusion-tada">Conclusion :tada:</h2>

<p>The same actor. The same <code class="language-plaintext highlighter-rouge">receive</code>. The same <code class="language-plaintext highlighter-rouge">!</code>. Running on a JVM, compiled to a native binary, or animating a banana war in your browser. That is Cats-Actors now.</p>

<p>A huge thank you to <a href="https://github.com/rlavolee">Rémi Lavolée</a> and <a href="https://github.com/Voltir">Nick Childers</a> for making this possible.</p>

<p>Check out the <a href="https://github.com/suprnation/cats-actors">Cats-Actors repository</a> and clone the <a href="https://github.com/cloudmark/cats-actor-sample">cats-actor-sample repository</a>, pick a platform, and get hacking.</p>

<p>As always, stay safe, keep hacking!</p>]]></content><author><name>Mark Galea</name></author><category term="cats-actors" /><summary type="html"><![CDATA[Imagine writing your actor logic once (typed messages, functional state, the ! operator, supervision and all) and then deciding on a whim whether it runs as a JVM service, a self-contained native binary, or a live interactive app in your browser. No rewrites, no ports, no platform-specific glue. Just one codebase. Cats-Actors can do that now, and in this post we are going to have some fun with it. We will throw a token around a ring of actors on both JVM and Scala Native, and then (because why not) we will drop eight monkey actors into a banana-throwing arena right here inside this page. Real actors. Real messages. Running in your browser.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://cloudmark.me/images/cats-actors/logo-small.png" /><media:content medium="image" url="https://cloudmark.me/images/cats-actors/logo-small.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Typed Actors in Action - Exploring Cats-Actors with Alice and Bob</title><link href="https://cloudmark.me/Cats-Actors-In-The-Wild/" rel="alternate" type="text/html" title="Typed Actors in Action - Exploring Cats-Actors with Alice and Bob" /><published>2024-06-27T00:00:00+02:00</published><updated>2024-06-27T00:00:00+02:00</updated><id>https://cloudmark.me/Cats-Actors-In-The-Wild</id><content type="html" xml:base="https://cloudmark.me/Cats-Actors-In-The-Wild/"><![CDATA[<p><img class="title" src="/images/cats-actors/transaction-2.png" />
Today marks an exciting milestone with the release of Cats-Actors 2.0.0-RC1. This version introduces typed actors, a feature that the community has eagerly awaited. To showcase this new capability, we’ll walk through a classic example of handling wallet transactions between two users, Alice and Bob.
So, sit back and relax as we explore how Alice sends money to Bob using typed actors in Cats-Actors.</p>

<h3 id="meet-alice-and-bob">Meet Alice and Bob</h3>

<p>Alice and Bob are best friends and tech enthusiasts who often lend and borrow money from each other. Today, Alice needs to send some money to Bob to settle a shared expense. To handle this transaction, they decide to use the latest release of Cats-Actors, excited to explore its new typed actors feature.</p>

<p>Typed actors ensure type-checked message passing at compile time, reducing runtime errors. Alice and Bob will create wallet actors to manage their balances and use a transaction actor to coordinate the money transfer from Alice’s wallet to Bob’s.</p>

<h3 id="setting-up-your-project">Setting Up Your Project</h3>
<p>To begin working with typed actors in Cats-Actors, you’ll need to set up your Scala project to include the necessary dependencies and explore the framework’s resources.</p>

<h4 id="adding-dependencies">Adding Dependencies</h4>

<p>First, ensure your Scala project is configured to fetch dependencies from JitPack, a popular repository for GitHub-hosted projects. Add the following lines to your build.sbt file:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code>   <span class="n">resolvers</span> <span class="o">+=</span> <span class="s">"JitPack"</span> <span class="n">at</span> <span class="s">"https://jitpack.io"</span>

   <span class="n">libraryDependencies</span> <span class="o">+=</span> <span class="s">"com.github.suprnation"</span> <span class="o">%</span> <span class="s">"cats-actors_2.13"</span> <span class="o">%</span> <span class="s">"2.0.0-RC1"</span>
</code></pre></div></div>

<p>In the above snippet, <code class="language-plaintext highlighter-rouge">"2.0.0-RC1"</code> should be replaced with the latest version of Cats-Actors available on JitPack. These dependencies enable you to utilize Cats-Actors in your Scala application.</p>

<p>Visit the <a href="https://github.com/suprnation/cats-actors/">Cats-Actors GitHub repository</a> to explore comprehensive documentation, examples, and community contributions related to the framework.</p>

<blockquote>
  <p>Note to view and run all code samples discussed in this blog post, clone the <a href="https://github.com/cloudmark/cats-actor-sample">GitHub repository</a>.</p>
</blockquote>

<h3 id="the-walletactor-managing-alice-and-bobs-wallets-bank">The WalletActor: Managing Alice and Bob’s Wallets :bank:</h3>

<p>The <code class="language-plaintext highlighter-rouge">WalletActor</code> is responsible for managing commands related to wallet operations, including retrieving balances, depositing funds, and withdrawing funds. It ensures robustness by strictly typing its <code class="language-plaintext highlighter-rouge">receive</code> operations to handle only <code class="language-plaintext highlighter-rouge">Command</code> messages, thereby preventing runtime errors. Let’s delve into how it works.</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">package</span> <span class="nn">com.suprnation.samples</span>

<span class="k">import</span> <span class="nn">cats.effect.</span><span class="o">{</span><span class="nc">ExitCode</span><span class="o">,</span> <span class="nc">IO</span><span class="o">,</span> <span class="nc">IOApp</span><span class="o">,</span> <span class="nc">Ref</span><span class="o">}</span>
<span class="k">import</span> <span class="nn">cats.implicits._</span>
<span class="k">import</span> <span class="nn">com.suprnation.actor.Actor.</span><span class="o">{</span><span class="nc">Actor</span><span class="o">,</span> <span class="nc">Receive</span><span class="o">}</span>
<span class="k">import</span> <span class="nn">com.suprnation.actor.ActorRef.ActorRef</span>
<span class="k">import</span> <span class="nn">com.suprnation.actor._</span>

<span class="k">object</span> <span class="nc">WalletActor</span> <span class="o">{</span>
  <span class="k">sealed</span> <span class="k">trait</span> <span class="nc">Command</span>
  <span class="k">case</span> <span class="k">class</span> <span class="nc">GetBalance</span><span class="o">(</span><span class="n">replyTo</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Balance</span><span class="o">])</span> <span class="k">extends</span> <span class="nc">Command</span>
  <span class="k">case</span> <span class="k">class</span> <span class="nc">Deposit</span><span class="o">(</span><span class="n">amount</span><span class="k">:</span> <span class="kt">BigDecimal</span><span class="o">,</span> <span class="n">replyTo</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Response</span><span class="o">]])</span> <span class="k">extends</span> <span class="nc">Command</span>
  <span class="k">case</span> <span class="k">class</span> <span class="nc">Withdraw</span><span class="o">(</span><span class="n">amount</span><span class="k">:</span> <span class="kt">BigDecimal</span><span class="o">,</span> <span class="n">replyTo</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Response</span><span class="o">]])</span> <span class="k">extends</span> <span class="nc">Command</span>

  <span class="k">sealed</span> <span class="k">trait</span> <span class="nc">Response</span>
  <span class="k">case</span> <span class="k">class</span> <span class="nc">TransactionFailed</span><span class="o">(</span><span class="n">reason</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Response</span>
  <span class="k">case</span> <span class="k">class</span> <span class="nc">Balance</span><span class="o">(</span><span class="n">amount</span><span class="k">:</span> <span class="kt">BigDecimal</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Response</span>

  <span class="k">def</span> <span class="nf">create</span><span class="o">(</span><span class="n">walletId</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Command</span><span class="o">]]</span> <span class="k">=</span>
    <span class="k">for</span> <span class="o">{</span>
      <span class="n">balance</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">(</span><span class="nv">BigDecimal</span><span class="o">.</span><span class="py">decimal</span><span class="o">(</span><span class="mf">0.0</span><span class="o">))</span>
    <span class="o">}</span> <span class="k">yield</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Command</span><span class="o">]</span> <span class="o">{</span>
      <span class="k">override</span> <span class="k">def</span> <span class="nf">receive</span><span class="k">:</span> <span class="kt">Receive</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Command</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
        <span class="k">case</span> <span class="nc">Deposit</span><span class="o">(</span><span class="n">amount</span><span class="o">,</span> <span class="n">replyTo</span><span class="o">)</span> <span class="k">=&gt;</span>
          <span class="nv">balance</span><span class="o">.</span><span class="py">update</span><span class="o">(</span><span class="k">_</span> <span class="o">+</span> <span class="n">amount</span><span class="o">)</span> <span class="o">&gt;&gt;</span>
            <span class="nv">balance</span><span class="o">.</span><span class="py">get</span><span class="o">.</span><span class="py">flatMap</span><span class="o">(</span><span class="n">newBalance</span> <span class="k">=&gt;</span>
              <span class="nv">IO</span><span class="o">.</span><span class="py">println</span><span class="o">(</span>
                <span class="n">s</span><span class="s">"[${context.self.path.name}] Deposited $amount to $walletId. New balance: $newBalance"</span>
              <span class="o">)</span> <span class="o">&gt;&gt;</span>
                <span class="nv">replyTo</span><span class="o">.</span><span class="py">fold</span><span class="o">(</span><span class="nv">IO</span><span class="o">.</span><span class="py">unit</span><span class="o">)(</span><span class="k">_</span> <span class="o">!</span> <span class="nc">Balance</span><span class="o">(</span><span class="n">newBalance</span><span class="o">))</span>
            <span class="o">)</span>

        <span class="k">case</span> <span class="nc">Withdraw</span><span class="o">(</span><span class="n">amount</span><span class="o">,</span> <span class="n">replyTo</span><span class="o">)</span> <span class="k">=&gt;</span>
          <span class="nv">balance</span><span class="o">.</span><span class="py">get</span><span class="o">.</span><span class="py">flatMap</span> <span class="o">{</span> <span class="n">currentBalance</span> <span class="k">=&gt;</span>
            <span class="nf">if</span> <span class="o">(</span><span class="n">currentBalance</span> <span class="o">&gt;=</span> <span class="n">amount</span><span class="o">)</span> <span class="o">{</span>
              <span class="nv">balance</span><span class="o">.</span><span class="py">update</span><span class="o">(</span><span class="k">_</span> <span class="o">-</span> <span class="n">amount</span><span class="o">)</span> <span class="o">&gt;&gt;</span>
                <span class="nv">balance</span><span class="o">.</span><span class="py">get</span><span class="o">.</span><span class="py">flatMap</span><span class="o">(</span><span class="n">newBalance</span> <span class="k">=&gt;</span>
                  <span class="nv">IO</span><span class="o">.</span><span class="py">println</span><span class="o">(</span>
                    <span class="n">s</span><span class="s">"[${context.self.path.name}] Withdrew $amount from $walletId. New balance: $newBalance"</span>
                  <span class="o">)</span> <span class="o">&gt;&gt;</span>
                    <span class="nv">replyTo</span><span class="o">.</span><span class="py">fold</span><span class="o">(</span><span class="nv">IO</span><span class="o">.</span><span class="py">unit</span><span class="o">)(</span><span class="k">_</span> <span class="o">!</span> <span class="nc">Balance</span><span class="o">(</span><span class="n">newBalance</span><span class="o">))</span>
                <span class="o">)</span>
            <span class="o">}</span> <span class="k">else</span> <span class="nv">replyTo</span><span class="o">.</span><span class="py">fold</span><span class="o">(</span><span class="nv">IO</span><span class="o">.</span><span class="py">unit</span><span class="o">)(</span><span class="k">_</span> <span class="o">!</span> <span class="nc">TransactionFailed</span><span class="o">(</span><span class="n">s</span><span class="s">"Insufficient funds in $walletId"</span><span class="o">))</span>
          <span class="o">}</span>

        <span class="k">case</span> <span class="nc">GetBalance</span><span class="o">(</span><span class="n">replyTo</span><span class="o">)</span> <span class="k">=&gt;</span>
          <span class="k">for</span> <span class="o">{</span>
            <span class="n">currentBalance</span> <span class="k">&lt;-</span> <span class="nv">balance</span><span class="o">.</span><span class="py">get</span>
            <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">replyTo</span> <span class="o">!</span> <span class="nc">Balance</span><span class="o">(</span><span class="n">currentBalance</span><span class="o">)</span>
          <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
      <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="breaking-down-the-walletactor">Breaking Down the WalletActor</h4>

<p>The <code class="language-plaintext highlighter-rouge">WalletActor</code> handles three main commands:</p>

<ol>
  <li>
    <p><strong>GetBalance</strong>: This command is used to query the current balance of the wallet. It takes an <code class="language-plaintext highlighter-rouge">ActorRef</code> that will receive the balance as a response.</p>

    <div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="k">case</span> <span class="k">class</span> <span class="nc">GetBalance</span><span class="o">(</span><span class="n">replyTo</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Balance</span><span class="o">])</span> <span class="k">extends</span> <span class="nc">Command</span>
</code></pre></div>    </div>
  </li>
  <li>
    <p><strong>Deposit</strong>: This command adds a specified amount to the wallet’s balance. It also optionally takes an <code class="language-plaintext highlighter-rouge">ActorRef</code> to send a response indicating the new balance.</p>

    <div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="k">case</span> <span class="k">class</span> <span class="nc">Deposit</span><span class="o">(</span><span class="n">amount</span><span class="k">:</span> <span class="kt">BigDecimal</span><span class="o">,</span> <span class="n">replyTo</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Response</span><span class="o">]])</span> <span class="k">extends</span> <span class="nc">Command</span>
</code></pre></div>    </div>
  </li>
  <li>
    <p><strong>Withdraw</strong>: This command deducts a specified amount from the wallet’s balance if there are sufficient funds. It can also take an <code class="language-plaintext highlighter-rouge">ActorRef</code> for response purposes.</p>

    <div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="k">case</span> <span class="k">class</span> <span class="nc">Withdraw</span><span class="o">(</span><span class="n">amount</span><span class="k">:</span> <span class="kt">BigDecimal</span><span class="o">,</span> <span class="n">replyTo</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Response</span><span class="o">]])</span> <span class="k">extends</span> <span class="nc">Command</span>
</code></pre></div>    </div>
  </li>
</ol>

<p>Responses include the current balance and a transaction failure message if something goes wrong:</p>

<ul>
  <li><strong>TransactionFailed</strong>: Indicates a failed transaction with a reason.</li>
  <li><strong>Balance</strong>: Represents the current balance of the wallet.</li>
</ul>

<p>The create method initializes the <code class="language-plaintext highlighter-rouge">WalletActor</code> with a starting balance of 0. Its <code class="language-plaintext highlighter-rouge">receive</code> method is strictly typed to handle only <code class="language-plaintext highlighter-rouge">Command</code> messages, ensuring type safety and minimizing runtime errors.</p>

<h3 id="the-transactionactor-coordinating-the-transfer-money_mouth_face">The TransactionActor: Coordinating the Transfer :money_mouth_face:</h3>

<p>With Alice and Bob’s wallets all set, it’s time to master the art of money transfer. The <code class="language-plaintext highlighter-rouge">TransactionActor</code> takes on the pivotal role of seamlessly managing transactions between them.</p>

<p>Before we dive into the code, let’s explore the intricate workings of the transaction state machine.</p>

<h4 id="the-transaction-state-machine-">The Transaction State Machine 🤖</h4>

<p>The <code class="language-plaintext highlighter-rouge">TransactionActor</code> takes charge of orchestrating the flow of a transaction between two wallets. The process involves the following states:</p>

<ol>
  <li><strong>PreStart</strong>: Initialization phase where the actor sends a withdrawal request to the source wallet.</li>
  <li><strong>awaitWithdraw</strong>: Waits for confirmation of the withdrawal from the source wallet.</li>
  <li><strong>awaitDeposit</strong>: Waits for confirmation of the deposit to the destination wallet.</li>
  <li><strong>Transaction Complete</strong>: Indicates that the transaction was successful and the actor can be stopped.</li>
  <li><strong>Transaction Failed</strong>: Indicates that the transaction failed, either during withdrawal or deposit, and the actor can be stopped.</li>
</ol>

<p>Here’s a state machine diagram to visualize this flow:</p>

<div class="mermaid">
stateDiagram
    PreStart: PreStart
    awaitWithdraw: awaitWithdraw
    awaitDeposit: awaitDeposit
    TransactionComplete: Transaction Complete
    TransactionFailed: Transaction Failed

    PreStart --&gt; awaitWithdraw: Send withdraw request
    awaitWithdraw --&gt; awaitDeposit: Withdraw successful
    awaitWithdraw --&gt; TransactionFailed: Withdraw failed
    awaitDeposit --&gt; TransactionComplete: Deposit successful
    awaitDeposit --&gt; TransactionFailed: Deposit failed
    TransactionFailed --&gt; [*]: Stop actor
    TransactionComplete --&gt; [*]: Stop actor
</div>

<h4 id="implementing-the-transactionactor">Implementing the TransactionActor</h4>
<p>With the state machine as our guide, let’s roll up our sleeves and bring the <code class="language-plaintext highlighter-rouge">TransactionActor</code> to life!</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">object</span> <span class="nc">TransactionActor</span> <span class="o">{</span>
  <span class="k">sealed</span> <span class="k">trait</span> <span class="nc">Response</span>
  <span class="k">case</span> <span class="k">class</span> <span class="nc">TransactionSuccess</span><span class="o">(</span><span class="n">transactionId</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Response</span>
  <span class="k">case</span> <span class="k">class</span> <span class="nc">TransactionFailed</span><span class="o">(</span><span class="n">reason</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Response</span>

  <span class="k">def</span> <span class="nf">create</span><span class="o">(</span>
      <span class="n">transactionId</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
      <span class="n">parent</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Response</span><span class="o">],</span>
      <span class="n">fromWallet</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">WalletActor.Command</span><span class="o">],</span>
      <span class="n">toWallet</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">WalletActor.Command</span><span class="o">],</span>
      <span class="n">amount</span><span class="k">:</span> <span class="kt">BigDecimal</span>
  <span class="o">)</span><span class="k">:</span> <span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Nothing</span><span class="o">]</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Nothing</span><span class="o">]</span> <span class="o">{</span>

    <span class="k">override</span> <span class="k">def</span> <span class="nf">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">IO</span><span class="o">.</span><span class="py">println</span><span class="o">(</span>
        <span class="n">s</span><span class="s">"~~~ [Tx: $transactionId] =&gt; Sending withdraw request to [${fromWallet.path.name}].  Awaiting confirmation.  ~~~"</span>
      <span class="o">)</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">fromWallet</span> <span class="o">!</span> <span class="nv">WalletActor</span><span class="o">.</span><span class="py">Withdraw</span><span class="o">(</span><span class="n">amount</span><span class="o">,</span> <span class="nv">context</span><span class="o">.</span><span class="py">self</span><span class="o">.</span><span class="py">widenRequest</span><span class="o">.</span><span class="py">some</span><span class="o">)</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">become</span><span class="o">(</span><span class="n">awaitWithdraw</span><span class="o">)</span>
    <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>

    <span class="k">def</span> <span class="nf">awaitWithdraw</span><span class="k">:</span> <span class="kt">Receive</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">WalletActor.Response</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="k">case</span> <span class="nv">WalletActor</span><span class="o">.</span><span class="py">Balance</span><span class="o">(</span><span class="k">_</span><span class="o">)</span> <span class="k">=&gt;</span>
        <span class="k">for</span> <span class="o">{</span>
          <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">IO</span><span class="o">.</span><span class="py">println</span><span class="o">(</span>
            <span class="n">s</span><span class="s">"~~~ [Tx: $transactionId] =&gt; Withdraw from [${fromWallet.path.name}] confirmed.  Depositing to [${toWallet.path.name}]. ~~~"</span>
          <span class="o">)</span>
          <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">toWallet</span> <span class="o">!</span> <span class="nv">WalletActor</span><span class="o">.</span><span class="py">Deposit</span><span class="o">(</span><span class="n">amount</span><span class="o">,</span> <span class="nv">context</span><span class="o">.</span><span class="py">self</span><span class="o">.</span><span class="py">widenRequest</span><span class="o">.</span><span class="py">some</span><span class="o">)</span>
          <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">become</span><span class="o">(</span><span class="n">awaitDeposit</span><span class="o">)</span>
        <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>

      <span class="k">case</span> <span class="nv">WalletActor</span><span class="o">.</span><span class="py">TransactionFailed</span><span class="o">(</span><span class="n">reason</span><span class="o">)</span> <span class="k">=&gt;</span>
        <span class="n">parent</span> <span class="o">!</span> <span class="nc">TransactionFailed</span><span class="o">(</span><span class="n">s</span><span class="s">"Withdraw from source wallet failed: $reason"</span><span class="o">)</span>
        <span class="nv">context</span><span class="o">.</span><span class="py">stop</span><span class="o">(</span><span class="nv">context</span><span class="o">.</span><span class="py">self</span><span class="o">)</span>
    <span class="o">}</span>

    <span class="k">def</span> <span class="nf">awaitDeposit</span><span class="k">:</span> <span class="kt">Receive</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">WalletActor.Response</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="k">case</span> <span class="nv">WalletActor</span><span class="o">.</span><span class="py">Balance</span><span class="o">(</span><span class="k">_</span><span class="o">)</span> <span class="k">=&gt;</span>
        <span class="k">for</span> <span class="o">{</span>
          <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">IO</span><span class="o">.</span><span class="py">println</span><span class="o">(</span>
            <span class="n">s</span><span class="s">"~~~ [Tx: $transactionId] =&gt; Deposit to [${toWallet.path.name}] confirmed.  Killing actor - transaction complete! ~~~"</span>
          <span class="o">)</span>
          <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">parent</span> <span class="o">!</span> <span class="nc">TransactionSuccess</span><span class="o">(</span><span class="n">transactionId</span><span class="o">)</span>
          <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">stop</span><span class="o">(</span><span class="nv">context</span><span class="o">.</span><span class="py">self</span><span class="o">)</span>
        <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>

      <span class="k">case</span> <span class="nv">WalletActor</span><span class="o">.</span><span class="py">TransactionFailed</span><span class="o">(</span><span class="n">reason</span><span class="o">)</span> <span class="k">=&gt;</span>
        <span class="n">parent</span> <span class="o">!</span> <span class="nc">TransactionFailed</span><span class="o">(</span><span class="n">s</span><span class="s">"Deposit to destination wallet failed: $reason"</span><span class="o">)</span>
        <span class="nv">context</span><span class="o">.</span><span class="py">stop</span><span class="o">(</span><span class="nv">context</span><span class="o">.</span><span class="py">self</span><span class="o">)</span>
    <span class="o">}</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h2 id="lights-camera-action-clapper">Lights, Camera, Action! :clapper:</h2>
<p>It’s showtime for our main application! Here, we’ll orchestrate the entire ensemble: setting up the actor system, casting wallet actors for Alice and Bob, and kickstart a thrilling transaction between them. Plus, we’ve got a backstage reporter actor to capture all the action and reactions!</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">object</span> <span class="nc">Main</span> <span class="k">extends</span> <span class="nc">IOApp</span> <span class="o">{</span>
  <span class="k">def</span> <span class="nf">run</span><span class="o">(</span><span class="n">args</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">])</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">ExitCode</span><span class="o">]</span> <span class="k">=</span>
    <span class="nc">ActorSystem</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="s">"actor-system"</span><span class="o">).</span><span class="py">use</span> <span class="o">{</span> <span class="n">system</span> <span class="k">=&gt;</span>
      <span class="k">for</span> <span class="o">{</span>
        <span class="n">auditor</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Any</span><span class="o">]</span> <span class="o">{</span>
          <span class="k">override</span> <span class="k">def</span> <span class="nf">receive</span><span class="k">:</span> <span class="kt">Receive</span><span class="o">[</span><span class="kt">IO</span>, <span class="kt">Any</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span> <span class="k">case</span> <span class="n">response</span> <span class="k">=&gt;</span>
            <span class="k">val</span> <span class="nv">sender</span><span class="k">:</span> <span class="kt">String</span> <span class="o">=</span> <span class="nv">context</span><span class="o">.</span><span class="py">sender</span><span class="o">.</span><span class="py">map</span><span class="o">(</span><span class="nv">_</span><span class="o">.</span><span class="py">path</span><span class="o">.</span><span class="py">name</span><span class="o">).</span><span class="py">getOrElse</span><span class="o">(</span><span class="s">"N/A"</span><span class="o">)</span>
            <span class="nv">IO</span><span class="o">.</span><span class="py">println</span><span class="o">(</span><span class="n">s</span><span class="s">"[From: $sender] =&gt; $response"</span><span class="o">)</span>
          <span class="o">}</span>
        <span class="o">},</span> <span class="s">"reporter"</span><span class="o">)</span>

        <span class="n">alice</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nv">WalletActor</span><span class="o">.</span><span class="py">create</span><span class="o">(</span><span class="s">"alice"</span><span class="o">),</span> <span class="s">"alice-actor"</span><span class="o">)</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">alice</span> <span class="o">!</span> <span class="nc">Deposit</span><span class="o">(</span><span class="mi">100</span><span class="o">,</span> <span class="nv">auditor</span><span class="o">.</span><span class="py">some</span><span class="o">)</span>

        <span class="n">bob</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nv">WalletActor</span><span class="o">.</span><span class="py">create</span><span class="o">(</span><span class="s">"bob"</span><span class="o">),</span> <span class="s">"bob-actor"</span><span class="o">)</span>

        <span class="c1">// The transaction actor does not receive any messages, it coordinates flow between two actors.</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">[</span><span class="kt">Nothing</span><span class="o">](</span>
          <span class="nv">TransactionActor</span><span class="o">.</span><span class="py">create</span><span class="o">(</span><span class="s">"alice-&gt;bob::1"</span><span class="o">,</span> <span class="n">auditor</span><span class="o">,</span> <span class="n">alice</span><span class="o">,</span> <span class="n">bob</span><span class="o">,</span> <span class="nc">BigDecimal</span><span class="o">(</span><span class="mi">100</span><span class="o">)),</span> <span class="s">"tx-coordinator"</span>
        <span class="o">)</span>

        <span class="c1">// Retrieve the new balances</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">alice</span> <span class="o">!</span> <span class="nc">GetBalance</span><span class="o">(</span><span class="n">auditor</span><span class="o">)</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">bob</span> <span class="o">!</span> <span class="nc">GetBalance</span><span class="o">(</span><span class="n">auditor</span><span class="o">)</span>

      <span class="o">}</span> <span class="k">yield</span> <span class="nv">ExitCode</span><span class="o">.</span><span class="py">Success</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="the-workflow-step-by-step-rocket">The Workflow: Step by Step :rocket:</h4>

<ol>
  <li><strong>Initialization</strong>: The <code class="language-plaintext highlighter-rouge">ActorSystem</code> is set up, and a <code class="language-plaintext highlighter-rouge">reporter</code> actor is created to log actions and results.</li>
  <li><strong>Creating Wallets</strong>: Wallet actors for Alice and Bob are created, and an initial deposit is made to Alice.</li>
  <li><strong>Transaction Coordination</strong>: A <code class="language-plaintext highlighter-rouge">TransactionActor</code> is created to manage the transfer of 100 units from Alice’s wallet to Bob’s. The coordinator sends a withdrawal request to Alice’s wallet and, upon confirmation, sends a deposit request to Bob’s wallet.</li>
  <li><strong>Logging Results</strong>: The <code class="language-plaintext highlighter-rouge">reporter</code> actor logs the balance of each wallet after the transaction is complete.</li>
</ol>

<h4 id="sample-output-and-logs-explanation-log">Sample Output and Logs Explanation :log:</h4>
<p>Below is a snapshot of what you might see when running the application, along with detailed explanations for each log entry:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">[</span>alice-actor] Deposited 100 to alice. New balance: 100.0
<span class="o">[</span>From: alice-actor] <span class="o">=&gt;</span> Balance<span class="o">(</span>100.0<span class="o">)</span>
<span class="o">[</span>alice-actor] Withdrew 100 from alice. New balance: 0.0
~~~ <span class="o">[</span>Tx: alice-&gt;bob::1] <span class="o">=&gt;</span> Withdraw from <span class="o">[</span>alice-actor] confirmed.  Depositing to <span class="o">[</span>bob-actor]. ~~~
<span class="o">[</span>From: alice-actor] <span class="o">=&gt;</span> Balance<span class="o">(</span>0.0<span class="o">)</span>
<span class="o">[</span>From: bob-actor] <span class="o">=&gt;</span> Balance<span class="o">(</span>0.0<span class="o">)</span>
<span class="o">[</span>bob-actor] Deposited 100 to bob. New balance: 100.0
~~~ <span class="o">[</span>Tx: alice-&gt;bob::1] <span class="o">=&gt;</span> Deposit to <span class="o">[</span>bob-actor] confirmed.  Killing actor - transaction <span class="nb">complete</span><span class="o">!</span> ~~~
</code></pre></div></div>

<ul>
  <li><code class="language-plaintext highlighter-rouge">~~~ [Tx: alice-&gt;bob::1] =&gt; Sending withdraw request to [alice-actor].  Awaiting confirmation.  ~~~</code>: The transaction actor initiates the withdrawal from Alice’s wallet.</li>
  <li><code class="language-plaintext highlighter-rouge">[alice-actor] Deposited 100 to alice. New balance: 100.0</code>: Alice’s wallet receives a deposit of 100 units.</li>
  <li><code class="language-plaintext highlighter-rouge">[From: alice-actor] =&gt; Balance(100.0)</code>: The reporter logs the balance of Alice’s wallet.</li>
  <li><code class="language-plaintext highlighter-rouge">[alice-actor] Withdrew 100 from alice. New balance: 0.0</code>: Alice’s wallet processes the withdrawal.</li>
  <li><code class="language-plaintext highlighter-rouge">~~~ [Tx: alice-&gt;bob::1] =&gt; Withdraw from [alice-actor] confirmed.  Depositing to [bob-actor]. ~~~</code>: The transaction actor confirms the withdrawal and starts the deposit to Bob’s wallet.</li>
  <li><code class="language-plaintext highlighter-rouge">[From: alice-actor] =&gt; Balance(0.0)</code>: The reporter logs the updated balance of Alice’s wallet.</li>
  <li><code class="language-plaintext highlighter-rouge">[From: bob-actor] =&gt; Balance(0.0)</code>: The reporter logs the initial balance of Bob’s wallet.</li>
  <li><code class="language-plaintext highlighter-rouge">[bob-actor] Deposited 100 to bob. New balance: 100.0</code>: Bob’s wallet receives the deposit.</li>
  <li><code class="language-plaintext highlighter-rouge">~~~ [Tx: alice-&gt;bob::1] =&gt; Deposit to [bob-actor] confirmed.  Killing actor - transaction complete! ~~~</code>: The transaction actor confirms the deposit and completes the transaction.</li>
</ul>

<h2 id="conclusion-tada">Conclusion :tada:</h2>
<p>With the release of Cats-Actors 2.0.0-RC1, typed actors bring a new level of safety and clarity to actor-based programming in Scala. This example demonstrated a classic Alice-to-Bob transaction, showcasing the simplicity and effectiveness of typed actors. Whether you’re building simple applications or complex distributed systems, typed actors can help you write more reliable and maintainable code.</p>

<p>Try it out for yourself, and explore the possibilities that typed actors open up in your projects! :rocket:</p>

<p>As always, stay safe, keep hacking!</p>]]></content><author><name>Mark Galea</name></author><category term="cats-actors" /><summary type="html"><![CDATA[Today marks an exciting milestone with the release of Cats-Actors 2.0.0-RC1. This version introduces typed actors, a feature that the community has eagerly awaited. To showcase this new capability, we’ll walk through a classic example of handling wallet transactions between two users, Alice and Bob. So, sit back and relax as we explore how Alice sends money to Bob using typed actors in Cats-Actors.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://cloudmark.me/images/cats-actors/logo-small.png" /><media:content medium="image" url="https://cloudmark.me/images/cats-actors/logo-small.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">A Logic Circuit Simulator with Cats-Actors</title><link href="https://cloudmark.me/Cats-Actors/" rel="alternate" type="text/html" title="A Logic Circuit Simulator with Cats-Actors" /><published>2024-06-14T00:00:00+02:00</published><updated>2024-06-14T00:00:00+02:00</updated><id>https://cloudmark.me/Cats-Actors</id><content type="html" xml:base="https://cloudmark.me/Cats-Actors/"><![CDATA[<p><img class="title" src="/images/cats-actors/logo-small.png" />
Functional programming and the actor model are two powerful paradigms in modern software development. They might seem like they’re in opposition, but in reality, they complement each other beautifully. Scala, as a versatile language, allows multiple paradigms to coexist, and Cats-Actors, a functional programming-based actor system, exemplifies this harmony. Cats-Actors is a reimagining of the actor paradigm model married with the functional paradigm.</p>

<p>Imagine you’re working at ACME Inc., where your task is to create a logic circuit verifier to ensure the reliability of their motherboards. These motherboards will be used in a mission to launch cats into space, and no one wants these feline astronauts to be at risk. You’ve been tasked with developing a logic circuit simulator that accounts for the internal delays of digital circuits, ensuring that all signals stabilize on each clock tick. We certainly don’t want a motherboard with AND gates still transitioning when it’s time to read the values. So, gear up, and let’s embark on this Cats-Actors adventure to build a robust logic circuit simulator and ensure those kittens have a safe sendoff!</p>

<h3 id="setting-up-your-project">Setting Up Your Project</h3>

<p>To get started with Cats-Actors, you need to set up your Scala project with the necessary dependencies. Add the
following to your <code class="language-plaintext highlighter-rouge">build.sbt</code> file:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">resolvers</span> <span class="o">+=</span> <span class="s">"JitPack"</span> <span class="n">at</span> <span class="s">"https://jitpack.io"</span>

<span class="n">libraryDependencies</span> <span class="o">+=</span> <span class="s">"com.github.suprnation"</span> <span class="o">%</span> <span class="s">"cats-actors_2.13"</span> <span class="o">%</span> <span class="s">"1.0.1"</span>
</code></pre></div></div>

<blockquote>
  <p>For a complete listing of all code samples and to clone the project, visit the <a href="https://github.com/cloudmark/cats-actor-sample">GitHub repository</a>.</p>
</blockquote>

<h2 id="understanding-the-actor-model">Understanding the Actor Model</h2>
<p>Before we dive into building our logic circuit simulator, let’s take a moment to understand the actor model. Imagine
actors as independent workers in a factory. Each worker has their own tasks and responsibilities, and they communicate
with each other by passing messages. This setup ensures that no one is stepping on anyone else’s toes, making it easier
to build systems that are both concurrent and fault-tolerant.</p>

<p>In the Cats-Actors framework, these actors get an extra boost from functional programming principles. This means our
actors will use immutable data and pure functions, making our system more predictable and easier to maintain.</p>

<p>So, what can actors do in this model?</p>

<ol>
  <li><strong>Send Messages</strong>: Just like sending a text, actors communicate by sending messages to each other. Each actor has a
mailbox where it receives these messages.</li>
  <li><strong>Create Actors</strong>: Need more hands on deck? Actors can create new actors to help with tasks.</li>
  <li><strong>Change Behavior</strong>: Actors can switch up their behavior based on the messages they get, allowing them to adapt to
different situations.</li>
</ol>

<p>By combining the actor model with functional programming, we get the best of both worlds. This synergy helps us build
systems that are robust, scalable, and easy to maintain.</p>

<h2 id="building-our-logic-circuit-simulator">Building Our Logic Circuit Simulator</h2>
<p>In this section, we’ll start building the core components of our logic circuit simulator using Cats-Actors. Our goal is to construct various logic gates and combine them to simulate complex circuits. Let’s break down the components and build them step by step.</p>

<p>First, we’ll start by creating the Wire actor, which will transport signals. After that, we’ll create basic logic gates like AND, OR, and an alternative OR gate using De Morgan’s laws. We’ll then combine these gates into more complex components such as Half Adders and Full Adders, and finally, we’ll build Demultiplexers.</p>

<p>Ready? Let’s dive in.</p>

<h3 id="1-creating-the-wire-actor">1. Creating the Wire Actor</h3>
<p>The Wire actor is responsible for transporting signals, which can be either true (high voltage) or false (low voltage). It allows component actors to subscribe to state changes and notifies them whenever its state changes.</p>

<p>Here’s the code for the Wire actor:</p>
<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">wire</span><span class="o">(</span><span class="nc">_currentState</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="k">for</span> <span class="o">{</span>
        <span class="n">associationsRef</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">(</span><span class="nv">Map</span><span class="o">.</span><span class="py">empty</span><span class="o">[</span><span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span>, <span class="kt">String</span><span class="o">])</span>
        <span class="n">currentStateRef</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">(</span><span class="nc">_currentState</span><span class="o">)</span>
      <span class="o">}</span> <span class="k">yield</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
        <span class="k">override</span> <span class="k">def</span> <span class="nf">receive</span><span class="k">:</span> <span class="kt">Receive</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
          <span class="k">case</span> <span class="nc">AddComponent</span><span class="o">(</span><span class="n">name</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">b</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">])</span> <span class="k">=&gt;</span>
            <span class="k">for</span> <span class="o">{</span>
              <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">associationsRef</span><span class="o">.</span><span class="py">update</span><span class="o">(</span><span class="k">_</span> <span class="o">+</span> <span class="o">(</span><span class="n">b</span> <span class="o">-&gt;</span> <span class="n">name</span><span class="o">))</span>
              <span class="n">currentState</span> <span class="k">&lt;-</span> <span class="nv">currentStateRef</span><span class="o">.</span><span class="py">get</span>
              <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">b</span> <span class="o">!</span> <span class="nc">StateChange</span><span class="o">(</span><span class="n">name</span><span class="o">,</span> <span class="n">currentState</span><span class="o">)</span>
            <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>

          <span class="k">case</span> <span class="nc">GetValue</span> <span class="k">=&gt;</span> <span class="nv">currentStateRef</span><span class="o">.</span><span class="py">get</span>

          <span class="k">case</span> <span class="n">s</span><span class="k">:</span> <span class="kt">Boolean</span> <span class="o">=&gt;</span>
            <span class="nv">currentStateRef</span><span class="o">.</span><span class="py">get</span><span class="o">.</span><span class="py">map</span><span class="o">(</span><span class="k">_</span> <span class="o">!=</span> <span class="n">s</span><span class="o">).</span><span class="py">ifM</span><span class="o">(</span>
              <span class="k">for</span> <span class="o">{</span>
                <span class="n">currentState</span> <span class="k">&lt;-</span> <span class="nv">currentStateRef</span><span class="o">.</span><span class="py">updateAndGet</span><span class="o">(</span><span class="k">_</span> <span class="k">=&gt;</span> <span class="n">s</span><span class="o">)</span>
                <span class="n">associations</span> <span class="k">&lt;-</span> <span class="nv">associationsRef</span><span class="o">.</span><span class="py">get</span>
                <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">associations</span><span class="o">.</span><span class="py">toList</span><span class="o">.</span><span class="py">parTraverse_</span> <span class="o">{</span> 
                  <span class="nf">case</span> <span class="o">(</span><span class="n">ref</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">name</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">=&gt;</span>
                     <span class="n">ref</span> <span class="o">!</span> <span class="nc">StateChange</span><span class="o">(</span><span class="n">name</span><span class="o">,</span> <span class="n">currentState</span><span class="o">)</span>
                <span class="o">}</span>
              <span class="o">}</span> <span class="nf">yield</span> <span class="o">(),</span>
              <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span>
         <span class="o">)</span>
     <span class="o">}</span>
   <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>In this code, the Wire actor maintains its current state (<code class="language-plaintext highlighter-rouge">currentState</code>) and a map of associations where each entry maps a subscribing actor to a wire name. When it receives an <code class="language-plaintext highlighter-rouge">AddComponent</code> message, it adds the subscribing actor to its associations and sends the current state to the subscriber. When it receives a boolean value, it updates its state and notifies all subscribed components if the state has changed. Broadcasting state changes to all associations is done in parallel using <code class="language-plaintext highlighter-rouge">parTraverse_</code>.</p>

<h2 id="2-creating-the-basic-logic-gates">2. Creating the Basic Logic Gates</h2>
<p>Now, let’s move on to creating the logic gates. We’ll start with the NOT gate (Inverter). The Inverter actor will take an input and output the inverted result after a delay.</p>

<p>Here’s the code for the Inverter actor:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">inverter</span><span class="o">(</span><span class="n">input</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">output</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">])</span><span class="k">:</span> <span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
    <span class="n">input</span> <span class="o">!</span> <span class="nc">AddComponent</span><span class="o">(</span><span class="s">"in"</span><span class="o">,</span> <span class="n">self</span><span class="o">)</span>
  <span class="o">}</span>

  <span class="k">override</span> <span class="k">val</span> <span class="nv">receive</span><span class="k">:</span> <span class="kt">Actor.Receive</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
    <span class="k">case</span> <span class="nc">StateChange</span><span class="o">(</span><span class="k">_</span><span class="o">,</span> <span class="n">s</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span> <span class="k">=&gt;</span>
      <span class="o">(</span><span class="nv">IO</span><span class="o">.</span><span class="py">sleep</span><span class="o">(</span><span class="n">inverterDelay</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="o">(</span><span class="n">output</span> <span class="o">!</span> <span class="o">(!</span><span class="n">s</span><span class="o">))).</span><span class="py">start</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">inverter</code> actor registers itself with the input wire, receiving updates under the name “in”. When it receives a state change, it waits for the inverter delay before sending the inverted signal to the output. This process is run in the background using <code class="language-plaintext highlighter-rouge">start</code>, allowing the actor to continue processing other messages.</p>

<p>Next, we’ll create the AND gate. The And actor will take two inputs and output the result of their AND operation.</p>

<p>Here’s the code for the And actor:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">and</span><span class="o">(</span><span class="n">input0</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">input1</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">output</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">])</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]]</span> <span class="k">=</span> <span class="o">{</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">in0</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">[</span><span class="kt">Option</span><span class="o">[</span><span class="kt">Boolean</span><span class="o">]](</span><span class="nc">None</span><span class="o">)</span>
    <span class="n">in1</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">[</span><span class="kt">Option</span><span class="o">[</span><span class="kt">Boolean</span><span class="o">]](</span><span class="nc">None</span><span class="o">)</span>
  <span class="o">}</span> <span class="k">yield</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
    <span class="k">override</span> <span class="k">def</span> <span class="nf">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="o">(</span><span class="n">input0</span> <span class="o">!</span> <span class="nc">AddComponent</span><span class="o">(</span><span class="s">"in0"</span><span class="o">,</span> <span class="n">self</span><span class="o">),</span> 
       <span class="n">input1</span> <span class="o">!</span> <span class="nc">AddComponent</span><span class="o">(</span><span class="s">"in1"</span><span class="o">,</span> <span class="n">self</span><span class="o">)).</span><span class="py">parTupled</span><span class="o">.</span><span class="py">void</span>
    <span class="o">}</span>

    <span class="k">override</span> <span class="k">val</span> <span class="nv">receive</span><span class="k">:</span> <span class="kt">Actor.Receive</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="k">case</span> <span class="nc">StateChange</span><span class="o">(</span><span class="s">"in0"</span><span class="o">,</span> <span class="n">b</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">in0</span><span class="o">.</span><span class="py">set</span><span class="o">(</span><span class="nv">b</span><span class="o">.</span><span class="py">some</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="nv">sendMessage</span><span class="o">.</span><span class="py">start</span>
      <span class="k">case</span> <span class="nc">StateChange</span><span class="o">(</span><span class="s">"in1"</span><span class="o">,</span> <span class="n">b</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">in1</span><span class="o">.</span><span class="py">set</span><span class="o">(</span><span class="nv">b</span><span class="o">.</span><span class="py">some</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="nv">sendMessage</span><span class="o">.</span><span class="py">start</span>
    <span class="o">}</span>

    <span class="k">private</span> <span class="k">val</span> <span class="nv">sendMessage</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span>
      <span class="o">(</span><span class="nv">in0</span><span class="o">.</span><span class="py">get</span><span class="o">,</span> <span class="nv">in1</span><span class="o">.</span><span class="py">get</span><span class="o">).</span><span class="py">flatMapN</span> <span class="o">{</span>
        <span class="nf">case</span> <span class="o">(</span><span class="nc">Some</span><span class="o">(</span><span class="n">first</span><span class="o">),</span> <span class="nc">Some</span><span class="o">(</span><span class="n">second</span><span class="o">))</span> <span class="k">=&gt;</span>
          <span class="nv">IO</span><span class="o">.</span><span class="py">sleep</span><span class="o">(</span><span class="n">andDelay</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="o">(</span><span class="n">output</span> <span class="o">!</span> <span class="o">(</span><span class="n">first</span> <span class="o">&amp;&amp;</span> <span class="n">second</span><span class="o">))</span>
        <span class="k">case</span> <span class="k">_</span> <span class="k">=&gt;</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span>
      <span class="o">}</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The AND actor listens for state changes from its two input wires. When either input changes, it checks if both inputs are true and sends the result to the output wire after a specified delay (<code class="language-plaintext highlighter-rouge">andDelay</code>). Note how the state changes are run in the background using <code class="language-plaintext highlighter-rouge">start</code>.</p>

<p>Similarly, we can create the OR actor, which outputs true if at least one input is true.</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">or</span><span class="o">(</span><span class="n">input0</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">input1</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">output</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">])</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]]</span> <span class="k">=</span> <span class="o">{</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">in0</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">[</span><span class="kt">Option</span><span class="o">[</span><span class="kt">Boolean</span><span class="o">]](</span><span class="nc">None</span><span class="o">)</span>
    <span class="n">in1</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">[</span><span class="kt">Option</span><span class="o">[</span><span class="kt">Boolean</span><span class="o">]](</span><span class="nc">None</span><span class="o">)</span>
  <span class="o">}</span> <span class="k">yield</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
    <span class="k">override</span> <span class="k">def</span> <span class="nf">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="o">(</span><span class="n">input0</span> <span class="o">!</span> <span class="nc">AddComponent</span><span class="o">(</span><span class="s">"in0"</span><span class="o">,</span> <span class="n">self</span><span class="o">),</span> 
      <span class="n">input1</span> <span class="o">!</span> <span class="nc">AddComponent</span><span class="o">(</span><span class="s">"in1"</span><span class="o">,</span> <span class="n">self</span><span class="o">)).</span><span class="py">parTupled</span><span class="o">.</span><span class="py">void</span>
    <span class="o">}</span>

    <span class="k">override</span> <span class="k">val</span> <span class="nv">receive</span><span class="k">:</span> <span class="kt">Actor.Receive</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="k">case</span> <span class="nc">StateChange</span><span class="o">(</span><span class="s">"in0"</span><span class="o">,</span> <span class="n">b</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">in0</span><span class="o">.</span><span class="py">set</span><span class="o">(</span><span class="nv">b</span><span class="o">.</span><span class="py">some</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="nv">sendMessage</span><span class="o">.</span><span class="py">start</span>
      <span class="k">case</span> <span class="nc">StateChange</span><span class="o">(</span><span class="s">"in1"</span><span class="o">,</span> <span class="n">b</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">in1</span><span class="o">.</span><span class="py">set</span><span class="o">(</span><span class="nv">b</span><span class="o">.</span><span class="py">some</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="nv">sendMessage</span><span class="o">.</span><span class="py">start</span>
    <span class="o">}</span>

    <span class="k">private</span> <span class="k">def</span> <span class="nf">sendMessage</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="o">(</span><span class="nv">in0</span><span class="o">.</span><span class="py">get</span><span class="o">,</span> <span class="nv">in1</span><span class="o">.</span><span class="py">get</span><span class="o">).</span><span class="py">flatMapN</span> <span class="o">{</span>
        <span class="nf">case</span> <span class="o">(</span><span class="nc">Some</span><span class="o">(</span><span class="n">first</span><span class="o">),</span> <span class="nc">Some</span><span class="o">(</span><span class="n">second</span><span class="o">))</span> <span class="k">=&gt;</span>
          <span class="nv">IO</span><span class="o">.</span><span class="py">sleep</span><span class="o">(</span><span class="n">orDelay</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="o">(</span><span class="n">output</span> <span class="o">!</span> <span class="o">(</span><span class="n">first</span> <span class="o">||</span> <span class="n">second</span><span class="o">))</span>
        <span class="k">case</span> <span class="k">_</span> <span class="k">=&gt;</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span>
      <span class="o">}</span>
    <span class="o">}</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The Or actor’s logic is very similar to the And actor’s logic. It registers with the input wires, listens for state changes, and sends the result to the output wire after the specified delay.</p>

<p>We can notice many commonalities between the And and Or actors. To eliminate redundancy, we can create a higher-order actor called <code class="language-plaintext highlighter-rouge">reducer</code>, which takes a reduction function and a delay as parameters. This actor will generalize the logic for creating gates with two inputs and one output.</p>

<p>Here’s the code for the <code class="language-plaintext highlighter-rouge">reducer</code>:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">reducer</span><span class="o">(</span><span class="n">reduceFn</span><span class="k">:</span> <span class="o">(</span><span class="kt">Boolean</span><span class="o">,</span> <span class="kt">Boolean</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nc">Boolean</span><span class="o">,</span> <span class="n">delay</span><span class="k">:</span> <span class="kt">Duration</span><span class="o">)</span>
            <span class="o">(</span><span class="n">input0</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span><span class="n">input1</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> 
            <span class="n">output</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span>
<span class="o">)</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]]</span> <span class="k">=</span> <span class="o">{</span>
  <span class="k">for</span> <span class="o">{</span>
    <span class="n">in0</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">[</span><span class="kt">Option</span><span class="o">[</span><span class="kt">Boolean</span><span class="o">]](</span><span class="nc">None</span><span class="o">)</span>
    <span class="n">in1</span> <span class="k">&lt;-</span> <span class="nc">Ref</span><span class="o">[</span><span class="kt">IO</span><span class="o">].</span><span class="py">of</span><span class="o">[</span><span class="kt">Option</span><span class="o">[</span><span class="kt">Boolean</span><span class="o">]](</span><span class="nc">None</span><span class="o">)</span>
  <span class="o">}</span> <span class="k">yield</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
    <span class="k">override</span> <span class="k">def</span> <span class="nf">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span>
      <span class="o">(</span><span class="n">input0</span> <span class="o">!</span> <span class="nc">AddComponent</span><span class="o">(</span><span class="s">"in0"</span><span class="o">,</span> <span class="n">self</span><span class="o">),</span> 
      <span class="n">input1</span> <span class="o">!</span> <span class="nc">AddComponent</span><span class="o">(</span><span class="s">"in1"</span><span class="o">,</span> <span class="n">self</span><span class="o">)).</span><span class="py">parTupled</span><span class="o">.</span><span class="py">void</span>

    <span class="k">override</span> <span class="k">val</span> <span class="nv">receive</span><span class="k">:</span> <span class="kt">Actor.Receive</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="k">case</span> <span class="nc">StateChange</span><span class="o">(</span><span class="s">"in0"</span><span class="o">,</span> <span class="n">b</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">in0</span><span class="o">.</span><span class="py">set</span><span class="o">(</span><span class="nv">b</span><span class="o">.</span><span class="py">some</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="nv">sendMessage</span><span class="o">.</span><span class="py">start</span>
      <span class="k">case</span> <span class="nc">StateChange</span><span class="o">(</span><span class="s">"in1"</span><span class="o">,</span> <span class="n">b</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nv">in1</span><span class="o">.</span><span class="py">set</span><span class="o">(</span><span class="nv">b</span><span class="o">.</span><span class="py">some</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="nv">sendMessage</span><span class="o">.</span><span class="py">start</span>
    <span class="o">}</span>

    <span class="k">private</span> <span class="k">def</span> <span class="nf">sendMessage</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
      <span class="o">(</span><span class="nv">in0</span><span class="o">.</span><span class="py">get</span><span class="o">,</span> <span class="nv">in1</span><span class="o">.</span><span class="py">get</span><span class="o">).</span><span class="py">flatMapN</span> <span class="o">{</span>
        <span class="nf">case</span> <span class="o">(</span><span class="nc">Some</span><span class="o">(</span><span class="n">first</span><span class="o">),</span> <span class="nc">Some</span><span class="o">(</span><span class="n">second</span><span class="o">))</span> <span class="k">=&gt;</span>
          <span class="nv">IO</span><span class="o">.</span><span class="py">sleep</span><span class="o">(</span><span class="n">delay</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="o">(</span><span class="n">output</span> <span class="o">!</span> <span class="nf">reduceFn</span><span class="o">(</span><span class="n">first</span><span class="o">,</span> <span class="n">second</span><span class="o">))</span>
        <span class="k">case</span> <span class="k">_</span> <span class="k">=&gt;</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span>
      <span class="o">}</span>
    <span class="o">}</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Using this higher-order function, we can rewrite the AND and OR gates as follows:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">val</span> <span class="nv">and</span> <span class="k">=</span> <span class="nf">reducer</span><span class="o">(</span><span class="k">_</span> <span class="o">&amp;&amp;</span> <span class="k">_</span><span class="o">,</span> <span class="n">andDelay</span><span class="o">)(</span><span class="k">_</span><span class="o">,</span> <span class="k">_</span><span class="o">,</span> <span class="k">_</span><span class="o">)</span>
<span class="k">val</span> <span class="nv">or</span> <span class="k">=</span> <span class="nf">reducer</span><span class="o">(</span><span class="k">_</span> <span class="o">||</span> <span class="k">_</span><span class="o">,</span> <span class="n">orDelay</span><span class="o">)(</span><span class="k">_</span><span class="o">,</span> <span class="k">_</span><span class="o">,</span> <span class="k">_</span><span class="o">)</span>
</code></pre></div></div>

<p>This approach keeps the logic for the AND and OR gates intact while reducing redundancy.</p>

<p>Next, let’s create an alternative implementation of the OR gate using De Morgan’s laws, which, given the timings, will be more efficient. Chip manufacturers often specialize in certain gates to reduce production costs and make those gates super efficient. Other gates can be formed using De Morgan’s laws or truth table deductions. According to De Morgan’s laws:</p>

\[\begin{eqnarray*}
A \lor B &amp;=&amp; \neg(\neg A \land \neg B)
\end{eqnarray*}\]

<p>By using this transformation, we can create the <code class="language-plaintext highlighter-rouge">OrAlt</code> actor:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">orAlt</span><span class="o">(</span><span class="n">input0</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">input1</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">output</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">])</span><span class="k">:</span> <span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span>
  <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
    <span class="k">override</span> <span class="k">val</span> <span class="nv">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
      <span class="n">notInput0</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"notInput0"</span><span class="o">)</span>
      <span class="n">notInput1</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"notInput1"</span><span class="o">)</span>
      <span class="n">notOutput0</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"notOutput0"</span><span class="o">)</span>

      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">inverter</span><span class="o">(</span><span class="n">input0</span><span class="o">,</span> <span class="n">notInput0</span><span class="o">)),</span> <span class="s">"A"</span><span class="o">)</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">inverter</span><span class="o">(</span><span class="n">input1</span><span class="o">,</span> <span class="n">notInput1</span><span class="o">)),</span> <span class="s">"B"</span><span class="o">)</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">and</span><span class="o">(</span><span class="n">notInput0</span><span class="o">,</span> <span class="n">notInput1</span><span class="o">,</span> <span class="n">notOutput0</span><span class="o">)),</span> <span class="s">"notAB"</span><span class="o">)</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">inverter</span><span class="o">(</span><span class="n">notOutput0</span><span class="o">,</span> <span class="n">output</span><span class="o">)),</span> <span class="s">"notNotAB"</span><span class="o">)</span>
    <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
  <span class="o">}</span>
</code></pre></div></div>

<p>In the OrAlt actor, we first invert both inputs, then AND these inverted inputs, and finally invert the result. This approach leverages the efficiency of De Morgan’s laws to potentially reduce the overall computation time, especially in complex circuits.</p>

<blockquote>
  <p>Note how we are now dealing at a higher level of abstraction – we focus on the logical connections between components rather than the internal workings of the actors. A typical approach in the typelevel community is using FS2 and managing these wirings manually. Achieving the same level of abstraction with FS2 can be more challenging. This isn’t to say FS2 is inferior, but Cats-Actors can simplify dynamic graph constructions and modifications at runtime, particularly when handling dynamic stream graphs.</p>
</blockquote>

<p>By using De Morgan’s transformation, we can optimize the OR gate, which typically has a delay of 10ms. In this alternative implementation, we use a NOT gate on each input, an AND gate to combine these negated inputs, and another NOT gate on top of everything. Given that all these components run in parallel, we would have a total delay of only 3ms from the input perturbations, significantly improving efficiency.</p>

<h2 id="3-creating-more-complex-components">3. Creating More Complex Components</h2>

<p>Now that we have created basic logic gates, let’s move on to combining these gates into more complex components. We’ll start with the Half Adder. A Half Adder is a digital circuit that performs addition of two binary digits. It has two inputs, <code class="language-plaintext highlighter-rouge">a</code> and <code class="language-plaintext highlighter-rouge">b</code>, and two outputs, <code class="language-plaintext highlighter-rouge">s</code> (sum) and <code class="language-plaintext highlighter-rouge">c</code> (carry). The sum output is the XOR of the inputs, and the carry output is the AND of the inputs.</p>

<p>Here’s the code for the Half Adder:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">halfAdder</span><span class="o">(</span><span class="n">a</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">b</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">s</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">c</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">])</span><span class="k">:</span> <span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
  <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
    <span class="k">override</span> <span class="k">val</span> <span class="nv">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
      <span class="n">d</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"d"</span><span class="o">)</span>
      <span class="n">e</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"e"</span><span class="o">)</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">or</span><span class="o">(</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">,</span> <span class="n">d</span><span class="o">)),</span> <span class="s">"Or"</span><span class="o">)</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">and</span><span class="o">(</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">,</span> <span class="n">c</span><span class="o">)),</span> <span class="s">"And"</span><span class="o">)</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">inverter</span><span class="o">(</span><span class="n">c</span><span class="o">,</span> <span class="n">e</span><span class="o">)),</span> <span class="s">"Inverter"</span><span class="o">)</span>
      <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">and</span><span class="o">(</span><span class="n">d</span><span class="o">,</span> <span class="n">e</span><span class="o">,</span> <span class="n">s</span><span class="o">)),</span> <span class="s">"And2"</span><span class="o">)</span>
    <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The Half Adder actor uses our previously defined gates to create the sum and carry outputs. It uses an OR gate, an AND gate, and an inverter to achieve this.</p>

<p>Next, let’s create the Full Adder, which adds three binary digits (two significant bits and a carry bit). The Full Adder outputs a sum and a carry. We’ll use two Half Adders and an OR gate to construct the Full Adder:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">fullAdder</span><span class="o">(</span><span class="n">a</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">b</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">cin</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">sum</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">cout</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">])</span><span class="k">:</span> <span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
    <span class="k">override</span> <span class="k">val</span> <span class="nv">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
        <span class="n">s</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)))</span>
        <span class="n">c1</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)))</span>
        <span class="n">c2</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)))</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">halfAdder</span><span class="o">(</span><span class="n">a</span><span class="o">,</span> <span class="n">cin</span><span class="o">,</span> <span class="n">s</span><span class="o">,</span> <span class="n">c1</span><span class="o">)),</span> <span class="s">"HalfAdder1"</span><span class="o">)</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">halfAdder</span><span class="o">(</span><span class="n">b</span><span class="o">,</span> <span class="n">s</span><span class="o">,</span> <span class="n">sum</span><span class="o">,</span> <span class="n">c2</span><span class="o">)),</span> <span class="s">"HalfAdder2"</span><span class="o">)</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">or</span><span class="o">(</span><span class="n">c1</span><span class="o">,</span> <span class="n">c2</span><span class="o">,</span> <span class="n">cout</span><span class="o">)),</span> <span class="s">"OrGate"</span><span class="o">)</span>
    <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
<span class="o">}</span>
</code></pre></div></div>

<p>By leveraging the Half Adder, the Full Adder actor becomes simpler and more modular. This demonstrates the power of building higher-order components from simpler ones, enhancing our digital circuit simulation capabilities.</p>

<p>Next, let’s build a 2-to-1 Demultiplexer (Demux2), which directs an input signal to one of the two output lines based on a control signal. Here’s the code for Demux2:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">demux2</span><span class="o">(</span><span class="n">in</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">c</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">out1</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">out0</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">])</span><span class="k">:</span> <span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
    <span class="k">override</span> <span class="k">val</span> <span class="nv">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
        <span class="n">notC</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"not"</span><span class="o">)</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">inverter</span><span class="o">(</span><span class="n">c</span><span class="o">,</span> <span class="n">notC</span><span class="o">)),</span> <span class="s">"InverterA"</span><span class="o">)</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">and</span><span class="o">(</span><span class="n">in</span><span class="o">,</span> <span class="n">notC</span><span class="o">,</span> <span class="n">out1</span><span class="o">)),</span> <span class="s">"AndGateA"</span><span class="o">)</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">and</span><span class="o">(</span><span class="n">in</span><span class="o">,</span> <span class="n">c</span><span class="o">,</span> <span class="n">out0</span><span class="o">)),</span> <span class="s">"AndGateB"</span><span class="o">)</span>
    <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Finally, let’s create a General Demultiplexer (Demux), which can handle multiple control signals and direct the input signal to one of the output lines. The Demux actor uses recursion to handle multiple control signals, dynamically creating a demux of any size by wiring Demux2 actors together. This approach illustrates the flexibility and power of combining actors and functional programming in Cats-Actors. Here’s the code for Demux:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">demux</span><span class="o">(</span><span class="n">in</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">],</span> <span class="n">c</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">]],</span> <span class="n">out</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">ActorRef</span><span class="o">[</span><span class="kt">IO</span><span class="o">]])</span><span class="k">:</span> <span class="kt">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">Actor</span><span class="o">[</span><span class="kt">IO</span><span class="o">]</span> <span class="o">{</span>
    <span class="k">override</span> <span class="k">val</span> <span class="nv">preStart</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="n">c</span> <span class="k">match</span> <span class="o">{</span>
        <span class="k">case</span> <span class="n">c_n</span> <span class="o">::</span> <span class="nc">Nil</span> <span class="k">=&gt;</span>
            <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">demux2</span><span class="o">(</span><span class="n">in</span><span class="o">,</span> <span class="n">c_n</span><span class="o">,</span> <span class="nv">out</span><span class="o">.</span><span class="py">head</span><span class="o">,</span> <span class="nf">out</span><span class="o">(</span><span class="mi">1</span><span class="o">)))).</span><span class="py">void</span>

        <span class="k">case</span> <span class="n">c_n</span> <span class="o">::</span> <span class="n">c_rest</span> <span class="k">=&gt;</span>
            <span class="k">for</span> <span class="o">{</span>
                <span class="n">out1</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)))</span>
                <span class="n">out0</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)))</span>
                <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">demux2</span><span class="o">(</span><span class="n">in</span><span class="o">,</span> <span class="n">c_n</span><span class="o">,</span> <span class="n">out1</span><span class="o">,</span> <span class="n">out0</span><span class="o">)))</span>
                <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">demux</span><span class="o">(</span><span class="n">out1</span><span class="o">,</span> <span class="n">c_rest</span><span class="o">,</span> <span class="nv">out</span><span class="o">.</span><span class="py">take</span><span class="o">(</span><span class="nv">out</span><span class="o">.</span><span class="py">size</span> <span class="o">/</span> <span class="mi">2</span><span class="o">))))</span>
                <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">context</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="nf">demux</span><span class="o">(</span><span class="n">out0</span><span class="o">,</span> <span class="n">c_rest</span><span class="o">,</span> <span class="nv">out</span><span class="o">.</span><span class="py">drop</span><span class="o">(</span><span class="nv">out</span><span class="o">.</span><span class="py">size</span> <span class="o">/</span> <span class="mi">2</span><span class="o">))))</span>
            <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>

        <span class="k">case</span> <span class="nc">Nil</span> <span class="k">=&gt;</span> <span class="nv">IO</span><span class="o">.</span><span class="py">unit</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Note how we can create a demux of any size by recursively wiring Demux2 actors. This exemplifies the power of Cats-Actors, allowing us to use actors and functional programming in unison, and even employ recursion to create dynamic structures.</p>

<blockquote>
  <p>One key advantage of Cats-Actors is its ability to create dynamic stream graphs without needing to manage the intricate details of wiring these streams manually. Cats-Actors is particularly beneficial when dealing with dynamic graphs of streams that need to be constructed or modified at runtime. This approach simplifies the development of dynamic, evolving systems, making it an excellent choice for complex and adaptable applications.</p>
</blockquote>

<h2 id="putting-it-all-together">Putting It All Together</h2>
<p>Now, let’s put all our components together and create a Logic Circuit Simulator. This main application will set up a simulation board to test a demultiplexer with two control inputs and four outputs.</p>

<p>Here’s the complete code for the Logic Circuit Simulator:</p>
<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">object</span> <span class="nc">LogicCircuitSimulator</span> <span class="k">extends</span> <span class="nc">IOApp</span> <span class="o">{</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">run</span><span class="o">(</span><span class="n">args</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">String</span><span class="o">])</span><span class="k">:</span> <span class="kt">IO</span><span class="o">[</span><span class="kt">ExitCode</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
    <span class="nc">ActorSystem</span><span class="o">[</span><span class="kt">IO</span><span class="o">](</span><span class="s">"De-multiplexer Board Simulator"</span><span class="o">).</span><span class="py">use</span><span class="o">(</span><span class="n">system</span> <span class="k">=&gt;</span>
      <span class="k">for</span> <span class="o">{</span>
        <span class="n">in1</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">(</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"in1"</span><span class="o">)</span>
        <span class="n">c1</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">(</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"c1"</span><span class="o">)</span>
        <span class="n">c2</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">(</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"c2"</span><span class="o">)</span>
        <span class="n">out1</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">(</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"out1"</span><span class="o">)</span>
        <span class="n">out2</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">(</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"out2"</span><span class="o">)</span>
        <span class="n">out3</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">(</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"out3"</span><span class="o">)</span>
        <span class="n">out4</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">PropsF</span><span class="o">(</span><span class="nf">wire</span><span class="o">(</span><span class="kc">false</span><span class="o">)),</span> <span class="s">"out4"</span><span class="o">)</span>

        <span class="n">allActors</span> <span class="k">=</span> <span class="nc">List</span><span class="o">(</span><span class="n">in1</span><span class="o">,</span> <span class="n">c1</span><span class="o">,</span> <span class="n">c2</span><span class="o">,</span> <span class="n">out1</span><span class="o">,</span> <span class="n">out2</span><span class="o">,</span> <span class="n">out3</span><span class="o">,</span> <span class="n">out4</span><span class="o">)</span>
        <span class="n">printTruthTable</span> <span class="k">=</span>
          <span class="k">for</span> <span class="o">{</span>
            <span class="n">outputs</span> <span class="k">&lt;-</span> <span class="nv">allActors</span><span class="o">.</span><span class="py">parTraverse</span><span class="o">(</span><span class="k">_</span> <span class="o">?[</span><span class="kt">Boolean</span><span class="o">]</span> <span class="nc">GetValue</span><span class="o">)</span>
            <span class="n">result</span> <span class="k">=</span> <span class="nv">allActors</span><span class="o">.</span><span class="py">zip</span><span class="o">(</span><span class="n">outputs</span><span class="o">).</span><span class="py">map</span> <span class="o">{</span>
              <span class="nf">case</span> <span class="o">(</span><span class="n">actor</span><span class="o">,</span> <span class="n">value</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">s</span><span class="s">"${actor.path.name}::$value"</span>
            <span class="o">}.</span><span class="py">mkString</span><span class="o">(</span><span class="s">"\t"</span><span class="o">)</span>
            <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">IO</span><span class="o">.</span><span class="py">println</span><span class="o">(</span><span class="n">result</span><span class="o">)</span>
          <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>

        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">system</span><span class="o">.</span><span class="py">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">(</span><span class="nf">demux</span><span class="o">(</span><span class="n">in1</span><span class="o">,</span> <span class="nc">List</span><span class="o">(</span><span class="n">c2</span><span class="o">,</span> <span class="n">c1</span><span class="o">),</span> <span class="nc">List</span><span class="o">(</span><span class="n">out4</span><span class="o">,</span> <span class="n">out3</span><span class="o">,</span> <span class="n">out2</span><span class="o">,</span> <span class="n">out1</span><span class="o">))))</span>

        <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">in1</span> <span class="o">!</span> <span class="kc">true</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">printTruthTable</span><span class="o">.</span><span class="py">delayBy</span><span class="o">(</span><span class="mi">1</span> <span class="n">second</span><span class="o">)</span>

        <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">c1</span> <span class="o">!</span> <span class="kc">true</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">printTruthTable</span><span class="o">.</span><span class="py">delayBy</span><span class="o">(</span><span class="mi">1</span> <span class="n">second</span><span class="o">)</span>

        <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">c1</span> <span class="o">!</span> <span class="kc">false</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">c2</span> <span class="o">!</span> <span class="kc">true</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">printTruthTable</span><span class="o">.</span><span class="py">delayBy</span><span class="o">(</span><span class="mi">1</span> <span class="n">second</span><span class="o">)</span>

        <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">c1</span> <span class="o">!</span> <span class="kc">true</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">printTruthTable</span><span class="o">.</span><span class="py">delayBy</span><span class="o">(</span><span class="mi">1</span> <span class="n">second</span><span class="o">)</span>

        <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">in1</span> <span class="o">!</span> <span class="kc">false</span>
        <span class="k">_</span> <span class="k">&lt;-</span> <span class="nv">printTruthTable</span><span class="o">.</span><span class="py">delayBy</span><span class="o">(</span><span class="mi">1</span> <span class="n">second</span><span class="o">)</span>
      <span class="o">}</span> <span class="nf">yield</span> <span class="o">()</span>
    <span class="o">).</span><span class="py">as</span><span class="o">(</span><span class="nv">ExitCode</span><span class="o">.</span><span class="py">Success</span><span class="o">)</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>In the main application, we first set up the board simulator to test a demultiplexer with two control inputs and four outputs. We create all the necessary wires for the input, control, and output signals. Notice how elegant it is to query all actors to retrieve their values in parallel using <code class="language-plaintext highlighter-rouge">allActors.parTraverse(_ ?[Boolean] GetValue)</code>.</p>

<p>We then create the demultiplexer, which routes the input signal based on the control signals. For instance, when we set <code class="language-plaintext highlighter-rouge">in1</code> to <code class="language-plaintext highlighter-rouge">true</code>, we expect <code class="language-plaintext highlighter-rouge">out4</code> to be <code class="language-plaintext highlighter-rouge">true</code>. Similarly, we can change the control signals <code class="language-plaintext highlighter-rouge">c1</code> and <code class="language-plaintext highlighter-rouge">c2</code> and observe the expected outputs. This dynamic manipulation and observation of the circuit’s state showcase how state changes propagate through the circuit and how the outputs change accordingly.</p>

<p>By printing the truth table, the program shows the state of all wires at each step, demonstrating the robustness and efficiency of our logic circuit simulator built with Cats-Actors. This powerful approach allows us to dynamically create and modify our circuit, demonstrating the harmony between functional programming and the actor model in Cats-Actors.</p>

<h2 id="conclusion">Conclusion</h2>
<p>In this tutorial, we’ve explored the synergy between the actor model and functional programming by building a robust logic circuit simulator using Cats-Actors. We’ve created basic components like wires and logic gates, and combined them into more complex structures such as half adders, full adders, and demultiplexers. Through this process, we’ve demonstrated how Cats-Actors enables us to build dynamic, reliable systems with ease.</p>

<p>The power of Cats-Actors lies in its ability to manage concurrency and state in a highly predictable and maintainable manner. By leveraging functional programming principles, we’ve shown how to create a system that is both scalable and fault-tolerant. This approach simplifies the development of complex, evolving systems, making it an excellent choice for various applications.</p>

<p>If you’re interested in learning more or contributing to the project, check out the <a href="https://github.com/suprnation/cats-actors">Cats-Actors GitHub repository</a>. This repository contains comprehensive documentation and additional examples to help you get started with building your own actor-based systems.</p>

<p>As always, stay safe, keep hacking!</p>]]></content><author><name>Mark Galea</name></author><category term="cats-actors" /><summary type="html"><![CDATA[Functional programming and the actor model are two powerful paradigms in modern software development. They might seem like they’re in opposition, but in reality, they complement each other beautifully. Scala, as a versatile language, allows multiple paradigms to coexist, and Cats-Actors, a functional programming-based actor system, exemplifies this harmony. Cats-Actors is a reimagining of the actor paradigm model married with the functional paradigm.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://cloudmark.me/images/cats-actors/logo-small.png" /><media:content medium="image" url="https://cloudmark.me/images/cats-actors/logo-small.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>