<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="/rss.xsl" type="text/xsl"?>
  <rss version="2.0"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:media="http://search.yahoo.com/mrss/" 
  xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Koray Ulusan | Writings</title>
    <link>https://korayulusan.github.io</link>
    <description>Thoughts, Research &amp; Engineering | 7 Posts</description>
    <language>en-us</language>
    <lastBuildDate>Thu, 22 Oct 2026 20:41:20 GMT</lastBuildDate>
    <atom:link href="https://korayulusan.github.io/rss.xml" rel="self" type="application/rss+xml"/>
    
  <item>
    <title>Building Frequency Altered Feedback in the Browser</title>
    <link>https://korayulusan.github.io/blog/frequency-altered-feedback-browser-psola-ola-speech-therapy/</link>
    <guid isPermaLink="true">https://korayulusan.github.io/blog/frequency-altered-feedback-browser-psola-ola-speech-therapy/</guid>
    <pubDate>Mon, 25 May 2026 05:48:47 GMT</pubDate>
    <description>How I implemented real-time FAF pitch shifting in the browser for speech therapy: the wrong algorithm first, why PSOLA is the right one, the latency math, jitter measurement, and the bugs I hit along the way.</description>
    <media:content url="https://korayulusan.github.io/og/blog/building-frequency-altered-feedback-in-the-browser-landscape-thumbnail.jpeg" medium="image" />
    <enclosure url="https://korayulusan.github.io/og/blog/building-frequency-altered-feedback-in-the-browser-landscape-thumbnail.jpeg" length="0" type="image/jpeg" />
    <content:encoded><![CDATA[<div style="background-color: #1c1c1d; color: #e8e8e8; font-family: sans-serif;"> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">TL;DR</h3> <p>I extended <a href="https://korayulusan.github.io/delayed-auditory-feedback-online/" style="color:#70a5fd">DAF Online</a> with real-time <strong>Frequency Altered Feedback (FAF)</strong>. FAF shifts the pitch of your voice in your headphones while you speak, which can reduce stuttering through the choral effect. It took me three algorithms to get it right, plus careful latency bookkeeping and a jitter benchmark that works around a limitation of <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">AudioWorkletGlobalScope</code>. This post goes through all of it.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <img alt="The DAF Online interface featuring a clean, minimalist design with the addition of FAF sliders." height="2398" src="https://korayulusan.github.io/static/faf-browser-psola-ola-pitch-shifting.Bc12Lu1Z_ZIRiXO.webp" width="2520" class="w-full block border-2 border-border h-full m-0 object-cover" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 leading-relaxed max-w-[90%] mt-4 mx-auto text-center" style="text-align:center"> <span class="font-bold text-muted">Figure 1:</span> The DAF Online interface featuring a clean, minimalist design with the addition of FAF sliders. </figcaption> </figure>  <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">What is Frequency Altered Feedback?</h2> <p><strong>Delayed Auditory Feedback (DAF)</strong> slows speech by creating a timing mismatch between articulation and perception. <a href="https://korayulusan.github.io/blog/i-built-delayed-auditory-feedback-online-tool/" style="color:#70a5fd">I covered DAF in the previous post.</a></p> <p><strong>Frequency Altered Feedback (FAF)</strong> works differently. It shifts the pitch of your voice in your headphones by a ratio <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r$</code>, where</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$r = 2^{s/12}$$</pre> <p>and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$s$</code> is the semitone shift. A shift of 3–6 semitones is enough for the <strong>choral effect</strong>: it sounds like someone is speaking along with you, and many people who stutter are more fluent when speaking in unison with someone else.</p> <p>The two are thought to work through different mechanisms: DAF mainly disrupts auditory-motor timing, while FAF mainly mimics choral speech. Clinical devices like SpeechEasy combine both, which is why DAF Online now supports them together.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Clinical semitone ranges</h3> <table style="margin-top:1em;border-collapse:collapse;width:100%"><thead><tr><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Goal</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Range</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Mechanism</th></tr></thead><tbody><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>Stuttering therapy</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$3$</code>-<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$6$</code> semitones</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Choral effect. ~35% fluency improvement at 3 st, 65–70% at 6 st. Below ~2 st too subtle; above ~6 st diminishing returns and unnatural quality.</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>Pitch-Shift Reflex (PSR) research</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$50$</code>-<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$200$</code> cents (<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$0.5$</code>-<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$2$</code> st)</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Small enough that the brain reads the shift as accidental pitch drift, triggering an involuntary compensatory counter-shift within 50–150 ms. Larger shifts are interpreted as an external error and no reflex fires.</td></tr></tbody></table> <p>The app’s ±300-cent range mode is there for PSR experiments.</p>   <span class="font-black block mb-2 text-[10px] text-accent tracking-[0.2em] uppercase">Key Takeaway</span>  <p>FAF and DAF work through different mechanisms. That’s why clinical hardware offers both, and why the tool lets you combine them or use either alone.</p>   <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">First attempt: WSOLA</h2> <p>My first version used WSOLA (Waveform Similarity Overlap-Add), which moves its input read head at a speed proportional to <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r$</code>:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">._inR </span><span style="color:#F97583">+=</span><span style="color:#79B8FF"> H</span><span style="color:#F97583"> *</span><span style="color:#E1E4E8"> r;</span></span></code></pre> <p>For <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r &gt; 1$</code> (pitch up), the read head runs ahead of the incoming audio and the buffer drains faster than it fills. For <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r &lt; 1$</code>, it falls behind. Either way, <strong>pitch and delay are coupled</strong>: <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$+8$</code> semitones made the DAF delay audibly shorter and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$-8$</code> made it longer. That doesn’t work when the delay is the whole point.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Fixed-anchor OLA</h2> <p>To fix this, I got rid of the moving read head. On every synthesis hop, the analysis position sits at a fixed offset behind the write head:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\text{anchor} = w_{in} - L$$</pre> <p>where <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$w_{in}$</code> is the input write head and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$L$</code> is the lookback depth. The pitch shift happens by resampling <em>inside</em> each grain: <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G \cdot r$</code> input samples are linearly interpolated onto <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G$</code> output samples.</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\text{srcPos}(i) = \text{anchor} + \frac{i}{G - 1} \cdot G \cdot r, \quad i \in [0, G-1]$$</pre> <ul> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r &gt; 1:\quad$</code> <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G \cdot r &gt; G$</code>, so more input is squeezed into <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G$</code> outputs → higher pitch</li> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r = 1:\quad$</code> <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G \cdot r = G$</code>, no change</li> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r &lt; 1:\quad$</code> <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G \cdot r &lt; G$</code>, so less input is stretched over <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G$</code> outputs → lower pitch</li> </ul> <p>Since the anchor doesn’t move relative to the write head, changing <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r$</code> no longer changes the delay.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Choosing <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$R_{max}$</code> and the lookback depth</h3> <p>The read span <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G \cdot r$</code> grows with <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r$</code>. At the maximum shift (<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r = R_{max} = 2.0$</code>, +12 semitones), a grain reads <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$512$</code> input samples, and all of them have to be in the ring buffer already:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$L = \lceil G \cdot R_{max} \rceil + 2 = \lceil 256 \times 2.0 \rceil + 2 = 514 \text{ samples} \approx 10.7 \text{ ms at 48 kHz}$$</pre> <p>The extra 2 samples make sure the interpolation never reads past the write head at exactly <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r = R_{max}$</code>. With anchor at <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$w_{in} - 514$</code>, the maximum source position is:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\text{srcPos}_{max} = (w_{in} - 514) + 256 \times 2.0 = w_{in} - 2$$</pre> <p>which leaves two samples of margin. This is the opposite of the old design. Before, the lookback depended on the <em>smallest</em> ratio (<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$R_{min}$</code>), because that decided how far back the read head could fall. Now it depends on the <em>largest</em> ratio (<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$R_{max}$</code>), because that decides how wide the read span gets.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Amplitude</h3> <p>With a fixed grain size <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G = 256$</code> and a fixed hop <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$H = 128$</code> (50% overlap), the Hann windows add up to about 1 for any <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r$</code>, so the grains stay at gain 1.0.</p> <p>The PSOLA processor below is different. Its hop <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\lfloor T_0 / r \rfloor$</code> depends on <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$T_0$</code> and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r$</code>, so the window sum changes with <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$r$</code> and needs a <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$1/r$</code> correction to keep the volume steady.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Why I switched to PSOLA</h2> <p>Fixed-anchor OLA solved the delay problem and is cheap to run. But its <strong>grains don’t line up with the pitch periods of the voice</strong>.</p> <p>A 256-sample grain of a 150 Hz voice at 48 kHz covers 0.8 pitch periods, and the next grain starts somewhere random in the next cycle. The Hann window softens the jump but can’t remove it, and you hear it as a metallic flutter on long vowels once the shift goes past ±2 semitones.</p> <p>Long vowels at 3–6 semitones are exactly what stuttering therapy needs, so this mattered.</p> <p><strong>TD-PSOLA</strong> (Time-Domain Pitch Synchronous Overlap-Add) lines the grains up with the voice’s own pitch periods. Each grain is <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$2T_0$</code> samples long and centered on a pitch mark (a glottal closure instant). The synthesis hop is <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$T_0 / r$</code>, and that’s what changes the pitch you hear. Since neighboring grains start at the same point in their pitch cycles, they add up cleanly and the output sounds smooth.</p> <p><strong>FD-PSOLA</strong> (Frequency-Domain PSOLA) takes an FFT of each grain, changes the spectrum and transforms it back. It sounds better at large shifts, but it costs more and the FFT window adds latency, which rules it out for real-time FAF in the browser.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">PSOLA implementation</h2> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">YIN pitch detection</h3> <p>YIN (<a href="https://www.semanticscholar.org/paper/YIN%2C-a-fundamental-frequency-estimator-for-speech-Cheveign%C3%A9-Kawahara/4581aa7dec34a64c826d50b3dc0826602c197826" style="color:#70a5fd">de Cheveigné &amp; Kawahara, 2002</a>) estimates <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$T_0$</code> with the cumulative mean normalized difference function. The raw difference function is:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$d(\tau) = \sum_{j=0}^{W-1} \left( x[j] - x[j - \tau] \right)^2$$</pre> <p>Normalized by the running cumulative mean:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$d'(\tau) = \frac{d(\tau) \cdot \tau}{\sum_{k=1}^{\tau} d(k)}$$</pre> <p><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$d'(\tau)$</code> stays near 1.0 for aperiodic signals and drops below a threshold (0.15 here) at the true period. Keeping a running sum makes the normalization <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$O(1)$</code> per <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\tau$</code>. I rerun it every 4 grains (~20 ms), since <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$T_0$</code> doesn’t change faster than that in normal speech, and smooth the estimate with a first-order IIR filter:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\hat{T}_0 \leftarrow 0.85 \cdot \hat{T}_0 + 0.15 \cdot T_0^{raw}$$</pre> <p>This stops the grain size from jumping between voiced segments.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Pitch mark detection</h3> <p>With <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$T_0$</code> known, the processor needs a pitch mark, the sample to center the grain on. It searches near the analysis anchor for a <strong>negative-to-positive zero crossing</strong>. The direction matters. My first version just looked for the smallest <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$|$</code>sample<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$|$</code>, which can land on an upward crossing for one grain and a downward one for the next, and that effectively halves the pitch you hear. If there’s no upward crossing in the search window (it happens when the signal is locally flat), it falls back to the smallest <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$|$</code>sample<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$|$</code>.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Unvoiced fallback</h3> <p>Fricatives, plosive releases and silence have no <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$T_0$</code>. YIN returns <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">_voiced = false</code>, and the processor switches to a <strong>128-sample passthrough</strong>: it copies the input straight to the output, with a short crossfade when switching between voiced and unvoiced. There’s no pitch to shift there anyway, and running PSOLA on an <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">/s/</code> only makes artifacts. A plain copy also costs almost nothing, unlike a Hann-windowed OLA fallback.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">PSOLA latency and the voice type selector</h3> <p>The lookback has to cover <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$T_{max}$</code> samples, one period at the lowest expected pitch, so that a grain centered on a pitch mark always has its full <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$2T_0$</code> window available:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$T_{max} = \left\lfloor \frac{f_s}{f_{floor}} \right\rfloor, \quad L_{PSOLA} = \frac{T_{max}}{f_s} \times 1000 \text{ ms}$$</pre> <p><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">pitchFloor</code> is passed in <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">processorOptions</code> when the node is created, since it’s a setting that can’t change later through an <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">AudioParam</code>:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">new</span><span style="color:#B392F0"> AudioWorkletNode</span><span style="color:#E1E4E8">(ctx, </span><span style="color:#9ECBFF">'pitch-shifter-psola'</span><span style="color:#E1E4E8">, {</span></span>
<span class="line"><span style="color:#E1E4E8">  processorOptions: { pitchFloor: </span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">._pitchFloor },</span></span>
<span class="line"><span style="color:#E1E4E8">});</span></span></code></pre> <p>The voice type selector adjusts this value:</p> <table style="margin-top:1em;border-collapse:collapse;width:100%"><thead><tr><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Voice type</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$f_{floor}$</code></th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$T_{max}$</code> @ 48 kHz</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$L_{PSOLA}$</code></th></tr></thead><tbody><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Deep</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">80 Hz</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">600 samples</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">≈ 12.5 ms</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Average</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">120 Hz</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">400 samples</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">≈ 8.3 ms</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">High-pitched</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">150 Hz</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">320 samples</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">≈ 6.7 ms</td></tr></tbody></table> <p>So picking the right voice type also sets the algorithm’s minimum latency.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Loading both processors in one blob</h2> <p>The app has both OLA and PSOLA. Each processor is a self-contained IIFE string, so I concatenate them into one blob and load it with a single <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">addModule()</code> call. No extra Vite config, no files in <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">public/</code>:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">const</span><span style="color:#79B8FF"> blob</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Blob</span><span style="color:#E1E4E8">([</span><span style="color:#79B8FF">COMBINED_CODE</span><span style="color:#E1E4E8">], { type: </span><span style="color:#9ECBFF">'application/javascript'</span><span style="color:#E1E4E8"> });</span></span>
<span class="line"><span style="color:#F97583">await</span><span style="color:#E1E4E8"> ctx.audioWorklet.</span><span style="color:#B392F0">addModule</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">URL</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">createObjectURL</span><span style="color:#E1E4E8">(blob));</span></span></code></pre> <p>The Hann table (1024 floats, 4 KB) is created once at module scope and shared by all nodes.</p> <p>Switching between OLA and PSOLA means rebuilding the nodes, because <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">processorOptions.pitchFloor</code> can only be set at creation. So mode switches skip the fast path that otherwise just updates the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">pitchRatio</code> AudioParams when the number of voices stays the same.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Several shifted voices at once</h2> <p>The app can play <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$N$</code> pitch-shifted copies at the same time. The graph looks like this:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\text{source} \rightarrow \left\{ \begin{array}{c} \text{fafNode}_1 \\ \vdots \\ \text{fafNode}_N \end{array} \right\} \rightarrow \text{sumGain}\!\left(\tfrac{1}{N}\right) \rightarrow \text{delayNode} \rightarrow \text{out}$$</pre> <p>The <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$1/N$</code> gain keeps the volume the same as <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$N$</code> grows. Parallel worklet nodes don’t add up their latency, since they all run in the same 128-sample render pass.</p> <p>PSOLA nodes apply their own <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$1/r$</code> correction, as explained above, and OLA nodes run at gain 1. The <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$1/N$</code> gain works on top of either.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">The effective delay display</h2> <p>The total delay you hear uses the same equation as DAF:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$k_{eff} = k_{user} + k_{sys}$$</pre> <p>where <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k_{user}$</code> is the slider value and</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$k_{sys} = k_{floor} + k_{FAF}$$</pre> <p>with <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k_{floor}$</code> = <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">baseLatency</code> + <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">outputLatency</code> from the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">AudioContext</code>, plus the microphone’s <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">latency</code> from <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">MediaStreamTrack.getSettings()</code> where the browser reports it, and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k_{FAF}$</code> the algorithmic latency of whichever FAF mode is active. The display updates whenever one of these changes: you move the slider, toggle FAF, start a session, resume the graph or change the voice type.</p> <p>Chrome reports <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">outputLatency = 0</code> right after the context is created and only fills in the real value later. Calling <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">measureLatencyFloor</code> again after 200 ms picks it up without running the full benchmark.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Measuring jitter</h2> <p>Measuring jitter inside an <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">AudioWorklet</code> turned out to be tricky.</p> <p>My first idea was to time the gaps between <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">process()</code> calls with <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">currentTime</code>. That always gives a standard deviation of 0, because <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">currentTime</code> is the <em>audio clock</em>. The spec says it advances by exactly <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$128 / f_s$</code> seconds per quantum, so it shows when quanta were supposed to run, not when they did.</p> <p><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">performance.now()</code> isn’t available in <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">AudioWorkletGlobalScope</code>. <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">Date.now()</code> is, but it only has 1 ms resolution. At 48 kHz a quantum is 2.67 ms, so two quanta can fall on the same millisecond and give a 0 ms gap, which shows up as fake spikes. The mean of <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">Date.now()</code> intervals is right, but their standard deviation is meaningless.</p> <p>What worked was measuring <strong>drift from the expected time</strong> instead of intervals. At the first quantum, I record both <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">currentFrame</code> (an exact sample count) and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">Date.now()</code> (the coarse wall clock):</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\text{drift}[n] = t_{wall}[n] - \left( t_0 + \frac{f[n] - f_0}{f_s} \times 1000 \right)$$</pre> <p>where <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$f[n]$</code> is <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">currentFrame</code> at quantum <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n$</code>, and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$f_0$</code> and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$t_0$</code> are the values from the first quantum. <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">currentFrame</code> counts exact samples, so the expected time has no rounding error. Even with 1 ms resolution, the drift is useful: if the CPU stalls for 8 ms, the drift jumps by about 8 ms. I report the standard deviation of the drift as the jitter.</p>   <span class="flex items-center gap-3 font-bold text-heading/80 text-sm tracking-tight"> <span class="text-accent">◈</span> Why drift and not intervals? </span> <span class="transition-transform duration-300 group-open:rotate-180 text-muted">↓</span>   <p>An interval is the difference of two rounded timestamps, so both ends add rounding noise. Drift compares one rounded timestamp with an exact prediction from <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">currentFrame</code>, so only one end does. That halves the variance of the rounding noise compared to raw intervals.</p>   <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Bugs I ran into</h2> <p><strong><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">onStateChange</code> null dereference.</strong> The original listener:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">._ctx?.</span><span style="color:#B392F0">addEventListener</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">'statechange'</span><span style="color:#E1E4E8">, () </span><span style="color:#F97583">=&gt;</span><span style="color:#B392F0"> cb</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">._ctx</span><span style="color:#F97583">!</span><span style="color:#E1E4E8">.state));</span></span></code></pre> <p>Closing the context sets <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">this._ctx = null</code>, and then the context fires one last <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">statechange</code> event with state <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">"closed"</code>. The <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">!</code> then dereferences null and throws. The fix is to read the state from the event target instead of the field:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">._ctx?.</span><span style="color:#B392F0">addEventListener</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">'statechange'</span><span style="color:#E1E4E8">, (</span><span style="color:#FFAB70">e</span><span style="color:#E1E4E8">) </span><span style="color:#F97583">=&gt;</span></span>
<span class="line"><span style="color:#B392F0">  cb</span><span style="color:#E1E4E8">((e.target </span><span style="color:#F97583">as</span><span style="color:#B392F0"> AudioContext</span><span style="color:#E1E4E8">).state)</span></span>
<span class="line"><span style="color:#E1E4E8">);</span></span></code></pre> <p><strong><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">this._graph!</code> after <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">await</code> in teardown/rebuild chain.</strong></p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">._graph.</span><span style="color:#B392F0">setFAFNodes</span><span style="color:#E1E4E8">([])</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">then</span><span style="color:#E1E4E8">(() </span><span style="color:#F97583">=&gt;</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">._graph</span><span style="color:#F97583">!</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">setFAFNodes</span><span style="color:#E1E4E8">(semitones)) </span><span style="color:#6A737D">// throws if DAF stopped mid-await</span></span></code></pre> <p>If the user stops DAF between the teardown and the rebuild, <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">this._graph</code> is null and the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">!</code> throws. Using <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">this._graph?.setFAFNodes(semitones)</code> instead just does nothing when the session has ended.</p> <p><strong><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">activateModeBtn</code> called before declaration.</strong> Chrome hoists block-scoped function declarations within a block; Firefox and Safari do not (ES2015 strict mode). The setup call to <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">activateModeBtn('faf-type', 'single')</code> preceded the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">function</code> declaration by 10 lines within the same <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">DOMContentLoaded</code> callback. This works on Chrome but throws a <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">TypeError</code> on Firefox. Fixed by reordering the declaration above the call.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">OLA or PSOLA?</h2> <table style="margin-top:1em;border-collapse:collapse;width:100%"><thead><tr><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"></th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">OLA (Standard)</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">PSOLA (High-Fidelity, Default)</th></tr></thead><tbody><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Latency @ 120 Hz floor</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">≈ 10.7 ms (fixed)</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">≈ 8.3 ms</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Quality at ±4 st</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Audible flutter on vowels</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Phase-coherent, natural</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Requires voice type config</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">No</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Yes</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Computational cost</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Low</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Low + YIN every ~20 ms</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Unvoiced handling</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Direct passthrough</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Direct passthrough</td></tr></tbody></table> <p>High-Fidelity (PSOLA) is the default, and it’s what I’d use for therapy. OLA used to have lower latency, but with a 120 Hz floor PSOLA is now slightly faster. Standard (OLA) still makes sense if you want a fixed latency without choosing a voice type, or if you only shift by 2 semitones or less, where the flutter is hard to hear.</p> <p>You can try both modes yourself at <a href="https://korayulusan.github.io/delayed-auditory-feedback-online/" style="color:#70a5fd">DAF Online</a>.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">References</h2> <ul> <li>Natke, U., et al. (2001). <a href="https://www.researchgate.net/publication/222671766_Fluency_fundamental_frequency_and_speech_rate_under_frequency-shifted_auditory_feedback_in_stuttering_and_nonstuttering_persons" style="color:#70a5fd">Fluency, fundamental frequency, and speech rate under frequency-shifted auditory feedback in stuttering and nonstuttering persons.</a> Journal of the Acoustical Society of America.</li> <li>Kalinowski, J., et al. (1996). <a href="https://pubs.asha.org/doi/abs/10.1044/jshr.3902.396" style="color:#70a5fd">Effect of alterations in auditory feedback and speech rate on stuttering frequency.</a> Journal of Speech and Hearing Research, 39, 396–407.</li> </ul>  <p class="mt-8 text-muted/80"> Thanks for reading! If you have questions, feedback, or want to discuss a project, feel free to drop me an <a style="color:#70a5fd"><span>email</span></a> or message. </p> 
      <div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); text-align: center; font-family: 'JetBrains Mono', monospace; color: #9ca3af;">
        <span style="color: #ffb86c;">◆</span> 
        Originally published at 
        <a href="https://korayulusan.github.io/blog/frequency-altered-feedback-browser-psola-ola-speech-therapy/" style="color: #ffb86c; text-decoration: none; border-bottom: 1px solid #ffb86c;">korayulusan.github.io</a>
      </div>
    </div>]]></content:encoded>
  </item>

  <item>
    <title>The 1000th Sheet of A4 Paper</title>
    <link>https://korayulusan.github.io/blog/the-1000th-sheet-of-a4-paper/</link>
    <guid isPermaLink="true">https://korayulusan.github.io/blog/the-1000th-sheet-of-a4-paper/</guid>
    <pubDate>Fri, 22 May 2026 05:54:42 GMT</pubDate>
    <description>After 1000 sheets of handwritten university notes, what I&apos;ve learned about A4 paper: weight, whiteness, smoothness and opacity, from a consumer&apos;s perspective.</description>
    <media:content url="https://korayulusan.github.io/og/blog/the-1000th-sheet-of-a4-paper-landscape-thumbnail.jpeg" medium="image" />
    <enclosure url="https://korayulusan.github.io/og/blog/the-1000th-sheet-of-a4-paper-landscape-thumbnail.jpeg" length="0" type="image/jpeg" />
    <content:encoded><![CDATA[<div style="background-color: #1c1c1d; color: #e8e8e8; font-family: sans-serif;"> <p>Today marks the 1000th sheet of A4 paper I’ve used since I began university back in 2020.<sup class="footnote-ref"><a href="#fn-1" style="color:#70a5fd">1</a></sup> My studying technique is writing what I’ve learned using pen and paper. All the theoretical knowledge, math, and most stuff that isn’t code belong on paper. Typing these ideas is less memorable than writing them by hand. Flashcards, though, belong in Anki.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose sm:w-[50%]">   <p></p>    <figcaption class="mx-auto leading-relaxed max-w-[90%] mt-4 text-center text-muted/80 text-sm" style="text-align:center"> <span class="font-bold text-muted">Figure 1:</span> A magazine file of my handwritten university notes. </figcaption> </figure>  <p>I was close to running out of paper, so I bought another 500-sheet stack. When buying paper, you’ll find there are a lot of options if you look closely. I want to write briefly about A4 paper types for writing with a pen from a consumer perspective. Quality Class A is really nice to write on. Quality Class C is okay at the end of the day. Since I don’t use that much paper, I think using Class A would be a good choice to write on. Here are the details:</p> <ul> <li><strong>Paper Weight (GSM):</strong> <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$80~\text{g/m}^2$</code> is your standard copy paper, while <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$90~\text{g/m}^2$</code> is heavier and feels nicer. <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$80~\text{g/m}^2$</code> works fine.</li> <li><strong>Whiteness (CIE):</strong> Higher CIE means brighter paper. I prefer around 170 CIE for better contrast. When writing with a pen, I really like 170 CIE. 145 CIE is your average white paper, and when you go down to 100 CIE, it’s noticeably duller. I thought about including a comparison image here, but digital screens don’t do it justice. <br /> It is measured via a spectrophotometer that shines light on the paper.</li> <li><strong>Smoothness:</strong> Well, you guessed it right—it’s how smooth it is. The smoother the paper, the more time it can take to absorb ink, which might lead to smudging if you’re not careful. 220 ml/min is good for ballpoint pens, but 170 ml/min feels nicer to touch.<br /> It’s measured via the Bendtsen method, where a ring is pressed against the paper and the air volume passing between the ring and paper is measured.</li> <li><strong>Opacity (Ghosting):</strong> Higher opacity means less ink bleed-through. 93% is good for single-sided writing, while 95% opacity is good for double-sided writing. Usually, this isn’t a big issue as I mostly write using a pencil.</li> <li><strong>Glossy vs. Matte:</strong> For writing, matte is usually better, and glossy is more for printing photos.</li> </ul> <p>If you want to dig deeper, there is literature about its <a href="https://openlibrary.org/isbn/9780393239614" style="color:#70a5fd">history</a>, <a href="https://openlibrary.org/isbn/9780969462859" style="color:#70a5fd">manufacturing</a>, <a href="https://openlibrary.org/isbn/9783527331840" style="color:#70a5fd">measurement</a>, and more. But it’s not my expertise.</p>  <h2 class="pb-0 font-semibold mb-4 text-heading text-sm tracking-widest uppercase" style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif"> Footnotes </h2> <ol class="pl-6 space-y-4 text-body-text/90 text-sm"> <li class="footnote-item" style="list-style-type:decimal !important"><span>It's probably more than that; I use the uni's printers, some copy shops, and other A4 stacks that are not in my home.</span><a href="#fnref-1" class="hover:underline footnote-back ml-2 no-underline text-accent/90 text-xs" title="Back to text" style="color:#70a5fd">↩</a></li> </ol>   <p class="text-muted/80 mt-8"> Thanks for reading! If you have questions, feedback, or want to discuss a project, feel free to drop me an <a style="color:#70a5fd"><span>email</span></a> or message. </p> 
      <div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); text-align: center; font-family: 'JetBrains Mono', monospace; color: #9ca3af;">
        <span style="color: #ffb86c;">◆</span> 
        Originally published at 
        <a href="https://korayulusan.github.io/blog/the-1000th-sheet-of-a4-paper/" style="color: #ffb86c; text-decoration: none; border-bottom: 1px solid #ffb86c;">korayulusan.github.io</a>
      </div>
    </div>]]></content:encoded>
  </item>

  <item>
    <title>The Tech Stack Behind This Site</title>
    <link>https://korayulusan.github.io/blog/the-tech-stack-behind-this-site/</link>
    <guid isPermaLink="true">https://korayulusan.github.io/blog/the-tech-stack-behind-this-site/</guid>
    <pubDate>Wed, 22 Apr 2026 05:54:40 GMT</pubDate>
    <description>Technologies and tools I used to build this website.</description>
    <media:content url="https://korayulusan.github.io/og/blog/the-tech-stack-behind-this-site-landscape-thumbnail.jpeg" medium="image" />
    <enclosure url="https://korayulusan.github.io/og/blog/the-tech-stack-behind-this-site-landscape-thumbnail.jpeg" length="0" type="image/jpeg" />
    <content:encoded><![CDATA[<div style="background-color: #1c1c1d; color: #e8e8e8; font-family: sans-serif;"> <p>I built this website in April 2026 using <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">Astro 6</code>, <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">Tailwind CSS 4</code> and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">MDX</code>. It builds with <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">Vite 7</code>, and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">Terser</code> and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">astro-compress</code> shrink the output. <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\LaTeX$</code> is rendered with <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">remark-math</code> and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">rehype-katex</code>. There’s also an <a href="https://korayulusan.github.io/rss.xml" style="color:#70a5fd">RSS feed</a>, with an <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">xsl</code> stylesheet so it looks nice in the browser.</p> <p>In late April, I added <a href="https://korayulusan.github.io/photos/" style="color:#70a5fd">/photos</a> and some CSS changes, plus a thumbnail renderer using the good old <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">Canvas API</code> for OpenGraph images and JSON-LD. That’s what the “<em>share as image</em>” button on posts uses: it draws a thumbnail with the post title on the fly. /photos has <a href="https://korayulusan.github.io/photos/photos-rss.xml" style="color:#70a5fd">its own RSS feed</a> too.</p> <p>A <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">make</code> file runs everything from building the <em>content collections</em> to minifying and deploying to <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">GitHub Pages</code>, using <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">exiftool</code> and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">gh</code> along the way, plus a lot of <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">awk</code>, <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">xargs</code>, <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">find</code> and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">grep</code>. I <a href="https://github.com/KorayUlusan/korayulusan.github.io" style="color:#70a5fd">push the built site as one compressed archive</a> instead of loose files, so the repo itself isn’t a ready-made copy of the site.</p> <p>I didn’t want to start from <em>al-folio</em> or a similar template, so I built it from scratch. The first version took three days and the second another 2 to 3. Fixing the small details took a few more, but now I know how every part works, and I’m happy with it. I hope you like it, too!</p>  <p class="mt-8 text-muted/80"> Thanks for reading! If you have questions, feedback, or want to discuss a project, feel free to drop me an <a style="color:#70a5fd"><span>email</span></a> or message. </p> 
      <div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); text-align: center; font-family: 'JetBrains Mono', monospace; color: #9ca3af;">
        <span style="color: #ffb86c;">◆</span> 
        Originally published at 
        <a href="https://korayulusan.github.io/blog/the-tech-stack-behind-this-site/" style="color: #ffb86c; text-decoration: none; border-bottom: 1px solid #ffb86c;">korayulusan.github.io</a>
      </div>
    </div>]]></content:encoded>
  </item>

  <item>
    <title>I Built a Free DAF Tool to Replace Paid Native Apps</title>
    <link>https://korayulusan.github.io/blog/i-built-delayed-auditory-feedback-online-tool/</link>
    <guid isPermaLink="true">https://korayulusan.github.io/blog/i-built-delayed-auditory-feedback-online-tool/</guid>
    <pubDate>Mon, 20 Apr 2026 05:39:25 GMT</pubDate>
    <description>DAF devices cost hundreds of dollars, so I built a free version that runs in the browser with 6–13 ms latency. By April 2026 it had 500+ users a month.</description>
    <media:content url="https://korayulusan.github.io/og/blog/i-built-a-free-daf-tool-to-replace-paid-native-app-landscape-thumbnail.jpeg" medium="image" />
    <enclosure url="https://korayulusan.github.io/og/blog/i-built-a-free-daf-tool-to-replace-paid-native-app-landscape-thumbnail.jpeg" length="0" type="image/jpeg" />
    <content:encoded><![CDATA[<div style="background-color: #1c1c1d; color: #e8e8e8; font-family: sans-serif;"> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">TL;DR</h3> <p>I built <strong>DAF Online</strong>, a <a href="https://korayulusan.github.io/delayed-auditory-feedback-online/" style="color:#70a5fd">free, browser-based tool for speech therapy</a> for people who stutter and people with Parkinson’s. There are native apps and $1000 devices for this, but I wanted something that runs in the browser. With the <strong>Web Audio API</strong> and a very small audio graph, I got the latency down to 6–13 ms.</p> <p><strong>Update:</strong> I’ve since added Frequency Altered Feedback (FAF) to the tool. It was harder to build because it needs buffering, but it’s another option for therapy. I wrote about it <a href="https://korayulusan.github.io/blog/frequency-altered-feedback-browser-psola-ola-speech-therapy/" style="color:#70a5fd">here</a>.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">What is Delayed Auditory Feedback?</h2> <p>With Delayed Auditory Feedback (DAF), you hear your own voice played back with a short delay. That small delay has a surprisingly big effect.</p> <p>For many people who stutter, speaking while hearing a slightly delayed version of your own voice reduces stuttering, often immediately. One explanation is the <strong>choral effect</strong>: it sounds like someone is speaking along with you, and many people who stutter are more fluent when speaking in unison. Speech-language pathologists (SLPs) also use DAF with Parkinson’s patients, where the delay works like a speed limit and slows their speech down.</p> <p>So the tool is for people who stutter, people with Parkinson’s, and SLPs doing remote sessions who want patients to practice at home without installing anything.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <img alt="The DAF Online interface featuring a clean, minimalist design with a central 'Start' button and a delay slider." height="1458" src="https://korayulusan.github.io/static/delayed-auditory-feedback-online-user-interface.CZBQFSuM_1UuCwj.webp" width="1858" class="w-full block h-full m-0 object-cover border-2 border-border" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 leading-relaxed max-w-[90%] mt-4 mx-auto text-center" style="text-align:center"> <span class="font-bold text-muted">Figure 1:</span> The DAF Online interface featuring a clean, minimalist design with a central 'Start' button and a delay slider. </figcaption> </figure>  <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">What existed before (early 2025)</h2> <p>When I looked for a free DAF tool that runs in the browser, I couldn’t find one that worked.</p> <p>This is roughly what was out there:</p> <ul> <li><strong>Dedicated hardware</strong> (e.g., <a href="https://casafuturatech.com/daf-devices/" style="color:#70a5fd">Casa Futura</a>, <a href="https://www.speecheasy.com/" style="color:#70a5fd">SpeechEasy</a>): $1000–$2500+. Clinically tested, but you have to order one, wait for it and pay.</li> <li><strong>Native mobile apps (e.g., <a href="https://speechtools.co/daf-pro" style="color:#70a5fd">DAF Pro</a>)</strong>: There are a few on iOS and Android. Some have a free tier, most want a subscription. They work fine on recent phones.</li> <li><strong>Websites</strong>: The few I found either sent you to a native app, were missing features or had long delays. I couldn’t find one you could just open and use.</li> <li><strong>GitHub</strong>: There were a few DAF repos, some using the Web Audio API and some in C++ or Python. None of them were hosted anywhere, so you had to run them yourself.</li> </ul> <p>The basic implementation isn’t hard. The Web Audio API has had a <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">DelayNode</code> for years. Nobody had put one online in a usable form.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">The math</h2> <p>The output is just the input shifted in time:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$y[n] = \alpha \cdot x[n - (k_{user} + k_{sys})]$$</pre> <p>Where:</p> <ul> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$y[n]$</code>: The signal the user hears at time <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n$</code></li> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$x[n]$</code>: The user’s voice entering the microphone</li> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k_{user}$</code>: the delay you set with the slider</li> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k_{sys}$</code>: the latency your hardware and OS add on top</li> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\alpha$</code>: Gain (volume)</li> </ul> <p>So the delay you actually hear is</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$k_{eff} = k_{user} + k_{sys}$$</pre> <p><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k_{sys}$</code> is easy to forget, but it’s never zero. If it’s large, your “50 ms” delay is really 100 ms, which feels completely different and may not help at all.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Why latency matters so much</h2> <p>For DAF to be useful in therapy, the <strong>device latency</strong> should stay under <strong>15–20 ms</strong>. That’s the time your hardware and software take before your chosen delay is even added.</p> <p>If <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k_{sys}$</code> is already 50 ms and you set 50 ms, you hear a 100 ms echo. High latency also tends to come with <strong>jitter</strong>, where the delay keeps changing slightly. That makes it feel unstable, and the choral effect doesn’t kick in.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Latency by device</h3> <table style="margin-top:1em;border-collapse:collapse;width:100%"><thead><tr><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Setup</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Typical Internal Latency</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Verdict</th></tr></thead><tbody><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>Dedicated PC Drivers/Hardware</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><a href="https://soundorp.com/low-latency-audio-interface-top-10-picks/" style="color:#70a5fd">1–9 ms</a></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Excellent</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>Dedicated DAF Hardware</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><a href="https://doi.org/10.1044/2020_JSLHR-19-00419" style="color:#70a5fd">&lt; 10 ms</a></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Excellent</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>High-End PC + Chrome<sup class="footnote-ref"><a href="#fn-1" style="color:#70a5fd">1</a></sup></strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">6–10 ms</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Excellent</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>iPhone 16 + Safari<sup class="footnote-ref"><a href="#fn-2" style="color:#70a5fd">2</a></sup></strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">13 ms</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Good</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>aptX Low Latency codec (Bluetooth)</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><a href="https://en.wikipedia.org/wiki/AptX" style="color:#70a5fd">40 ms</a></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Borderline</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>AAC codec (Bluetooth)</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><a href="https://besttechradar.com/sbc-vs-aac-bluetooth-codec/" style="color:#70a5fd">100–200 ms</a></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Unusable</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>SBC codec (Bluetooth)</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><a href="https://besttechradar.com/sbc-vs-aac-bluetooth-codec/" style="color:#70a5fd">150–250 ms</a></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Unusable</td></tr></tbody></table> <p>On recent hardware my implementation gets 6–13 ms, depending on the device and browser.</p> <p>Native apps used to have the edge here, since iOS and Android give them direct access to the hardware buffer. The browser sits one layer above that, but with the right settings you get most of the way there.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Testing your own setup</h3> <p>Set the software delay to <strong>0 ms</strong>. Speak a sharp “P” or “K” sound. If you hear one sound, your latency is probably under 15 ms. If you hear it twice, like a short echo, it’s above 30 ms, and you should switch to wired headphones or a better audio driver before using it for therapy.</p>   <span class="text-[10px] uppercase block font-black mb-2 text-accent tracking-[0.2em]">Avoid Bluetooth</span>  <p>Most Bluetooth headphones don’t work for DAF. Their codecs (AAC, SBC) add 100–250 ms, more than the delay you’d set, so you can’t control what you hear. Use wired headphones.</p>   <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Keeping latency low</h2> <p>To compete with dedicated hardware, <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k_{sys}$</code> had to be as small as possible. Three things helped most.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">1. A small audio graph</h3> <p>Every node in a Web Audio graph adds some overhead, so the graph is just four nodes in a line, with no branches.</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#6A737D">// Minimal linear topology for maximum performance</span></span>
<span class="line"><span style="color:#B392F0">_connectAudioNodes</span><span style="color:#E1E4E8">() {</span></span>
<span class="line"><span style="color:#F97583">    const</span><span style="color:#79B8FF"> nodes</span><span style="color:#F97583"> =</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.audioNodes;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A737D">    // source (Mic) -&gt; delay (DAF) -&gt; gain (Vol) -&gt; destination (Output)</span></span>
<span class="line"><span style="color:#E1E4E8">    nodes.source.</span><span style="color:#B392F0">connect</span><span style="color:#E1E4E8">(nodes.delayNode);</span></span>
<span class="line"><span style="color:#E1E4E8">    nodes.delayNode.</span><span style="color:#B392F0">connect</span><span style="color:#E1E4E8">(nodes.gainNode);</span></span>
<span class="line"><span style="color:#E1E4E8">    nodes.gainNode.</span><span style="color:#B392F0">connect</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.audioContext.destination);</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">2. Asking for the smallest buffer</h3> <p>By default, browsers use the “interactive” latency mode, about a 50 ms buffer. With <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">latencyHint: 0</code>, the browser <a href="https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/AudioContext#latencyhint" style="color:#70a5fd">asks for the smallest buffer the hardware allows</a>. Using the device’s own sample rate also avoids resampling.</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#B392F0">_createAudioContext</span><span style="color:#E1E4E8">() {</span></span>
<span class="line"><span style="color:#F97583">    const</span><span style="color:#79B8FF"> contextOptions</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#6A737D">        // Request absolute minimum buffer size from hardware</span></span>
<span class="line"><span style="color:#E1E4E8">        latencyHint: </span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#E1E4E8">    };</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A737D">    // Match native hardware sample rate to bypass resampling lag</span></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.deviceSampleRate) {</span></span>
<span class="line"><span style="color:#E1E4E8">        contextOptions.sampleRate </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.deviceSampleRate;</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.audioContext </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#E1E4E8"> (window.AudioContext </span><span style="color:#F97583">||</span><span style="color:#E1E4E8"> window.webkitAudioContext)(contextOptions);</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">3. Showing the real delay</h3> <p>The tool reads <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">baseLatency</code> and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">outputLatency</code> from the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">AudioContext</code> and adds them to what’s shown, so you see the real delay, including what your device adds.</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#6A737D">// Measuring the true hardware "floor"</span></span>
<span class="line"><span style="color:#F97583">const</span><span style="color:#79B8FF"> outputMs</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> (</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.audioContext.baseLatency </span><span style="color:#F97583">+</span><span style="color:#E1E4E8"> (</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.audioContext.outputLatency </span><span style="color:#F97583">||</span><span style="color:#79B8FF"> 0</span><span style="color:#E1E4E8">)) </span><span style="color:#F97583">*</span><span style="color:#79B8FF"> 1000</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.measuredFloorMs </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> outputMs;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A737D">// UI shows both the target and the honest effective delay</span></span>
<span class="line"><span style="color:#F97583">const</span><span style="color:#79B8FF"> effective</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Math.</span><span style="color:#B392F0">round</span><span style="color:#E1E4E8">(targetDelay </span><span style="color:#F97583">+</span><span style="color:#E1E4E8"> measuredFloorMs);</span></span>
<span class="line"><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.displayLabel </span><span style="color:#F97583">=</span><span style="color:#9ECBFF"> `${</span><span style="color:#E1E4E8">targetDelay</span><span style="color:#9ECBFF">} ms (~${</span><span style="color:#E1E4E8">effective</span><span style="color:#9ECBFF">} ms effective)`</span><span style="color:#E1E4E8">;</span></span></code></pre> <p>If you see “50 ms (~56 ms effective)”, you know what’s going on. If you see “50 ms” and hear 100 ms, you’d think the tool is broken.</p> <p>The snippet only covers the output side. Microphone latency isn’t part of the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">AudioContext</code>, so the current version adds it from <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">MediaStreamTrack.getSettings().latency</code> in browsers that report it.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Frequency Altered Feedback (FAF)</h2> <p>FAF is also used in speech therapy. Instead of delaying your voice, it shifts its pitch up or down, which can also help some people speak more fluently. I built DAF first because it’s more common and its latency requirements are clearer. I’ve since added FAF too and wrote up <a href="https://korayulusan.github.io/blog/frequency-altered-feedback-browser-psola-ola-speech-therapy/" style="color:#70a5fd">how I built it</a>.</p> <p>FAF is harder because the audio has to be buffered before it can be pitch-shifted. That buffer adds latency, and past 15–20 ms the effect stops working. More on that below.</p>   <span class="flex items-center gap-3 font-bold text-heading/80 text-sm tracking-tight"> <span class="text-accent">◈</span> FAF and the cost of buffering </span> <span class="transition-transform duration-300 group-open:rotate-180 text-muted">↓</span>   <p>A delay line just holds samples and plays them back. Pitch shifting has to look at a window of the signal first, and that window adds latency before your chosen delay even starts.</p><p>At 44.1 kHz, the added latency is</p><pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$L_{ms} = \frac{N}{f_s} \cdot 1000$$</pre> <table style="margin-top:1em;border-collapse:collapse;width:100%"><thead><tr><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Buffer Size (Samples)</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Latency Added (at 44.1kHz)</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Therapeutic Verdict</th></tr></thead><tbody><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>128</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">~2.9 ms</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Fine</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>256</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">~5.8 ms</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Fine</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>512</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">~11.6 ms</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Borderline</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left"><strong>1024</strong></td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">~23.2 ms</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Already over the threshold</td></tr></tbody></table><h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Why you can’t skip the buffer</h3><p>You could process sample by sample and just play faster, like speeding up a record. That works for about half a second, until playback runs ahead of the input and you get a gap. To stay in sync with the speaker, you have to cut the audio into small grains and crossfade them (SOLA), which needs an <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">AudioWorklet</code> and a minimum window size.</p><h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Phase vocoders vs. granular synthesis</h3><p>Phase vocoders sound better. They shift pitch with FFTs and don’t sound metallic. But they need big buffers for enough frequency resolution, usually 1024 samples or more, which is already 23 ms of latency, past the limit.</p><p>Granular synthesis sounds rougher but runs on 128 or 256 samples. For therapy, a slightly robotic voice at 10 ms is more useful than a natural one at 40 ms.</p>   <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">SEO: why the page has so much text</h2> <p>“Delayed Auditory Feedback” is a very niche search term. If you <a href="https://trends.google.com/explore?q=%2Fm%2F0wpkvb1%2C%2Fm%2F070yw&amp;date=all&amp;geo=Worldwide" style="color:#70a5fd">compare it with “Stuttering” in Google Trends</a>, you can see how few people search for the tool compared with the condition.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <img alt="Delayed Auditory Feedback (Blue) vs Stuttering (Red) search interest over time according to Google Trends" height="830" src="https://korayulusan.github.io/static/delayed-auditory-feedback-google-trends-stats.BycJ2d-G_13S4eo.webp" width="1488" class="w-full block h-full m-0 object-cover" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 leading-relaxed max-w-[90%] mt-4 mx-auto text-center" style="text-align:center"> <span class="font-bold text-muted">Figure 2:</span> Delayed Auditory Feedback (Blue) vs Stuttering (Red) search interest over time according to Google Trends </figcaption> </figure> <p>Getting the tool in front of the people who need it took as long as building it.</p> <p>Most visitors already know what DAF is and search for a tool that works. A page with only a slider and a button wouldn’t rank for anything. For the first few months, the tool sat at positions 11–15, below hardware sellers and native apps, so almost nobody found it.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <img alt="Google Search Console stats since the tool's launch" height="814" src="https://korayulusan.github.io/static/delayed-auditory-feedback-search-console-stats.D8aWFvra_2vcVfO.webp" width="2238" class="w-full block h-full m-0 object-cover" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 leading-relaxed max-w-[90%] mt-4 mx-auto text-center" style="text-align:center"> <span class="font-bold text-muted">Figure 3:</span> Google Search Console stats since the tool's launch </figcaption> </figure> <p>After I added detailed, accurate text about the science and how to use it, the page reached a <strong>2.4 weighted average position</strong> for its main keywords. <strong>85% of organic traffic</strong> came from top-3 results, with a <strong>75% CTR</strong> on the main search terms (March 2026).</p> <blockquote style="border-left:4px solid rgba(255, 255, 255, 0.1);padding-left:15px;color:#9ca3af;font-style:italic;margin:10px 0"> <p>Fun fact: “DAF” is also the Dutch truck maker <a href="https://www.daf.com/" style="color:#70a5fd">DAF Trucks N.V</a>. If you search “DAF” on its own, Google assumes you want a 7.5-ton truck, not a speech aid.</p> </blockquote> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Conclusion</h2> <p>With the right settings and a small audio graph, a DAF tool in the browser can get close to native app latency on decent hardware, with nothing to install or pay for.</p> <p>It wasn’t hard to build. Speech therapy is a small market and few developers build for people who stutter or have Parkinson’s, so nobody had done it. That’s why I wanted to.</p> <p>If you want to look at the implementation or try the tool yourself:</p> <ul> <li><strong><a href="https://korayulusan.github.io/delayed-auditory-feedback-online/" style="color:#70a5fd">Try DAF Online</a></strong></li> <li><strong><a href="https://github.com/korayulusan/delayed-auditory-feedback-online" style="color:#70a5fd">Source code on GitHub</a></strong></li> </ul>  <h2 class="text-sm font-semibold mb-4 pb-0 text-heading tracking-widest uppercase" style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif"> Footnotes </h2> <ol class="text-sm pl-6 space-y-4 text-body-text/90"> <li style="list-style-type:decimal !important" class="footnote-item"><span>My implementation.</span><a href="#fnref-1" class="text-accent/90 footnote-back hover:underline ml-2 no-underline text-xs" title="Back to text" style="color:#70a5fd">↩</a></li> <li style="list-style-type:decimal !important" class="footnote-item"><span>My implementation.</span><a href="#fnref-2" class="text-accent/90 footnote-back hover:underline ml-2 no-underline text-xs" title="Back to text" style="color:#70a5fd">↩</a></li> </ol>   <p class="mt-8 text-muted/80"> Thanks for reading! If you have questions, feedback, or want to discuss a project, feel free to drop me an <a style="color:#70a5fd"><span>email</span></a> or message. </p> 
      <div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); text-align: center; font-family: 'JetBrains Mono', monospace; color: #9ca3af;">
        <span style="color: #ffb86c;">◆</span> 
        Originally published at 
        <a href="https://korayulusan.github.io/blog/i-built-delayed-auditory-feedback-online-tool/" style="color: #ffb86c; text-decoration: none; border-bottom: 1px solid #ffb86c;">korayulusan.github.io</a>
      </div>
    </div>]]></content:encoded>
  </item>

  <item>
    <title>Enhancing Facial Realism with Synthetic Data Augmentation</title>
    <link>https://korayulusan.github.io/blog/genai-synthetic-data-facial-resemblance-dreambooth-instantid/</link>
    <guid isPermaLink="true">https://korayulusan.github.io/blog/genai-synthetic-data-facial-resemblance-dreambooth-instantid/</guid>
    <pubDate>Wed, 28 May 2025 05:39:11 GMT</pubDate>
    <description>My CVPR 2025 workshop paper: classical augmentations hurt few-shot face personalization, and training DreamBooth on InstantID-generated portraits improves facial resemblance.</description>
    <media:content url="https://korayulusan.github.io/og/blog/enhancing-facial-realism-with-synthetic-data-augme-landscape-thumbnail.jpeg" medium="image" />
    <enclosure url="https://korayulusan.github.io/og/blog/enhancing-facial-realism-with-synthetic-data-augme-landscape-thumbnail.jpeg" length="0" type="image/jpeg" />
    <content:encoded><![CDATA[<div style="background-color: #1c1c1d; color: #e8e8e8; font-family: sans-serif;"> <p>This post is about my paper at the <a href="#citation" style="color:#70a5fd">CVPR 2025 Workshop on Synthetic Data for Computer Vision</a> (SynData4CV).</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">TL;DR</h3> <p>Classical augmentations like flipping and rotating distort facial identity. I used <strong>InstantID</strong> to generate synthetic portraits of the subject and trained <strong>DreamBooth</strong> on them instead. The resulting headshots resemble the person noticeably better.</p> <figure class="my-10 fig-root md:my-12 mx-auto not-prose">  <img alt="Schematic diagram showing the pipeline from real images to synthetic dataset generation using InstantID and DreamBooth." height="904" src="https://korayulusan.github.io/static/genai-synthetic-data-augmentation-pipeline.w29XHU9g_ZMEplz.webp" width="2252" class="block h-full m-0 object-cover w-full bg-white opacity-95 p-4" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 text-center leading-relaxed max-w-[90%] mt-4 mx-auto" style="text-align:center"> <span class="font-bold text-muted">Figure 1:</span> Schematic diagram showing the pipeline from real images to synthetic dataset generation using InstantID and DreamBooth. </figcaption> </figure>  <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Few-shot portraits</h2> <p>Say you have five phone photos of yourself and want a LinkedIn headshot. A personalized diffusion model like <em>DreamBooth</em> can do this, but it has to learn what you look like from those five images and then put you into scenes it has never seen you in. Keeping the face recognizable is the hard part.</p> <p>This is called few-shot personalization. Two goals pull against each other: <strong>identity retention</strong> (the output should look like you) and <strong>recontextualization</strong> (you can be put into whatever scene the prompt asks for). Training setups usually favor one over the other. In <a href="#citation" style="color:#70a5fd">“Generating Synthetic Data via Augmentations for Improved Facial Resemblance in DreamBooth and InstantID”</a>, I tried using one generative model to produce training data for another.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Why classical augmentations hurt</h2> <p>The usual way to get more training data is classical augmentation: random flips, crops, rotations and color jitter. They work well for large classification datasets. With a handful of face photos, they made things worse.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Flips and rotations</h3> <p><strong>Random Horizontal Flip</strong> looks harmless, but faces aren’t symmetric. A mole on the left cheek, a crooked smile or the side your hair is parted on all switch sides. The model sees two slightly different people and blends them into one that looks off.</p> <p><strong>Random Rotation</strong> adds black padding at the corners, and the model learns that as part of the subject. It also tilts the facial landmarks, so generated faces come out tilted too.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Color jitter</h3> <p><strong>Color Jittering</strong> changes brightness, contrast, saturation and hue. The model ties those changes to the rare token that stands for your subject, so generations come out with odd skin tones or lighting that wasn’t in any of the real photos.</p> <figure class="my-10 fig-root md:my-12 mx-auto not-prose">  <figure class="flex flex-col gap-2.5 m-0"> <img alt="Skin tone discoloration and hue jitter artifacts caused by classical color augmentations." height="1333" src="https://korayulusan.github.io/static/dreambooth-hue-jitter-discoloration-artifact.juBlnH-o_1NTxo7.webp" width="1000" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 2:</span> Skin tone discoloration and hue jitter artifacts caused by classical color augmentations. </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Rotation artifacts that always position the subject in tilted positions." height="1333" src="https://korayulusan.github.io/static/ai-portrait-rotation-artifact-padding.DJWcrjVc_2gdfAk.webp" width="1000" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 3:</span> Rotation artifacts that always position the subject in tilted positions. </figcaption> </figure>  </figure> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Background removal</h3> <p>Swapping the background with a segmentation model like <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$U^2$</code>-Net seemed like a good way to stop the background leaking into the subject. But the mask around fine hair leaves a blurry halo, and the model learns the halo as part of the person. After that, clean background changes are very hard to get.</p>   <span class="block text-[10px] uppercase font-black mb-2 text-accent tracking-[0.2em]">Key Takeaway</span>  <p>With only a few real photos, the model has nothing to tell it that an augmentation artifact isn’t part of the person, so it learns the artifacts too.</p>   <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Generating the training data with InstantID</h2> <p>Instead of distorting the real photos, we generated new photos of the person with a model that already handles faces well. InstantID takes the subject’s facial landmarks and a few reference images and produces realistic portraits in different poses, lighting and settings while keeping the face intact. Since these images come from a diffusion model, DreamBooth doesn’t have to bridge the gap between real and augmented photos.</p> <p>Fine-tuning DreamBooth on this data gave measurably better facial resemblance, and the model could still place the person in new scenes.</p> <figure class="my-10 fig-root md:my-12 mx-auto not-prose">  <img alt="Technical workflow architecture illustrating the integration of InstantID and DreamBooth for facial fidelity." height="742" src="https://korayulusan.github.io/static/instantid-dreambooth-workflow-diagram.BvKQXwyO_1t84E0.webp" width="2376" class="block h-full m-0 object-cover w-full bg-white opacity-95 p-4" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 text-center leading-relaxed max-w-[90%] mt-4 mx-auto" style="text-align:center"> <span class="font-bold text-muted">Figure 4:</span> Technical workflow architecture illustrating the integration of InstantID and DreamBooth for facial fidelity. </figcaption> </figure> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">What I’d recommend</h2> <p>If you’re building a portrait personalization pipeline, this is what worked for us.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">1. Balance real and synthetic images</h3> <p>Diversity matters most for avoiding overfitting. No single concept, like one background, one outfit or one generated style, should make up more than 25% of the training set. If synthetic images outnumber the real ones, the model starts copying InstantID’s look instead of the person’s face.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">2. Use four reference images</h3> <p>With <strong>four reference images</strong>, InstantID gave the best balance between effort and facial similarity. With fewer, the face changed between generations. More than four barely helped and meant more images to prepare.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">3. Resolution matters</h3> <p>Images of about <strong>1 megapixel</strong> match SDXL’s training resolution and looked best. Upscaling small images brings in compression artifacts, and downscaling large ones loses fine facial detail. For phone photos, a center crop to roughly 1024 × 1024 works well.</p> <figure class="my-10 fig-root md:my-12 mx-auto not-prose">  <figure class="flex flex-col gap-2.5 m-0"> <img alt="Loss in facial detail caused by bicubic downsampling." height="1000" src="https://korayulusan.github.io/static/low-resolution-bicubic-downsampling-artifacts.CjcDl4AL_ZaYVPR.webp" width="1499" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 5:</span> Loss in facial detail caused by bicubic downsampling. </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Comparison of standard upscaling versus high-fidelity ESRGAN enhancement." height="1000" src="https://korayulusan.github.io/static/esrgan-upscaling-facial-detail-comparison.BNop2tSC_eBSVq.webp" width="1500" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 6:</span> Comparison of standard upscaling versus high-fidelity ESRGAN enhancement. </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Impact of resampling on facial feature sharpness." height="1000" src="https://korayulusan.github.io/static/resolution-interpolation-resampling-comparison.sooEzftK_Z2klTYE.webp" width="1498" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 7:</span> Impact of resampling on facial feature sharpness. </figcaption> </figure>  </figure> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">4. Skip the flips, rotations, and jitter</h3> <p>Don’t use Random Horizontal Flip, Random Rotation or Color Jitter when fine-tuning on faces. They help large classification models, but not here.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Measuring resemblance with FaceDistance</h2> <p>Looking at outputs by eye is subjective, and we needed a way to rank checkpoints and see whether the synthetic data helped. So we built <strong>FaceDistance</strong>, a metric based on <strong>FaceNet</strong> embeddings.</p> <p>FaceNet maps a face to a 128-dimensional embedding, where similar faces end up close together. FaceDistance is the average cosine distance between the embedding of a generated image <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G_i$</code> and those of the reference images <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\{R_j\}$</code>:</p> <p><strong>Definition:</strong> Given batches of generated images <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$G = \{G_i\}_{i=1}^m$</code> and original reference images <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$R = \{R_j\}_{j=1}^n$</code>, the <strong>FaceDistance</strong> is defined as:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\bigl[\operatorname{FaceDistance}(G, R)\bigr]_i := \frac{1}{n} \sum_{j=1}^n \delta^{[0,2]}_{\text{cos}}\!\bigl(f(G_i),\, f(R_j)\bigr)$$</pre> <p>Here:</p> <ul> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$f$</code> is <strong>MTCNN</strong> for face detection followed by <strong>FaceNet</strong> for the embedding.</li> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\delta_{\cos}$</code> is the cosine distance, clipped to <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$[0, 2]$</code> to guard against rounding errors.</li> </ul> <p>Lower is better.</p> <p>FaceDistance is a coarse filter. It reliably catches images where the model lost the person completely, but it can’t tell a good image from a great one.</p> <p>When we had at least 8 references (<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n \geq 8$</code>), dropping the <strong>15%</strong> with the highest distance from the training set consistently gave cleaner, more recognizable results.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">User study</h2> <p>We also asked <strong>97 white-collar workers</strong> to rate the generated headshots. Both DreamBooth and InstantID often produced portraits they couldn’t tell apart from real professional photos.</p> <p>People who cared most about <strong>identity</strong> (“does this look like the person?”) tended to prefer DreamBooth. People who cared more about looks preferred InstantID’s polished, retouched style. So if the face has to match closely, use DreamBooth with generative augmentation. If a studio look matters more, InstantID on its own is enough.</p> <figure class="my-10 fig-root md:my-12 mx-auto not-prose">  <figure class="flex flex-col gap-2.5 m-0"> <img alt="DreamBooth with generative augmentation" height="2048" src="https://korayulusan.github.io/static/dreambooth-synthetic-augmentation-facial-fidelity-result.DcXJFhPF_1Krwoa.webp" width="2048" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 8:</span> DreamBooth with generative augmentation </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Generative augmentation via InstantID" height="1556" src="https://korayulusan.github.io/static/InstantID-generative-augmentation-facial-fidelity-result2.COpA5q-a_2jHS77.webp" width="1559" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 9:</span> Generative augmentation via InstantID </figcaption> </figure>  </figure> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Conclusion</h2> <p>For few-shot face personalization, several common augmentations make the results worse. Generating the extra training images with InstantID worked much better, and it gets you from a few casual photos to a usable professional portrait.</p> <p>More generally, I now see synthetic data as a way to control what a model learns, and not only as something to fall back on when real data runs out. I expect pipelines where one model prepares data for another to become more common.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Acknowledgments</h2> <p>Thanks to <strong>Benjamin Kiefer</strong> for supervising this work. He shaped its technical direction and guided me through publishing my first paper, and our weekly meetings and his detailed feedback made a big difference.</p> <p>Thanks also to <strong>Naman Deep Singh</strong> for his advice on image copyright, which helped me understand what we could and couldn’t use in the dataset.</p> <p>I am also grateful to the CVPR SynData4CV workshop reviewers for their constructive comments.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Citation</h2> <p>If you build on this work, or want the full list of references, see the paper:</p>    <span class="font-bold uppercase tracking-[0.2em] text-[10px] text-muted">APA7</span>        <p>Ulusan, K., &amp; Kiefer, B. (2025, May). Generating synthetic data via augmentations for improved facial resemblance in DreamBooth and InstantID [Paper presentation]. CVPR Workshop on Synthetic Data for Computer Vision (SynData4CV), Nashville, TN, United States. <a href="https://arxiv.org/abs/2505.03557" style="color:#70a5fd">https://arxiv.org/abs/2505.03557</a></p>        <span class="font-bold uppercase tracking-[0.2em] text-[10px] text-muted">BibTeX</span>        <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">@inproceedings</span><span style="color:#E1E4E8">{</span><span style="color:#B392F0">ulusan2025generating</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#79B8FF">  author</span><span style="color:#E1E4E8">        = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">Ulusan, Koray and Kiefer, Benjamin</span><span style="color:#9ECBFF">}</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#79B8FF">  title</span><span style="color:#E1E4E8">         = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">Generating Synthetic Data via Augmentations for</span></span>
<span class="line"><span style="color:#E1E4E8">                   Improved Facial Resemblance in {DreamBooth} and {InstantID}</span><span style="color:#9ECBFF">}</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#79B8FF">  booktitle</span><span style="color:#E1E4E8">     = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">Synthetic Data for Computer Vision Workshop at {CVPR} 2025</span><span style="color:#9ECBFF">}</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#79B8FF">  year</span><span style="color:#E1E4E8">          = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">2025</span><span style="color:#9ECBFF">}</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#79B8FF">  url</span><span style="color:#E1E4E8">           = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">https://openreview.net/forum?id=2o0RxrcV23</span><span style="color:#9ECBFF">}</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#79B8FF">  eprint</span><span style="color:#E1E4E8">        = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">2505.03557</span><span style="color:#9ECBFF">}</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#79B8FF">  archivePrefix</span><span style="color:#E1E4E8"> = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">arXiv</span><span style="color:#9ECBFF">}</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#79B8FF">  primaryClass</span><span style="color:#E1E4E8">  = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">cs.CV</span><span style="color:#9ECBFF">}</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#79B8FF">  doi</span><span style="color:#E1E4E8">           = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">10.48550/arXiv.2505.03557</span><span style="color:#9ECBFF">}</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>    <ul> <li>The full paper is available at <a href="https://arxiv.org/abs/2505.03557" style="color:#70a5fd">arXiv:2505.03557</a></li> <li>Project webpage is <a href="https://synthetic-face-augmentation.github.io/" style="color:#70a5fd">synthetic-face-augmentation.github.io</a></li> </ul>  <p class="mt-8 text-muted/80"> Thanks for reading! If you have questions, feedback, or want to discuss a project, feel free to drop me an <a style="color:#70a5fd"><span>email</span></a> or message. </p> 
      <div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); text-align: center; font-family: 'JetBrains Mono', monospace; color: #9ca3af;">
        <span style="color: #ffb86c;">◆</span> 
        Originally published at 
        <a href="https://korayulusan.github.io/blog/genai-synthetic-data-facial-resemblance-dreambooth-instantid/" style="color: #ffb86c; text-decoration: none; border-bottom: 1px solid #ffb86c;">korayulusan.github.io</a>
      </div>
    </div>]]></content:encoded>
  </item>

  <item>
    <title>Modifying TD3 with PER, N-Step Returns, and Reward Shaping</title>
    <link>https://korayulusan.github.io/blog/rl-hockey-td3-per-reward-shaping-curriculum/</link>
    <guid isPermaLink="true">https://korayulusan.github.io/blog/rl-hockey-td3-per-reward-shaping-curriculum/</guid>
    <pubDate>Tue, 25 Feb 2025 06:53:18 GMT</pubDate>
    <description>How I modified Twin Delayed DDPG with Prioritized Experience Replay, reward shaping, and multi-step learning to train an agent in a simulated air hockey environment and what broke along the way.</description>
    <media:content url="https://korayulusan.github.io/og/blog/modifying-td3-with-per-n-step-returns-and-reward-s-landscape-thumbnail.jpeg" medium="image" />
    <enclosure url="https://korayulusan.github.io/og/blog/modifying-td3-with-per-n-step-returns-and-reward-s-landscape-thumbnail.jpeg" length="0" type="image/jpeg" />
    <content:encoded><![CDATA[<div style="background-color: #1c1c1d; color: #e8e8e8; font-family: sans-serif;"> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">TL;DR</h3> <p>I added three techniques to <strong>TD3</strong>: Prioritized Experience Replay (PER), potential-based reward shaping and multi-step returns, and used it to train an agent for a simulated air hockey game. Most of the changes made it <em>worse</em>. What helped was a <strong>curriculum</strong>: training on the shooting and defending modes first, then playing full games against the opponent. The final agent wins 98.3% of games against the strong built-in opponent.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">The environment</h2> <p>Air hockey is hard for RL. Goals are rare, and before one happens there’s a long stretch of positioning that gets no reward at all. The agent has to learn to move to the puck, hit it in the right direction and switch between attack and defense, while the reward stays at zero until someone scores.</p> <p>I used <strong>HockeyEnv</strong> (a.k.a. “Laser Hockey”), a Box2D/Gymnasium simulation of a two-player air hockey game. The observation space is 18-dimensional (positions, velocities, angles of both player and puck), and the action space is a 4-dimensional continuous vector covering movement and shooting. An episode lasts up to 250 timesteps in normal mode and 80 in the shooting and defending training modes.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose w-[80%]">  <img alt="Example HockeyEnv State: A 2D environment where 2 agents compete against each other to score goals with a puck while defending their own goal." height="934" src="https://korayulusan.github.io/static/hockey-env-reinforcement-learning-simulation-environment.B1wib9Kd_Z1sruSO.webp" width="1186" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 text-center leading-relaxed max-w-[90%] mt-4 mx-auto" style="text-align:center"> <span class="font-bold text-muted">Figure 1:</span> Example HockeyEnv State: A 2D environment where 2 agents compete against each other to score goals with a puck while defending their own goal. </figcaption> </figure>  <p>Just running a good off-policy algorithm and waiting didn’t work. Early on, the agent learns to stand still and play for a draw, since that beats the random actions it starts with, and it’s hard to get it out of that.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">TD3</h2> <p>TD3 is an actor-critic algorithm. To fix DDPG’s tendency to overestimate Q-values, it keeps <em>two</em> critics and uses the smaller of their estimates in the target:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$y = r_t + \gamma \min_{k=1,2} Q_{\theta_k'}(s_{t+1},\, \pi_{\phi'}(s_{t+1}) + \epsilon), \quad \epsilon \sim \text{clip}(\mathcal{N}(0,\sigma), -c, c)$$</pre> <p>It also updates the actor less often than the critics (the “Delayed” in the name), so the critics can settle before the policy follows them. I built <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">UlusanTD3</code> on top of <a href="https://github.com/DLR-RM/stable-baselines3" style="color:#70a5fd">Stable Baselines 3</a> by extending its <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">TD3</code> class with the three techniques below. The name is just so the graders could find it; underneath it’s normal TD3.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">1. Prioritized Experience Replay</h2> <p>Normal experience replay samples uniformly from a FIFO buffer. <strong>PER</strong> [Schaul et al., 2015] samples transitions where the agent was more <em>wrong</em> (higher TD error) more often, on the idea that they teach more. A transition is sampled with probability</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$P(i) = \frac{p_i^\alpha}{\sum_k p_k^\alpha}$$</pre> <p>where <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\alpha$</code> sets how strong the prioritization is and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$p_i$</code> is the priority of transition <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$i$</code>. With two critics, I used the absolute value of their average TD error:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$p_i = \left|\frac{1}{2}(\delta_1 + \delta_2)_i\right| + \epsilon$$</pre> <p>I clip the TD errors to <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$[\epsilon, 1]$</code>. Without the upper limit, one terrible prediction early in training can dominate the buffer for the rest of the run and throw off the actor.</p> <p>Sampling high-error transitions more often biases the updates, and <strong>importance-sampling (IS) weights</strong> correct for that:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$w_i = \left(N \cdot P(i)\right)^{-\beta}, \quad \text{normalized by } \max_i w_i$$</pre> <p>The weights go into the critic loss in place of the plain MSE:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\mathcal{L}(\theta_k) = \mathbb{E}\left[w \cdot \delta_k^2\right]$$</pre> <p>Since the two critics can end up on different scales, I gave each its own optimizer instead of adding their losses:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#6A737D"># In UlusanTD3.__init__</span></span>
<span class="line"><span style="color:#F97583">if</span><span style="color:#79B8FF"> isinstance</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">self</span><span style="color:#E1E4E8">.replay_buffer, PrioritizedExperienceReplayBuffer):</span></span>
<span class="line"><span style="color:#79B8FF">    self</span><span style="color:#E1E4E8">.critic1_optimizer </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> th.optim.Adam(</span></span>
<span class="line"><span style="color:#79B8FF">        self</span><span style="color:#E1E4E8">.critic.q_networks[</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">].parameters(), </span><span style="color:#FFAB70">lr</span><span style="color:#F97583">=</span><span style="color:#E1E4E8">learning_rate</span></span>
<span class="line"><span style="color:#E1E4E8">    )</span></span>
<span class="line"><span style="color:#79B8FF">    self</span><span style="color:#E1E4E8">.critic2_optimizer </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> th.optim.Adam(</span></span>
<span class="line"><span style="color:#79B8FF">        self</span><span style="color:#E1E4E8">.critic.q_networks[</span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">].parameters(), </span><span style="color:#FFAB70">lr</span><span style="color:#F97583">=</span><span style="color:#E1E4E8">learning_rate</span></span>
<span class="line"><span style="color:#E1E4E8">    )</span></span></code></pre> <p>The PER buffer uses a <strong>SumSegmentTree</strong>, so updating a priority and sampling both take O(log N). With a million transitions in the buffer, you need that:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> _sample_indicies_proportional</span><span style="color:#E1E4E8">(self, batch_size: </span><span style="color:#79B8FF">int</span><span style="color:#E1E4E8">) -&gt; np.ndarray:</span></span>
<span class="line"><span style="color:#E1E4E8">    p_total </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> self</span><span style="color:#E1E4E8">._td_errors.sum(</span><span style="color:#FFAB70">end</span><span style="color:#F97583">=</span><span style="color:#79B8FF">self</span><span style="color:#E1E4E8">.size())</span></span>
<span class="line"><span style="color:#E1E4E8">    segment_length </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> p_total </span><span style="color:#F97583">/</span><span style="color:#E1E4E8"> batch_size</span></span>
<span class="line"><span style="color:#E1E4E8">    elem_at_segment_prefixsum </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (</span></span>
<span class="line"><span style="color:#E1E4E8">        np.arange(batch_size) </span><span style="color:#F97583">+</span><span style="color:#E1E4E8"> np.random.uniform(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">, batch_size)</span></span>
<span class="line"><span style="color:#E1E4E8">    ) </span><span style="color:#F97583">*</span><span style="color:#E1E4E8"> segment_length</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> [</span></span>
<span class="line"><span style="color:#79B8FF">        self</span><span style="color:#E1E4E8">._td_errors.find_prefixsum_idx(p)</span></span>
<span class="line"><span style="color:#F97583">        for</span><span style="color:#E1E4E8"> p </span><span style="color:#F97583">in</span><span style="color:#E1E4E8"> elem_at_segment_prefixsum</span></span>
<span class="line"><span style="color:#E1E4E8">    ]</span></span></code></pre> <p>I had to back the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">SegmentTree</code> with a NumPy array, because a Python list was too slow for that buffer size and that many updates.</p> <p>After each gradient step, the priorities get the latest TD errors:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#6A737D"># Back in the train loop</span></span>
<span class="line"><span style="color:#E1E4E8">td_errors </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (td_error1 </span><span style="color:#F97583">+</span><span style="color:#E1E4E8"> td_error2) </span><span style="color:#F97583">/</span><span style="color:#79B8FF"> 2.0</span></span>
<span class="line"><span style="color:#79B8FF">self</span><span style="color:#E1E4E8">.replay_buffer.set_priorities(</span></span>
<span class="line"><span style="color:#E1E4E8">    batch_inds,</span></span>
<span class="line"><span style="color:#E1E4E8">    td_errors.abs().squeeze().detach().cpu().numpy()</span></span>
<span class="line"><span style="color:#E1E4E8">)</span></span></code></pre> <p>In the end, PER made things <em>worse</em> in every configuration I tried. More on that below.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">2. Potential-based reward shaping</h2> <p>With sparse rewards, extra reward signals that encode what you know about the task can speed up learning. <strong>Potential-based reward shaping</strong> [Ng et al., 1999] does this without changing the optimal policy by adding</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$F(s_t, s_{t+1}) = \gamma \phi(s_{t+1}) - \phi(s_t)$$</pre> <p>Because of this form, the optimal policy stays the same and only the speed of getting there changes. The potential function <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\phi: S \to \mathbb{R}$</code> can be anything you think is useful.</p> <p>HockeyEnv already reports some sub-rewards in its <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">info</code> dict. I combined:</p> <ul> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">closeness_to_puck</code>: reward for staying near the puck</li> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">touch_puck</code>: bonus for hitting it</li> <li><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">puck_direction</code>: reward for sending it toward the opponent’s goal</li> </ul> <p>I also tried two others and dropped them. <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">centered_puck</code> added noise and slowed training, and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">game_length</code> taught the agent to step aside and let in own goals.</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> shaped_reward</span><span style="color:#E1E4E8">(rewards, infos):</span></span>
<span class="line"><span style="color:#E1E4E8">    phis </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> [</span></span>
<span class="line"><span style="color:#E1E4E8">        (info.get(</span><span style="color:#9ECBFF">"prev_potential_reward"</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">),</span></span>
<span class="line"><span style="color:#E1E4E8">         info.get(</span><span style="color:#9ECBFF">"current_potential_reward"</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">))</span></span>
<span class="line"><span style="color:#F97583">        for</span><span style="color:#E1E4E8"> info </span><span style="color:#F97583">in</span><span style="color:#E1E4E8"> infos</span></span>
<span class="line"><span style="color:#E1E4E8">    ]</span></span>
<span class="line"><span style="color:#6A737D">    # F(s, s') = gamma * phi(s') - phi(s)</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> [</span></span>
<span class="line"><span style="color:#E1E4E8">        r </span><span style="color:#F97583">+</span><span style="color:#79B8FF"> self</span><span style="color:#E1E4E8">.gamma </span><span style="color:#F97583">*</span><span style="color:#E1E4E8"> phi </span><span style="color:#F97583">-</span><span style="color:#E1E4E8"> phi_prev</span></span>
<span class="line"><span style="color:#F97583">        for</span><span style="color:#E1E4E8"> r, (phi_prev, phi) </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> zip</span><span style="color:#E1E4E8">(rewards, phis)</span></span>
<span class="line"><span style="color:#E1E4E8">    ]</span></span></code></pre> <p>HockeyEnv is fully observable, so I compute <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\phi$</code> from the state at every step without approximating anything.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">3. Multi-step returns</h2> <p>TD3 normally bootstraps one step ahead. In hockey, the shot happens many timesteps before the goal, so a one-step target can’t connect the two.</p> <p>The <strong>truncated n-step return</strong> adds up the next <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n$</code> rewards:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$R_t^{(n)} = \sum_{k=0}^{n-1} \gamma^k \cdot r_{t+k}$$</pre> <p>and substituting it into the TD3 target:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$y = R_t^{(n)} + \gamma^n \min_{k=1,2} Q_{\theta_k'}(s_{t+n},\, \pi_{\phi'}(s_{t+n}) + \epsilon)$$</pre> <p>Combined with reward shaping, the potential terms telescope and the target becomes</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$y = \sum_{k=0}^{n-1} \gamma^k r_{t+k} + \gamma^n \Phi(s_{t+n}) - \Phi(s_t) + \gamma^n \min_{k=1,2} Q_{\theta_k'}(s_{t+n},\, \pi_{\phi'}(s_{t+n}) + \epsilon)$$</pre> <p>To implement it, I keep the last <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n$</code> transitions in a small buffer before adding them to the replay buffer, and flush it early when the episode ends:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> add</span><span style="color:#E1E4E8">(self, obs, next_obs, action, reward, done, infos):</span></span>
<span class="line"><span style="color:#79B8FF">    self</span><span style="color:#E1E4E8">._reward_info_buffer.append((reward, infos))</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#79B8FF"> any</span><span style="color:#E1E4E8">(done):</span></span>
<span class="line"><span style="color:#6A737D">        # flush remaining transitions on episode end</span></span>
<span class="line"><span style="color:#F97583">        while</span><span style="color:#79B8FF"> len</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">self</span><span style="color:#E1E4E8">._reward_info_buffer) </span><span style="color:#F97583">&gt;</span><span style="color:#79B8FF"> 0</span><span style="color:#E1E4E8">:</span></span>
<span class="line"><span style="color:#79B8FF">            self</span><span style="color:#E1E4E8">._add_n_step_return(obs, next_obs, action, done, infos)</span></span>
<span class="line"><span style="color:#F97583">        return</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#79B8FF"> len</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">self</span><span style="color:#E1E4E8">._reward_info_buffer) </span><span style="color:#F97583">&lt;</span><span style="color:#79B8FF"> self</span><span style="color:#E1E4E8">.n_step_return_num:</span></span>
<span class="line"><span style="color:#F97583">        return</span><span style="color:#6A737D">  # keep buffering</span></span>
<span class="line"></span>
<span class="line"><span style="color:#79B8FF">    self</span><span style="color:#E1E4E8">._add_n_step_return(obs, next_obs, action, done, infos)</span></span></code></pre> <p>The discount in the Bellman target also becomes <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\gamma^n$</code>:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#E1E4E8">target_q_values </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (</span></span>
<span class="line"><span style="color:#E1E4E8">    replay_data.rewards</span></span>
<span class="line"><span style="color:#F97583">    +</span><span style="color:#E1E4E8"> (</span><span style="color:#79B8FF">1</span><span style="color:#F97583"> -</span><span style="color:#E1E4E8"> replay_data.dones)</span></span>
<span class="line"><span style="color:#F97583">    *</span><span style="color:#79B8FF"> self</span><span style="color:#E1E4E8">.gamma </span><span style="color:#F97583">**</span><span style="color:#79B8FF"> self</span><span style="color:#E1E4E8">.n_step_return_num  </span><span style="color:#6A737D"># γⁿ instead of γ in TD3</span></span>
<span class="line"><span style="color:#F97583">    *</span><span style="color:#E1E4E8"> next_q_values</span></span>
<span class="line"><span style="color:#E1E4E8">).detach()</span></span></code></pre> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Ablation: most of it didn’t help</h2> <p>I ran 26 combinations of the three techniques, with <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n \in \{2, 3, 4, 5, 10, 20, 30\}$</code> for the multi-step returns, and evaluated each against the weak built-in opponent. The results weren’t great.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <figure class="flex flex-col gap-2.5 m-0"> <img alt="Comparative results of 26 configurations showing that standard RL improvements often struggle to beat the baseline in this environment." height="1357" src="https://korayulusan.github.io/static/td3-reinforcement-learning-ablation-study-reward-graph.kjqmTqxt_ir91C.webp" width="2024" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 2:</span> Comparative results of 26 configurations showing that standard RL improvements often struggle to beat the baseline in this environment. </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Detailed reward progression highlighting the modest performance gains of the 3-step return variant." height="1440" src="https://korayulusan.github.io/static/td3-reinforcement-learning-ablation-study-reward-graph-core.CpZ0HDFD_9EH3B.webp" width="2024" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 3:</span> Detailed reward progression highlighting the modest performance gains of the 3-step return variant. </figcaption> </figure>  </figure> <p>Most variants did <em>worse</em> than plain TD3. Only the 3-step return beat the baseline consistently, and only by a little.</p> <p>PER never helped. Without IS weights, training diverged right away, because the critic only saw high-error transitions and learned a skewed picture. With IS weights, training was stable but still worse than the baseline.</p>   <span class="block text-[10px] uppercase font-black mb-2 text-accent tracking-[0.2em]">Key Takeaway</span>  <p>I don’t think PER failing was a bug in my code. It works best when the data distribution stays the same, and here it kept changing as the agent and its situations changed.</p>   <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Curriculum learning</h2> <p>What made the difference was changing what the agent trained on, not the algorithm.</p> <p>Against a strong opponent, the agent quickly learns that a draw (never scoring, never conceding) is safer than trying to score. Once it’s there, it rarely leaves, because a missed shot gives the opponent a chance and that risk outweighs what it expects to gain.</p> <p>My curriculum had two phases.</p> <p><strong>Phase 1 (steps 0 to 440k):</strong> Alternate between HockeyEnv’s shooting mode and defending mode every episode. These simpler scenarios make the agent learn the basics, aiming and shooting, tracking and blocking. Episodes are only 80 steps, so training goes much faster.</p> <p><strong>Phase 2 (steps 440k+):</strong> Empty the replay buffer and train in full games against the strong <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">BasicOpponent</code>. Emptying the buffer keeps the old drills from mixing with the new data.</p> <p>Before, the agent was stuck below a 50% win rate against the strong opponent. With the curriculum it reached <strong>98.3%</strong> within 110k steps of Phase 2. Its win rate against the <em>weak</em> opponent also went up during Phase 1, even though it hadn’t played a single full game yet.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <img alt="Win/Draw/Loss breakdown during curriculum training." height="1134" src="https://korayulusan.github.io/static/curriculum-learning-air-hockey-shooting-defending-modes.DTTGJ9TM_Z1LRJGN.webp" width="2740" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 text-center leading-relaxed max-w-[90%] mt-4 mx-auto" style="text-align:center"> <span class="font-bold text-muted">Figure 4:</span> Win/Draw/Loss breakdown during curriculum training. </figcaption> </figure> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">PER and the curriculum</h2> <p>The replay buffer is emptied when the curriculum moves to Phase 2. For plain TD3 that’s a clean reset, but with PER it went wrong.</p> <p>The first Phase 2 transitions have large TD errors, since the agent has never seen full-game states. In my runs, their IS weights <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$w_i = (N \cdot P(i))^{-\beta}$</code> then dropped close to zero (see the plots below). With near-zero weights, the critic barely learned from those transitions, and the actor, which follows the critic, diverged.</p> <p>So I left PER out of the final curriculum setup.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <figure class="flex flex-col gap-2.5 m-0"> <img alt="Critic loss divergence: The immediate spike in TD error when the curriculum changes destabilizes training." height="664" src="https://korayulusan.github.io/static/prioritized-experience-replay-per-critic-loss-divergence-graph-1.E5L85_T2_103Mdn.webp" width="708" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 5:</span> Critic loss divergence: The immediate spike in TD error when the curriculum changes destabilizes training. </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Importance Sampling (IS) weights dropping to near zero, effectively preventing the agent from learning." height="638" src="https://korayulusan.github.io/static/prioritized-experience-replay-per-critic-loss-divergence-graph-2.CQAntnOX_sVtEP.webp" width="740" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 6:</span> Importance Sampling (IS) weights dropping to near zero, effectively preventing the agent from learning. </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Behavioral shift toward drawing with longer episodes, which is a local optimum that the agent can't escape from." height="688" src="https://korayulusan.github.io/static/prioritized-experience-replay-per-critic-loss-divergence-graph-3.cS8LXscS_29DXec.webp" width="702" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 7:</span> Behavioral shift toward drawing with longer episodes, which is a local optimum that the agent can't escape from. </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Reward progression showing that the agent fails to improve after the curriculum switch, confirming the learning collapse." height="678" src="https://korayulusan.github.io/static/prioritized-experience-replay-per-critic-loss-divergence-graph-4.DKfiukvr_1CFtjt.webp" width="706" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 8:</span> Reward progression showing that the agent fails to improve after the curriculum switch, confirming the learning collapse. </figcaption> </figure>  </figure> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Self-Play</h2> <p>I also tried self-play, training the agent against a pool of its own past checkpoints, hoping it would learn more than how to beat the scripted <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">BasicOpponent</code>.</p> <p>It didn’t work. Both sides learned to <em>avoid the puck</em> rather than risk conceding, and episodes got longer and longer toward the 250-step limit. Once that happened it fed itself: an agent that attacked got punished by an opponent that had learned to exploit attacking.</p> <p>From the agent’s point of view this is reasonable: “don’t touch the puck” really does have a higher expected return than a risky shot. Mixing in <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">BasicOpponent</code> episodes or clearing the buffer when switching opponents didn’t fix it.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <figure class="flex flex-col gap-2.5 m-0"> <img alt="Mean episode length trends in self-play, showing the convergence toward a 250-step 'mutual avoidance' strategy." height="666" src="https://korayulusan.github.io/static/rl-self-play-agent-deadlock-episode-length-trends.DLvfHUZO_ZjfnRT.webp" width="718" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 9:</span> Mean episode length trends in self-play, showing the convergence toward a 250-step 'mutual avoidance' strategy. </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Visualization of the drawing deadlock where both agents prioritize safety over scoring." height="480" src="https://korayulusan.github.io/static/rl-self-play-agent-deadlock.CLCg0h3A_1BsSvb.webp" width="600" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 10:</span> Visualization of the drawing deadlock where both agents prioritize safety over scoring. </figcaption> </figure>  </figure> <p>From what other students told me, what works is mixing self-play with the shooting and defending drills and an easy opponent for the whole run, so the agent doesn’t forget that scoring is the point.</p>   <span class="block text-[10px] uppercase font-black mb-2 text-accent tracking-[0.2em]">Key Takeaway</span>  <p>Self-play on its own got stuck in a draw. Keeping the scoring drills in the mix the whole time is what I’d try next.</p>   <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Tournament</h2> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <figure class="flex flex-col gap-2.5 m-0"> <img alt="UlusanTD3 (orange) playing against strong built-in opponent, employing an aggressive strategy. (immediate 4 Wins)" height="960" src="https://korayulusan.github.io/static/td3-basicstrong-startswithball.BxC_Xmqw_ZmAbif.webp" width="1200" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 11:</span> UlusanTD3 (orange) playing against strong built-in opponent, employing an aggressive strategy. (immediate 4 Wins) </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="UlusanTD3 (orange) defending against strong built-in opponent, showing improved defensive positioning. (4 Wins)" height="960" src="https://korayulusan.github.io/static/td3-basicstrong-startswithoutball.jJcZissb_Z2kyQmB.webp" width="1200" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 12:</span> UlusanTD3 (orange) defending against strong built-in opponent, showing improved defensive positioning. (4 Wins) </figcaption> </figure>  </figure> <p>The final agent (3-step return, curriculum, no PER) competed in the 2025 RL course tournament at the University of Tübingen, ranking <strong>131/146</strong> (including stale accounts) with a <strong>40% win rate</strong> against other students’ agents. Some students chose not to join the tournament.</p> <p>That’s a more honest number than the 98.3% against <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">BasicOpponent</code>. My self-play loop failed because the rewards were so sparse. Other students kept the training modes in their curriculum, which gave more reward signal and avoided the draw. Agents with world models didn’t do much better than TD3-style ones. What worked best was training on the tournament games to learn the other agents’ quirks. That’s overfitting, but it works in a competition, and yes, it was allowed.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <img alt="Tournament final ranking showing our agent's position at 131 and a 40% win rate." height="565" src="https://korayulusan.github.io/static/air-hockey-rl-tournament-final-ranking-win-rate.D8jfs0ve_2lrHjG.webp" width="922" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 text-center leading-relaxed max-w-[90%] mt-4 mx-auto" style="text-align:center"> <span class="font-bold text-muted">Figure 13:</span> Tournament final ranking showing our agent's position at 131 and a 40% win rate. </figcaption> </figure> <p>If I had kept the defending and shooting modes during self-play, I think I would have placed noticeably higher.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">What I’d do differently</h2> <p><strong>PER:</strong> Be careful with it when the training data changes mid-run, as with a curriculum or changing opponents. The stored priorities stop matching the data. I’d either clear the buffer at each change or skip PER.</p> <p><strong>Reward shaping:</strong> Pick the terms in <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\phi$</code> carefully. Something that sounds sensible can reward the wrong thing, like <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">game_length</code> rewarding own goals. The theory says shaping doesn’t change the optimal policy, but that’s in the limit, and a real training run is far from it.</p> <p><strong>Multi-step returns:</strong> Keep <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n$</code> small, around 2 to 5. With <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n$</code> between 10 and 30, the return estimate gets noisy and the target less reliable. Only <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n = 3$</code> beat the baseline consistently for me.</p> <p><strong>Self-play:</strong> Mix in the skill drills from the start. Self-play from scratch found the draw before it found scoring.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Conclusion</h2> <p>Adding improvements to TD3 mostly made it worse. The curriculum, which changed <em>what the agent practiced</em> rather than <em>how it learned</em>, is what made it good.</p> <p>With rewards this sparse, the training setup mattered more than the algorithm. PER, multi-step returns and reward shaping all change how the agent learns from its data, while the curriculum changes what data it gets in the first place.</p> <p>If I picked this up again, I’d build a self-play loop that picks opponents from a pool and keeps the skill drills in.</p> <p>If you want more detail:</p> <ul> <li><a href="https://github.com/KorayUlusan/Reinforcement-Learning-TD3/blob/main/hockey-technical-report.pdf" style="color:#70a5fd">Technical Report</a></li> <li><a href="https://github.com/KorayUlusan/Reinforcement-Learning-TD3/blob/main/hockey-presentation.pdf" style="color:#70a5fd">Presentation</a></li> <li><a href="https://github.com/KorayUlusan/Reinforcement-Learning-TD3" style="color:#70a5fd">GitHub Repo</a></li> <li><a href="https://github.com/KorayUlusan/Reinforcement-Learning-TD3/blob/main/src/agents/ulusan_td3.py" style="color:#70a5fd">RL Agent’s Code</a></li> </ul> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Acknowledgments</h2> <p>I did this project for the RL course (2024/25) taught by Prof. Georg Martius at the University of Tübingen, together with Elia Frederick Reppchen (Rainbow DQN) and ChandraLekha Ramireddy (SAC). We trained on the <a href="https://uni-tuebingen.de/fakultaeten/mathematisch-naturwissenschaftliche-fakultaet/fachbereiche/informatik/lehrstuehle/kognitive-systeme/projects/tcml-cluster/" style="color:#70a5fd">TCML cluster</a> offered by the Cognitive Systems Chair (of Prof. Andreas Zell) at the University of Tübingen.</p>  <p class="mt-8 text-muted/80"> Thanks for reading! If you have questions, feedback, or want to discuss a project, feel free to drop me an <a style="color:#70a5fd"><span>email</span></a> or message. </p> 
      <div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); text-align: center; font-family: 'JetBrains Mono', monospace; color: #9ca3af;">
        <span style="color: #ffb86c;">◆</span> 
        Originally published at 
        <a href="https://korayulusan.github.io/blog/rl-hockey-td3-per-reward-shaping-curriculum/" style="color: #ffb86c; text-decoration: none; border-bottom: 1px solid #ffb86c;">korayulusan.github.io</a>
      </div>
    </div>]]></content:encoded>
  </item>

  <item>
    <title>Trustworthy ML: OOD Generalization, XAI, and Calibration</title>
    <link>https://korayulusan.github.io/blog/trustworthy-ml-ood-xai-uncertainty/</link>
    <guid isPermaLink="true">https://korayulusan.github.io/blog/trustworthy-ml-ood-xai-uncertainty/</guid>
    <pubDate>Sat, 14 Dec 2024 06:47:54 GMT</pubDate>
    <description>Three homework assignments from Trustworthy ML (WS 2024-25): ensemble diversification with PoE and HSIC on dSprites, feature attribution via saliency and CAM on CUB-200, influence functions with a kNN speedup, and calibration from proper scoring rules.</description>
    <media:content url="https://korayulusan.github.io/og/blog/trustworthy-ml-ood-generalization-xai-and-calibrat-landscape-thumbnail.jpeg" medium="image" />
    <enclosure url="https://korayulusan.github.io/og/blog/trustworthy-ml-ood-generalization-xai-and-calibrat-landscape-thumbnail.jpeg" length="0" type="image/jpeg" />
    <content:encoded><![CDATA[<div style="background-color: #1c1c1d; color: #e8e8e8; font-family: sans-serif;"> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">TL;DR</h3> <p>Three homework sets from <em>Trustworthy Machine Learning</em>. They covered <strong>OOD generalization</strong> (ensemble diversification, IRM, adversarial attacks on LLMs), <strong>explainability</strong> (feature attribution, training data attribution), and <strong>uncertainty</strong> (calibration, epistemic/aleatoric decomposition, deep ensembles). They were hard at the time, but I still use a lot of what I learned in them.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">OOD Generalization</h2> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Our setup</h3> <p>In domain generalization you train on labeled source domains <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$D_1, \dots, D_n$</code> and never see the target domain. The exercise was a bit different: <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n$</code> source domains plus a batch of <em>unlabeled</em> samples from the deployment domain <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$D_{n+1}$</code>. Having those unlabeled samples means you can use semi-supervised adaptation, which pure domain generalization can’t.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Learning from Failure</h3> <p><em>Learning from Failure</em> (LfF, NeurIPS 2020) avoids having to label which features are spurious. You first train a deliberately biased model. It gets wrong exactly the samples where the spurious cue (say, color) points the wrong way. A second model is then trained with those samples weighted up. So you don’t need bias annotations, because the biased model’s mistakes tell you where the bias is.</p> <p>This assumes the spurious correlation is <em>easier</em> to learn than the real one, so the biased model picks it up first. That’s true on synthetic benchmarks, but I’m less sure it holds on real data.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">dSprites and the diagonal setup</h3> <p>All experiments used <a href="https://github.com/deepmind/dsprites-dataset" style="color:#70a5fd">dSprites</a>: 64x64 images of shapes (square, ellipse, heart) with latent factors for color, shape, scale, orientation and position. Each latent is binned into 3 classes.</p> <p>Most experiments used the <strong>diagonal dataset</strong>, where the bias cue and the task cue are perfectly correlated in training (<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">off_diag_proportion = 0</code>), so color always equals shape. A model that only learns color gets 100% training accuracy. On the unbiased test set its color-based guesses drop to chance (33%), and shape accuracy shows whether it learned anything else. With <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">off_diag_proportion = 0.1</code>, 10% of the training samples break the correlation, which weakens the spurious signal a little.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Product of Experts</h3> <p>The PoE loss adds the members’ logits before the softmax. Up to normalization, that’s the same as multiplying their softmax distributions:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$p_{\text{PoE}}(y \mid x) \propto \prod_{m=1}^{M} p_m(y \mid x) = \text{softmax}\!\left(\sum_{m=1}^{M} \ell_m(x)\right)$$</pre> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">class</span><span style="color:#B392F0"> ModelTrainerPoE</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">ModelTrainer</span><span style="color:#E1E4E8">):</span></span>
<span class="line"><span style="color:#F97583">    def</span><span style="color:#B392F0"> train_loop</span><span style="color:#E1E4E8">(self, images_batch, labels_batch, epoch</span><span style="color:#F97583">=</span><span style="color:#79B8FF">None</span><span style="color:#E1E4E8">):</span></span>
<span class="line"><span style="color:#E1E4E8">        labels_batch </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> labels_batch[</span><span style="color:#79B8FF">self</span><span style="color:#E1E4E8">.task_label_index]</span></span>
<span class="line"><span style="color:#E1E4E8">        logits_dict </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> self</span><span style="color:#E1E4E8">.model(images_batch)</span></span>
<span class="line"><span style="color:#F97583">        for</span><span style="color:#E1E4E8"> idx, (_, logits) </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> enumerate</span><span style="color:#E1E4E8">(logits_dict.items()):</span></span>
<span class="line"><span style="color:#E1E4E8">            combined </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> logits </span><span style="color:#F97583">if</span><span style="color:#E1E4E8"> idx </span><span style="color:#F97583">==</span><span style="color:#79B8FF"> 0</span><span style="color:#F97583"> else</span><span style="color:#E1E4E8"> combined </span><span style="color:#F97583">+</span><span style="color:#E1E4E8"> logits</span></span>
<span class="line"><span style="color:#F97583">        return</span><span style="color:#E1E4E8"> F.cross_entropy(combined, labels_batch)</span></span></code></pre> <p>When I trained two identical ResNet18s together on the fully diagonal dataset, both learned color. They have the same architecture and data and get the same gradients through the summed logits, so there’s no reason for them to differ.</p> <p>Three changes together got them to learn different things:</p> <ol> <li><strong>Heterogeneous architectures</strong>: ResNet18 for member 0, ResNet101 for member 1.</li> <li><strong>Grayscale input for member 1</strong>, so it can’t use color at all.</li> <li><strong>Sequential training</strong>: only member 0 trains in epoch 1, then member 1.</li> </ol> <p>A cosine-similarity penalty between the members’ outputs helped a little more:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#E1E4E8">diversity_penalty </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> 0</span></span>
<span class="line"><span style="color:#F97583">for</span><span style="color:#E1E4E8"> i, i_outs </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> enumerate</span><span style="color:#E1E4E8">(logits_dict.values()):</span></span>
<span class="line"><span style="color:#F97583">    for</span><span style="color:#E1E4E8"> j, j_outs </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> enumerate</span><span style="color:#E1E4E8">(logits_dict.values()):</span></span>
<span class="line"><span style="color:#F97583">        if</span><span style="color:#E1E4E8"> i </span><span style="color:#F97583">!=</span><span style="color:#E1E4E8"> j:</span></span>
<span class="line"><span style="color:#E1E4E8">            diversity_penalty </span><span style="color:#F97583">+=</span><span style="color:#E1E4E8"> F.cosine_similarity(i_outs, j_outs).mean()</span></span>
<span class="line"><span style="color:#E1E4E8">loss </span><span style="color:#F97583">+=</span><span style="color:#79B8FF"> 0.1</span><span style="color:#F97583"> *</span><span style="color:#E1E4E8"> diversity_penalty</span></span></code></pre> <p>The grayscale input is the reliable part. The penalty only pushes the members apart and doesn’t control what they disagree <em>on</em>.</p>   <span class="block text-[10px] uppercase font-black mb-2 text-accent tracking-[0.2em]">Key Takeaway</span>  <p>PoE on its own doesn’t make identical members learn different features. They need different inputs, different architectures or an explicit penalty.</p>   <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">HSIC regularization</h3> <p><a href="https://arxiv.org/abs/1910.02806" style="color:#70a5fd">ReBias (ICML 2020)</a> uses the Hilbert-Schmidt Independence Criterion to make an unbiased model’s embeddings independent of a biased model’s. HSIC measures statistical dependence using centered kernel matrices:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\text{HSIC}(K, L) = \frac{1}{m^2} \operatorname{tr}(\tilde{K} \tilde{L}), \quad \tilde{K} = HKH, \quad H = I - \tfrac{1}{m}\mathbf{1}\mathbf{1}^\top$$</pre> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> _hsic_loss</span><span style="color:#E1E4E8">(self, embeddings):</span></span>
<span class="line"><span style="color:#E1E4E8">    em1, em2 </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> embeddings</span></span>
<span class="line"><span style="color:#F97583">    def</span><span style="color:#B392F0"> rbf_kernel</span><span style="color:#E1E4E8">(x, sigma</span><span style="color:#F97583">=</span><span style="color:#79B8FF">1.0</span><span style="color:#E1E4E8">):</span></span>
<span class="line"><span style="color:#F97583">        return</span><span style="color:#E1E4E8"> torch.exp(</span><span style="color:#F97583">-</span><span style="color:#E1E4E8">torch.cdist(x, x, </span><span style="color:#FFAB70">p</span><span style="color:#F97583">=</span><span style="color:#79B8FF">2</span><span style="color:#E1E4E8">)</span><span style="color:#F97583">**</span><span style="color:#79B8FF">2</span><span style="color:#F97583"> /</span><span style="color:#E1E4E8"> sigma</span><span style="color:#F97583">**</span><span style="color:#79B8FF">2</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    K, L </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> rbf_kernel(em1), rbf_kernel(em2)</span></span>
<span class="line"><span style="color:#E1E4E8">    m </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> K.shape[</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">]</span></span>
<span class="line"><span style="color:#E1E4E8">    H </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (torch.eye(m) </span><span style="color:#F97583">-</span><span style="color:#E1E4E8"> torch.ones(m, m)</span><span style="color:#F97583">/</span><span style="color:#E1E4E8">m).to(K.device)</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> (</span><span style="color:#79B8FF">1</span><span style="color:#F97583">/</span><span style="color:#E1E4E8">m</span><span style="color:#F97583">**</span><span style="color:#79B8FF">2</span><span style="color:#E1E4E8">) </span><span style="color:#F97583">*</span><span style="color:#E1E4E8"> torch.trace(H </span><span style="color:#F97583">@</span><span style="color:#E1E4E8"> K </span><span style="color:#F97583">@</span><span style="color:#E1E4E8"> H </span><span style="color:#F97583">@</span><span style="color:#E1E4E8"> (H </span><span style="color:#F97583">@</span><span style="color:#E1E4E8"> L </span><span style="color:#F97583">@</span><span style="color:#E1E4E8"> H))</span></span></code></pre> <p>The training loss is <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\mathcal{L}_{CE} + \alpha \cdot \text{HSIC}(z_{\text{biased}}, z_{\text{unbiased}})$</code>.</p> <p>I ran the BiasedNet + ResNet18 ensemble with <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">ALPHA</code> varied over five orders of magnitude, and the accuracies barely changed. The HSIC value itself stayed small and stable, which points at the kernel bandwidth. With <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\sigma = 1$</code> and 512-dimensional embeddings, the pairwise distances are so large that the RBF kernel saturates and there’s almost no gradient. Picking the bandwidth from the data (for example with the median heuristic) should fix that, but I didn’t get to try it.<sup class="footnote-ref"><a href="#fn-1" style="color:#70a5fd">1</a></sup></p> <p><code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">off_diag_proportion</code> mattered more than HSIC. Going from 0% to 10% off-diagonal samples raised ResNet18’s shape accuracy from 33% to 41%, with or without HSIC.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">IRM</h3> <p><a href="https://arxiv.org/abs/1907.02893" style="color:#70a5fd">Invariant Risk Minimization (Arjovsky et al., 2019)</a> doesn’t use an ensemble. It learns one representation on which the best linear classifier is the same in every training environment. To check this, it multiplies the representation by a dummy scalar <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$w$</code> fixed at 1 and looks at the gradient of each environment’s loss with respect to <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$w$</code>. If <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\nabla_w \mathcal{L}_e(\Phi \cdot w)\big|_{w=1} \approx 0$</code> for every <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$e$</code>, then <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$w = 1$</code> is optimal in all of them.</p> <p>In the implementation, I split each batch by environment, computed the ERM loss and the squared gradient norm for each environment (one backward pass each), and added them up: <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\mathcal{L}_{\text{IRM}} = \sum_e \mathcal{L}_e + \lambda \sum_e \lVert \nabla_{w|w=1} \mathcal{L}_e \rVert^2$</code>. On dSprites, IRM wasn’t clearly better than ERM early in training. That fits what’s known about IRM: if the environments aren’t different enough, the penalty is easy to satisfy without learning anything invariant.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Adversarial attacks on LLMs</h3> <p><a href="https://arxiv.org/abs/2307.15043" style="color:#70a5fd">GCG (Zou et al., 2023)</a> showed that aligned LLMs can be jailbroken by adding an adversarial suffix to a harmful prompt. The suffix comes from a greedy coordinate search. You take the gradient of the target string’s cross-entropy with respect to the one-hot token embeddings, pick the top-<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k$</code> replacement candidates for each suffix position, try them all in a forward pass and keep the best one.</p> <p>We had to write three pieces. <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">get_loss</code> is the cross-entropy between the logits at the target positions and the target token ids. <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">compute_token_gradient</code> embeds the input as one-hot vectors, runs the model on them, calls <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">get_loss</code> and returns the gradient with respect to the one-hot matrix. <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">sample_ids_from_grad</code> scores candidate tokens by the negative gradient at each suffix position and samples replacements, without replacement, from the top-<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k$</code>. The <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">run_gcg</code> loop and the evaluation were given.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">XAI</h2> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Remove-and-classify</h3> <p>Judging an attribution map by eye isn’t very reliable. Remove-and-classify (RAC) turns it into a number that works for any model: sort the pixels by attribution, remove the top <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k$</code> at a time, rerun the model and measure how much accuracy drops. A lower area under that curve (a lower RAC score) means the method found the pixels the model relies on.</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> remove_and_classify</span><span style="color:#E1E4E8">(model, dataset, explanations, k</span><span style="color:#F97583">=</span><span style="color:#79B8FF">100</span><span style="color:#E1E4E8">):</span></span>
<span class="line"><span style="color:#E1E4E8">    sorted_ranks </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> sort_explanations_by_importance(explanations)</span></span>
<span class="line"><span style="color:#E1E4E8">    performances </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> []</span></span>
<span class="line"><span style="color:#F97583">    for</span><span style="color:#E1E4E8"> i </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> range</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">, width </span><span style="color:#F97583">*</span><span style="color:#E1E4E8"> height, k):</span></span>
<span class="line"><span style="color:#F97583">        for</span><span style="color:#E1E4E8"> idx, coords </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> enumerate</span><span style="color:#E1E4E8">([sorted_ranks[j][i:i</span><span style="color:#F97583">+</span><span style="color:#E1E4E8">k]</span></span>
<span class="line"><span style="color:#F97583">                                      for</span><span style="color:#E1E4E8"> j </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> range</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">len</span><span style="color:#E1E4E8">(explanations))]):</span></span>
<span class="line"><span style="color:#E1E4E8">            rows, cols </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> zip</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">*</span><span style="color:#E1E4E8">coords)</span></span>
<span class="line"><span style="color:#E1E4E8">            dataset.data[idx][rows, cols] </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> 128</span><span style="color:#6A737D">  # replace with grey</span></span>
<span class="line"><span style="color:#E1E4E8">        performances.append(model_accuracy(model, dataset))</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> performances</span></span></code></pre> <p>The centered Gaussian baseline ranks pixels by how close they are to the center, ignoring the image. In CUB-200 the bird is usually near the center, so this works better than you’d think. The figure below shows it on Fashion-MNIST, where every item is centered: removing the central 800 pixels takes accuracy from 90% down to chance.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <img alt="Accuracy vs. feature removal step for the centered Gaussian baseline on Fashion-MNIST" height="432" src="https://korayulusan.github.io/static/py2-feature-removal.Bk5zEuNC_2e6Jkq.webp" width="567" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 text-center leading-relaxed max-w-[90%] mt-4 mx-auto" style="text-align:center"> <span class="font-bold text-muted">Figure 1:</span> Accuracy vs. feature removal step for the centered Gaussian baseline on Fashion-MNIST </figcaption> </figure>  <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Saliency</h3> <p>Saliency (Simonyan et al., 2013) is the gradient of the predicted class score with respect to the input:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$M_{ij} = \max_c \left| \frac{\partial f_c(x)}{\partial x_{ij,c}} \right|$$</pre> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> saliency</span><span style="color:#E1E4E8">(model, dataset, sample_idx):</span></span>
<span class="line"><span style="color:#E1E4E8">    image, _ </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> dataset[sample_idx]</span></span>
<span class="line"><span style="color:#E1E4E8">    image </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> image.to(device).unsqueeze(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">).requires_grad_(</span><span style="color:#79B8FF">True</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    output </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> model(image)[</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">]</span></span>
<span class="line"><span style="color:#E1E4E8">    output[output.argmax(</span><span style="color:#FFAB70">dim</span><span style="color:#F97583">=</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">)].backward()</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> image.grad.abs().max(</span><span style="color:#FFAB70">dim</span><span style="color:#F97583">=</span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">)[</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">].squeeze().cpu()</span></span></code></pre> <p>It needs only one backward pass. The maps are noisy, though, because gradients saturate in much of a deep network, so they highlight edges more than the parts of the bird that matter.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <img alt="Saliency map overlaid on a CUB-200 bird image" height="389" src="https://korayulusan.github.io/static/py2-saliency-output.wcxD96Oe_6vh9t.webp" width="519" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 text-center leading-relaxed max-w-[90%] mt-4 mx-auto" style="text-align:center"> <span class="font-bold text-muted">Figure 2:</span> Saliency map overlaid on a CUB-200 bird image </figcaption> </figure> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">CAM</h3> <p>CAM (Zhou et al., 2016) works only on architectures where the classifier is a global average pooling followed by a linear layer (or a 1x1 convolution). The activation map for class <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$c$</code> is a weighted sum of final-layer feature maps:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\text{CAM}_c(x, y) = \sum_k w_k^c f_k(x, y)$$</pre> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> class_activation_map</span><span style="color:#E1E4E8">(model, dataset, sample_idx):</span></span>
<span class="line"><span style="color:#E1E4E8">    activation </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> {}</span></span>
<span class="line"><span style="color:#E1E4E8">    model.layer4[</span><span style="color:#F97583">-</span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">].relu.register_forward_hook(</span></span>
<span class="line"><span style="color:#F97583">        lambda</span><span style="color:#E1E4E8"> m, i, o: activation.update({</span><span style="color:#9ECBFF">'f'</span><span style="color:#E1E4E8">: o.detach()})</span></span>
<span class="line"><span style="color:#E1E4E8">    )</span></span>
<span class="line"><span style="color:#E1E4E8">    image </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> dataset[sample_idx][</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">].to(device).unsqueeze(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    img_class </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> model(image).argmax(</span><span style="color:#FFAB70">dim</span><span style="color:#F97583">=</span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    cam </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (model.conv_last.weight[img_class].squeeze(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#F97583">           *</span><span style="color:#E1E4E8"> activation[</span><span style="color:#9ECBFF">'f'</span><span style="color:#E1E4E8">].squeeze(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">)).sum(</span><span style="color:#FFAB70">dim</span><span style="color:#F97583">=</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    cam </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> F.interpolate(cam[</span><span style="color:#79B8FF">None</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">None</span><span style="color:#E1E4E8">], </span><span style="color:#FFAB70">size</span><span style="color:#F97583">=</span><span style="color:#E1E4E8">image.shape[</span><span style="color:#F97583">-</span><span style="color:#79B8FF">2</span><span style="color:#E1E4E8">:], </span><span style="color:#FFAB70">mode</span><span style="color:#F97583">=</span><span style="color:#9ECBFF">'bicubic'</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> cam.squeeze().detach().cpu()</span></span></code></pre> <p>CAM localizes well because it uses the network’s own classifier weights to weight the feature maps. It needs GAP followed by a single linear layer. ResNet-style networks already end that way, but VGG-style networks with several fully connected layers have to be modified.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <img alt="Class activation map overlaid on a CUB-200 bird image" height="389" src="https://korayulusan.github.io/static/py2-cam-output.DSA4bKdD_2sQIK5.webp" width="479" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" />  <figcaption class="text-sm text-muted/80 text-center leading-relaxed max-w-[90%] mt-4 mx-auto" style="text-align:center"> <span class="font-bold text-muted">Figure 3:</span> Class activation map overlaid on a CUB-200 bird image </figcaption> </figure> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Training data attribution</h3> <p>Feature attribution asks which pixels led to a prediction. Training data attribution asks which training examples did.</p> <p>The influence function of training example <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$z_j$</code> on test example <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$z$</code> approximates the change in test loss from removing <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$z_j$</code> and retraining:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\text{IF}(z_j, z) \approx -\nabla_\theta \mathcal{L}(z, \hat\theta)^\top H_{\hat\theta}^{-1} \nabla_\theta \mathcal{L}(z_j, \hat\theta)$$</pre> <p>Computing <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$H^{-1}v$</code> is the expensive step. LiSSA (used in <a href="https://arxiv.org/abs/2012.15781" style="color:#70a5fd">FastIF</a>) estimates it iteratively over minibatches using the recurrence:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$H^{-1}v \approx \sum_{t=0}^{T}(I - H)^t v$$</pre> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#E1E4E8">new_estimate </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> [</span></span>
<span class="line"><span style="color:#E1E4E8">    a </span><span style="color:#F97583">+</span><span style="color:#E1E4E8"> (</span><span style="color:#79B8FF">1</span><span style="color:#F97583"> -</span><span style="color:#E1E4E8"> damp) </span><span style="color:#F97583">*</span><span style="color:#E1E4E8"> b </span><span style="color:#F97583">-</span><span style="color:#E1E4E8"> c </span><span style="color:#F97583">/</span><span style="color:#E1E4E8"> scale</span></span>
<span class="line"><span style="color:#F97583">    for</span><span style="color:#E1E4E8"> a, b, c </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> zip</span><span style="color:#E1E4E8">(v, last_estimate, this_estimate)</span></span>
<span class="line"><span style="color:#E1E4E8">]</span></span></code></pre> <p>To evaluate it, you retrain after removing the top <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$p\%$</code> most helpful, most harmful or random training examples and check how the confidence on the test example changes. Removing helpful examples is supposed to lower it, and removing harmful ones to raise it.</p> <p><strong>kNN speedup.</strong> Computing influence for every training example is <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$O(n)$</code>. FastIF only computes the gradient dot products for the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k$</code> nearest neighbors in embedding space, using the final layer’s <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">[CLS]</code> token as the embedding:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> embed_one_example</span><span style="color:#E1E4E8">(model, example):</span></span>
<span class="line"><span style="color:#F97583">    with</span><span style="color:#E1E4E8"> torch.no_grad():</span></span>
<span class="line"><span style="color:#E1E4E8">        out </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> model(</span><span style="color:#F97583">**</span><span style="color:#E1E4E8">example, </span><span style="color:#FFAB70">output_hidden_states</span><span style="color:#F97583">=</span><span style="color:#79B8FF">True</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#F97583">        return</span><span style="color:#E1E4E8"> out.hidden_states[</span><span style="color:#F97583">-</span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">][</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">]</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> get_knn_indices</span><span style="color:#E1E4E8">(model, embedded_train, test_input, k</span><span style="color:#F97583">=</span><span style="color:#79B8FF">100</span><span style="color:#E1E4E8">):</span></span>
<span class="line"><span style="color:#E1E4E8">    test_emb </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> embed_one_example(model, test_input)</span></span>
<span class="line"><span style="color:#E1E4E8">    dists </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> torch.cdist(torch.stack(embedded_train), test_emb.unsqueeze(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">))</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> torch.topk(dists.squeeze(</span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">), </span><span style="color:#FFAB70">k</span><span style="color:#F97583">=</span><span style="color:#E1E4E8">k, </span><span style="color:#FFAB70">largest</span><span style="color:#F97583">=</span><span style="color:#79B8FF">False</span><span style="color:#E1E4E8">).indices</span></span></code></pre> <p>The inverse-Hessian-vector product still uses the whole training set, since the Hessian depends on all of it. Only the final dot products are limited to the neighbors.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Discussion</h3> <p>On feature attribution: the centered Gaussian baseline doing well on CUB-200 tells you more about the dataset than about attribution. Birds are near the center in most images, so anything that highlights the center looks good on RAC. Filling removed pixels with gray (128) is also a weak test. The gray patches themselves show the model where pixels were removed, and the images no longer look like anything it was trained on. Learned inpainting, or averaging over a conditional distribution, would be a fairer test.</p> <p>On training data attribution: LiSSA only converges if the Hessian’s spectral radius is below 1, which is what the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">scale</code> parameter is for. Eigenvalues near zero blow up the matching components of <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$H^{-1}v$</code>, and the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">damp</code> term, which adds a small value to the diagonal, keeps that in check. <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">params_filter</code> limits the gradients to some of the parameters, usually just the final layer. For large pretrained models that’s a reasonable compromise, since the last layer carries most of the task-specific signal and full-model gradients would be far too expensive. For the kNN speedup, you can compare the scores from the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k$</code> nearest neighbors against full influence while varying <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k$</code>. Compute drops roughly as <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$k/n$</code>.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Calibration</h2> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">BCE as a proper scoring rule</h3> <p>A scoring rule is <strong>strictly proper</strong> if the expected loss is lowest only when you report the true probability. For binary cross-entropy, let <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$p = P(Y=1)$</code>. The expected loss is:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\mathbb{E}[\mathcal{L}(q, Y)] = -(p\log q + (1-p)\log(1-q))$$</pre> <p>Setting <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\frac{d}{dq} = 0$</code> gives <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$p/q = (1-p)/(1-q)$</code>, which simplifies to <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$p = q$</code>. The second derivative is <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$p/q^2 + (1-p)/(1-q)^2 &gt; 0$</code>, so the function is strictly convex and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$q = p$</code> is the only minimum.</p> <p>For contrast, the linear loss <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\mathcal{L}(q,y) = -yq + (1-y)(1-q)$</code> has expected value <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$1 - p - q$</code>, minimized at <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$q \to 1$</code> regardless of <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$p$</code>. It is not a proper scoring rule.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Calibration metrics</h3> <p><strong>Expected Calibration Error</strong> bins predictions by confidence and measures the weighted average gap between confidence and accuracy:</p> <pre style="text-align:center;background:rgba(255,184,108,0.05);padding:12px;border:1px dashed rgba(255,184,108,0.3);border-radius:8px;color:#ffb86c;font-family:monospace">$$\text{ECE} = \sum_{b=1}^{B} \frac{|B_b|}{n} \left| \text{acc}(B_b) - \text{conf}(B_b) \right|$$</pre> <p><strong>NLL</strong> is itself a proper scoring rule, so it rewards calibration directly. <strong>AUROC</strong> only measures how well the model separates the classes, which has nothing to do with calibration. A model that predicts 0.51 for every positive and 0.49 for every negative gets a perfect AUROC and terrible calibration.</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> ece_score</span><span style="color:#E1E4E8">(pred_prob, y, n_bins</span><span style="color:#F97583">=</span><span style="color:#79B8FF">10</span><span style="color:#E1E4E8">):</span></span>
<span class="line"><span style="color:#E1E4E8">    bin_edges </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> torch.linspace(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">, n_bins </span><span style="color:#F97583">+</span><span style="color:#79B8FF"> 1</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    ece </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> torch.tensor(</span><span style="color:#79B8FF">0.0</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#F97583">    for</span><span style="color:#E1E4E8"> i </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> range</span><span style="color:#E1E4E8">(n_bins):</span></span>
<span class="line"><span style="color:#E1E4E8">        mask </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (bin_edges[i] </span><span style="color:#F97583">&lt;=</span><span style="color:#E1E4E8"> pred_prob) </span><span style="color:#F97583">&amp;</span><span style="color:#E1E4E8"> (pred_prob </span><span style="color:#F97583">&lt;</span><span style="color:#E1E4E8"> bin_edges[i</span><span style="color:#F97583">+</span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">])</span></span>
<span class="line"><span style="color:#F97583">        if</span><span style="color:#E1E4E8"> mask.any():</span></span>
<span class="line"><span style="color:#E1E4E8">            acc </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (pred_prob[mask].round() </span><span style="color:#F97583">==</span><span style="color:#E1E4E8"> y[mask]).float().mean()</span></span>
<span class="line"><span style="color:#E1E4E8">            conf </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> pred_prob[mask].mean()</span></span>
<span class="line"><span style="color:#E1E4E8">            ece </span><span style="color:#F97583">+=</span><span style="color:#E1E4E8"> (mask.sum() </span><span style="color:#F97583">/</span><span style="color:#79B8FF"> len</span><span style="color:#E1E4E8">(pred_prob)) </span><span style="color:#F97583">*</span><span style="color:#E1E4E8"> (acc </span><span style="color:#F97583">-</span><span style="color:#E1E4E8"> conf).abs()</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> ece</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> nll_score</span><span style="color:#E1E4E8">(pred_prob, y):</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#F97583"> -</span><span style="color:#E1E4E8">torch.mean(y </span><span style="color:#F97583">*</span><span style="color:#E1E4E8"> torch.log(pred_prob) </span><span style="color:#F97583">+</span><span style="color:#E1E4E8"> (</span><span style="color:#79B8FF">1</span><span style="color:#F97583"> -</span><span style="color:#E1E4E8"> y) </span><span style="color:#F97583">*</span><span style="color:#E1E4E8"> torch.log(</span><span style="color:#79B8FF">1</span><span style="color:#F97583"> -</span><span style="color:#E1E4E8"> pred_prob))</span></span></code></pre> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Which model is which</h3> <p>We got four unnamed binary classifiers and had to work out what each one was from ECE, NLL and AUROC:</p> <table style="margin-top:1em;border-collapse:collapse;width:100%"><thead><tr><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Model</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">ECE</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">NLL</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">AUROC</th><th style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Verdict</th></tr></thead><tbody><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">1</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">High</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">High</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Low</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Uncalibrated, inaccurate, overconfident</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">2</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Low</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Moderate</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Low</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Calibrated, inaccurate</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">3</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Low</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Low</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">~0.99</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Calibrated, accurate</td></tr><tr><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">4</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">High</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">High</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">High</td><td style="border:1px solid rgba(255, 255, 255, 0.1);padding:8px;text-align:left">Uncalibrated, accurate, underconfident</td></tr></tbody></table> <p>Model 3’s reliability diagram looks strange at 10 bins: well calibrated on average, but jumpy from bin to bin. At 50 bins you can see why. Almost all of its predictions are very confident, and it rarely outputs anything in between.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <figure class="flex flex-col gap-2.5 m-0 sm:col-span-full sm:mx-auto sm:w-1/2"> <img alt="Reliability diagram for model 1 (10 bins)" height="2469" src="https://korayulusan.github.io/static/py3-acc-conf-graph1.DdD3bFhF_Te0qI.webp" width="2550" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 4:</span> Reliability diagram for model 1 (10 bins) </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0 col-start-1"> <img alt="Reliability diagram for model 2 (10 bins)" height="2469" src="https://korayulusan.github.io/static/py3-acc-conf-graph2.9nT-xCGk_elXTX.webp" width="2550" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 5:</span> Reliability diagram for model 2 (10 bins) </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Reliability diagram for model 2 (50 bins)" height="2467" src="https://korayulusan.github.io/static/py3-acc-conf-graph3.Db6AS6x-_1sskxT.webp" width="2550" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 6:</span> Reliability diagram for model 2 (50 bins) </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Reliability diagram for model 3 (10 bins)" height="2466" src="https://korayulusan.github.io/static/py3-acc-conf-graph4.Dj18qX-3_1AiFKP.webp" width="2550" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 7:</span> Reliability diagram for model 3 (10 bins) </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Reliability diagram for model 3 (50 bins)" height="2467" src="https://korayulusan.github.io/static/py3-acc-conf-graph5.BEJWUTxL_Z1DRU5J.webp" width="2550" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 8:</span> Reliability diagram for model 3 (50 bins) </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0 sm:col-span-full sm:mx-auto sm:w-1/2"> <img alt="Reliability diagram for model 4 (10 bins)" height="2465" src="https://korayulusan.github.io/static/py3-acc-conf-graph6.By3nDgE1_Z1uHHkn.webp" width="2550" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 9:</span> Reliability diagram for model 4 (10 bins) </figcaption> </figure>  </figure> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Cheating ECE</h3> <p>Model 5 had a bad ECE of 0.25. Its labels had been shuffled, keeping the class balance but breaking the link to each sample, so the model itself couldn’t be improved. The task was to make the score look better anyway.</p> <p>ECE puts predictions into bins, and that leaves room to cheat: 0.48 and 0.52 end up in different bins even though they’re almost the same. You can use this by running gradient descent on the predictions against the shuffled labels, reshuffling the labels at every step:</p> <pre class="astro-code github-dark" style="background-color:#24292e !important;color:#e1e4e8 !important;padding:16px;border-radius:8px;border:1px dashed rgba(255,184,108,0.3);overflow-x:auto;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;line-height:1.5;margin:20px 0"><code><span class="line"><span style="color:#F97583">def</span><span style="color:#B392F0"> lower_ece</span><span style="color:#E1E4E8">(pred_prob, shuffled_y):</span></span>
<span class="line"><span style="color:#E1E4E8">    pred_prob </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> pred_prob.clone().detach().requires_grad_(</span><span style="color:#79B8FF">True</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    optimizer </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> torch.optim.Adam([pred_prob])</span></span>
<span class="line"><span style="color:#F97583">    for</span><span style="color:#E1E4E8"> step </span><span style="color:#F97583">in</span><span style="color:#79B8FF"> range</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">1000</span><span style="color:#E1E4E8">):</span></span>
<span class="line"><span style="color:#E1E4E8">        optimizer.zero_grad()</span></span>
<span class="line"><span style="color:#E1E4E8">        loss </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> differentiable_ece(pred_prob, shuffled_y)</span></span>
<span class="line"><span style="color:#E1E4E8">        loss.backward()</span></span>
<span class="line"><span style="color:#E1E4E8">        optimizer.step()</span></span>
<span class="line"><span style="color:#E1E4E8">        pred_prob.data.clamp_(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">        shuffled_y </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> shuffled_y[torch.randperm(shuffled_y.size(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">))]</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> pred_prob.detach()</span></span></code></pre> <p>Because of the reshuffling, the optimizer can’t fit any particular labeling. The predictions get pushed toward 0.5, and in the 10-bin ECE that looks calibrated, because confidence and accuracy end up roughly equal in each bin.</p> <figure class="mx-auto fig-root md:my-12 my-10 not-prose">  <figure class="flex flex-col gap-2.5 m-0"> <img alt="Model 5 reliability diagram before ECE manipulation" height="2460" src="https://korayulusan.github.io/static/py3-acc-conf-graph7.B8_HXrQC_Z1ngpAg.webp" width="2550" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 10:</span> Model 5 reliability diagram before ECE manipulation </figcaption> </figure><figure class="flex flex-col gap-2.5 m-0"> <img alt="Reliability diagram after collapsing predictions toward 0.5" height="2466" src="https://korayulusan.github.io/static/py3-acc-conf-graph8.Cx2BMDVM_1pNRR7.webp" width="2550" class="block h-full m-0 object-cover w-full" style="max-width:100%;height:auto;border-radius:8px;border:1px solid rgba(255, 255, 255, 0.1);margin:10px 0;display:block" /> <figcaption class="text-sm text-muted/80 text-center leading-snug px-2" style="text-align:center"> <span class="font-bold text-muted">Figure 11:</span> Reliability diagram after collapsing predictions toward 0.5 </figcaption> </figure>  </figure> <p><strong>You can’t do this with NLL.</strong> NLL is strictly proper, so changing <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\hat{p}$</code> in any way that doesn’t bring it closer to the true <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$P(Y=1)$</code> raises the expected NLL. Pushing everything to 0.5 gives NLL <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\geq \log 2 \approx 0.693$</code>, which is worse than any model that has learned anything. NLL has no bins to exploit.</p>   <span class="block text-[10px] uppercase font-black mb-2 text-accent tracking-[0.2em]">Key Takeaway</span>  <p>You can game ECE without improving the model, but not NLL. That’s one reason papers prefer NLL for calibration.</p>   <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Epistemic uncertainty: ensembles</h3> <p>The second part of the uncertainty homework was about three ways to estimate epistemic uncertainty with ensembles. <strong>Bagging</strong> trains <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$N$</code> models on bootstrap samples (<code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$n$</code> examples drawn with replacement, so each model sees about 63% of the unique examples) and averages their predictions. <strong><a href="https://arxiv.org/abs/1506.02142" style="color:#70a5fd">MC Dropout (Gal &amp; Ghahramani, 2016)</a></strong> keeps dropout on at test time and runs <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$M$</code> random forward passes. Epistemic uncertainty is the Jensen-Shannon divergence between the <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$M$</code> predictions, and aleatoric uncertainty is their average entropy. <strong><a href="https://arxiv.org/abs/1802.10026" style="color:#70a5fd">Fast Geometric Ensembling (Garipov et al., 2018)</a></strong> keeps training a converged model with a cyclical learning rate and saves a snapshot at the low point of each cycle. You get an ensemble for much less than training <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$N$</code> models from scratch.</p> <p>The idea is that all three give higher epistemic uncertainty on OOD inputs, where the members disagree more, while aleatoric uncertainty stays about the same, since it comes from the data and not the model. MC Dropout is known to underestimate epistemic uncertainty because dropout is a rough approximation of the posterior. FGE snapshots end up in different basins, so they tend to disagree more on hard examples.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Aleatoric uncertainty: ELK and EDL</h3> <p>Total uncertainty splits into an epistemic and an aleatoric part. For an ensemble, the entropy of the mean prediction equals the members’ average entropy (aleatoric) plus the mutual information between the prediction and the model parameters (epistemic). With <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$M$</code> samples, the Monte Carlo estimates are <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\hat{U}_{\text{aleatoric}} = \frac{1}{M}\sum_m H[p_m]$</code> and <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\hat{U}_{\text{epistemic}} = H[\bar{p}] - \hat{U}_{\text{aleatoric}}$</code>.</p> <p><a href="https://arxiv.org/abs/1806.01768" style="color:#70a5fd">Evidential Deep Learning (Sensoy et al., 2018)</a> puts a Dirichlet distribution over the class probabilities, so one forward pass gives you a prediction and its uncertainty. Without a regularizer, the network learns to make the Dirichlet parameters huge on the training data, and the uncertainty drops to almost zero even for wrong predictions. The regularizer adds the KL divergence to a flat Dirichlet, weighted by the prediction error. That penalizes evidence for wrong answers, so the model stays uncertain where it has been wrong.</p> <h3 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">LLM uncertainty</h3> <p>For GPT-2 we used MC Dropout: keep the model in <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">train()</code> mode at test time, run <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$M$</code> forward passes, and take the entropy of the mean next-token distribution (total uncertainty) and the JSD between the passes (epistemic). Where the model keeps putting high probability on one token, epistemic uncertainty should be low. Rare or grammatically ambiguous positions should get high uncertainty. For the BERT NER task, we expected uncertainty to be highest at entity boundaries and on entity types that are rare in training, and lowest on tokens that are clearly O.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Closing thoughts</h2> <p>Across all three homeworks, the metrics kept having blind spots. ECE can be gamed, AUROC ignores calibration, RAC depends on how you fill in removed pixels, and tuning a hyperparameter on the test set uses the test set for model selection. The metrics are still useful, but I wouldn’t trust a single number on its own.</p> <p>HSIC was a sneakier case. Changing <code style="background:rgba(255, 184, 108, 0.1);color:#ffb86c;padding:2px 5px;border-radius:4px;font-family:monospace">$\alpha$</code> by several orders of magnitude did nothing to accuracy because the kernel bandwidth was too small for the embedding size, so the loss term was effectively zero. The loss value changed, so it looked like it was working, but the gradients were negligible. When a regularizer has no effect, it’s easy to conclude you don’t need it, when the real problem is that it isn’t doing anything.</p> <p>The thing from the PoE part I’ve used most since is the grayscale trick. Removing color from the input works better than adding a loss term to discourage it, and it’s obvious what it does. When you can change the input or the architecture, that’s usually more reliable than a penalty.</p> <h2 style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif">Acknowledgments</h2> <p>I did these homeworks with Ali Zhunis and Esma Doğrusözlü for the Trustworthy Machine Learning course (2024/25), taught by Prof. Seong Joon Oh at the University of Tübingen. The course gave us the team name <a href="https://en.wikipedia.org/wiki/Aldebaran" style="color:#70a5fd">Aldebaran</a>, after an orange giant star. We used Kaggle for compute.</p>  <h2 class="text-sm font-semibold mb-4 pb-0 text-heading tracking-widest uppercase" style="color:#ffb86c;margin-top:1.5em;margin-bottom:0.5em;font-family:sans-serif"> Footnotes </h2> <ol class="text-sm pl-6 space-y-4 text-body-text/90"> <li style="list-style-type:decimal !important" class="footnote-item"><span>Evaluating HSIC's contribution rigorously also requires ablating α=0 on identical training runs, not just sweeping α on the test set. Any hyperparameter choice tuned against the test set is quietly using test information.</span><a href="#fnref-1" class="text-accent/90 footnote-back hover:underline ml-2 no-underline text-xs" title="Back to text" style="color:#70a5fd">↩</a></li> </ol>   <p class="mt-8 text-muted/80"> Thanks for reading! If you have questions, feedback, or want to discuss a project, feel free to drop me an <a style="color:#70a5fd"><span>email</span></a> or message. </p> 
      <div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); text-align: center; font-family: 'JetBrains Mono', monospace; color: #9ca3af;">
        <span style="color: #ffb86c;">◆</span> 
        Originally published at 
        <a href="https://korayulusan.github.io/blog/trustworthy-ml-ood-xai-uncertainty/" style="color: #ffb86c; text-decoration: none; border-bottom: 1px solid #ffb86c;">korayulusan.github.io</a>
      </div>
    </div>]]></content:encoded>
  </item>
  </channel>
</rss>