Pota019 commited on
Commit
8316df9
·
verified ·
1 Parent(s): e9aec48

Fit real model execution within remaining free GPU quota

Browse files
Files changed (1) hide show
  1. app.py +130 -130
app.py CHANGED
@@ -1,130 +1,130 @@
1
- """Gradio Space entrypoint for the packaged HarnessLab workspace."""
2
-
3
- import hashlib
4
- import json
5
- import os
6
- from pathlib import Path
7
- import zipfile
8
-
9
-
10
- def unpack_bundle(root: Path) -> None:
11
- bundle = root / "harnesslab_bundle.zip"
12
- manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
13
- if hashlib.sha256(bundle.read_bytes()).hexdigest() != manifest["bundle_sha256"]:
14
- raise ValueError("Bundle checksum mismatch")
15
- with zipfile.ZipFile(bundle) as archive:
16
- expected = {entry["path"]: entry["sha256"] for entry in manifest["files"]}
17
- if set(archive.namelist()) != set(expected):
18
- raise ValueError("Bundle file manifest mismatch")
19
- for name in archive.namelist():
20
- target = (root / name).resolve()
21
- if not target.is_relative_to(root.resolve()):
22
- raise ValueError("Invalid bundle member path")
23
- if hashlib.sha256(archive.read(name)).hexdigest() != expected[name]:
24
- raise ValueError("Bundle member checksum mismatch")
25
- archive.extractall(root)
26
-
27
-
28
- def main() -> None:
29
- root = Path(__file__).resolve().parent
30
- unpack_bundle(root)
31
- os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
32
- os.environ.setdefault("GRADIO_SSR_MODE", "False")
33
- import gradio as gr
34
- import spaces
35
- import uvicorn
36
- from space_app import app as workspace
37
- from transformers import AutoModelForCausalLM, AutoTokenizer
38
- import torch
39
- import tempfile
40
- from uuid import uuid4
41
-
42
- model_id = "Qwen/Qwen3-4B-Instruct-2507"
43
- tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=False)
44
- model = AutoModelForCausalLM.from_pretrained(
45
- model_id, torch_dtype=torch.float16, low_cpu_mem_usage=True, trust_remote_code=False,
46
- ).eval().to("cuda")
47
-
48
- @spaces.GPU(duration=120)
49
- def run_model(case_id: str) -> dict:
50
- # GPU workers start from the image, not the CPU process's runtime files.
51
- unpack_bundle(root)
52
- from adapters.transformers_local import TransformersLocalAdapter
53
- from harness.hf_evaluation import evaluate_case
54
- adapter = TransformersLocalAdapter(model_id=model_id, model=model, tokenizer=tokenizer)
55
- path = Path(tempfile.gettempdir()) / f"harnesslab-hf-{uuid4()}.json"
56
- batch = evaluate_case(adapter, case_id, model_id, getattr(model.config, "_commit_hash", None), root, path)
57
- return {"report": batch.model_dump(mode="json")}
58
-
59
- def publish_result(result: dict) -> tuple[dict, str]:
60
- # GPU functions run in an isolated worker; update the web process here.
61
- from harness.batch import BatchReport
62
- from space_app import store_report
63
- batch = BatchReport.model_validate_json(json.dumps(result["report"]))
64
- path = Path(tempfile.gettempdir()) / f"harnesslab-hf-{uuid4()}.json"
65
- path.write_text(batch.model_dump_json(indent=2), encoding="utf-8")
66
- report_id = store_report(batch, "real_live")
67
- return {**batch.summary(), "workspace_report": f"/?report={report_id}",
68
- "failure_reason": batch.cases[0].report.evaluation.failure_reason}, str(path)
69
-
70
- def test_public_mcp() -> tuple[dict, str]:
71
- from harness.mcp_client import MCPClient
72
- with MCPClient("https://mcp.deepwiki.com/mcp") as client:
73
- server = client.initialize()
74
- tools = client.list_tools()
75
- result = client.call_tool("read_wiki_structure", {"repoName": "openai/openai-python"})
76
- record = {"server": server, "protocol_version": client.protocol_version,
77
- "endpoint": "https://mcp.deepwiki.com/mcp", "tools": [tool.name for tool in tools],
78
- "called_tool": "read_wiki_structure", "arguments": {"repoName": "openai/openai-python"},
79
- "call": result.model_dump(mode="json")}
80
- path = Path(tempfile.gettempdir()) / f"harnesslab-mcp-{uuid4()}.json"
81
- path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
82
- return record, str(path)
83
-
84
- @spaces.GPU(duration=10)
85
- def gpu_environment_check() -> dict[str, str | float]:
86
- """Optional real CUDA check; never invoked during startup or Mock runs."""
87
- import torch
88
-
89
- start = torch.cuda.Event(enable_timing=True)
90
- end = torch.cuda.Event(enable_timing=True)
91
- value = torch.ones(1, device="cuda")
92
- start.record()
93
- result = value * 2
94
- end.record()
95
- torch.cuda.synchronize()
96
- return {"device": torch.cuda.get_device_name(), "check_value": float(result.item()),
97
- "kernel_time_seconds": start.elapsed_time(end) / 1000,
98
- "purpose": "GPU environment diagnostic; not a model performance benchmark"}
99
-
100
- with gr.Blocks(title="HarnessLab") as info:
101
- gr.Markdown("# HarnessLab — 실제 모델 평가\n[평가 워크스페이스 열기](/)\n\nQwen3-4B-Instruct-2507을 이 Space에서 실행합니다. API 키나 로컬 PC�� 필요 없습니다. 1회 실행은 시나리오 1개이며 최대 120초의 ZeroGPU 작업을 요청합니다. 무료 쿼터를 사용합니다.")
102
- scenario = gr.Dropdown(["S01", "S02", "S03", "S04", "S05"], value="S01", label="평가 시나리오")
103
- execute = gr.Button("실제 모델 평가 실행 — ZeroGPU 사용", variant="primary")
104
- summary = gr.JSON(label="실제 실행 결과")
105
- artifact = gr.File(label="평가 Trace JSON 다운로드")
106
- event = execute.click(run_model, inputs=[scenario], outputs=[summary], api_name="evaluate_model", concurrency_limit=1)
107
- event.then(publish_result, inputs=[summary], outputs=[summary, artifact], api_name=False)
108
- gr.Markdown("## 외부 MCP 연동 예제 — DeepWiki\nGPU나 API 키 없이 외부 공개 MCP 서버의 도구 목록을 읽고, openai/openai-python 문서 목차를 조회합니다.")
109
- mcp_button = gr.Button("DeepWiki MCP 연결 테스트 — GPU 미사용")
110
- mcp_result = gr.JSON(label="MCP 실제 호출 결과")
111
- mcp_file = gr.File(label="MCP 호출 기록 JSON")
112
- mcp_button.click(test_public_mcp, inputs=[], outputs=[mcp_result, mcp_file], api_name="test_deepwiki_mcp", concurrency_limit=1)
113
- gr.Markdown("## 선택: GPU 환경 확인\n버튼을 누를 때만 ZeroGPU 쿼터를 사용합니다(요청 최대 10초). Mock 평가와 기록 조회에는 필요하지 않습니다.")
114
- diagnostic = gr.Button("GPU 환경 확인 — ZeroGPU 쿼터 사용")
115
- gpu_result = gr.JSON(label="환경 확인 결과 — 모델 성능 지표가 아닙니다")
116
- diagnostic.click(gpu_environment_check, inputs=[], outputs=[gpu_result], api_name="gpu_environment")
117
- info.show_error = True
118
- application = gr.mount_gradio_app(workspace, info, path="/gradio", ssr_mode=False)
119
- # Mounting bypasses Blocks.launch(), which normally sends this registration.
120
- try:
121
- from spaces.zero import startup as zero_startup
122
- except ImportError:
123
- pass
124
- else:
125
- zero_startup()
126
- uvicorn.run(application, host="0.0.0.0", port=7860, workers=1)
127
-
128
-
129
- if __name__ == "__main__":
130
- main()
 
1
+ """Gradio Space entrypoint for the packaged HarnessLab workspace."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import zipfile
8
+
9
+
10
+ def unpack_bundle(root: Path) -> None:
11
+ bundle = root / "harnesslab_bundle.zip"
12
+ manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
13
+ if hashlib.sha256(bundle.read_bytes()).hexdigest() != manifest["bundle_sha256"]:
14
+ raise ValueError("Bundle checksum mismatch")
15
+ with zipfile.ZipFile(bundle) as archive:
16
+ expected = {entry["path"]: entry["sha256"] for entry in manifest["files"]}
17
+ if set(archive.namelist()) != set(expected):
18
+ raise ValueError("Bundle file manifest mismatch")
19
+ for name in archive.namelist():
20
+ target = (root / name).resolve()
21
+ if not target.is_relative_to(root.resolve()):
22
+ raise ValueError("Invalid bundle member path")
23
+ if hashlib.sha256(archive.read(name)).hexdigest() != expected[name]:
24
+ raise ValueError("Bundle member checksum mismatch")
25
+ archive.extractall(root)
26
+
27
+
28
+ def main() -> None:
29
+ root = Path(__file__).resolve().parent
30
+ unpack_bundle(root)
31
+ os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
32
+ os.environ.setdefault("GRADIO_SSR_MODE", "False")
33
+ import gradio as gr
34
+ import spaces
35
+ import uvicorn
36
+ from space_app import app as workspace
37
+ from transformers import AutoModelForCausalLM, AutoTokenizer
38
+ import torch
39
+ import tempfile
40
+ from uuid import uuid4
41
+
42
+ model_id = "Qwen/Qwen3-4B-Instruct-2507"
43
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=False)
44
+ model = AutoModelForCausalLM.from_pretrained(
45
+ model_id, torch_dtype=torch.float16, low_cpu_mem_usage=True, trust_remote_code=False,
46
+ ).eval().to("cuda")
47
+
48
+ @spaces.GPU(duration=45)
49
+ def run_model(case_id: str) -> dict:
50
+ # GPU workers start from the image, not the CPU process's runtime files.
51
+ unpack_bundle(root)
52
+ from adapters.transformers_local import TransformersLocalAdapter
53
+ from harness.hf_evaluation import evaluate_case
54
+ adapter = TransformersLocalAdapter(model_id=model_id, model=model, tokenizer=tokenizer)
55
+ path = Path(tempfile.gettempdir()) / f"harnesslab-hf-{uuid4()}.json"
56
+ batch = evaluate_case(adapter, case_id, model_id, getattr(model.config, "_commit_hash", None), root, path)
57
+ return {"report": batch.model_dump(mode="json")}
58
+
59
+ def publish_result(result: dict) -> tuple[dict, str]:
60
+ # GPU functions run in an isolated worker; update the web process here.
61
+ from harness.batch import BatchReport
62
+ from space_app import store_report
63
+ batch = BatchReport.model_validate_json(json.dumps(result["report"]))
64
+ path = Path(tempfile.gettempdir()) / f"harnesslab-hf-{uuid4()}.json"
65
+ path.write_text(batch.model_dump_json(indent=2), encoding="utf-8")
66
+ report_id = store_report(batch, "real_live")
67
+ return {**batch.summary(), "workspace_report": f"/?report={report_id}",
68
+ "failure_reason": batch.cases[0].report.evaluation.failure_reason}, str(path)
69
+
70
+ def test_public_mcp() -> tuple[dict, str]:
71
+ from harness.mcp_client import MCPClient
72
+ with MCPClient("https://mcp.deepwiki.com/mcp") as client:
73
+ server = client.initialize()
74
+ tools = client.list_tools()
75
+ result = client.call_tool("read_wiki_structure", {"repoName": "openai/openai-python"})
76
+ record = {"server": server, "protocol_version": client.protocol_version,
77
+ "endpoint": "https://mcp.deepwiki.com/mcp", "tools": [tool.name for tool in tools],
78
+ "called_tool": "read_wiki_structure", "arguments": {"repoName": "openai/openai-python"},
79
+ "call": result.model_dump(mode="json")}
80
+ path = Path(tempfile.gettempdir()) / f"harnesslab-mcp-{uuid4()}.json"
81
+ path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
82
+ return record, str(path)
83
+
84
+ @spaces.GPU(duration=10)
85
+ def gpu_environment_check() -> dict[str, str | float]:
86
+ """Optional real CUDA check; never invoked during startup or Mock runs."""
87
+ import torch
88
+
89
+ start = torch.cuda.Event(enable_timing=True)
90
+ end = torch.cuda.Event(enable_timing=True)
91
+ value = torch.ones(1, device="cuda")
92
+ start.record()
93
+ result = value * 2
94
+ end.record()
95
+ torch.cuda.synchronize()
96
+ return {"device": torch.cuda.get_device_name(), "check_value": float(result.item()),
97
+ "kernel_time_seconds": start.elapsed_time(end) / 1000,
98
+ "purpose": "GPU environment diagnostic; not a model performance benchmark"}
99
+
100
+ with gr.Blocks(title="HarnessLab") as info:
101
+ gr.Markdown("# HarnessLab — 실제 모델 평가\n[평가 워크스페이스 열기](/)\n\nQwen3-4B-Instruct-2507을 이 Space에서 실행합니다. API 키나 로컬 PC가 필요 없습니다. 1회 실행은 시나리오 1개이며 최대 45초의 ZeroGPU 작업을 요청합니다. 무료 쿼터를 사용합니다.")
102
+ scenario = gr.Dropdown(["S01", "S02", "S03", "S04", "S05"], value="S01", label="평가 시나리오")
103
+ execute = gr.Button("실제 모델 평가 실행 — ZeroGPU 사용", variant="primary")
104
+ summary = gr.JSON(label="실제 실행 결과")
105
+ artifact = gr.File(label="평가 Trace JSON 다운로드")
106
+ event = execute.click(run_model, inputs=[scenario], outputs=[summary], api_name="evaluate_model", concurrency_limit=1)
107
+ event.then(publish_result, inputs=[summary], outputs=[summary, artifact], api_name=False)
108
+ gr.Markdown("## 외부 MCP 연동 예제 — DeepWiki\nGPU나 API 키 없이 외부 공개 MCP 서버의 도구 목록을 읽고, openai/openai-python 문서 목차를 조회합니다.")
109
+ mcp_button = gr.Button("DeepWiki MCP 연결 테스트 — GPU 미사용")
110
+ mcp_result = gr.JSON(label="MCP 실제 호출 결과")
111
+ mcp_file = gr.File(label="MCP 호출 기록 JSON")
112
+ mcp_button.click(test_public_mcp, inputs=[], outputs=[mcp_result, mcp_file], api_name="test_deepwiki_mcp", concurrency_limit=1)
113
+ gr.Markdown("## 선택: GPU 환경 확인\n버튼을 누를 때만 ZeroGPU 쿼터를 사용합니다(요청 최대 10초). Mock 평가와 기록 조회에는 필요하지 않습니다.")
114
+ diagnostic = gr.Button("GPU 환경 확인 — ZeroGPU 쿼터 사용")
115
+ gpu_result = gr.JSON(label="환경 확인 결과 — 모델 성능 지표가 아닙니다")
116
+ diagnostic.click(gpu_environment_check, inputs=[], outputs=[gpu_result], api_name="gpu_environment")
117
+ info.show_error = True
118
+ application = gr.mount_gradio_app(workspace, info, path="/gradio", ssr_mode=False)
119
+ # Mounting bypasses Blocks.launch(), which normally sends this registration.
120
+ try:
121
+ from spaces.zero import startup as zero_startup
122
+ except ImportError:
123
+ pass
124
+ else:
125
+ zero_startup()
126
+ uvicorn.run(application, host="0.0.0.0", port=7860, workers=1)
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()