Spaces:
Running on Zero
Running on Zero
Fit real model execution within remaining free GPU quota
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Gradio Space entrypoint for the packaged HarnessLab workspace."""import hashlibimport jsonimport osfrom pathlib import Pathimport zipfiledef 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().parentunpack_bundle(root)os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")os.environ.setdefault("GRADIO_SSR_MODE", "False")import gradio as grimport spacesimport uvicornfrom space_app import app as workspacefrom transformers import AutoModelForCausalLM, AutoTokenizerimport torchimport tempfilefrom uuid import uuid4model_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=120)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 TransformersLocalAdapterfrom harness.hf_evaluation import evaluate_caseadapter = 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 BatchReportfrom space_app import store_reportbatch = 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)def test_public_mcp() -> tuple[dict, str]:from harness.mcp_client import MCPClientwith MCPClient("https://mcp.deepwiki.com/mcp") as client:server = client.initialize()tools = client.list_tools()result = client.call_tool("read_wiki_structure", {"repoName": "openai/openai-python"})record = {"server": server, "protocol_version": client.protocol_version,"endpoint": "https://mcp.deepwiki.com/mcp", "tools": [tool.name for tool in tools],"called_tool": "read_wiki_structure", "arguments": {"repoName": "openai/openai-python"},"call": result.model_dump(mode="json")}path = Path(tempfile.gettempdir()) / f"harnesslab-mcp-{uuid4()}.json"path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")return record, 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 torchstart = torch.cuda.Event(enable_timing=True)end = torch.cuda.Event(enable_timing=True)value = torch.ones(1, device="cuda")start.record()result = value * 2end.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") as info:gr.Markdown("# HarnessLab — 실제 모델 평가\n[평가 워크스페이스 열기](/)\n\nQwen3-4B-Instruct-2507을 이 Space에서 실행합니다. API 키나 로컬 PC�� 필요 없습니다. 1회 실행은 시나리오 1개이며 최대 120초의 ZeroGPU 작업을 요청합니다. 무료 쿼터를 사용합니다.")scenario = gr.Dropdown(["S01", "S02", "S03", "S04", "S05"], 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)gr.Markdown("## 외부 MCP 연동 예제 — DeepWiki\nGPU나 API 키 없이 외부 공개 MCP 서버의 도구 목록을 읽고, openai/openai-python 문서 목차를 조회합니다.")mcp_button = gr.Button("DeepWiki MCP 연결 테스트 — GPU 미사용")mcp_result = gr.JSON(label="MCP 실제 호출 결과")mcp_file = gr.File(label="MCP 호출 기록 JSON")mcp_button.click(test_public_mcp, inputs=[], outputs=[mcp_result, mcp_file], api_name="test_deepwiki_mcp", concurrency_limit=1)gr.Markdown("## 선택: GPU 환경 확인\n버튼을 누를 때만 ZeroGPU 쿼터를 사용합니다(요청 최대 10초). Mock 평가와 기록 조회에는 필요하지 않습니다.")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 = Trueapplication = 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_startupexcept ImportError:passelse:zero_startup()uvicorn.run(application, host="0.0.0.0", port=7860, workers=1)if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Gradio Space entrypoint for the packaged HarnessLab workspace."""import hashlibimport jsonimport osfrom pathlib import Pathimport zipfiledef 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().parentunpack_bundle(root)os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")os.environ.setdefault("GRADIO_SSR_MODE", "False")import gradio as grimport spacesimport uvicornfrom space_app import app as workspacefrom transformers import AutoModelForCausalLM, AutoTokenizerimport torchimport tempfilefrom uuid import uuid4model_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 TransformersLocalAdapterfrom harness.hf_evaluation import evaluate_caseadapter = 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 BatchReportfrom space_app import store_reportbatch = 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)def test_public_mcp() -> tuple[dict, str]:from harness.mcp_client import MCPClientwith MCPClient("https://mcp.deepwiki.com/mcp") as client:server = client.initialize()tools = client.list_tools()result = client.call_tool("read_wiki_structure", {"repoName": "openai/openai-python"})record = {"server": server, "protocol_version": client.protocol_version,"endpoint": "https://mcp.deepwiki.com/mcp", "tools": [tool.name for tool in tools],"called_tool": "read_wiki_structure", "arguments": {"repoName": "openai/openai-python"},"call": result.model_dump(mode="json")}path = Path(tempfile.gettempdir()) / f"harnesslab-mcp-{uuid4()}.json"path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")return record, 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 torchstart = torch.cuda.Event(enable_timing=True)end = torch.cuda.Event(enable_timing=True)value = torch.ones(1, device="cuda")start.record()result = value * 2end.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") as info:gr.Markdown("# HarnessLab — 실제 모델 평가\n[평가 워크스페이스 열기](/)\n\nQwen3-4B-Instruct-2507을 이 Space에서 실행합니다. API 키나 로컬 PC가 필요 없습니다. 1회 실행은 시나리오 1개이며 최대 45초의 ZeroGPU 작업을 요청합니다. 무료 쿼터를 사용합니다.")scenario = gr.Dropdown(["S01", "S02", "S03", "S04", "S05"], 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)gr.Markdown("## 외부 MCP 연동 예제 — DeepWiki\nGPU나 API 키 없이 외부 공개 MCP 서버의 도구 목록을 읽고, openai/openai-python 문서 목차를 조회합니다.")mcp_button = gr.Button("DeepWiki MCP 연결 테스트 — GPU 미사용")mcp_result = gr.JSON(label="MCP 실제 호출 결과")mcp_file = gr.File(label="MCP 호출 기록 JSON")mcp_button.click(test_public_mcp, inputs=[], outputs=[mcp_result, mcp_file], api_name="test_deepwiki_mcp", concurrency_limit=1)gr.Markdown("## 선택: GPU 환경 확인\n버튼을 누를 때만 ZeroGPU 쿼터를 사용합니다(요청 최대 10초). Mock 평가와 기록 조회에는 필요하지 않습니다.")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 = Trueapplication = 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_startupexcept ImportError:passelse:zero_startup()uvicorn.run(application, host="0.0.0.0", port=7860, workers=1)if __name__ == "__main__":main()
app.py+130-130