// TRL Recipes: progressive enhancement over pre-rendered static pages + catalog.json / per-recipe recipe.json. // - Root index.html (data-page="home") handles Home, interactive #/browse filtering, Cmd+K search, and redirects // legacy #/[/] and ?recipe=/ links to their static HTML pages. // - Static project pages (data-page="project") and recipe pages (data-page="recipe") are fully pre-rendered in HTML // by build.py; this script hydrates the interactive command builder, file modal, Cmd+K palette, theme toggle, // smooth scrolling, and Hugging Face Space parent-frame URL sync. const $ = (sel, el = document) => el.querySelector(sel); const $$ = (sel, el = document) => [...el.querySelectorAll(sel)]; const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); const APP_EL = $("#app"); const PAGE_KIND = APP_EL?.dataset.page || "home"; const ROOT = APP_EL?.dataset.root || ""; const store = { get(key) { try { return localStorage.getItem(key); } catch { return null; } }, set(key, value) { try { localStorage.setItem(key, value); } catch {} }, }; function syncParentUrl(hash) { if (window.parent === window) return; try { window.parent.postMessage({ hash }, "https://huggingface.co"); } catch {} } // One line per trainer, shown as the tooltip of its filter on the home page const TRAINERS = { AsyncGRPOTrainer: { blurb: "GRPO with generation and training decoupled: a vLLM server keeps producing rollouts while the trainer steps, for long agentic and multi-turn rollouts.", }, SFTTrainer: { blurb: "Supervised fine-tuning on conversations or completions, with full fine-tuning, LoRA or QLoRA.", }, }; // What people outside the recipe's team can run on: their own GPU, or HF Jobs const PLATFORMS = { local: "Local machine", hf_jobs: "HF Jobs" }; const PLATFORM_SHORT = { local: "Local", hf_jobs: "HF Jobs" }; const TASKS = { train: "Train", eval: "Evaluate" }; const GPUS = [ ["T4", /\bt4(?:x\d+|\b)/i], ["L4", /\bl4(?:x\d+|\b)/i], ["A10G", /\ba10g(?:x\d+|\b)/i], ["L40S", /\bl40s(?:x\d+|\b)/i], ["A100", /\ba100(?:x\d+|\b)/i], ["H100", /\bh100(?:x\d+|\b)/i], ["H200", /\bh200(?:x\d+|\b)/i], ["B200", /\bb200(?:x\d+|\b)/i], ["B300", /\bb300(?:x\d+|\b)/i], ]; const gpuRank = (name) => (name.startsWith("Any GPU") ? -1 : GPUS.findIndex(([n]) => n === name)); function gpusOf(r) { if (Array.isArray(r.gpus)) return r.gpus; const out = new Set(); for (const [platform, text] of Object.entries(r.hardware || {})) { if (!PLATFORMS[platform]) continue; const named = GPUS.filter(([, re]) => re.test(text)).map(([n]) => n); named.forEach((n) => out.add(n)); const memory = /(\d+)\s*GB/i.exec(text); if (!named.length && memory) out.add(`Any GPU, ${memory[1]} GB+`); } return [...out].sort((a, b) => gpuRank(a) - gpuRank(b)); } const platformsOf = (r) => { if (Array.isArray(r.platforms)) return r.platforms; return Object.keys(PLATFORMS).filter((p) => r.files?.[`train_${p}.sh`] || r.files?.[`eval_${p}.sh`]); }; const trlSource = (r) => { if (Array.isArray(r.trl_source)) return r.trl_source; if (!r.trl) return []; if (r.trl.fork || r.trl.patch) return ["TRL fork"]; return r.trl.commit ? ["TRL main"] : ["Released TRL"]; }; const usesBucket = (r, st) => st.platform === "hf_jobs" && (r.files?.[`${st.task}_${st.platform}.sh`] || "").includes("BUCKET="); let CATALOG = null; let lastPath = null; // ---------- helpers ---------- const ACRONYMS = { sft: "SFT", qlora: "QLoRA", lora: "LoRA", grpo: "GRPO", dpo: "DPO", rl: "RL", rlhf: "RLHF", vlm: "VLM" }; const pretty = (slug) => CATALOG?.projects?.find((p) => p.id === slug)?.title || slug .split(/[-_]+/) .map((word) => ACRONYMS[word.toLowerCase()] || word) .join(" ") .replace(/^./, (c) => c.toUpperCase()); const spaceName = () => (CATALOG?.space || "trl-lib/trl-recipes").split("/")[1]; const SPACE_URL = () => `https://huggingface.co/spaces/${CATALOG?.space || "trl-lib/trl-recipes"}`; const spaceUrl = (path, kind = "blob") => `${SPACE_URL()}/${kind}/main/${path}`; const rawUrl = (path) => `${SPACE_URL()}/resolve/main/${path}`; const hosted = (item) => `recipes/${item.id}`; const projectOf = (r) => CATALOG?.projects?.find((p) => p.id === r.project); const recipesOf = (p) => (CATALOG?.recipes || []).filter((r) => r.project === p.id); const itemHref = (item) => ROOT + (item.urls?.rel_html || item.guide_url || `recipes/${item.id}/index.html`); const browseHref = (key, value) => `${ROOT}index.html#/browse?${key}=${encodeURIComponent(value)}`; function fmt(value) { if (Array.isArray(value)) return value.join(", "); if (typeof value === "number" && value !== 0 && Math.abs(value) < 1e-3) return value.toExponential(); if (typeof value === "number") return value.toLocaleString("en-US"); if (typeof value === "object" && value !== null) return JSON.stringify(value); return String(value); } function avatar(r, size = "md") { return r.avatar ? `` : `${esc((r.org || "?")[0])}`; } const highlight = (text, language) => { try { return window.hljs ? hljs.highlight(text, { language }).value : esc(text); } catch { return esc(text); } }; const langOf = (name) => ({ sh: "bash", yaml: "yaml", yml: "yaml", patch: "diff", diff: "diff", py: "python", json: "json", md: "markdown" })[ name.split(".").pop() ] || "plaintext"; async function copyText(text, button) { try { await navigator.clipboard.writeText(text); } catch { const area = Object.assign(document.createElement("textarea"), { value: text }); document.body.append(area); area.select(); document.execCommand("copy"); area.remove(); } if (button) { const label = button.dataset.label || button.textContent; button.dataset.label = label; button.textContent = "Copied"; button.classList.add("is-done"); setTimeout(() => { button.textContent = label; button.classList.remove("is-done"); }, 1400); } } // ---------- catalog fragments (for home & #/browse) ---------- function chips(r) { const hp = r.hyperparameters_summary || r.hyperparameters || {}; const out = r.trainers.map((t) => `${esc(t)}`); const gpus = gpusOf(r); if (gpus.length) { const tip = Object.entries(r.hardware || {}) .map(([p, v]) => `${PLATFORMS[p] || p}: ${v}`) .join("\n"); out.push(`${esc(gpus.join(" · "))}`); } if (r.trl?.fork) out.push(`TRL fork`); if (hp.lora_r) out.push(`LoRA r${esc(hp.lora_r)}`); if (hp.max_steps) out.push(`${esc(fmt(hp.max_steps))} steps`); const harnesses = r.harnesses || r.meta?.harnesses; if (harnesses?.length) out.push(`${esc(harnesses.join(" · "))}`); return out.join(""); } function platformBadges(r) { const verified = r.verified || r.builder?.verified || {}; return Object.keys(PLATFORMS) .filter((p) => r.hardware?.[p]) .map( (p) => `${PLATFORM_SHORT[p]}` ) .join(""); } function card(r) { const modelId = r.model_id || r.meta?.model_id || ""; const [org, model] = modelId.split("/"); const desc = r.description ?? r.meta?.description ?? ""; const heading = r.is_guide ? r.title || model : model; return `
${avatar(r)}
${esc(heading)}${esc( r.is_guide ? modelId : org )}
${chips(r)}

${esc(desc)}

${esc(r.is_guide ? r.title : pretty(r.project))}${platformBadges( r )}
`; } function projectTile(p) { const recipes = recipesOf(p); const orgs = [...new Map(recipes.map((r) => [r.org, r])).values()]; return ` ${esc(p.trainers.join(" → "))} ${esc(p.title || pretty(p.name))}
${recipes.map((r) => `${esc(r.name)}`).join("")}

${esc(p.summary || "")}

${orgs.map((r) => avatar(r, "sm")).join("")} ${recipes.length} recipe${recipes.length === 1 ? "" : "s"} →
`; } const trainerNames = () => [...new Set((CATALOG?.recipes || []).flatMap((r) => r.trainers))].sort(); const FILTERS = [ ["project", "Project", (r) => [r.project]], ["trainer", "Trainer", (r) => r.trainers], ["hardware", "Hardware", gpusOf, (a, b) => gpuRank(a) - gpuRank(b)], ["platform", "Runs on", platformsOf, (a, b) => Object.keys(PLATFORMS).indexOf(a) - Object.keys(PLATFORMS).indexOf(b)], [ "verified", "Ran as written on", (r) => Object.keys(r.verified || {}).filter((p) => r.verified[p]), ], ["trl", "TRL", trlSource], ["harness", "Harness", (r) => r.harnesses || []], ["tag", "Tag", (r) => r.tags || []], ]; const facetLabel = (key, v) => key === "project" ? CATALOG.projects.find((p) => p.id === v)?.title || pretty(v) : key === "platform" || key === "verified" ? PLATFORMS[v] : v; function facetLinks(key, label) { const [, , get, order] = FILTERS.find(([k]) => k === key); const counts = new Map(); for (const r of CATALOG.recipes) for (const v of get(r)) counts.set(v, (counts.get(v) || 0) + 1); const values = [...counts.keys()].sort(order); return `
${label}
${values .map( (v) => `${esc(facetLabel(key, v))} ${counts.get(v)}` ) .join("")}
`; } function pageHome() { const trainers = trainerNames(); document.title = "TRL Recipes: reproducible training runs with TRL"; return `

TRL Recipes

Pick a project and a model, choose where it runs, copy the command that reproduces the run.

Each recipe has the exact launch scripts of a real training run with TRL, for HF Jobs or your own GPU, plus its evaluation, hyperparameters and the TRL changes it depends on. Nothing to clone: the commands fetch what they run from this Space. Machine-readable indexes: llms.txt and catalog.json.

${CATALOG.recipes.length} recipes${CATALOG.projects.length} project${ CATALOG.projects.length === 1 ? "" : "s" }${trainers.length} trainer${trainers.length === 1 ? "" : "s"}
${CATALOG.projects.map(projectTile).join("")}

All recipes

llms.txt →
${CATALOG.recipes.map(card).join("")}

Browse by

${facetLinks("hardware", "Hardware")}${facetLinks("platform", "Runs on")}${facetLinks("trainer", "Trainer")}${facetLinks("trl", "TRL")}
`; } function haystack(r) { return [ r.model_id, r.name, r.title, r.project, pretty(r.project), ...r.trainers, ...gpusOf(r), r.description, ...(r.tags || []), ...(r.harnesses || []), ] .filter(Boolean) .join(" ") .toLowerCase(); } function pageBrowse(query) { document.title = "Browse recipes · TRL Recipes"; const selected = Object.fromEntries(FILTERS.map(([key]) => [key, (query.get(key) || "").split(",").filter(Boolean)])); const text = (query.get("q") || "").toLowerCase(); const matches = CATALOG.recipes.filter( (r) => FILTERS.every(([key, , get]) => !selected[key].length || get(r).some((v) => selected[key].includes(v))) && (!text || haystack(r).includes(text)) ); const groups = FILTERS.map(([key, label, get, order]) => { const values = [...new Set(CATALOG.recipes.flatMap(get))].sort(order); return `
${label}
${values .map( (v) => `` ) .join("")}
`; }).join(""); return `

Browse all recipes

Filter ${CATALOG.recipes.length} recipes by project, trainer, the GPU they need, where they run and the TRL they use.

${groups}
${matches.length} recipe${matches.length === 1 ? "" : "s"}
${matches.length ? `
${matches.map(card).join("")}
` : `

No recipe matches these filters.

`}`; } function bindBrowse(query) { for (const button of $$("[data-filter]")) { button.addEventListener("click", () => { const key = button.dataset.filter; const values = new Set((query.get(key) || "").split(",").filter(Boolean)); values.has(button.dataset.value) ? values.delete(button.dataset.value) : values.add(button.dataset.value); values.size ? query.set(key, [...values].join(",")) : query.delete(key); location.hash = `#/browse${query.toString() ? "?" + query : ""}`; }); } const input = $("#browse-q"); input?.addEventListener("input", () => { input.value ? query.set("q", input.value) : query.delete("q"); const nextHash = `#/browse${query.toString() ? "?" + query : ""}`; history.replaceState(null, "", nextHash); syncParentUrl(nextHash); const text = input.value.toLowerCase(); const keep = new Set(CATALOG.recipes.filter((r) => !text || haystack(r).includes(text)).map(itemHref)); let shown = 0; for (const a of $$(".grid .card")) { const visible = keep.has(a.getAttribute("href")); a.hidden = !visible; shown += visible; } $(".result-count").textContent = `${shown} recipe${shown === 1 ? "" : "s"}`; }); } // ---------- command builder (hydrates #builder on static recipe pages) ---------- function resolveOptions(r, st) { const out = []; const values = {}; for (const option of r.builder?.[st.task] || []) { if (option.platforms && !option.platforms.includes(st.platform)) continue; if (option.when && !Object.entries(option.when).every(([k, v]) => values[k] === v)) continue; if (option.unless && Object.entries(option.unless).some(([k, v]) => values[k] === v)) continue; let value = st.values[option.env]; let adjusted = false; if (option.choices) { const choices = option.choices.map((c) => (typeof c === "string" ? { value: c } : c)); const allowed = choices.filter((c) => !c.platforms || c.platforms.includes(st.platform)).map((c) => c.value); if (option.multi) { const picked = (value ?? allowed.join(",")).split(",").filter((v) => allowed.includes(v)); value = picked.length ? picked : [allowed[0]]; } else if (!allowed.includes(value)) { adjusted = value !== undefined; value = allowed[0]; } out.push({ option, value, choices, allowed, adjusted }); } else { value = value ?? option.default ?? ""; out.push({ option, value }); } values[option.env] = value; } return out; } const shellQuote = (v) => (/^[\w@%+=:,./-]+$/.test(v) ? v : `"${String(v).replace(/(["\\`])/g, "\\$1")}"`); function directJob(r, task) { const sh = r.files?.[`${task}_hf_jobs.sh`]; if (!sh || /hf buckets|--volume/.test(sh)) return null; const line = sh .replace(/\\\n\s*/g, " ") .split("\n") .find((l) => l.trim().startsWith("hf jobs uv run ")); const m = line && !/\[@\]|\$\(/.test(line) && /^\s*hf jobs uv run (.*?)"\$SCRIPTS\/([\w.-]+\.py)" -- (.*)$/.exec(line); const shared = r.shared_files || projectOf(r)?.shared_files || []; if (!m || !shared.includes(m[2])) return null; const defaults = {}; for (const [, k, op, v] of sh.matchAll(/^(\w+)="\$\{\1:([-?])([^}]*)\}"/gm)) defaults[k] = op === "-" ? v : null; const vars = new Set([...`${m[1]} ${m[3]}`.matchAll(/\$\{?(\w+)/g)].map((x) => x[1])); const url = rawUrl(`recipes/${r.project}/scripts/${m[2]}`); return { flags: m[1].trim().replace(/\s+/g, " "), script: m[2], url, args: m[3].trim().replace(/\s+/g, " "), defaults, vars }; } function buildCommand(r, st, resolved) { const script = `${st.task}_${st.platform}.sh`; const env = []; for (const { option, value, allowed } of resolved) { if (option.multi) { if (value.length < allowed.length) env.push([option.hf_jobs_env || option.env, value.join(" ")]); } else if (value !== "" && value != null) env.push([option.env, value]); } if (st.task === "train" && st.smoke) env.push(["MAX_STEPS", "2"]); if (usesBucket(r, st)) env.push(["BUCKET", st.bucket || "/"]); const job = st.platform === "hf_jobs" && st.launch === "url" ? directJob(r, st.task) : null; if (job && env.every(([k]) => job.vars.has(k))) { const values = Object.fromEntries(env); const fill = (text) => text.replace(/"?\$\{?(\w+)\}?"?/g, (_, k) => { const v = values[k] ?? job.defaults[k]; return v == null ? `<${k}>` : shellQuote(v); }); return { script, direct: job, text: [`hf jobs uv run ${fill(job.flags)} \\`, ` ${job.url} -- \\`, ` ${fill(job.args)}`].join("\n") }; } const assigns = env.map(([k, v]) => `${k}=${shellQuote(v)}`); const dir = spaceName(); const space = r.space || CATALOG?.space || "trl-lib/trl-recipes"; const lines = [ `hf download ${space} --repo-type space --include "recipes/${r.project}/*" --local-dir ${dir}`, `cd ${dir}/${hosted(r)}`, ]; if (assigns.length > 1) lines.push(...assigns.map((a) => `${a} \\`), `bash ${script}`); else lines.push([...assigns, "bash", script].join(" ")); return { script, text: lines.join("\n") }; } function builderState(r, query) { const verified = r.builder?.verified || {}; const platforms = Object.keys(PLATFORMS).filter((p) => r.files?.[`train_${p}.sh`] || r.files?.[`eval_${p}.sh`]); const defaultPlatform = platforms.find((p) => verified[p]) || platforms[0]; const values = {}; for (const [k, v] of query) if (/^[A-Z][A-Z0-9_]*$/.test(k)) values[k] = v; const task = TASKS[query.get("task")] ? query.get("task") : "train"; const platform = platforms.includes(query.get("platform")) ? query.get("platform") : defaultPlatform; const launch = query.get("launch") === "files" ? "files" : "url"; return { task, platform, platforms, values, launch, smoke: query.get("smoke") === "1", bucket: query.get("bucket") || "", tab: "command" }; } function caveats(r, st, direct) { const out = []; if (r.trl?.fork) out.push(`It needs a TRL fork, not a release from PyPI: see TRL version.`); const sh = direct ? "" : r.files?.[`${st.task}_${st.platform}.sh`] || ""; for (const [, k, v] of sh.matchAll(/^(BUCKET|\w*SPACE_ID)="\$\{\1:-([\w.-]+\/[\w.-]+)\}"/gm)) { if (k === "BUCKET" && usesBucket(r, st) && st.bucket) continue; out.push( `${k} defaults to ${esc(v)}, which belongs to the recipe's authors: ${ k === "BUCKET" && usesBucket(r, st) ? "set Bucket to one in your namespace" : `prefix the command with ${k}=<you>/<name>` }.` ); } return out; } function builderQuery(st, resolved) { const q = new URLSearchParams({ task: st.task, platform: st.platform }); for (const { option, value } of resolved) { const v = Array.isArray(value) ? value.join(",") : value; if (v !== "" && v !== (option.default ?? "")) q.set(option.env, v); } if (st.smoke && st.task === "train") q.set("smoke", "1"); if (st.bucket && st.platform === "hf_jobs") q.set("bucket", st.bucket); if (st.launch === "files" && st.platform === "hf_jobs") q.set("launch", "files"); return q; } function segment(name, items, current, disabled = {}) { return `
${items .map( ([value, label]) => `` ) .join("")}
`; } function renderBuilder(r, st) { const el = $("#builder"); if (!el) return; if (!st.platforms.length) { const code = $("#command-code", el); const btn = $("#copy-command", el); if (btn && code) btn.onclick = (e) => copyText(code.textContent, e.currentTarget); syncParentUrl(`#/${r.id}`); return; } if (!r.files?.[`${st.task}_${st.platform}.sh`]) st.task = st.task === "train" ? "eval" : "train"; const resolved = resolveOptions(r, st); const hasTask = (t) => r.files?.[`${t}_${st.platform}.sh`]; const disabledTasks = Object.fromEntries(Object.keys(TASKS).filter((t) => !hasTask(t)).map((t) => [t, "No script for this platform"])); const verified = r.builder?.verified?.[st.platform]; const rows = [ ["Task", segment("task", Object.entries(TASKS), st.task, disabledTasks)], ["Run on", segment("platform", st.platforms.map((p) => [p, PLATFORMS[p]]), st.platform)], ]; if (st.platform === "hf_jobs" && directJob(r, st.task)) rows.push(["Launch", segment("launch", [["url", "One command"], ["files", "From the recipe files"]], st.launch)]); for (const { option, value, choices, allowed } of resolved) { if (option.choices) { const disabled = Object.fromEntries( choices.filter((c) => !allowed.includes(c.value)).map((c) => [c.value, `Not available on ${PLATFORMS[st.platform]}`]) ); const body = option.multi ? `
${choices .map( (c) => `` ) .join("")}
` : segment(`opt-${option.env}`, choices.map((c) => [c.value, c.value]), value, disabled); rows.push([option.label, body]); } else { rows.push([ option.label, ``, ]); } } const extras = []; if (st.task === "train") extras.push( `` ); if (usesBucket(r, st)) extras.push( `` ); if (extras.length) rows.push(["Options", `
${extras.join("")}
`]); const adjusted = resolved.filter((x) => x.adjusted); const { direct } = buildCommand(r, st, resolved); const blockers = caveats(r, st, direct); el.innerHTML = `

Command builder

${verified ? "Ran as written" : "Not run as written yet"}
${rows.map(([label, body]) => `
${esc(label)}${body}
`).join("")}
${adjusted.length ? `

${adjusted.map((x) => `${esc(x.option.label)} changed to ${esc(x.value)}: the previous value isn't available on ${PLATFORMS[st.platform]}.`).join(" ")}

` : ""} ${blockers.length ? `
Before you run
    ${blockers.map((b) => `
  • ${b}
  • `).join("")}
` : ""}

${ st.platform === "local" ? `Runs on this machine with uv, which installs the dependencies. ${ r.builder?.local_note?.[st.task] || `Needs ${esc(r.hardware?.local || "a GPU")}. Outputs go to ./outputs.` }` : direct ? `Needs the hf CLI logged in (hf auth login) and nothing else: the job fetches ${esc( direct.script )} from this Space. The job is submitted detached: follow it with hf jobs logs <job id>.` : usesBucket(r, st) ? `Needs the hf CLI logged in, and a bucket the job mounts on /outputs. The script uploads the files the job reads, then submits it detached.` : `Needs the hf CLI logged in. The job is submitted detached: follow it with hf jobs logs <job id>.` }${verified ? "" : ` These ${PLATFORMS[st.platform]} scripts have not been run as written yet.`}

`; const rerender = () => renderBuilder(r, st); for (const b of $$("[data-task]", el)) b.onclick = () => ((st.task = b.dataset.task), rerender()); for (const b of $$("[data-launch]", el)) b.onclick = () => ((st.launch = b.dataset.launch), rerender()); for (const b of $$("[data-platform]", el)) b.onclick = () => { st.platform = b.dataset.platform; if (!r.files?.[`${st.task}_${st.platform}.sh`]) st.task = st.task === "train" ? "eval" : "train"; rerender(); }; for (const { option } of resolved) { for (const b of $$(`[data-opt-${option.env.toLowerCase()}]`, el)) b.onclick = () => ((st.values[option.env] = b.getAttribute(`data-opt-${option.env.toLowerCase()}`)), rerender()); } for (const b of $$("[data-multi]", el)) b.onclick = () => { const current = resolveOptions(r, st).find((x) => x.option.env === b.dataset.multi).value; const next = current.includes(b.dataset.value) ? current.filter((v) => v !== b.dataset.value) : [...current, b.dataset.value]; if (!next.length) return; st.values[b.dataset.multi] = next.join(","); rerender(); }; for (const input of $$("[data-input]", el)) input.oninput = () => ((st.values[input.dataset.input] = input.value), updateOutput(r, st)); const smoke = $("[data-smoke]", el); if (smoke) smoke.onchange = () => ((st.smoke = smoke.checked), rerender()); const bucket = $("[data-bucket]", el); if (bucket) bucket.oninput = () => ((st.bucket = bucket.value.trim()), updateOutput(r, st)); for (const b of $$("[data-tab]", el)) b.onclick = () => ((st.tab = b.dataset.tab), updateOutput(r, st)); $("#copy-command", el).onclick = (e) => copyText(st.tab === "command" ? st.commandText : r.files[st.scriptName], e.currentTarget); updateOutput(r, st); } function updateOutput(r, st) { const resolved = resolveOptions(r, st); const { script, text } = buildCommand(r, st, resolved); st.commandText = text; st.scriptName = script; const hardware = r.hardware?.[st.platform] || ""; const parts = [TASKS[st.task], PLATFORMS[st.platform], st.task === "train" ? hardware : ""]; for (const { option, value } of resolved) if (option.choices) parts.push(Array.isArray(value) ? value.join(", ") : value); if (st.task === "train" && st.smoke) parts.push("smoke run"); $("#builder-summary").textContent = parts.filter(Boolean).join(" · "); $("#script-tab").textContent = script; for (const tab of $$("[data-tab]")) tab.classList.toggle("is-on", tab.dataset.tab === st.tab); const code = $("#command-code"); const body = st.tab === "command" ? text : r.files[script] || ""; code.innerHTML = highlight(body, "bash"); code.parentElement.classList.toggle("is-script", st.tab === "script"); const q = builderQuery(st, resolved).toString(); history.replaceState(null, "", q ? `?${q}` : location.pathname); syncParentUrl(`#/${r.id}${q ? `?${q}` : ""}`); } // ---------- modal and palette ---------- function openFile(text, name, path) { $("#modal-title").textContent = name; $("#modal-code").innerHTML = highlight(text, langOf(name)); $("#modal-github").href = spaceUrl(path); $("#modal-copy").onclick = (e) => copyText(text, e.currentTarget); $("#modal").hidden = false; document.body.classList.add("no-scroll"); } let paletteIndex = 0; function paletteItems(text) { if (!CATALOG) return []; const tokens = text.toLowerCase().split(/\s+/).filter(Boolean); const match = (s) => tokens.every((t) => s.includes(t)); const recipes = CATALOG.recipes.filter((r) => match(haystack(r))).map((r) => ({ href: itemHref(r), html: `${avatar(r, "sm")}${esc(r.is_guide ? r.title : r.model_id)}${esc( r.trainers.join(", ") )} · ${esc(r.is_guide ? r.title : pretty(r.project))}Recipe`, })); const projects = CATALOG.projects .filter((p) => match(`${p.title || ""} ${p.name} ${pretty(p.name)} ${p.trainers.join(" ")} ${p.summary || ""}`.toLowerCase())) .map((p) => ({ href: itemHref(p), html: `${esc(p.name[0].toUpperCase())}${esc( p.title || pretty(p.name) )}${esc(p.trainers.join(", "))}Project`, })); const trainers = trainerNames() .filter((t) => match(`${t} ${TRAINERS[t]?.blurb || ""}`.toLowerCase())) .map((t) => ({ href: browseHref("trainer", t), html: `${esc(t)}${ CATALOG.recipes.filter((r) => r.trainers.includes(t)).length } recipesTrainer`, })); return [...trainers, ...projects, ...recipes]; } function renderPalette() { const items = paletteItems($("#palette-input").value); paletteIndex = Math.min(paletteIndex, Math.max(items.length - 1, 0)); $("#palette-results").innerHTML = items.length ? items.map((it, i) => `
  • ${it.html}
  • `).join("") : `
  • No recipe or project matches.
  • `; } function openPalette() { $("#palette").hidden = false; document.body.classList.add("no-scroll"); const input = $("#palette-input"); input.value = ""; paletteIndex = 0; renderPalette(); input.focus(); } function closeOverlays() { $("#palette")?.setAttribute("hidden", ""); $("#modal")?.setAttribute("hidden", ""); document.body.classList.remove("no-scroll"); } // ---------- lookup & routing ---------- function findProject(slug) { const s = slug.toLowerCase(); return CATALOG.projects.find((p) => p.id.toLowerCase() === s); } function findRecipe(id) { const s = id.toLowerCase(); return CATALOG.recipes.find((r) => r.id.toLowerCase() === s || r.name.toLowerCase() === s); } function renderHomeRouter() { // Support ?recipe=/ and ?project= forwarded by huggingface.co/spaces/trl-lib/trl-recipes const search = new URLSearchParams(location.search); if (search.has("recipe")) { const rec = findRecipe(search.get("recipe")); if (rec) { search.delete("recipe"); const qs = search.toString(); return location.replace(`${itemHref(rec)}${qs ? `?${qs}` : ""}`); } } if (search.has("project")) { const proj = findProject(search.get("project")); if (proj) return location.replace(itemHref(proj)); } const hash = location.hash.slice(1) || "/"; const cut = hash.indexOf("?"); const path = decodeURIComponent(cut < 0 ? hash : hash.slice(0, cut)); const query = new URLSearchParams(cut < 0 ? "" : hash.slice(cut + 1)); const parts = path.split("/").filter(Boolean); closeOverlays(); if (!parts.length) { if (lastPath !== null) APP_EL.innerHTML = pageHome(); syncParentUrl("#/"); } else if (parts[0] === "browse") { APP_EL.innerHTML = pageBrowse(query); bindBrowse(query); syncParentUrl(`#/browse${query.toString() ? "?" + query : ""}`); } else if (trainerNames().some((t) => t.toLowerCase() === parts[0].toLowerCase())) { const trainer = trainerNames().find((t) => t.toLowerCase() === parts[0].toLowerCase()); if (parts.length === 1) return location.replace(`#/browse?trainer=${encodeURIComponent(trainer)}`); const rest = parts.slice(1).join("/"); const rec = findRecipe(rest); if (rec) return location.replace(`${itemHref(rec)}${query.toString() ? `?${query}` : ""}`); const proj = findProject(parts[1]); if (proj) return location.replace(itemHref(proj)); } else if (parts.length === 1 && findProject(parts[0])) { return location.replace(itemHref(findProject(parts[0]))); } else if (parts.length === 2 && findRecipe(parts.join("/"))) { const rec = findRecipe(parts.join("/")); return location.replace(`${itemHref(rec)}${query.toString() ? `?${query}` : ""}`); } else { document.title = "Not found · TRL Recipes"; APP_EL.innerHTML = `

    Recipe not found

    Nothing lives at ${esc( path )}. Browse all recipes →

    `; } if (path !== lastPath && lastPath !== null) window.scrollTo(0, 0); lastPath = path; } function initChrome() { const theme = store.get("theme"); if (theme) document.documentElement.dataset.theme = theme; $("#theme-toggle").onclick = () => { const current = document.documentElement.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"); const next = current === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = next; store.set("theme", next); }; $("#search-trigger").onclick = openPalette; document.addEventListener("click", (e) => { const target = e.target.closest("[data-scroll], [data-open-palette], [data-close]"); if (!target) return; if (target.hasAttribute("data-open-palette")) openPalette(); else if (target.hasAttribute("data-close")) closeOverlays(); else { e.preventDefault(); document.getElementById(target.dataset.scroll)?.scrollIntoView({ behavior: "smooth", block: "start" }); } }); document.addEventListener("keydown", (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); $("#palette").hidden ? openPalette() : closeOverlays(); } else if (e.key === "Escape") closeOverlays(); else if (e.key === "/" && !/INPUT|TEXTAREA/.test(document.activeElement.tagName)) { e.preventDefault(); openPalette(); } }); const input = $("#palette-input"); input.addEventListener("input", () => ((paletteIndex = 0), renderPalette())); input.addEventListener("keydown", (e) => { const links = $$("#palette-results a"); if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); paletteIndex = (paletteIndex + (e.key === "ArrowDown" ? 1 : -1) + links.length) % Math.max(links.length, 1); renderPalette(); $("#palette-results a.is-active")?.scrollIntoView({ block: "nearest" }); } else if (e.key === "Enter" && links[paletteIndex]) { location.href = links[paletteIndex].href; closeOverlays(); } }); } function highlightStaticBlocks() { if (!window.hljs) return; for (const code of $$(".prose pre code, #trl pre code")) hljs.highlightElement(code); } // ---------- bootstrap ---------- initChrome(); fetch(`${ROOT}catalog.json`) .then((response) => response.json()) .then((catalog) => { CATALOG = catalog; const note = $("#footer-note"); if (note) note.textContent = `${catalog.recipes.length} recipes, built ${catalog.generated_at}.`; if (PAGE_KIND === "home") { window.addEventListener("hashchange", renderHomeRouter); renderHomeRouter(); } else if (PAGE_KIND === "project") { highlightStaticBlocks(); syncParentUrl(`#/${APP_EL.dataset.project}`); } else if (PAGE_KIND === "recipe") { highlightStaticBlocks(); fetch("recipe.json") .then((res) => res.json()) .then((recipe) => { const st = builderState(recipe, new URLSearchParams(location.search)); renderBuilder(recipe, st); const copyBtn = $("#copy-link"); if (copyBtn) copyBtn.onclick = (e) => copyText(location.href, e.currentTarget); for (const b of $$("[data-view]")) { b.onclick = () => openFile(recipe.files[b.dataset.view], b.dataset.view, `${hosted(recipe)}/${b.dataset.view}`); } }) .catch(() => {}); } }) .catch(() => {});