Spaces:
Running on Zero
Running on Zero
File size: 5,644 Bytes
8316df9 27d8dd4 2e3c5a1 8316df9 2e3c5a1 8316df9 | 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 | """Gradio Space entrypoint for the packaged HarnessLab workspace."""
import hashlib
import json
import os
from pathlib import Path
import zipfile
def unpack_bundle(root: Path) -> None:
bundle = root / "harnesslab_bundle.zip"
manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
if hashlib.sha256(bundle.read_bytes()).hexdigest() != manifest["bundle_sha256"]:
raise ValueError("Bundle checksum mismatch")
with zipfile.ZipFile(bundle) as archive:
expected = {entry["path"]: entry["sha256"] for entry in manifest["files"]}
if set(archive.namelist()) != set(expected):
raise ValueError("Bundle file manifest mismatch")
for name in archive.namelist():
target = (root / name).resolve()
if not target.is_relative_to(root.resolve()):
raise ValueError("Invalid bundle member path")
if hashlib.sha256(archive.read(name)).hexdigest() != expected[name]:
raise ValueError("Bundle member checksum mismatch")
archive.extractall(root)
def main() -> None:
root = Path(__file__).resolve().parent
unpack_bundle(root)
os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
os.environ.setdefault("GRADIO_SSR_MODE", "False")
import gradio as gr
import spaces
import uvicorn
from space_app import app as workspace
from space_app import scenario_catalog
from harness.gradio_mcp_lab import build_mcp_lab
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import tempfile
from uuid import uuid4
model_id = "Qwen/Qwen3-4B-Instruct-2507"
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=False)
model = AutoModelForCausalLM.from_pretrained(
model_id, torch_dtype=torch.float16, low_cpu_mem_usage=True, trust_remote_code=False,
).eval().to("cuda")
@spaces.GPU(duration=45)
def run_model(case_id: str) -> dict:
# GPU workers start from the image, not the CPU process's runtime files.
unpack_bundle(root)
from adapters.transformers_local import TransformersLocalAdapter
from harness.hf_evaluation import evaluate_case
adapter = TransformersLocalAdapter(model_id=model_id, model=model, tokenizer=tokenizer)
path = Path(tempfile.gettempdir()) / f"harnesslab-hf-{uuid4()}.json"
batch = evaluate_case(adapter, case_id, model_id, getattr(model.config, "_commit_hash", None), root, path)
return {"report": batch.model_dump(mode="json")}
def publish_result(result: dict) -> tuple[dict, str]:
# GPU functions run in an isolated worker; update the web process here.
from harness.batch import BatchReport
from space_app import store_report
batch = BatchReport.model_validate_json(json.dumps(result["report"]))
path = Path(tempfile.gettempdir()) / f"harnesslab-hf-{uuid4()}.json"
path.write_text(batch.model_dump_json(indent=2), encoding="utf-8")
report_id = store_report(batch, "real_live")
return {**batch.summary(), "workspace_report": f"/?report={report_id}",
"failure_reason": batch.cases[0].report.evaluation.failure_reason}, str(path)
@spaces.GPU(duration=10)
def gpu_environment_check() -> dict[str, str | float]:
"""Optional real CUDA check; never invoked during startup or Mock runs."""
import torch
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
value = torch.ones(1, device="cuda")
start.record()
result = value * 2
end.record()
torch.cuda.synchronize()
return {"device": torch.cuda.get_device_name(), "check_value": float(result.item()),
"kernel_time_seconds": start.elapsed_time(end) / 1000,
"purpose": "GPU environment diagnostic; not a model performance benchmark"}
with gr.Blocks(title="HarnessLab · 외부 MCP 테스트") as info:
build_mcp_lab(gr)
with gr.Accordion("ZeroGPU 모델 평가 · 선택 기능", open=False, elem_id="zero-gpu"):
gr.Markdown("Qwen3-4B로 시나리오 하나를 실행합니다. ZeroGPU 쿼터를 사용합니다.")
scenario = gr.Dropdown(list(scenario_catalog()), value="S01", label="평가 시나리오")
execute = gr.Button("실제 모델 평가 실행 — ZeroGPU 사용", variant="primary")
summary = gr.JSON(label="실제 실행 결과")
artifact = gr.File(label="평가 Trace JSON 다운로드")
event = execute.click(run_model, inputs=[scenario], outputs=[summary], api_name="evaluate_model", concurrency_limit=1)
event.then(publish_result, inputs=[summary], outputs=[summary, artifact], api_name=False)
diagnostic = gr.Button("GPU 환경 확인 — ZeroGPU 쿼터 사용")
gpu_result = gr.JSON(label="환경 확인 결과")
diagnostic.click(gpu_environment_check, inputs=[], outputs=[gpu_result], api_name="gpu_environment")
info.show_error = True
application = gr.mount_gradio_app(workspace, info, path="/gradio", ssr_mode=False)
# Mounting bypasses Blocks.launch(), which normally sends this registration.
try:
from spaces.zero import startup as zero_startup
except ImportError:
pass
else:
zero_startup()
uvicorn.run(application, host="0.0.0.0", port=7860, workers=1)
if __name__ == "__main__":
main()
|