v2-zeroshot driver
Browse files- v2-zeroshot/src/eval_v2zs.py +32 -0
- v2-zeroshot/src/onstart.sh +17 -0
- v2-zeroshot/src/run.sh +0 -0
- v2-zeroshot/src/train_v2zs.py +152 -0
- v2-zeroshot/src/v2_zeroshot.yaml +12 -0
v2-zeroshot/src/eval_v2zs.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Score the zero-shot retrain with code-embed-v2's official harness settings (same pins as the UniXcoder
|
| 2 |
+
baseline): mteb 2.26.17, sentence-transformers 6.2.0, fp32, 1,024 tokens, encode batch 64."""
|
| 3 |
+
import json
|
| 4 |
+
import sys
|
| 5 |
+
import time
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import mteb
|
| 9 |
+
from huggingface_hub import HfApi
|
| 10 |
+
from mteb.cache import ResultCache
|
| 11 |
+
from mteb.models.sentence_transformer_wrapper import SentenceTransformerEncoderWrapper
|
| 12 |
+
from sentence_transformers import SentenceTransformer
|
| 13 |
+
|
| 14 |
+
MODEL, OUT = sys.argv[1], Path("/workspace/results")
|
| 15 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 16 |
+
model = SentenceTransformer(MODEL, device="cuda")
|
| 17 |
+
model.max_seq_length = 1024
|
| 18 |
+
wrapper = SentenceTransformerEncoderWrapper(model)
|
| 19 |
+
wrapper.mteb_model_meta = wrapper.mteb_model_meta.model_copy(update={"name": "divakantpandey/code-embed-v2-zeroshot"})
|
| 20 |
+
tasks, seen = [], set()
|
| 21 |
+
for b in ("MTEB(Code, v1)", "CoIR", "CoREB(v1)"):
|
| 22 |
+
for t in mteb.get_benchmark(b).tasks:
|
| 23 |
+
if t.metadata.name not in seen:
|
| 24 |
+
seen.add(t.metadata.name)
|
| 25 |
+
tasks.append(t)
|
| 26 |
+
for t in tasks:
|
| 27 |
+
t0 = time.time()
|
| 28 |
+
mteb.evaluate(wrapper, [t], encode_kwargs={"batch_size": 64}, cache=ResultCache(str(OUT / "cache")))
|
| 29 |
+
print(f"eval done {t.metadata.name} in {(time.time() - t0) / 60:.1f} min", flush=True)
|
| 30 |
+
HfApi().upload_folder(folder_path=str(OUT), repo_id="divakantpandey/code-embed-v3-src",
|
| 31 |
+
path_in_repo="v2-zeroshot/results", commit_message=f"v2-zeroshot eval {t.metadata.name}")
|
| 32 |
+
(OUT / "DONE").write_text("ok")
|
v2-zeroshot/src/onstart.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
mkdir -p /workspace && cd /workspace
|
| 3 |
+
exec >> /workspace/onstart.log 2>&1
|
| 4 |
+
echo "boot $(date -u)"
|
| 5 |
+
command -v git >/dev/null && command -v curl >/dev/null || { apt-get update -qq && apt-get install -y -qq git curl ca-certificates; }
|
| 6 |
+
[ -x "$HOME/.local/bin/uv" ] || curl -LsSf https://astral.sh/uv/install.sh | sh
|
| 7 |
+
export PATH="$HOME/.local/bin:$PATH" HF_HOME=/workspace/.cache/huggingface UV_LINK_MODE=copy
|
| 8 |
+
[ -d code ] || git clone -q https://github.com/divakantpandey/code-embed-v3 code
|
| 9 |
+
git -C code checkout -q d34068d
|
| 10 |
+
for f in run.sh train_v2zs.py eval_v2zs.py v2_zeroshot.yaml; do
|
| 11 |
+
curl -fsSL -H "Authorization: Bearer $HF_TOKEN" -o /workspace/$f \
|
| 12 |
+
https://huggingface.co/divakantpandey/code-embed-v3-src/resolve/main/v2-zeroshot/src/$f
|
| 13 |
+
done
|
| 14 |
+
(cd code && uv python install 3.12 && uv sync --frozen)
|
| 15 |
+
nvidia-smi
|
| 16 |
+
nohup bash /workspace/run.sh >> /workspace/run.log 2>&1 &
|
| 17 |
+
echo "started run.sh pid $!"
|
v2-zeroshot/src/run.sh
ADDED
|
File without changes
|
v2-zeroshot/src/train_v2zs.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""code-embed-v2's three-stage recipe on zero-shot data, re-implemented in Sentence Transformers.
|
| 2 |
+
|
| 3 |
+
Architecture and hyperparameters copy the released v2 checkpoint and configs/v2_multilingual_config.yaml:
|
| 4 |
+
UniXcoder-base, mean pooling, Dense 768->1536 GELU, Dense 1536->1536, Normalize; 1,024 tokens; bf16;
|
| 5 |
+
per-device batch 32 x 4 accumulation; one epoch per stage. Gradient accumulation does not add in-batch
|
| 6 |
+
negatives, so each step sees 31 negatives, as in v2.
|
| 7 |
+
|
| 8 |
+
--smoke runs every stage for a few steps on streamed rows and prints samples/s, so the full run's time
|
| 9 |
+
and cost can be projected before it starts.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from datasets import Dataset, concatenate_datasets
|
| 20 |
+
from sentence_transformers import SentenceTransformer
|
| 21 |
+
from sentence_transformers.models import Dense, Normalize, Pooling, Transformer
|
| 22 |
+
from sentence_transformers.sentence_transformer.losses import MatryoshkaLoss, MultipleNegativesRankingLoss
|
| 23 |
+
from sentence_transformers.sentence_transformer.trainer import SentenceTransformerTrainer
|
| 24 |
+
from sentence_transformers.sentence_transformer.training_args import SentenceTransformerTrainingArguments
|
| 25 |
+
from transformers import TrainerCallback
|
| 26 |
+
|
| 27 |
+
BASE = "microsoft/unixcoder-base"
|
| 28 |
+
DIMS = [64, 128, 256, 384, 768, 1536]
|
| 29 |
+
DIM_WEIGHTS = [0.1, 0.1, 0.15, 0.15, 0.25, 0.25]
|
| 30 |
+
STAGES = {
|
| 31 |
+
1: {"lr": 3.0e-5, "warmup": 0.10, "sched": "cosine", "scale": 1 / 0.05},
|
| 32 |
+
2: {"lr": 2.6975e-5, "warmup": 0.15, "sched": "cosine_with_restarts", "scale": 25.0},
|
| 33 |
+
3: {"lr": 1.0e-5, "warmup": 0.10, "sched": "cosine", "scale": 25.0},
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def build_model() -> SentenceTransformer:
|
| 38 |
+
tr = Transformer(BASE, max_seq_length=1024)
|
| 39 |
+
pool = Pooling(tr.get_word_embedding_dimension(), pooling_mode="mean")
|
| 40 |
+
d1 = Dense(768, 1536, activation_function=torch.nn.GELU())
|
| 41 |
+
d2 = Dense(1536, 1536, activation_function=torch.nn.Identity())
|
| 42 |
+
return SentenceTransformer(modules=[tr, pool, d1, d2, Normalize()])
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def load_pairs(data_dir: str) -> Dataset:
|
| 46 |
+
from code_embed_v3.data.build import load_mix
|
| 47 |
+
|
| 48 |
+
mix, _ = load_mix(data_dir, require_audit=True)
|
| 49 |
+
parts = [mix[k].select_columns(["anchor", "positive"]) for k in sorted(mix)]
|
| 50 |
+
return concatenate_datasets(parts).shuffle(seed=42)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def smoke_pairs(n: int) -> Dataset:
|
| 54 |
+
from datasets import load_dataset
|
| 55 |
+
|
| 56 |
+
rows = []
|
| 57 |
+
for lang, k in (("php", 3), ("java", 3), ("python", 2), ("go", 2), ("javascript", 1), ("ruby", 1)):
|
| 58 |
+
it = load_dataset(f"nomic-ai/cornstack-{lang}-v1", split="train", streaming=True)
|
| 59 |
+
for i, r in enumerate(it):
|
| 60 |
+
if i >= n * k // 12:
|
| 61 |
+
break
|
| 62 |
+
rows.append({"anchor": r["query"], "positive": r["document"]})
|
| 63 |
+
return Dataset.from_list(rows).shuffle(seed=42)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class Throughput(TrainerCallback):
|
| 67 |
+
def __init__(self, path: Path, stage: int, eff_batch: int) -> None:
|
| 68 |
+
self.path, self.stage, self.eff = path, stage, eff_batch
|
| 69 |
+
self.t0: float | None = None
|
| 70 |
+
|
| 71 |
+
def on_step_end(self, args, state, control, **kw): # noqa: ANN001, ANN003, ANN201
|
| 72 |
+
if state.global_step == 5:
|
| 73 |
+
self.t0 = time.time()
|
| 74 |
+
if self.t0 and state.global_step % 50 == 0:
|
| 75 |
+
sps = (state.global_step - 5) * self.eff / (time.time() - self.t0)
|
| 76 |
+
left = (state.max_steps - state.global_step) * self.eff / sps / 3600
|
| 77 |
+
self.path.write_text(json.dumps({"stage": self.stage, "step": state.global_step,
|
| 78 |
+
"max_steps": state.max_steps, "samples_per_s": round(sps, 1),
|
| 79 |
+
"stage_hours_left": round(left, 2)}))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def run_stage(model: SentenceTransformer, stage: int, pairs: Dataset, out: Path, max_steps: int, report: str) -> float:
|
| 83 |
+
cfg = STAGES[stage]
|
| 84 |
+
ds = pairs.map(lambda b: {"anchor": b["positive"]}, batched=True) if stage == 1 else pairs
|
| 85 |
+
inner = MultipleNegativesRankingLoss(model, scale=cfg["scale"])
|
| 86 |
+
loss = MatryoshkaLoss(model, inner, matryoshka_dims=DIMS, matryoshka_weights=DIM_WEIGHTS) if stage == 3 else inner
|
| 87 |
+
args = SentenceTransformerTrainingArguments(
|
| 88 |
+
output_dir=str(out / f"ckpt{stage}"),
|
| 89 |
+
num_train_epochs=1,
|
| 90 |
+
max_steps=max_steps,
|
| 91 |
+
per_device_train_batch_size=32,
|
| 92 |
+
gradient_accumulation_steps=4,
|
| 93 |
+
learning_rate=cfg["lr"],
|
| 94 |
+
warmup_steps=cfg["warmup"],
|
| 95 |
+
lr_scheduler_type=cfg["sched"],
|
| 96 |
+
weight_decay=0.01,
|
| 97 |
+
max_grad_norm=1.0,
|
| 98 |
+
bf16=True,
|
| 99 |
+
tf32=True,
|
| 100 |
+
logging_steps=25,
|
| 101 |
+
save_strategy="steps",
|
| 102 |
+
save_steps=2000,
|
| 103 |
+
save_total_limit=1,
|
| 104 |
+
dataloader_num_workers=8,
|
| 105 |
+
report_to=report,
|
| 106 |
+
run_name=f"v2-zeroshot-stage{stage}",
|
| 107 |
+
seed=42,
|
| 108 |
+
)
|
| 109 |
+
tp = Throughput(out / "throughput.json", stage, 128)
|
| 110 |
+
t0 = time.time()
|
| 111 |
+
SentenceTransformerTrainer(model=model, args=args, train_dataset=ds, loss=loss, callbacks=[tp]).train()
|
| 112 |
+
hours = (time.time() - t0) / 3600
|
| 113 |
+
if max_steps < 0:
|
| 114 |
+
model.save(str(out / f"stage{stage}"))
|
| 115 |
+
return hours
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def main() -> None:
|
| 119 |
+
p = argparse.ArgumentParser()
|
| 120 |
+
p.add_argument("--data-dir", default="/workspace/data/v2_zeroshot")
|
| 121 |
+
p.add_argument("--out", default="/workspace/out")
|
| 122 |
+
p.add_argument("--smoke", action="store_true")
|
| 123 |
+
a = p.parse_args()
|
| 124 |
+
out = Path(a.out)
|
| 125 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
model = build_model()
|
| 127 |
+
print(model, flush=True)
|
| 128 |
+
if a.smoke:
|
| 129 |
+
pairs = smoke_pairs(128 * 60)
|
| 130 |
+
res = {}
|
| 131 |
+
for s in (1, 2, 3):
|
| 132 |
+
t0 = time.time()
|
| 133 |
+
run_stage(model, s, pairs, out / "smoke", max_steps=40, report="none")
|
| 134 |
+
res[s] = round((time.time() - t0), 1)
|
| 135 |
+
print(f"smoke stage {s}: 40 steps in {res[s]} s", flush=True)
|
| 136 |
+
print("SMOKE OK", json.dumps(res), flush=True)
|
| 137 |
+
return
|
| 138 |
+
pairs = load_pairs(a.data_dir)
|
| 139 |
+
print(f"{len(pairs):,} training pairs", flush=True)
|
| 140 |
+
done = json.loads((out / "stages.json").read_text()) if (out / "stages.json").exists() else {}
|
| 141 |
+
for s in (1, 2, 3):
|
| 142 |
+
if str(s) in done:
|
| 143 |
+
model = SentenceTransformer(str(out / f"stage{s}"), device="cuda")
|
| 144 |
+
continue
|
| 145 |
+
h = run_stage(model, s, pairs, out, max_steps=-1, report="wandb")
|
| 146 |
+
done[str(s)] = round(h, 3)
|
| 147 |
+
(out / "stages.json").write_text(json.dumps(done))
|
| 148 |
+
print(f"stage {s} done in {h:.2f} h", flush=True)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
main()
|
v2-zeroshot/src/v2_zeroshot.yaml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# code-embed-v2's language mix (1.84M CodeSearchNet train pairs) rebuilt from CoRNStack, which has no
|
| 2 |
+
# provenance link to any MTEB(Code, v1) / CoIR / CoREB(v1) task. +500 per source for the dev hold-out.
|
| 3 |
+
output_dir: /workspace/data/v2_zeroshot
|
| 4 |
+
seed: 42
|
| 5 |
+
dev_rows: 500
|
| 6 |
+
sources:
|
| 7 |
+
- {name: cornstack_php, loader: cornstack, family: nl2code, license: apache-2.0, hf_id: nomic-ai/cornstack-php-v1, max_rows: 511500}
|
| 8 |
+
- {name: cornstack_java, loader: cornstack, family: nl2code, license: apache-2.0, hf_id: nomic-ai/cornstack-java-v1, max_rows: 444500}
|
| 9 |
+
- {name: cornstack_python, loader: cornstack, family: nl2code, license: apache-2.0, hf_id: nomic-ai/cornstack-python-v1, max_rows: 405500}
|
| 10 |
+
- {name: cornstack_go, loader: cornstack, family: nl2code, license: apache-2.0, hf_id: nomic-ai/cornstack-go-v1, max_rows: 312500}
|
| 11 |
+
- {name: cornstack_javascript, loader: cornstack, family: nl2code, license: apache-2.0, hf_id: nomic-ai/cornstack-javascript-v1, max_rows: 117500}
|
| 12 |
+
- {name: cornstack_ruby, loader: cornstack, family: nl2code, license: apache-2.0, hf_id: nomic-ai/cornstack-ruby-v1, max_rows: 48500}
|