Spaces:
Running
Running
File size: 39,354 Bytes
9b49dba 874bff8 9b49dba 874bff8 9b49dba ec02119 874bff8 9b49dba ec02119 874bff8 ec02119 9b49dba ec02119 9b49dba ec02119 9b49dba ec02119 9b49dba 874bff8 9b49dba 874bff8 9b49dba ec02119 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba ec02119 9b49dba ec02119 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 ec02119 874bff8 9b49dba ec02119 c9e2074 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 ec02119 9b49dba ec02119 9b49dba ec02119 874bff8 ec02119 874bff8 ec02119 9b49dba 874bff8 9b49dba 874bff8 ec02119 9b49dba ec02119 874bff8 9b49dba 874bff8 9b49dba 874bff8 ec02119 9b49dba 874bff8 ec02119 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 ec02119 9b49dba ec02119 9b49dba ec02119 874bff8 ec02119 874bff8 ec02119 874bff8 ec02119 9b49dba ec02119 9b49dba ec02119 874bff8 9b49dba 874bff8 ec02119 9b49dba ec02119 874bff8 ec02119 874bff8 9b49dba 874bff8 9b49dba 874bff8 ec02119 874bff8 ec02119 874bff8 ec02119 874bff8 9b49dba 874bff8 ec02119 874bff8 ec02119 9b49dba 874bff8 ec02119 874bff8 9b49dba 874bff8 ec02119 874bff8 9b49dba 874bff8 ec02119 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 c9e2074 ec02119 874bff8 ec02119 874bff8 9b49dba ec02119 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba 874bff8 c9e2074 874bff8 9b49dba 874bff8 9b49dba 874bff8 9b49dba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 | // 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 #/<project>[/<model>] and ?recipe=<project>/<model> 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
? `<img class="avatar avatar-${size}" src="${esc(r.avatar)}" alt="" loading="lazy">`
: `<span class="avatar avatar-${size} avatar-letter">${esc((r.org || "?")[0])}</span>`;
}
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) => `<span class="chip chip-mono">${esc(t)}</span>`);
const gpus = gpusOf(r);
if (gpus.length) {
const tip = Object.entries(r.hardware || {})
.map(([p, v]) => `${PLATFORMS[p] || p}: ${v}`)
.join("\n");
out.push(`<span class="chip" title="${esc(tip)}">${esc(gpus.join(" · "))}</span>`);
}
if (r.trl?.fork) out.push(`<span class="chip chip-warn" title="Needs a TRL fork, not a release from PyPI">TRL fork</span>`);
if (hp.lora_r) out.push(`<span class="chip">LoRA r${esc(hp.lora_r)}</span>`);
if (hp.max_steps) out.push(`<span class="chip">${esc(fmt(hp.max_steps))} steps</span>`);
const harnesses = r.harnesses || r.meta?.harnesses;
if (harnesses?.length) out.push(`<span class="chip">${esc(harnesses.join(" · "))}</span>`);
return out.join("");
}
function platformBadges(r) {
const verified = r.verified || r.builder?.verified || {};
return Object.keys(PLATFORMS)
.filter((p) => r.hardware?.[p])
.map(
(p) =>
`<span class="pbadge ${verified[p] ? "is-verified" : ""}" title="${esc(
verified[p] ? "Ran as written on this platform" : "Ported, not run on this platform yet"
)}"><i></i>${PLATFORM_SHORT[p]}</span>`
)
.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 `<a class="card" href="${esc(itemHref(r))}">
<div class="card-head">${avatar(r)}<div class="card-title"><strong>${esc(heading)}</strong><span>${esc(
r.is_guide ? modelId : org
)}</span></div></div>
<div class="chips">${chips(r)}</div>
<p class="card-desc">${esc(desc)}</p>
<div class="card-foot"><span class="card-project">${esc(r.is_guide ? r.title : pretty(r.project))}</span><span class="pbadges">${platformBadges(
r
)}</span></div>
</a>`;
}
function projectTile(p) {
const recipes = recipesOf(p);
const orgs = [...new Map(recipes.map((r) => [r.org, r])).values()];
return `<a class="tile" href="${esc(itemHref(p))}">
<span class="tile-kicker">${esc(p.trainers.join(" → "))}</span>
<strong class="tile-title">${esc(p.title || pretty(p.name))}</strong>
<div class="chips">${recipes.map((r) => `<span class="chip">${esc(r.name)}</span>`).join("")}</div>
<p class="tile-desc">${esc(p.summary || "")}</p>
<div class="tile-foot"><span class="avatar-stack">${orgs.map((r) => avatar(r, "sm")).join("")}</span>
<span class="tile-count">${recipes.length} recipe${recipes.length === 1 ? "" : "s"} →</span></div>
</a>`;
}
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 `<div class="filter-row"><span class="filter-label">${label}</span><div class="seg">${values
.map(
(v) =>
`<a class="pill" href="#/browse?${key}=${encodeURIComponent(v)}" title="${esc(
key === "trainer" ? TRAINERS[v]?.blurb || "" : ""
)}">${esc(facetLabel(key, v))} <small>${counts.get(v)}</small></a>`
)
.join("")}</div></div>`;
}
function pageHome() {
const trainers = trainerNames();
document.title = "TRL Recipes: reproducible training runs with TRL";
return `<section class="hero">
<h1>TRL Recipes</h1>
<p class="lede">Pick a project and a model, choose where it runs, copy the command that reproduces the run.</p>
<p class="hero-sub">Each recipe has the exact launch scripts of a real training run with
<a href="https://github.com/huggingface/trl" target="_blank" rel="noopener">TRL</a>, for
<a href="https://huggingface.co/docs/huggingface_hub/guides/jobs" target="_blank" rel="noopener">HF Jobs</a> 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: <a href="llms.txt">llms.txt</a> and <a href="catalog.json">catalog.json</a>.</p>
<button class="hero-search" type="button" data-open-palette>
<svg viewBox="0 0 20 20" aria-hidden="true"><circle cx="9" cy="9" r="6"/><path d="M14 14l4 4"/></svg>
<span>Search models, projects or trainers…</span><kbd>⌘K</kbd>
</button>
<div class="stats"><span><b>${CATALOG.recipes.length}</b> recipes</span><span><b>${CATALOG.projects.length}</b> project${
CATALOG.projects.length === 1 ? "" : "s"
}</span><span><b>${trainers.length}</b> trainer${trainers.length === 1 ? "" : "s"}</span></div>
</section>
<section class="section">
<div class="section-head"><h2>Projects</h2>
<a class="more" href="#/browse">Filter all ${CATALOG.recipes.length} recipes →</a></div>
<div class="grid grid-tiles">${CATALOG.projects.map(projectTile).join("")}</div>
</section>
<section class="section" id="all-recipes">
<div class="section-head"><h2>All recipes</h2>
<a class="more" href="llms.txt">llms.txt →</a></div>
<div class="grid">${CATALOG.recipes.map(card).join("")}</div>
</section>
<section class="section">
<div class="section-head"><h2>Browse by</h2></div>
<div class="filters">
${facetLinks("hardware", "Hardware")}${facetLinks("platform", "Runs on")}${facetLinks("trainer", "Trainer")}${facetLinks("trl", "TRL")}
</div>
</section>`;
}
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 `<div class="filter-row"><span class="filter-label">${label}</span><div class="seg">${values
.map(
(v) =>
`<button type="button" class="pill ${selected[key].includes(v) ? "is-on" : ""}" data-filter="${key}" data-value="${esc(
v
)}">${esc(facetLabel(key, v))}</button>`
)
.join("")}</div></div>`;
}).join("");
return `<section class="page-head">
<h1>Browse all recipes</h1>
<p class="lede">Filter ${CATALOG.recipes.length} recipes by project, trainer, the GPU they need, where they run and the TRL they use.</p>
</section>
<div class="filters">
<input class="filter-search" id="browse-q" type="search" placeholder="Filter by name…" value="${esc(query.get("q") || "")}">
${groups}
</div>
<div class="result-count">${matches.length} recipe${matches.length === 1 ? "" : "s"}</div>
${matches.length ? `<div class="grid">${matches.map(card).join("")}</div>` : `<p class="empty">No recipe matches these filters.</p>`}`;
}
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 || "<your user>/<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 <a href="#trl" data-scroll="trl">TRL version</a>.`);
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(
`<code>${k}</code> defaults to <code>${esc(v)}</code>, which belongs to the recipe's authors: ${
k === "BUCKET" && usesBucket(r, st) ? "set Bucket to one in your namespace" : `prefix the command with <code>${k}=<you>/<name></code>`
}.`
);
}
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 `<div class="seg" role="radiogroup">${items
.map(
([value, label]) =>
`<button type="button" class="pill ${current === value ? "is-on" : ""}" data-${name}="${esc(value)}" ${
disabled[value] ? `disabled title="${esc(disabled[value])}"` : ""
} role="radio" aria-checked="${current === value}">${esc(label)}</button>`
)
.join("")}</div>`;
}
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
? `<div class="seg">${choices
.map(
(c) =>
`<button type="button" class="pill ${value.includes(c.value) ? "is-on" : ""}" data-multi="${esc(option.env)}" data-value="${esc(
c.value
)}" ${disabled[c.value] ? "disabled" : ""}>${esc(c.value)}</button>`
)
.join("")}</div>`
: segment(`opt-${option.env}`, choices.map((c) => [c.value, c.value]), value, disabled);
rows.push([option.label, body]);
} else {
rows.push([
option.label,
`<input class="text-input" type="text" data-input="${esc(option.env)}" value="${esc(value)}" placeholder="${esc(
option.placeholder || option.default || ""
)}" spellcheck="false">`,
]);
}
}
const extras = [];
if (st.task === "train")
extras.push(
`<label class="toggle"><input type="checkbox" data-smoke ${st.smoke ? "checked" : ""}><span></span>Smoke run <code>MAX_STEPS=2</code></label>`
);
if (usesBucket(r, st))
extras.push(
`<label class="inline-input">Bucket <input class="text-input text-input-sm" type="text" data-bucket value="${esc(
st.bucket
)}" placeholder="<your user>/<bucket>" spellcheck="false"></label>`
);
if (extras.length) rows.push(["Options", `<div class="extras">${extras.join("")}</div>`]);
const adjusted = resolved.filter((x) => x.adjusted);
const { direct } = buildCommand(r, st, resolved);
const blockers = caveats(r, st, direct);
el.innerHTML = `<div class="builder-head">
<div><h2>Command builder</h2><p class="builder-summary" id="builder-summary"></p></div>
<span class="status ${verified ? "is-verified" : "is-untested"}">${verified ? "Ran as written" : "Not run as written yet"}</span>
</div>
<div class="builder-rows">${rows.map(([label, body]) => `<div class="brow"><span class="blabel">${esc(label)}</span>${body}</div>`).join("")}</div>
${adjusted.length ? `<p class="notice">${adjusted.map((x) => `${esc(x.option.label)} changed to <code>${esc(x.value)}</code>: the previous value isn't available on ${PLATFORMS[st.platform]}.`).join(" ")}</p>` : ""}
${blockers.length ? `<div class="notice"><b>Before you run</b><ul>${blockers.map((b) => `<li>${b}</li>`).join("")}</ul></div>` : ""}
<div class="terminal">
<div class="terminal-bar">
<div class="tabs" role="tablist"><button type="button" class="tab" data-tab="command">Command</button><button type="button" class="tab" data-tab="script" id="script-tab"></button></div>
<button type="button" class="btn btn-sm btn-term" id="copy-command">Copy</button>
</div>
<pre class="code terminal-code"><code id="command-code"></code></pre>
</div>
<p class="builder-note">${
st.platform === "local"
? `Runs on this machine with <a href="https://docs.astral.sh/uv/" target="_blank" rel="noopener">uv</a>, which installs the dependencies. ${
r.builder?.local_note?.[st.task] || `Needs ${esc(r.hardware?.local || "a GPU")}. Outputs go to <code>./outputs</code>.`
}`
: direct
? `Needs the <code>hf</code> CLI logged in (<code>hf auth login</code>) and nothing else: the job fetches <code>${esc(
direct.script
)}</code> from this Space. The job is submitted detached: follow it with <code>hf jobs logs <job id></code>.`
: usesBucket(r, st)
? `Needs the <code>hf</code> CLI logged in, and a bucket the job mounts on <code>/outputs</code>. The script uploads the files the job reads, then submits it detached.`
: `Needs the <code>hf</code> CLI logged in. The job is submitted detached: follow it with <code>hf jobs logs <job id></code>.`
}${verified ? "" : ` <b>These ${PLATFORMS[st.platform]} scripts have not been run as written yet.</b>`}</p>`;
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")}<span class="pi-main"><b>${esc(r.is_guide ? r.title : r.model_id)}</b><small>${esc(
r.trainers.join(", ")
)} · ${esc(r.is_guide ? r.title : pretty(r.project))}</small></span><span class="pi-kind">Recipe</span>`,
}));
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: `<span class="avatar avatar-sm avatar-letter">${esc(p.name[0].toUpperCase())}</span><span class="pi-main"><b>${esc(
p.title || pretty(p.name)
)}</b><small>${esc(p.trainers.join(", "))}</small></span><span class="pi-kind">Project</span>`,
}));
const trainers = trainerNames()
.filter((t) => match(`${t} ${TRAINERS[t]?.blurb || ""}`.toLowerCase()))
.map((t) => ({
href: browseHref("trainer", t),
html: `<img class="avatar avatar-sm" src="${esc($(".brand-mark").src)}" alt=""><span class="pi-main"><b>${esc(t)}</b><small>${
CATALOG.recipes.filter((r) => r.trainers.includes(t)).length
} recipes</small></span><span class="pi-kind">Trainer</span>`,
}));
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) => `<li><a href="${esc(it.href)}" class="${i === paletteIndex ? "is-active" : ""}">${it.html}</a></li>`).join("")
: `<li class="palette-empty">No recipe or project matches.</li>`;
}
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=<project>/<model> and ?project=<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 = `<section class="page-head"><h1>Recipe not found</h1><p class="lede">Nothing lives at <code>${esc(
path
)}</code>. <a href="#/browse">Browse all recipes →</a></p></section>`;
}
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(() => {});
|