Text Generation
PEFT
Safetensors
English
pyspark
data-engineering
code-generation
qlora
lora
delta-lake
conversational
Instructions to use hoodarunner/pyspark-coding-assistant-lora with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use hoodarunner/pyspark-coding-assistant-lora with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3") model = PeftModel.from_pretrained(base_model, "hoodarunner/pyspark-coding-assistant-lora") - Notebooks
- Google Colab
- Kaggle
File size: 9,381 Bytes
de46078 | 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 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | """Run a model over the suite and score it.
pass@k uses the unbiased estimator from Chen et al. (2021), "Evaluating Large
Language Models Trained on Code" -- not the naive "did any of k samples pass",
which is biased upward and not comparable across different n.
"""
from __future__ import annotations
import json
import time
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from pyspark.sql import SparkSession
from .harness import ExecResult, evaluate_candidate
from .models import DummyModel, Model, ModelError
from .prompting import build_prompt, extract_code
from .schema import Task
def pass_at_k(n: int, c: int, k: int) -> float:
"""Probability that at least one of k samples drawn from n passes.
n = samples generated, c = samples that passed.
"""
if n < k:
raise ValueError(f"cannot estimate pass@{k} from only {n} samples")
if n - c < k:
return 1.0
# Product form avoids overflow in the binomial coefficients.
prob = 1.0
for i in range(k):
prob *= (n - c - i) / (n - i)
return 1.0 - prob
@dataclass
class SampleRecord:
task_id: str
category: str
difficulty: str
sample_index: int
passed: bool
status: str
detail: str
raw_response: str
extracted_code: str
latency_s: float
@dataclass
class TaskRecord:
task_id: str
category: str
difficulty: str
probes: str
n: int
c: int
statuses: dict[str, int] = field(default_factory=dict)
@dataclass
class RunReport:
model: str
n_samples: int
temperature: float
started_at: str
duration_s: float
n_tasks: int
pass_at_1: float
pass_at_k: dict[str, float]
by_category: dict[str, dict]
by_difficulty: dict[str, dict]
failure_modes: dict[str, int]
tasks: list[TaskRecord]
samples: list[SampleRecord]
def to_json(self) -> str:
return json.dumps(asdict(self), indent=2)
def get_spark(app_name: str = "spark-eval") -> SparkSession:
"""A small, deterministic, local Spark session.
Single shuffle partition is deliberate: it makes float aggregation order
reproducible and cuts per-task overhead by more than half. Tasks are tiny;
parallelism buys nothing here.
"""
return (
SparkSession.builder.appName(app_name)
.master("local[2]")
.config("spark.sql.shuffle.partitions", "1")
.config("spark.default.parallelism", "2")
.config("spark.sql.adaptive.enabled", "false")
.config("spark.ui.enabled", "false")
.config("spark.sql.session.timeZone", "UTC")
.config("spark.driver.memory", "2g")
.getOrCreate()
)
def run_suite(
tasks: list[Task],
model: Model,
*,
n_samples: int = 1,
ks: tuple[int, ...] = (1,),
temperature: float = 0.2,
max_tokens: int = 1024,
timeout: int = 60,
spark: SparkSession | None = None,
keep_responses: bool = True,
progress: bool = True,
) -> RunReport:
owns_spark = spark is None
spark = spark or get_spark()
spark.sparkContext.setLogLevel("ERROR")
started = datetime.now(timezone.utc)
t0 = time.time()
samples: list[SampleRecord] = []
task_records: list[TaskRecord] = []
failure_modes: dict[str, int] = defaultdict(int)
for idx, task in enumerate(tasks, 1):
prompt = build_prompt(task)
# The dummy backend needs the gold answer keyed by the exact prompt.
if isinstance(model, DummyModel):
model.register(prompt, task.solution)
statuses: dict[str, int] = defaultdict(int)
passed_count = 0
for s in range(n_samples):
s_t0 = time.time()
try:
raw = model.generate(prompt, temperature, max_tokens)
except ModelError as exc:
raw = ""
result = ExecResult(False, "model_error", str(exc))
code = ""
else:
code = extract_code(raw)
if not code.strip():
result = ExecResult(False, "empty_response", "no code in response")
else:
result = evaluate_candidate(spark, task, code, timeout=timeout)
latency = time.time() - s_t0
statuses[result.status] += 1
if result.ok:
passed_count += 1
else:
failure_modes[result.status] += 1
samples.append(
SampleRecord(
task_id=task.id,
category=task.category,
difficulty=task.difficulty,
sample_index=s,
passed=result.ok,
status=result.status,
detail=result.detail,
raw_response=raw if keep_responses else "",
extracted_code=code if keep_responses else "",
latency_s=round(latency, 3),
)
)
# A broken reference solution means the benchmark is lying. Stop.
if result.status == "reference_broken":
raise RuntimeError(result.detail)
task_records.append(
TaskRecord(
task_id=task.id,
category=task.category,
difficulty=task.difficulty,
probes=task.probes,
n=n_samples,
c=passed_count,
statuses=dict(statuses),
)
)
if progress:
mark = "PASS" if passed_count == n_samples else (
"FAIL" if passed_count == 0 else f"{passed_count}/{n_samples}"
)
print(
f"[{idx:>3}/{len(tasks)}] {task.id:<40} {mark}",
flush=True,
)
def _agg(records: list[TaskRecord]) -> dict:
if not records:
return {"n_tasks": 0, "pass_at_1": 0.0}
out = {
"n_tasks": len(records),
"pass_at_1": round(
sum(pass_at_k(r.n, r.c, 1) for r in records) / len(records), 4
),
}
for k in ks:
if k > 1 and n_samples >= k:
out[f"pass_at_{k}"] = round(
sum(pass_at_k(r.n, r.c, k) for r in records) / len(records), 4
)
return out
by_category: dict[str, dict] = {}
for cat in sorted({r.category for r in task_records}):
by_category[cat] = _agg([r for r in task_records if r.category == cat])
by_difficulty: dict[str, dict] = {}
for diff in ("easy", "medium", "hard"):
subset = [r for r in task_records if r.difficulty == diff]
if subset:
by_difficulty[diff] = _agg(subset)
overall = _agg(task_records)
report = RunReport(
model=model.name,
n_samples=n_samples,
temperature=temperature,
started_at=started.isoformat(),
duration_s=round(time.time() - t0, 2),
n_tasks=len(task_records),
pass_at_1=overall["pass_at_1"],
pass_at_k={
f"pass_at_{k}": overall[f"pass_at_{k}"]
for k in ks
if k > 1 and f"pass_at_{k}" in overall
},
by_category=by_category,
by_difficulty=by_difficulty,
failure_modes=dict(sorted(failure_modes.items(), key=lambda kv: -kv[1])),
tasks=task_records,
samples=samples,
)
if owns_spark:
spark.stop()
return report
def format_report(report: RunReport) -> str:
"""Human-readable summary. The JSON is the machine-readable artifact."""
lines = [
"",
"=" * 68,
f" spark-eval | {report.model}",
"=" * 68,
f" tasks {report.n_tasks}",
f" samples {report.n_samples} per task @ temperature {report.temperature}",
f" duration {report.duration_s}s",
"",
f" pass@1 {report.pass_at_1:.1%}",
]
for key, v in report.pass_at_k.items():
label = "pass@" + key.rsplit("_", 1)[-1]
lines.append(f" {label:<11} {v:.1%}")
def _plural(n: int) -> str:
return f"{n} task" if n == 1 else f"{n} tasks"
# Worst category first: the point of the breakdown is finding the weakness.
lines += ["", " By category", " " + "-" * 46]
for cat, stats in sorted(
report.by_category.items(), key=lambda kv: kv[1]["pass_at_1"]
):
lines.append(
f" {cat:<22} {stats['pass_at_1']:>6.1%} ({_plural(stats['n_tasks'])})"
)
if report.by_difficulty:
lines += ["", " By difficulty", " " + "-" * 46]
for diff, stats in report.by_difficulty.items():
lines.append(
f" {diff:<22} {stats['pass_at_1']:>6.1%} ({_plural(stats['n_tasks'])})"
)
if report.failure_modes:
lines += ["", " Failure modes", " " + "-" * 46]
total = sum(report.failure_modes.values())
for mode, count in report.failure_modes.items():
lines.append(f" {mode:<22} {count:>4} ({count / total:.0%})")
lines += ["", "=" * 68, ""]
return "\n".join(lines)
def write_report(report: RunReport, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(report.to_json())
|