import marimo

__generated_with = "0.25.1"
app = marimo.App(width="medium")


@app.cell
def _():
    import math
    import marimo as mo

    return math, mo


@app.cell
def _(mo):
    mo.md(r"""
    **Linear Attention capacity lab (Article 09).** Three stored positions, two-dimensional
    unit-length Keys, fixed Values $v_1=(2,0)$, $v_2=(0,3)$, $v_3=(1,1)$.
    Query one of the stored Keys, scaled by $\beta$, and compare two reads:

    - **Softmax:** keeps all three K/V pairs and reads $\sum_i w_i v_i$ with $w=\operatorname{softmax}(\beta k^\top k_i)$.
    - **Linear:** keeps only $S=\sum_i v_i k_i^\top$ and $z=\sum_i k_i$, with $\phi(x)=x$, and reads $S q/(z^\top q)$.

    Keys stay on the quarter circle between 0° and 90°, so every similarity is non-negative and the
    linear read is a weighted average. Hand-built teaching values, not a trained model.
    """)
    return


@app.cell
def _(mo):
    angle1 = mo.ui.slider(0, 90, step=1, value=0, label="angle of k₁ (°)", show_value=True)
    angle2 = mo.ui.slider(0, 90, step=1, value=90, label="angle of k₂ (°)", show_value=True)
    angle3 = mo.ui.slider(0, 90, step=1, value=45, label="angle of k₃ (°)", show_value=True)
    write3 = mo.ui.checkbox(value=True, label="write the third position")
    which = mo.ui.dropdown(options=["k₁", "k₂", "k₃"], value="k₃", label="query with")
    beta = mo.ui.slider(1, 40, step=1, value=1, label="sharpness β", show_value=True)
    mo.vstack([
        mo.hstack([angle1, angle2, angle3], justify="start", wrap=True),
        mo.hstack([write3, which, beta], justify="start", wrap=True),
    ])
    return angle1, angle2, angle3, beta, which, write3


@app.cell
def _(angle1, angle2, angle3, beta, math, which, write3):
    VALUES = [(2.0, 0.0), (0.0, 3.0), (1.0, 1.0)]

    def unit(degrees):
        r = math.radians(degrees)
        return (math.cos(r), math.sin(r))

    def dot(a, b):
        return a[0] * b[0] + a[1] * b[1]

    keys_all = [unit(angle1.value), unit(angle2.value), unit(angle3.value)]
    n = 3 if write3.value else 2
    keys, values = keys_all[:n], VALUES[:n]

    S = [[sum(v[r] * k[c] for k, v in zip(keys, values)) for c in range(2)] for r in range(2)]
    z = (sum(k[0] for k in keys), sum(k[1] for k in keys))

    def linear_read(q):
        num = (S[0][0] * q[0] + S[0][1] * q[1], S[1][0] * q[0] + S[1][1] * q[1])
        den = dot(z, q)
        return (num[0] / den, num[1] / den)

    def softmax_read(q):
        scores = [dot(q, k) for k in keys]
        top = max(scores)
        e = [math.exp(s - top) for s in scores]
        total = sum(e)
        w = [x / total for x in e]
        return (sum(wi * v[0] for wi, v in zip(w, values)),
                sum(wi * v[1] for wi, v in zip(w, values))), w

    labels = ["k₁", "k₂", "k₃"][:n]
    index = min(["k₁", "k₂", "k₃"].index(which.value), n - 1)
    k_query = keys[index]
    q = (beta.value * k_query[0], beta.value * k_query[1])
    soft_out, soft_w = softmax_read(q)
    lin_out = linear_read(q)
    target = values[index]
    lin_all = [linear_read(k) for k in keys]
    soft_path = [softmax_read((b * k_query[0], b * k_query[1]))[0] for b in range(1, 41)]
    return (
        index,
        keys,
        labels,
        lin_all,
        lin_out,
        n,
        soft_out,
        soft_path,
        soft_w,
        target,
        values,
    )


@app.cell
def _(
    index,
    keys,
    labels,
    lin_all,
    lin_out,
    math,
    mo,
    n,
    soft_out,
    soft_path,
    soft_w,
    target,
    values,
):
    W, H = 760, 470
    # Value-space panel on the left, key circle on the right.
    vx0, vy0, vs = 70, 410, 105        # origin and pixels per unit in value space
    cx0, cy0, cr = 560, 380, 150       # key-circle origin and radius
    colors = ["#2563eb", "#d97706", "#db2777"]

    def V(p):
        return (vx0 + vs * p[0], vy0 - vs * p[1])

    def dist(a, b):
        return math.hypot(a[0] - b[0], a[1] - b[1])

    parts = []
    # value-space axes
    parts.append(f'<line x1="{vx0}" y1="{vy0}" x2="{vx0 + 3.3 * vs}" y2="{vy0}" stroke="#9ca3af"/>')
    parts.append(f'<line x1="{vx0}" y1="{vy0}" x2="{vx0}" y2="{vy0 - 3.5 * vs}" stroke="#9ca3af"/>')
    for t in (1, 2, 3):
        x, _ = V((t, 0)); _, y = V((0, t))
        parts.append(f'<text x="{x}" y="{vy0 + 18}" font-size="12" text-anchor="middle" fill="#6b7280">{t}</text>')
        parts.append(f'<text x="{vx0 - 10}" y="{y + 4}" font-size="12" text-anchor="end" fill="#6b7280">{t}</text>')
    parts.append(f'<text x="{vx0 + 1.6 * vs}" y="{vy0 + 38}" font-size="13" text-anchor="middle" fill="#374151">Value space</text>')
    # linear outputs are always collinear: draw the line through o(k1), o(k2)
    a, b = lin_all[0], lin_all[1]
    if dist(a, b) > 1e-9:
        dx, dy = b[0] - a[0], b[1] - a[1]
        p1 = V((a[0] - 2 * dx, a[1] - 2 * dy)); p2 = V((a[0] + 3 * dx, a[1] + 3 * dy))
        parts.append(f'<clipPath id="vc"><rect x="{vx0}" y="{vy0 - 3.5 * vs}" width="{3.3 * vs}" height="{3.5 * vs}"/></clipPath>')
        parts.append(f'<line clip-path="url(#vc)" x1="{p1[0]:.1f}" y1="{p1[1]:.1f}" x2="{p2[0]:.1f}" y2="{p2[1]:.1f}" stroke="#10b981" stroke-dasharray="6 5" stroke-width="1.5"/>')
    # target Values
    for i in range(n):
        x, y = V(values[i])
        parts.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="7" fill="none" stroke="{colors[i]}" stroke-width="2.5"/>')
        parts.append(f'<text x="{x + 10:.1f}" y="{y - 9:.1f}" font-size="13" fill="{colors[i]}">v{"₁₂₃"[i]}</text>')
    # every linear read o(k_i)
    for i in range(n):
        x, y = V(lin_all[i])
        parts.append(f'<rect x="{x - 4:.1f}" y="{y - 4:.1f}" width="8" height="8" fill="#10b981" opacity="0.55"/>')
    # softmax trajectory for beta = 1..40
    pts = " ".join(f"{V(p)[0]:.1f},{V(p)[1]:.1f}" for p in soft_path)
    parts.append(f'<polyline points="{pts}" fill="none" stroke="#6366f1" stroke-width="1.5" opacity="0.5"/>')
    sx, sy = V(soft_out); lx, ly = V(lin_out)
    parts.append(f'<circle cx="{sx:.1f}" cy="{sy:.1f}" r="6" fill="#6366f1"/>')
    parts.append(f'<rect x="{lx - 6:.1f}" y="{ly - 6:.1f}" width="12" height="12" fill="#10b981"/>')

    # key circle
    parts.append(f'<path d="M {cx0 + cr} {cy0} A {cr} {cr} 0 0 0 {cx0} {cy0 - cr}" fill="none" stroke="#d1d5db" stroke-width="2"/>')
    parts.append(f'<line x1="{cx0}" y1="{cy0}" x2="{cx0 + cr + 20}" y2="{cy0}" stroke="#9ca3af"/>')
    parts.append(f'<line x1="{cx0}" y1="{cy0}" x2="{cx0}" y2="{cy0 - cr - 20}" stroke="#9ca3af"/>')
    for i in range(n):
        x, y = cx0 + cr * keys[i][0], cy0 - cr * keys[i][1]
        width = 4 if i == index else 2.5
        parts.append(f'<line x1="{cx0}" y1="{cy0}" x2="{x:.1f}" y2="{y:.1f}" stroke="{colors[i]}" stroke-width="{width}"/>')
        parts.append(f'<text x="{x + 6:.1f}" y="{y - 6:.1f}" font-size="13" fill="{colors[i]}">k{"₁₂₃"[i]}</text>')
    parts.append(f'<text x="{cx0 + cr / 2}" y="{cy0 + 38}" font-size="13" text-anchor="middle" fill="#374151">Key directions (unit length)</text>')

    svg = (f'<svg viewBox="0 0 {W} {H}" role="img" aria-label="Value-space comparison of Softmax and linear reads, '
           f'with the stored key directions" style="width:100%;height:auto;background:white;border-radius:10px;">'
           + "".join(parts) + "</svg>")

    err_soft = dist(soft_out, target)
    err_lin = dist(lin_out, target)
    weights = ", ".join(f"{w:.3f}" for w in soft_w)
    rows = "".join(
        f"<tr><td>{labels[i]}</td><td>({values[i][0]:.0f}, {values[i][1]:.0f})</td>"
        f"<td>({lin_all[i][0]:.3f}, {lin_all[i][1]:.3f})</td></tr>" for i in range(n))
    legend = f"""
    <div style="font-family: system-ui, sans-serif; color:#374151; font-size:14px; line-height:1.5;">
      <div style="display:flex; gap:1.4rem; flex-wrap:wrap; margin:.4rem 0;">
        <span><span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#6366f1"></span>
          Softmax read ({soft_out[0]:.3f}, {soft_out[1]:.3f}); distance to target {err_soft:.3f}; weights [{weights}]</span>
        <span><span style="display:inline-block;width:10px;height:10px;background:#10b981"></span>
          Linear read ({lin_out[0]:.3f}, {lin_out[1]:.3f}); distance to target {err_lin:.3f}</span>
      </div>
      <div>Faint purple curve: the Softmax read as β goes from 1 to 40. Dashed green line: every linear read
      o(kᵢ) lies on it whenever three Keys are written in two dimensions.</div>
      <table style="margin-top:.4rem; border-collapse:collapse;">
        <tr><th style="text-align:left;padding-right:1rem">Key</th><th style="text-align:left;padding-right:1rem">target Value</th>
        <th style="text-align:left">linear read with that Key</th></tr>{rows}
      </table>
    </div>"""
    mo.Html(svg + legend)
    return


@app.cell
def _(mo):
    mo.md(r"""
    Things to try:

    1. **Default setting.** Query $k_3$ and raise $\beta$. Softmax moves to $v_3$; the linear read
       does not move at all, because with $\phi(x)=x$ both $S(\beta q)$ and $z^\top(\beta q)$ scale by $\beta$.
    2. **Untick "write the third position".** With $k_1$ at 0° and $k_2$ at 90°, each Key reads back its own
       Value exactly. Now move $k_2$ towards $k_1$: the read for $k_1$ drifts away from $v_1$.
    3. **Write the third position again** and move any Key anywhere on the quarter circle. Three directions
       in two dimensions are always linearly dependent, so the three linear reads stay on one line.
       $v_1, v_2, v_3$ are not on one line, so at least one Key cannot read back its own Value exactly.
       Softmax, with distinct unit Keys, recovers each Value as $\beta$ grows.
    """)
    return


if __name__ == "__main__":
    app.run()
