code2lora commited on
Commit
70f3950
·
verified ·
1 Parent(s): fdf0219

Remove smoke test

Browse files
Files changed (2) hide show
  1. tools/smoke_test.py +0 -140
  2. tools/smoke_test.sbatch +0 -20
tools/smoke_test.py DELETED
@@ -1,140 +0,0 @@
1
- #!/usr/bin/env python3
2
- """CPU smoke test for the Space.
3
-
4
- Builds a one-repo data directory (real GRU contexts and prompts, placeholder
5
- cached predictions), then drives every app handler and serves the UI once.
6
-
7
- C2L_DATA_DIR=/tmp/c2l_smoke python tools/smoke_test.py --repo MiniMax-AI/Mini-Agent
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- import argparse
13
- import gzip
14
- import json
15
- import os
16
- import sys
17
- import time
18
- import urllib.request
19
- from collections import defaultdict
20
- from pathlib import Path
21
-
22
- import numpy as np
23
- import pyarrow.parquet as pq
24
- import torch
25
-
26
- HERE = Path(__file__).resolve().parents[1]
27
- sys.path.insert(0, str(HERE))
28
-
29
- from c2l.core import CommitGRU # noqa: E402
30
-
31
- COMMITS = "/scratch/lhotsko/REPO_DATASET/commit_parquet_hf_v2/commits/cr_test.parquet"
32
- QNAS = "/scratch/lhotsko/REPO_DATASET/code2lora_snapshots_hf/qna/cr_test.parquet"
33
-
34
-
35
- def build(repo: str, out: Path) -> None:
36
- from huggingface_hub import hf_hub_download
37
- from transformers import AutoTokenizer
38
-
39
- out.mkdir(parents=True, exist_ok=True)
40
- safe = repo.replace("/", "__")
41
- ct = pq.read_table(COMMITS, filters=[("repo_id", "=", repo)]).to_pylist()
42
- ct.sort(key=lambda r: r["commit_index"])
43
- qt = pq.read_table(QNAS, columns=["repo_id", "commit_sha", "test_file", "lineno", "test_function",
44
- "prefix", "target"], filters=[("repo_id", "=", repo)]).to_pylist()
45
- by_sha = defaultdict(list)
46
- for q in qt:
47
- by_sha[q["commit_sha"]].append(q)
48
-
49
- state = torch.load(hf_hub_download("code2lora/code2lora-gru", "code2lora_gru.pt"),
50
- map_location="cpu", weights_only=False, mmap=True)
51
- gc = state.get("gru_config") or {}
52
- gru = CommitGRU(int(gc.get("diff_input_dim", 2048)), int(gc.get("repo_state_dim", 2048)),
53
- int(gc.get("hidden_dim", 2048)))
54
- gru.load_state_dict(state["gru_state"])
55
- gru.eval()
56
- with torch.no_grad():
57
- h = gru.init_hidden(torch.tensor(ct[0]["repo_state_embedding"]).unsqueeze(0))
58
- ctx = []
59
- for r in ct:
60
- h = gru.step(torch.tensor(r["diff_embedding"]).unsqueeze(0), h)
61
- ctx.append(gru.context(h).float())
62
- np.save(out / f"{safe}.ctx.npy", torch.cat(ctx).numpy().astype(np.float32))
63
-
64
- tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-Coder-1.5B")
65
- bos = tok.bos_token_id if tok.bos_token_id is not None else tok.eos_token_id
66
- commits, qnas = [], []
67
- for k, r in enumerate(ct):
68
- group = []
69
- for j, q in enumerate(by_sha[r["commit_sha"]][:8]):
70
- ids = ([bos] + tok.encode(q["prefix"], add_special_tokens=False))[-4096:]
71
- had_bos = ids[0] == bos
72
- group.append({"k": k, "test_file": q["test_file"], "lineno": int(q["lineno"] or 0),
73
- "test_function": q["test_function"] or "",
74
- "prompt": tok.decode(ids[1:] if had_bos else ids), "had_bos": had_bos,
75
- "n_prompt_tokens": len(ids), "target": q["target"],
76
- "base_pred": "placeholder", "base_em": 0.0, "base_es": 0.0,
77
- "c2l_pred": q["target"], "c2l_em": 1.0, "c2l_es": 1.0,
78
- **({"prev_pred": "placeholder", "prev_em": 0.0, "prev_es": 0.0} if j == 0 and k else {})})
79
- qnas.append(group)
80
- commits.append({"sha": r["commit_sha"], "commit_index": r["commit_index"],
81
- "timestamp": r["commit_timestamp"], "n_new_assertions": r["n_new_assertions"],
82
- "diff_preview": (r["production_code_diff"] or "")[:6000],
83
- "n_qnas": len(group), "base_em": 0.0 if group else None,
84
- "c2l_em": 1.0 if group else None, "time_travel": bool(group and k)})
85
- with gzip.open(out / f"{safe}.json.gz", "wt", encoding="utf-8") as f:
86
- json.dump({"repo_id": repo, "commits": commits, "qnas": qnas,
87
- "max_input_tokens": 4096, "max_new_tokens": 64}, f)
88
- (out / "index.json").write_text(json.dumps([{
89
- "repo_id": repo, "safe": safe, "n_commits": len(commits), "n_qnas": sum(map(len, qnas)),
90
- "base_em": 0.0, "c2l_em": 1.0, "n_time_travel": sum(c["time_travel"] for c in commits),
91
- "first_date": commits[0]["timestamp"], "last_date": commits[-1]["timestamp"],
92
- "description": "smoke test", "stars": 1234}]))
93
- print(f"[build] {repo}: {len(commits)} commits, {sum(map(len, qnas))} qnas", flush=True)
94
-
95
-
96
- def drive() -> None:
97
- t0 = time.time()
98
- import app
99
- print(f"[app] import + engine {time.time() - t0:.0f}s", flush=True)
100
- safe = app.INDEX[0]["safe"]
101
- r = app.on_repo(safe)
102
- k1 = r[1].value if hasattr(r[1], "value") else r[1]["value"]
103
- print("[on_repo] ok, start commit", k1, flush=True)
104
- r = app.on_commit(safe, k1, None)
105
- i = r[3].value if hasattr(r[3], "value") else r[3]["value"]
106
- print("[on_commit] ok, pick", i, flush=True)
107
- t = time.time()
108
- status, st, *_ = app.on_adapt(safe, k1, i)
109
- print(f"[on_adapt] {time.time() - t:.2f}s state={st}", flush=True)
110
- print(status[:400])
111
- _, preds, _ = app.on_pick(safe, k1, i, st)
112
- assert "Code2LoRA @ commit" in preds, preds
113
- t = time.time()
114
- live = app.on_live(safe, k1, i, st, progress=lambda *a, **k: None)
115
- print(f"[on_live] {time.time() - t:.1f}s\n{live}", flush=True)
116
- t = time.time()
117
- prompt = app.on_prefill(safe, k1, i)
118
- custom = app.on_custom(safe, k1, prompt, 32, st, progress=lambda *a, **k: None)
119
- print(f"[on_custom] {time.time() - t:.1f}s\n{custom[:1500]}", flush=True)
120
- for k in range(1, len(app.load_repo(safe)["commits"]) + 1):
121
- app.on_commit(safe, k, st)
122
- app.on_adapt(safe, k, 0)
123
- print("[all commits] ok", flush=True)
124
-
125
- app.demo.queue(max_size=32).launch(server_port=7861, prevent_thread_lock=True)
126
- body = urllib.request.urlopen("http://127.0.0.1:7861/", timeout=30).read()
127
- print(f"[serve] GET / -> {len(body)} bytes", flush=True)
128
- app.demo.close()
129
-
130
-
131
- if __name__ == "__main__":
132
- ap = argparse.ArgumentParser()
133
- ap.add_argument("--repo", default="MiniMax-AI/Mini-Agent")
134
- ap.add_argument("--build-only", action="store_true")
135
- args = ap.parse_args()
136
- data = Path(os.environ["C2L_DATA_DIR"])
137
- if not (data / "index.json").exists():
138
- build(args.repo, data)
139
- if not args.build_only:
140
- drive()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/smoke_test.sbatch DELETED
@@ -1,20 +0,0 @@
1
- #!/bin/bash
2
- # CPU smoke test mirroring the free Space tier (2 vCPU).
3
- # sbatch hf_space_demo/tools/smoke_test.sbatch
4
- #SBATCH --job-name=c2l_space_smoke
5
- #SBATCH --output=slurm_logs/c2l_space_smoke_%j.out
6
- #SBATCH --time=01:00:00
7
- #SBATCH --cpus-per-task=2
8
- #SBATCH --mem=24G
9
- #SBATCH --account=def-yuntian
10
-
11
- set -euo pipefail
12
- module purge 2>/dev/null || true
13
- module load StdEnv/2023 python/3.12 arrow
14
- P=/home/lhotsko/projects/def-yuntian/lhotsko/c2l_space
15
- source $P/venv/bin/activate
16
- cd /home/lhotsko/RepoPeftData/hf_space_demo
17
-
18
- export PYTHONUNBUFFERED=1 HF_HOME=$P/hf HF_HUB_OFFLINE=1 C2L_DATA_DIR=$P/smoke_data
19
- export OMP_NUM_THREADS=2 GRADIO_ANALYTICS_ENABLED=False
20
- python tools/smoke_test.py