YMRohit Codex commited on
Commit
e55beda
·
1 Parent(s): 1ed61a1

Reset mint progress on repeat runs

Browse files

Co-authored-by: Codex <codex@openai.com>

Files changed (1) hide show
  1. app.py +47 -11
app.py CHANGED
@@ -447,6 +447,13 @@ def _blob(d):
447
  return f"<span data-blob='{base64.b64encode(json.dumps(d).encode()).decode()}'></span>"
448
 
449
 
 
 
 
 
 
 
 
450
  def do_mint(recipe_json: str) -> str:
451
  try:
452
  r = json.loads(recipe_json or "{}")
@@ -454,10 +461,11 @@ def do_mint(recipe_json: str) -> str:
454
  return _blob({"error": "bad recipe"})
455
  if r.get("local"):
456
  try:
457
- return _blob(local_mint(r))
458
  except Exception as e:
459
- return _blob({"error": f"Local offline mint failed: {type(e).__name__}: {str(e)[:240]}",
460
- "local": True, "baseline": "eager"})
 
461
  base = PRO if r.get("pro") else ONE_B
462
  if r.get("mode") == "classic":
463
  payload = {"op": r.get("classic", "softmax")}
@@ -474,7 +482,7 @@ def do_mint(recipe_json: str) -> str:
474
  resp = requests.post(base, json=payload, timeout=600)
475
  if resp.status_code == 200 and resp.text.strip():
476
  try:
477
- return _blob(resp.json())
478
  except ValueError:
479
  last = "the model returned an unexpected response"
480
  else:
@@ -483,7 +491,9 @@ def do_mint(recipe_json: str) -> str:
483
  last = str(e)
484
  time.sleep(4)
485
  pro = " The 27B in Pro mode takes longer to wake. Try again, or turn Pro off." if r.get("pro") else ""
486
- return _blob({"error": f"The model is still waking up. Give it about 30 seconds and press Mint again.{pro}"})
 
 
487
 
488
 
489
  def fetch_lb(_=None):
@@ -508,7 +518,7 @@ except Exception:
508
  REPLAYS_JSON = "{}"
509
 
510
  APP_HTML = r"""
511
- <div id="km" data-build="2026-06-15-run-verify-docs">
512
  <div id="km-top">
513
  <div id="km-brand">
514
  <span class="mark"><span class="dot"></span>Kernel Mint</span>
@@ -909,6 +919,7 @@ APP_JS = r"""
909
 
910
  const state={tab:'build',mode:'build',slots:{mem:false,norm:'rmsnorm',act:'gelu',act2:null},classic:'softmax'};
911
  let buildTries=4, expertTries=5, resolvedExpert=null, lastMintedMode='build';
 
912
  const HIST=[];
913
 
914
  function animate(el,frames,opts){ if(el&&el.animate)el.animate(frames,opts); }
@@ -950,7 +961,8 @@ APP_JS = r"""
950
  $$('.km-page').forEach(p=>{p.hidden=p.dataset.page!==tab;});
951
  requestAnimationFrame(positionTabPill);
952
  if(tab==='expert')resolveExpert();
953
- if(tab==='lb')refreshLB();
 
954
  }
955
  $$('.km-tab').forEach(b=>b.addEventListener('click',()=>showTab(b.dataset.tab)));
956
  window.addEventListener('resize',positionTabPill);
@@ -1208,8 +1220,12 @@ APP_JS = r"""
1208
  // _n is a nonce: it makes the recipe JSON differ on every mint so Gradio always registers a
1209
  // value change and re-runs do_mint. Without it, minting the same recipe twice in a row left
1210
  // the textarea value unchanged and the second submit was dropped (the "needs a double-click"
1211
- // bug). do_mint ignores unknown keys.
1212
- const payload=Object.assign({},recipe,{_n:Date.now()});
 
 
 
 
1213
  const set=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,'value').set;
1214
  set.call(inp,JSON.stringify(payload));
1215
  inp.dispatchEvent(new Event('input',{bubbles:true}));
@@ -1221,9 +1237,19 @@ APP_JS = r"""
1221
  },80);
1222
  }
1223
  function refreshLB(){
 
1224
  const btn=document.querySelector('#km_lb_btn button')||document.querySelector('#km_lb_btn');
1225
  if(btn)btn.click();
1226
  }
 
 
 
 
 
 
 
 
 
1227
  let mintSafetyTimer=null;
1228
  function setMinting(on){
1229
  ['#km-build','#km-xbuild'].forEach(id=>{const b=$(id); if(b){b.disabled=on; b.classList.toggle('minting',on);}});
@@ -1298,6 +1324,13 @@ APP_JS = r"""
1298
  }
1299
  function wakingError(msg){return /waking|wake|timeout|timed out|still|unexpected|http|modal|loading/i.test(String(msg||''));}
1300
  function showResult(d,opts={}){
 
 
 
 
 
 
 
1301
  const mode=opts.mode||lastMintedMode||'build';
1302
  stopBuild();
1303
  stopReplay();
@@ -1314,6 +1347,7 @@ APP_JS = r"""
1314
  "<div class='km-result-top'><div class='km-verdict-icon bad'>!</div><div><span class='km-run-label'>"+(local?'local offline mint':'live mint')+"</span><b>"+(wake?'The live model is still waking':(local?'The local mint did not finish':'The live mint did not finish'))+"</b></div></div>"+
1315
  "<p class='km-dim'>"+(wake?'The backend scales to zero, so the first live mint can take about 90 seconds. The replay below is a real earlier mint, not a mockup.':(local?esc(d.error):'Backend said: '+esc(d.error)))+"</p>"+
1316
  (wake?replayBtn+"<p class='km-rawerr'>Backend said: "+esc(d.error)+"</p>":replayBtn)+"</div>";
 
1317
  return;
1318
  }
1319
  const a=attemptSummary(d);
@@ -1322,6 +1356,7 @@ APP_JS = r"""
1322
  "<div class='km-result-top'><div class='km-verdict-icon bad'>NO</div><div><span class='km-run-label'>referee verdict</span><b>Not verified yet</b></div></div>"+
1323
  "<div class='km-ref-summary'><b>"+a.passed+" of "+(a.total||'?')+"</b> attempts passed the referee</div>"+
1324
  attemptChips(d)+"<p class='km-dim'>"+esc(d.explanation||'Press Mint again, raise attempts, or change the operation.')+"</p></div>";
 
1325
  return;
1326
  }
1327
  const recorded=!!opts.recorded, local=!!d.local;
@@ -1360,8 +1395,9 @@ APP_JS = r"""
1360
  const hist=$('#km-hist');
1361
  if(hist)hist.innerHTML=HIST.slice(0,10).map(h=>"<div class='km-hrow'>"+h+"</div>").join('');
1362
  }
1363
- // The leaderboard refreshes when the user opens that tab (showTab), so there is no need to
1364
- // fetch it here. Keeping the mint path free of any leaderboard call avoids queue contention.
 
1365
  }
1366
 
1367
  let replayTimer=null;
 
447
  return f"<span data-blob='{base64.b64encode(json.dumps(d).encode()).decode()}'></span>"
448
 
449
 
450
+ def _with_nonce(d: dict, r: dict) -> dict:
451
+ out = dict(d or {})
452
+ if r.get("_n") is not None:
453
+ out["_n"] = r.get("_n")
454
+ return out
455
+
456
+
457
  def do_mint(recipe_json: str) -> str:
458
  try:
459
  r = json.loads(recipe_json or "{}")
 
461
  return _blob({"error": "bad recipe"})
462
  if r.get("local"):
463
  try:
464
+ return _blob(_with_nonce(local_mint(r), r))
465
  except Exception as e:
466
+ return _blob(_with_nonce(
467
+ {"error": f"Local offline mint failed: {type(e).__name__}: {str(e)[:240]}",
468
+ "local": True, "baseline": "eager"}, r))
469
  base = PRO if r.get("pro") else ONE_B
470
  if r.get("mode") == "classic":
471
  payload = {"op": r.get("classic", "softmax")}
 
482
  resp = requests.post(base, json=payload, timeout=600)
483
  if resp.status_code == 200 and resp.text.strip():
484
  try:
485
+ return _blob(_with_nonce(resp.json(), r))
486
  except ValueError:
487
  last = "the model returned an unexpected response"
488
  else:
 
491
  last = str(e)
492
  time.sleep(4)
493
  pro = " The 27B in Pro mode takes longer to wake. Try again, or turn Pro off." if r.get("pro") else ""
494
+ return _blob(_with_nonce(
495
+ {"error": f"The model is still waking up. Give it about 30 seconds and press Mint again.{pro}"},
496
+ r))
497
 
498
 
499
  def fetch_lb(_=None):
 
518
  REPLAYS_JSON = "{}"
519
 
520
  APP_HTML = r"""
521
+ <div id="km" data-build="2026-06-15-mint-reset-lb-live">
522
  <div id="km-top">
523
  <div id="km-brand">
524
  <span class="mark"><span class="dot"></span>Kernel Mint</span>
 
919
 
920
  const state={tab:'build',mode:'build',slots:{mem:false,norm:'rmsnorm',act:'gelu',act2:null},classic:'softmax'};
921
  let buildTries=4, expertTries=5, resolvedExpert=null, lastMintedMode='build';
922
+ let activeMintNonce=null, awaitingMint=false, pendingLBRefresh=false, lbRefreshTimer=null, lbPollTimer=null;
923
  const HIST=[];
924
 
925
  function animate(el,frames,opts){ if(el&&el.animate)el.animate(frames,opts); }
 
961
  $$('.km-page').forEach(p=>{p.hidden=p.dataset.page!==tab;});
962
  requestAnimationFrame(positionTabPill);
963
  if(tab==='expert')resolveExpert();
964
+ if(tab==='lb'){refreshLB(); setLBPolling(true);}
965
+ else setLBPolling(false);
966
  }
967
  $$('.km-tab').forEach(b=>b.addEventListener('click',()=>showTab(b.dataset.tab)));
968
  window.addEventListener('resize',positionTabPill);
 
1220
  // _n is a nonce: it makes the recipe JSON differ on every mint so Gradio always registers a
1221
  // value change and re-runs do_mint. Without it, minting the same recipe twice in a row left
1222
  // the textarea value unchanged and the second submit was dropped (the "needs a double-click"
1223
+ // bug). The backend echoes it back so stale blobs from the previous run cannot repaint the old
1224
+ // result over the new loading card while Gradio is preparing the next response.
1225
+ const nonce=Date.now().toString(36)+'-'+Math.random().toString(36).slice(2);
1226
+ const payload=Object.assign({},recipe,{_n:nonce});
1227
+ activeMintNonce=nonce;
1228
+ awaitingMint=true;
1229
  const set=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,'value').set;
1230
  set.call(inp,JSON.stringify(payload));
1231
  inp.dispatchEvent(new Event('input',{bubbles:true}));
 
1237
  },80);
1238
  }
1239
  function refreshLB(){
1240
+ if(awaitingMint){pendingLBRefresh=true;return;}
1241
  const btn=document.querySelector('#km_lb_btn button')||document.querySelector('#km_lb_btn');
1242
  if(btn)btn.click();
1243
  }
1244
+ function scheduleLBRefresh(delay=700){
1245
+ pendingLBRefresh=false;
1246
+ if(lbRefreshTimer)clearTimeout(lbRefreshTimer);
1247
+ lbRefreshTimer=setTimeout(refreshLB,delay);
1248
+ }
1249
+ function setLBPolling(on){
1250
+ if(lbPollTimer){clearInterval(lbPollTimer);lbPollTimer=null;}
1251
+ if(on)lbPollTimer=setInterval(()=>{if(state.tab==='lb')refreshLB();},15000);
1252
+ }
1253
  let mintSafetyTimer=null;
1254
  function setMinting(on){
1255
  ['#km-build','#km-xbuild'].forEach(id=>{const b=$(id); if(b){b.disabled=on; b.classList.toggle('minting',on);}});
 
1324
  }
1325
  function wakingError(msg){return /waking|wake|timeout|timed out|still|unexpected|http|modal|loading/i.test(String(msg||''));}
1326
  function showResult(d,opts={}){
1327
+ if(!opts.recorded&&awaitingMint&&String(d&&d._n||'')!==String(activeMintNonce||'')){
1328
+ return;
1329
+ }
1330
+ if(!opts.recorded&&awaitingMint){
1331
+ awaitingMint=false;
1332
+ activeMintNonce=null;
1333
+ }
1334
  const mode=opts.mode||lastMintedMode||'build';
1335
  stopBuild();
1336
  stopReplay();
 
1347
  "<div class='km-result-top'><div class='km-verdict-icon bad'>!</div><div><span class='km-run-label'>"+(local?'local offline mint':'live mint')+"</span><b>"+(wake?'The live model is still waking':(local?'The local mint did not finish':'The live mint did not finish'))+"</b></div></div>"+
1348
  "<p class='km-dim'>"+(wake?'The backend scales to zero, so the first live mint can take about 90 seconds. The replay below is a real earlier mint, not a mockup.':(local?esc(d.error):'Backend said: '+esc(d.error)))+"</p>"+
1349
  (wake?replayBtn+"<p class='km-rawerr'>Backend said: "+esc(d.error)+"</p>":replayBtn)+"</div>";
1350
+ if(pendingLBRefresh)scheduleLBRefresh();
1351
  return;
1352
  }
1353
  const a=attemptSummary(d);
 
1356
  "<div class='km-result-top'><div class='km-verdict-icon bad'>NO</div><div><span class='km-run-label'>referee verdict</span><b>Not verified yet</b></div></div>"+
1357
  "<div class='km-ref-summary'><b>"+a.passed+" of "+(a.total||'?')+"</b> attempts passed the referee</div>"+
1358
  attemptChips(d)+"<p class='km-dim'>"+esc(d.explanation||'Press Mint again, raise attempts, or change the operation.')+"</p></div>";
1359
+ if(pendingLBRefresh)scheduleLBRefresh();
1360
  return;
1361
  }
1362
  const recorded=!!opts.recorded, local=!!d.local;
 
1395
  const hist=$('#km-hist');
1396
  if(hist)hist.innerHTML=HIST.slice(0,10).map(h=>"<div class='km-hrow'>"+h+"</div>").join('');
1397
  }
1398
+ // The leaderboard refresh is deliberately decoupled from the mint call. Once the result has
1399
+ // arrived, the queue is free again, so refresh the board without hiding the just-rendered result.
1400
+ if(!recorded)scheduleLBRefresh(900);
1401
  }
1402
 
1403
  let replayTimer=null;