🎭 Theater & Live Performance · instrument addressing

Arc Lamp Tuner

Fine-tune Qwen/Qwen3.5-4B on 55 address sheets so the model emits JSON rig addresses from plot.

SFT · Structured Output· format fine-tune
Section · Tinker

The kernel.

full primer →

The base model can't hold instrument addressing's structural rules under pressure; a short Tinker SFT run on schema-locked examples teaches it the shape so directors get valid output on the first try, every time.

Why this primitiveSFT format teaches address JSON via schema-masked target loss.

Kernel
Supervised fine-tuning on `(input, structured_output)` pairs — JSON, DSLs, chord charts, poetic forms, lesson plans. Same Tinker SFT loop as instruction tuning, but the loss mask covers a rigid target schema so the model learns the shape as much as the content.
Drives the UI as
a report page showing the target schema, base-model failures, and post-training generations that hold the shape
Appendix · Secrets

Required key.

TINKER_API_KEY
Single key for every Tinker post-training call — SFT, RL, DPO. Used ONLY at build time inside Lovable's Linux sandbox; the deployed Worker never touches Tinker.
open ↗

Add this in your Lovable project under Settings → Secrets before pasting the prompt below.

Appendix · Mega-prompt

The build prompt.

Paste into a fresh Lovable project. Make sure the key above is set first. read the build strategy →

Build "Arc Lamp Tuner" as a ONE-SHOT Lovable build. The participant has only
5 credits — this single message must produce a working report page in one turn.

CONCEPT
Fine-tune Qwen/Qwen3.5-4B on 55 address sheets so the model emits JSON rig addresses from plot.
Discipline: Theater & Live Performance (instrument addressing).
Kernel: SFT · Structured Output — format fine-tune.
Base model (Tinker id): Qwen/Qwen3-8B.
Why this kernel: SFT format teaches address JSON via schema-masked target loss.

SANDBOX-TRAINING PATTERN (READ THIS FIRST):
Tinker is Python-only. The deployed Lovable app runs on Cloudflare Workers,
which cannot run Python. The training script in this prompt therefore runs
ONCE, in Lovable's Linux build sandbox, DURING this build turn. It writes its
output to `src/data/run-artifact.json`. The deployed site imports that JSON
and renders it. Do NOT try to call `tinker` from a server function. Do NOT
`pip install tinker` inside `src/`. The training script lives at
`scripts/train.py` and is executed once, then its imports are gone.

SHARP EDGES (verified in production — the script below already handles all
three; do NOT "simplify" them away):
- `forward_backward` returns `metrics={"loss:sum": <raw sum>}`. There is NO
  `r.loss` attribute. Read `r.metrics["loss:sum"]` and divide by the
  supervised-token count for the batch to get a comparable per-token mean.
- Batch indexing MUST wrap with `%`. A slice like `data[a:b] or data[:4]`
  silently retrains the head of the dataset once indices run past the end.
- Use the `_async` SDK surface everywhere: `create_lora_training_client_async`,
  `create_sampling_client_async`, `forward_backward_async`, `optim_step_async`,
  `sample_async`, `save_weights_and_get_sampling_client_async`. Sync variants
  do not exist in the SDK version this pattern was validated against.
- Loss-curve SVG stroke: the shadcn/Tailwind v4 tokens in `src/styles.css` are
  defined as `oklch(...)` values, NOT raw HSL channels. Writing
  `stroke="hsl(var(--primary))"` on the `<path>` resolves to `hsl(oklch(...))`,
  which is invalid, and the line paints with no color (chart looks empty).
  Use `stroke="var(--primary)"` directly, or `stroke="currentColor"` on an
  element with `text-primary`. Use `strokeWidth={2.5}` with
  `strokeLinejoin="round"` for mobile legibility.

LOVABLE BUDGET (HARD CAP: ONE-SHOT, ~5 CREDITS TOTAL):
The participant has FIVE Lovable credits for the whole build. This prompt MUST
ship on the FIRST message with zero follow-ups. Engineer for that.
- ONE TanStack Start app, ONE route (`src/routes/index.tsx`). No nav, no auth.
- ONE data file: `src/data/run-artifact.json` — produced by running the
  Python training script BELOW in the sandbox during this build turn.
- ONE component surface: hero + hand-rolled SVG loss curve + sample gallery.
- NO database, NO Lovable Cloud, NO backend at runtime, NO auth, NO uploads.
- NO tests, NO docs pages, NO settings screens, NO theming toggles.
- Libraries: template defaults only. No chart lib — draw the loss curve as an
  SVG polyline.
- Keep the diff small enough to land in one build pass.

STEP 1 — write `scripts/train.py` exactly as below (adapt PAIRS / PROMPTS /
TRIPLES to real instrument addressing examples; keep 40–80 of them). Then run it once in the
sandbox with `python -m pip install -q tinker` + `python scripts/train.py`.
The script writes `src/data/run-artifact.json`.

```python
# scripts/train.py — SFT for structured output on instrument addressing
#   $ python -m pip install -q tinker
#   $ TINKER_API_KEY=... python scripts/train.py
# See SANDBOX-TRAINING PATTERN + SHARP EDGES above; the three verified fixes
# (loss:sum normalization, %-wrapped batch indices, *_async everywhere) are
# already encoded — do not remove.
import asyncio, json, pathlib, time, tinker
from tinker import types

BASE  = "Qwen/Qwen3-8B"
OUT   = pathlib.Path("src/data/run-artifact.json")
STEPS = 250
BATCH = 4
LR    = 1e-4
RANK  = 16
SEP   = "\n---\n"

# TARGETS carry the exact schema — the loss mask covers the whole target
# so the model learns the SHAPE, not just the content.
PAIRS = [
    {"input": "...prompt about instrument addressing...", "target": '{"field":"value"}'},
    # ~50 total, each with a valid JSON/DSL target for instrument addressing.
]

async def main():
    t0 = time.time()
    svc = tinker.ServiceClient()
    train = await svc.create_lora_training_client_async(base_model=BASE, rank=RANK)
    tok = train.get_tokenizer()

    def datum(inp: str, tgt: str) -> types.Datum:
        p = tok.encode(inp + SEP, add_special_tokens=False)
        t = tok.encode(tgt, add_special_tokens=False) + [tok.eos_token_id]
        ids = p + t
        return types.Datum(
            model_input=types.ModelInput.from_ints(tokens=ids),
            loss_fn_inputs=dict(target_tokens=ids[1:] + [tok.eos_token_id],
                                weights=[0]*len(p) + [1]*len(t)),
        )

    data = [datum(x["input"], x["target"]) for x in PAIRS]
    sup_counts = [
        len(tok.encode(x["target"], add_special_tokens=False)) + 1
        for x in PAIRS
    ]

    async def sample(cli, q: str) -> str:
        r = await cli.sample_async(
            prompt=types.ModelInput.from_ints(tokens=tok.encode(q + SEP, add_special_tokens=False)),
            num_samples=1,
            sampling_params=types.SamplingParams(max_tokens=200, temperature=0.4))
        return tok.decode(r.sequences[0].tokens)

    probes   = [x["input"] for x in PAIRS[:6]]
    baseline = await svc.create_sampling_client_async(base_model=BASE)
    before   = [await sample(baseline, q) for q in probes]

    losses = []
    for step in range(STEPS):
        start = (step * BATCH) % len(data)
        idxs  = [(start + k) % len(data) for k in range(BATCH)]
        batch = [data[i] for i in idxs]

        fb = await train.forward_backward_async(data=batch, loss_fn="cross_entropy")
        r  = await fb.result_async()
        loss_sum = float(r.metrics["loss:sum"])
        n_sup    = sum(sup_counts[i] for i in idxs)
        losses.append([step, loss_sum / max(1, n_sup)])
        await (await train.optim_step_async(types.AdamParams(learning_rate=LR))).result_async()

    save  = await train.save_weights_and_get_sampling_client_async(name="final")
    after = [await sample(save, q) for q in probes]

    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps({
        "idea": "theater-arc-lamp-tuner-16", "kernel": "sft-format", "base_model": BASE,
        "training": {"steps": STEPS, "lr": LR, "batch_size": BATCH, "rank": RANK,
                      "loss_curve": losses},
        "samples": [{"prompt": q, "before": b, "after": a}
                    for q, b, a in zip(probes, before, after)],
        "wall_time_seconds": round(time.time() - t0, 1),
    }, indent=2))

asyncio.run(main())
```

STEP 2 — write `src/routes/index.tsx` exactly as below. It imports the JSON
artifact produced above and renders the report (hero + hand-rolled SVG loss
curve + before/after gallery). No runtime API calls, no server functions.

```tsx
// src/routes/index.tsx — renders the JSON artifact produced by scripts/train.py
import { createFileRoute } from "@tanstack/react-router";
import artifact from "@/data/run-artifact.json";

/** Built during the Tinker Folio Hackathon organised by StreetKode Fam during Indian Krump Festival 14 */
export const Route = createFileRoute("/")({
  head: () => ({ meta: [{ title: `Arc Lamp Tuner — Tinker Folio` }] }),
  component: Report,
});

function LossCurve({ points }: { points: [number, number][] }) {
  if (!points.length) return null;
  const w = 800, h = 240, pad = 24;
  const maxLoss = Math.max(...points.map((p) => p[1]));
  const minLoss = Math.min(...points.map((p) => p[1]));
  const scaleX = (x: number) => pad + (x / (points.length - 1)) * (w - pad * 2);
  const scaleY = (y: number) =>
    h - pad - ((y - minLoss) / Math.max(1e-6, maxLoss - minLoss)) * (h - pad * 2);
  const d = points.map((p, i) => `${i === 0 ? "M" : "L"}${scaleX(i)},${scaleY(p[1])}`).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full h-auto border border-border bg-card">
      <path d={d} fill="none" stroke="hsl(var(--primary))" strokeWidth={2} />
    </svg>
  );
}

function Report() {
  const a = artifact as typeof artifact;
  return (
    <main className="max-w-5xl mx-auto px-6 py-16">
      <span className="text-xs tracking-[0.28em] uppercase text-primary">{a.kernel} · {a.base_model}</span>
      <h1 className="font-serif text-4xl sm:text-6xl mt-3 italic">Arc Lamp Tuner</h1>
      <p className="mt-4 text-muted-foreground max-w-2xl">Fine-tuned on {a.training.steps} steps. Report generated by the training script; no runtime API calls.</p>
      <section className="mt-10">
        <h2 className="text-lg uppercase tracking-[0.2em] mb-3">Loss curve</h2>
        <LossCurve points={a.training.loss_curve} />
      </section>
      <section className="mt-12 grid gap-6">
        <h2 className="text-lg uppercase tracking-[0.2em]">Before vs after</h2>
        {a.samples?.map((s, i) => (
          <article key={i} className="border border-border p-6">
            <div className="text-xs uppercase tracking-[0.2em] text-primary">Prompt</div>
            <p className="mt-1 whitespace-pre-wrap break-words">{s.prompt}</p>
            <div className="grid sm:grid-cols-2 gap-4 mt-4">
              <div><div className="text-xs uppercase text-muted-foreground">Base</div><p className="mt-1 text-sm whitespace-pre-wrap break-words">{s.before}</p></div>
              <div><div className="text-xs uppercase text-primary">Tuned</div><p className="mt-1 text-sm whitespace-pre-wrap break-words">{s.after}</p></div>
            </div>
          </article>
        ))}
      </section>
      <footer className="mt-16 text-xs uppercase tracking-[0.28em] text-muted-foreground">
        Built during the Tinker Folio Hackathon organised by StreetKode Fam during Indian Krump Festival 14
      </footer>
    </main>
  );
}
```

STACK
- TanStack Start, index route only. No auth, no DB, no Lovable Cloud.
- Tailwind + shadcn tokens; editorial look, gold accent on warm-cream.
- Footer renders the credit below (also present as JSDoc on the route).

KEY — only ONE secret is required at BUILD time:
1. `TINKER_API_KEY`. Sign up at https://tinker-console.thinkingmachines.ai,
   copy the key. This key is used by the Python training script that Lovable
   runs in its Linux build sandbox. The deployed Cloudflare Worker never
   touches Tinker — training already happened; the site renders the saved
   artifact. If you want to re-train later, re-run the script locally with
   `pip install tinker` and `export TINKER_API_KEY=...`.

BILLING GOTCHA (WILL BLOCK YOU IF SKIPPED):
Tinker rejects training with HTTP 402 "Access is blocked due to billing
status" when the account has no payment method attached — even after a
balance top-up. Before running the script:
  1. Visit https://tinker.thinkingmachines.ai/billing/balance
  2. Attach a card AND confirm account status shows active.
  3. Wait ~1–2 minutes for propagation.
If the script prints the 402, this is why. Do not add retry loops — fix
the account state.

CREDIT (must appear in the report footer AND as JSDoc on the route):
Built during the Tinker Folio Hackathon organised by StreetKode Fam during Indian Krump Festival 14
Appendix · Market

Market sizing.

TAM
$30B
performance
SAM
$700M
lighting hardware
SOM
$9M
3K techs

Indicative figures for hackathon pitches — refine with your own research before raising.

See also

Adjacent entries.