File size: 6,514 Bytes
498f80b | 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 | """Data loading and preparation for guac-coder GRPO training."""
import json
import logging
import os
from pathlib import Path
from typing import Dict, Iterator, List, Optional
from guac_coder.config import DataConfig
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Prompt templates for code generation tasks
# ---------------------------------------------------------------------------
CODE_GENERATION_PROMPT = """You are guac-coder, an expert research scientist and Python programmer.
Write clean, objective, resumable Python code for the task below.
Rules:
- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.
- No plot grids, no plot titles.
- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.
- Use logging, not print.
- Write functions and __main__ guards. No bare scripts.
- Add checkpoint/resume logic where appropriate.
- No unnecessary narrative comments. Comments must be objective and concise.
- Avoid try/except unless absolutely necessary.
- Avoid classes unless the abstraction is genuinely needed.
- Write data incrementally, not in a single batch dump.
Task: {task}
Provide the full Python implementation.
"""
RESEARCH_TASKS: List[str] = [
"Implement a data loader that reads a CSV of galaxy properties, filters by redshift, and writes the filtered subset to disk with intermittent checkpointing.",
"Implement a function that computes the pairwise cosine similarity between rows of a sparse matrix and saves results incrementally to a feather file.",
"Implement a knowledge graph embedding trainer that saves entity/relation checkpoints every N batches and resumes from the latest checkpoint.",
"Implement a plotting utility that visualizes a 2D embedding space using chroptiks, with no grid, no title, and proper color mapping.",
"Implement a scientific paper metadata scraper that writes parsed metadata to CSV incrementally with logging at each stage.",
"Implement a mixture model fitter that logs likelihood values and saves model state periodically for resumable training.",
"Implement a text preprocessing pipeline for NLP experiments that reads raw text, tokenizes, and writes processed chunks to disk with checkpoint tracking.",
"Implement a benchmarking script that runs experiments, logs metrics via logging module, and appends results to a CSV after each trial.",
"Implement a function that generates synthetic tabular data for ML experiments and writes rows incrementally to parquet.",
"Implement a model evaluation script that loads a checkpointed model, evaluates on a test set, and logs metrics to CSV using pandas.",
]
def load_research_tasks(path: Optional[str] = None) -> List[str]:
"""Load research task prompts."""
if path and os.path.isfile(path):
with open(path, "r", encoding="utf-8") as fh:
if path.endswith(".jsonl"):
tasks = []
for line in fh:
obj = json.loads(line)
tasks.append(obj.get("task", obj.get("instruction", "")))
return [t for t in tasks if t]
else:
return [line.strip() for line in fh if line.strip()]
return RESEARCH_TASKS.copy()
def build_prompt(task: str) -> str:
"""Wrap a raw task in the system-style prompt."""
return CODE_GENERATION_PROMPT.format(task=task)
def prepare_training_examples(tasks: List[str]) -> Iterator[Dict]:
"""Yield dicts with 'prompt' and 'task' keys."""
for task in tasks:
yield {"prompt": build_prompt(task), "task": task}
def load_code_from_repos(cfg: DataConfig) -> Iterator[Dict]:
"""Walk source repositories and extract Python files as training examples.
Yields dicts with:
- prompt: generated prompt for the code
- code: the source code
- source_file: origin path
"""
for repo_path in cfg.source_repos:
repo = Path(repo_path)
if not repo.exists():
logger.warning("Repo path does not exist: %s", repo_path)
continue
for ext in cfg.filter_by_extension:
for fp in repo.rglob(f"*{ext}"):
try:
source = fp.read_text(encoding="utf-8")
lines = source.splitlines()
if cfg.min_code_lines <= len(lines) <= cfg.max_code_lines:
# Derive a task description from the file path
task = f"Implement the functionality in {fp.name} for the {fp.parent.name} module."
yield {
"prompt": build_prompt(task),
"code": source,
"source_file": str(fp),
}
except Exception as exc:
logger.debug("Skipped %s: %s", fp, exc)
def save_data(examples: Iterator[Dict], path: str) -> None:
"""Write examples to JSONL, appending incrementally."""
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
count = 0
with open(path, "w", encoding="utf-8") as fh:
for ex in examples:
fh.write(json.dumps(ex) + "\n")
count += 1
logger.info("Wrote %d examples to %s", count, path)
def load_data(path: str) -> List[Dict]:
"""Load examples from JSONL."""
examples = []
with open(path, "r", encoding="utf-8") as fh:
for line in fh:
examples.append(json.loads(line))
return examples
# ---------------------------------------------------------------------------
# Reference / SFT pair generation
# ---------------------------------------------------------------------------
def generate_sft_pairs(examples: List[Dict], output_path: str) -> None:
"""Create prompt->response pairs for supervised fine-tuning.
Each example must have 'prompt' and 'code' keys.
"""
pairs = []
for ex in examples:
if "code" in ex:
pairs.append({
"messages": [
{"role": "system", "content": ex["prompt"]},
{"role": "user", "content": ex.get("task", "Write the implementation.")},
{"role": "assistant", "content": ex["code"]},
]
})
with open(output_path, "w", encoding="utf-8") as fh:
for pair in pairs:
fh.write(json.dumps(pair) + "\n")
logger.info("Wrote %d SFT pairs to %s", len(pairs), output_path)
|