data: regenerated traces post-fix. np=2560 corpus: 16/20 valid (vs 12/20 at np=1536), no truncated row scores positive
Browse files- traces/fixed/summary_qwen3.5-0.8b.json +76 -0
- traces/fixed/traces_qwen3.5-0.8b.jsonl +0 -0
- traces/fixed2560/datasets/grpo_records.jsonl +0 -0
- traces/fixed2560/datasets/manifest.json +17 -0
- traces/fixed2560/datasets/preference_pairs.jsonl +2 -0
- traces/fixed2560/datasets/sft_pairs.jsonl +10 -0
- traces/fixed2560/summary_qwen3.5-0.8b.json +76 -0
- traces/fixed2560/traces_qwen3.5-0.8b.jsonl +0 -0
traces/fixed/summary_qwen3.5-0.8b.json
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"n_traces": 20,
|
| 3 |
+
"models": {
|
| 4 |
+
"qwen3.5:0.8b": {
|
| 5 |
+
"n": 20,
|
| 6 |
+
"n_scored": 20,
|
| 7 |
+
"code_sources": {
|
| 8 |
+
"fence": 12,
|
| 9 |
+
"fence_unterminated": 8
|
| 10 |
+
},
|
| 11 |
+
"empty_reasons": {},
|
| 12 |
+
"mean_reward": -0.2923,
|
| 13 |
+
"std_reward": 0.5869,
|
| 14 |
+
"min_reward": -1.0,
|
| 15 |
+
"max_reward": 0.3462,
|
| 16 |
+
"mean_code_chars": 4825.4,
|
| 17 |
+
"rules": {
|
| 18 |
+
"chroptiks_preference_reward": {
|
| 19 |
+
"mean": -0.3,
|
| 20 |
+
"fired_frac": 0.5
|
| 21 |
+
},
|
| 22 |
+
"intermittent_writes_reward": {
|
| 23 |
+
"mean": -0.45,
|
| 24 |
+
"fired_frac": 0.65
|
| 25 |
+
},
|
| 26 |
+
"logging_over_print_reward": {
|
| 27 |
+
"mean": -0.3,
|
| 28 |
+
"fired_frac": 0.7
|
| 29 |
+
},
|
| 30 |
+
"no_bargraphs_reward": {
|
| 31 |
+
"mean": -0.175,
|
| 32 |
+
"fired_frac": 1.0
|
| 33 |
+
},
|
| 34 |
+
"no_classes_reward": {
|
| 35 |
+
"mean": -0.4,
|
| 36 |
+
"fired_frac": 1.0
|
| 37 |
+
},
|
| 38 |
+
"no_plot_grids_reward": {
|
| 39 |
+
"mean": -0.1,
|
| 40 |
+
"fired_frac": 1.0
|
| 41 |
+
},
|
| 42 |
+
"no_plot_titles_reward": {
|
| 43 |
+
"mean": -0.25,
|
| 44 |
+
"fired_frac": 1.0
|
| 45 |
+
},
|
| 46 |
+
"no_seaborn_reward": {
|
| 47 |
+
"mean": -0.1,
|
| 48 |
+
"fired_frac": 1.0
|
| 49 |
+
},
|
| 50 |
+
"no_try_except_reward": {
|
| 51 |
+
"mean": -0.775,
|
| 52 |
+
"fired_frac": 1.0
|
| 53 |
+
},
|
| 54 |
+
"not_bare_script_reward": {
|
| 55 |
+
"mean": -0.1,
|
| 56 |
+
"fired_frac": 1.0
|
| 57 |
+
},
|
| 58 |
+
"objective_comments_reward": {
|
| 59 |
+
"mean": -0.1,
|
| 60 |
+
"fired_frac": 1.0
|
| 61 |
+
},
|
| 62 |
+
"pandas_csv_preference_reward": {
|
| 63 |
+
"mean": -0.35,
|
| 64 |
+
"fired_frac": 0.75
|
| 65 |
+
},
|
| 66 |
+
"resumable_checkpoint_reward": {
|
| 67 |
+
"mean": -0.4,
|
| 68 |
+
"fired_frac": 1.0
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
"traces_path": "/home/caug/npcww/guac-coder/traces/fixed/traces_qwen3.5-0.8b.jsonl",
|
| 74 |
+
"new_traces_this_run": 20,
|
| 75 |
+
"rater": "static"
|
| 76 |
+
}
|
traces/fixed/traces_qwen3.5-0.8b.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
traces/fixed2560/datasets/grpo_records.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
traces/fixed2560/datasets/manifest.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"traces_path": "traces/fixed2560/traces_qwen3.5-0.8b.jsonl",
|
| 3 |
+
"n_traces": 20,
|
| 4 |
+
"n_scored": 16,
|
| 5 |
+
"sft": {
|
| 6 |
+
"path": "traces/fixed2560/datasets/sft_pairs.jsonl",
|
| 7 |
+
"n": 10
|
| 8 |
+
},
|
| 9 |
+
"preference": {
|
| 10 |
+
"path": "traces/fixed2560/datasets/preference_pairs.jsonl",
|
| 11 |
+
"n": 2
|
| 12 |
+
},
|
| 13 |
+
"grpo": {
|
| 14 |
+
"path": "traces/fixed2560/datasets/grpo_records.jsonl",
|
| 15 |
+
"n": 16
|
| 16 |
+
}
|
| 17 |
+
}
|
traces/fixed2560/datasets/preference_pairs.jsonl
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"prompt": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a scientific paper metadata scraper that writes parsed metadata to CSV incrementally with logging at each stage.\n\nProvide the full Python implementation.\n", "task": "Implement a scientific paper metadata scraper that writes parsed metadata to CSV incrementally with logging at each stage.", "chosen": "import os\nimport sys\nimport logging\nimport pandas as pd\nfrom datetime import datetime\n\n# Configure logging without print output\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s | %(levelname)s | %(message)s\"\n)\nlogger = logging.getLogger(__name__)\n\ndef load_metadata_from_csv(filepath):\n \"\"\"Load metadata from a CSV file. Returns DataFrame with columns: 'date', 'type', 'value'.\"\"\"\n df = pd.read_csv(filepath)\n if df.empty:\n logger.warning(f\"No data found in {filepath}\")\n return None\n return df\n\ndef save_metadata_to_csv(df, filepath):\n \"\"\"Save dataframe to CSV file with metadata columns. Writes incrementally.\"\"\"\n if len(df.columns) != 3 or any(col == \"date\" and col == \"value\" for col in df.columns) or df[\"value\"].dtype == object:\n logger.warning(f\"Not valid metadata format: expected column 'date', 'type', 'value'. Got columns {df.columns.tolist()}\")\n \n if len(df.columns) < 3:\n pd.DataFrame({\"date\": pd.to_datetime(df.get(\"date\", None)), \"type\": pd.to_categorical(df.get(\"type\", 0), num_categories=3)})\n df = pd.DataFrame({\"date\": pd.to_datetime(df.get(\"date\", None)), \"type\": df[\"value\"].map(lambda x: x if not pd.isna(x) else 0)})\n \n logger.info(f\"Writing {len(df)} records to {filepath}\")\n df.to_csv(filepath, index=False)\n\ndef process_single_data_point(data_point):\n \"\"\"Process a single data point from the CSV.\"\"\"\n if len(data_point) < 2:\n return None\n \n date = str(data_point.get(\"date\", \"N/A\"))\n type_val = data_point.get(\"type\", \"unknown\")\n value_str = data_point.get(\"value\", \"\")\n \n if isinstance(type_val, pd.Series):\n try:\n type_map = {0: 'low', 1: 'medium', 2: 'high'}\n type = type_map[type_val]\n except KeyError as e:\n type = \"unknown\"\n elif type_val in (\"null\", \"N/A\"):\n type = \"unknown\"\n else:\n type = type_val\n\n # Handle numeric values by converting string to float if needed\n try:\n value = float(value_str)\n except (ValueError, TypeError):\n value = 0.0\n\n return {\n \"date\": date,\n \"type\": type,\n \"value\": value\n }\n\ndef process_batch(data_list):\n \"\"\"Process a list of data points and extract metadata.\"\"\"\n if not isinstance(data_list, list) or len(data_list) == 0:\n raise ValueError(\"Data list must contain at least one valid point\")\n \n results = []\n for item in data_list:\n result = process_single_data_point(item)\n if result is None:\n continue\n results.append(result)\n \n logger.info(f\"Processing {len(results)} records from batch\")\n\ndef main():\n input_file = \"./metadata.json\"\n output_file = \"./metadata.csv\"\n \n # Ensure directory exists for write operations\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n \n try:\n logger.info(\"Loading metadata from JSON file...\")\n with open(input_file, \"r\") as f:\n data_list = json.load(f)\n \n process_batch(data_list)\n logger.info(f\"Writing to CSV: {output_file}\")\n \n except FileNotFoundError as e:\n logger.error(f\"Input file not found: {e}\")\n sys.exit(1)\n except Exception as e:\n logger.error(f\"Error processing data: {e}\")\n sys.exit(1)\n\nif __name__ == \"__main__\":\n main()", "rejected": "import csv\nimport os\nimport sys\nimport pandas as pd\nfrom datetime import datetime\nimport logging\n\n# Configure logging with minimal output for paper metadata extraction\nclass LoggingHandler(logging.Handler):\n def __init__(self):\n super().__init__()\n self.logs = []\n \n def emit(self, record):\n log_line = f\"[{datetime.now().isoformat()}] LOG: {record.name} - [{record.levelname}] {record.getMessage()}\"\n self.logs.append(log_line)\n # Print only the last 10 lines for efficiency\n if len(self.logs) > 10:\n sys.stdout.write(\"\\n\".join(self.logs[-10:]) + \"\\n\")\n\ndef setup_logging():\n handler = LoggingHandler()\n logging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s - %(levelname)s - %(message)s',\n handlers=[handler]\n )\n return handler\n\ndef extract_metadata(filepath):\n \"\"\"\n Extracts metadata from a file.\n \n Args:\n filepath: Path to the source file\n \n Returns:\n pd.DataFrame: Dictionary of parsed metadata keys as columns\n \"\"\"\n # Initialize logging setup if not already done\n handler = None\n if os.path.exists(filepath):\n handler = setup_logging()\n \n try:\n with open(filepath, 'r', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n \n data = {k: v for k, v in reader.fieldnames}\n # Convert string dates to datetime objects (standard ISO format)\n data['creation_time'] = pd.to_datetime(data.get('creation_time', ''), errors='coerce')\n \n return pd.DataFrame(data)\n except Exception as e:\n print(f\"Error reading file {filepath}: {e}\", file=sys.stderr)\n return pd.DataFrame({})\n\ndef write_metadata_to_csv(filepath, metadata):\n \"\"\"\n Writes parsed metadata to a CSV file with incremental logging.\n \n Args:\n filepath: Path to the output file\n metadata: Dictionary of parsed metadata\n \"\"\"\n if os.path.exists(filepath):\n print(f\"Warning: Output file {filepath} already exists\", file=sys.stderr)\n\n handler = None\n if os.path.exists(filepath):\n handler = setup_logging()\n \n try:\n with open(filepath, 'w', newline='', encoding='utf-8') as f:\n writer = csv.DictWriter(f, fieldnames=metadata.keys())\n if writer.dtypes != pd.DtypeObj.none:\n writer.writeheader()\n \n for key, value in metadata.items():\n fieldname = key.lower().replace('_', ' ')\n # Convert string dates to datetime objects (standard ISO format)\n timestamp = pd.to_datetime(value, errors='coerce')\n writer.writerow({fieldname: str(timestamp)})\n except Exception as e:\n print(f\"Error writing file {filepath}: {e}\", file=sys.stderr)\n\ndef main():\n \"\"\"\n Main function to execute paper metadata scraper logic.\n Requires argument 'paper_file' for input/output paths.\n \"\"\"\n # Check for required script argument\n if len(sys.argv) < 2:\n print(\"Usage: python script.py <input_paper_file> <output_csv_file>\", file=sys.stderr)\n sys.exit(1)\n\n paper_file = sys.argv[1]\n csv_file = sys.argv[2]\n \n # Check for input and output files\n if not os.path.exists(paper_file):\n print(f\"Error: File {paper_file} not found\", file=sys.stderr)\n sys.exit(1)\n \n if not os.path.exists(csv_file):\n print(f\"Error: File {csv_file} not found\", file=sys.stderr)\n sys.exit(1)\n\n # Read metadata from paper file\n data = extract_metadata(paper_file)\n \n # Write incremental output to CSV\n write_metadata_to_csv(csv_file, data)\n \n print(f\"Successfully extracted and saved {len(data)} records to {csv_file}\")\n\nif __name__ == \"__main__\":\n main()", "chosen_reward": 0.34615384615384615, "rejected_reward": 0.0, "gap": 0.3462, "meta": {"source_model": "qwen3.5:0.8b", "task_id": 4}}
|
| 2 |
+
{"prompt": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a mixture model fitter that logs likelihood values and saves model state periodically for resumable training.\n\nProvide the full Python implementation.\n", "task": "Implement a mixture model fitter that logs likelihood values and saves model state periodically for resumable training.", "chosen": "import logging\nimport numpy as np\nfrom chroptiks import Chroptiks\nfrom pathlib import Path\nimport warnings\n\n# Configure logging to avoid warnings by default\nlogging.basicConfig(level=logging.INFO, format='%(message)s')\n\n# Global checkpoint state\nCHECKPOINT_PATH = \"model_checkpoint\"\n\nclass MixtureFitter:\n \"\"\"\n Fitter class for implementing a mixture model.\n \n Attributes:\n x_train (list): List of training samples.\n y_train (list): List of true labels for training samples.\n n_samples (int): Number of training samples.\n data (dict): Dictionary containing feature and label arrays.\n weights (dict): Dictionary storing hyperparameter values and their associated \n probabilities, initialized with defaults.\n likelihoods (list): List of calculated likelihood values during training.\n \n Methods:\n fit(self, X, y): Train the mixture model on the provided data.\n predict(self, X): Predict class labels for new samples using trained model.\n save_model(): Save current state to checkpoint file.\n load_checkpoint(): Load previous model state from checkpoint file.\n log_likelihood(self, label): Log likelihood value associated with a sample.\n \"\"\"\n\n def __init__(self, max_iterations=100000):\n \"\"\"\n Initialize the MixtureFitter.\n\n Args:\n max_iterations (int): Maximum number of iterations allowed before stopping training.\n \"\"\"\n self.X = np.array([])\n self.y = []\n self.n_samples = 0\n self.data = {}\n self.weights = {}\n self.likelihoods = []\n self.max_iterations = max_iterations\n\n def fit(self, X, y):\n \"\"\"\n Train the mixture model using maximum likelihood estimation.\n\n Args:\n X (np.ndarray): Feature matrix containing features for each sample. Shape: (n_samples, n_features).\n y (list): Label vector of length n_samples, where index i corresponds to label i in y.\n Each entry should be either 'A' or 'B'.\n\n Returns:\n Chroptiks: Trained model object with stored metrics and weights.\n \"\"\"\n # Initialize global state\n self.X = X\n self.y = y.copy()\n self.n_samples = len(y)\n\n # Initialize weights for all classes\n self.weights = {\"A\": 0.5, \"B\": 0.5}\n\n # Calculate initial likelihoods and log-likelihood\n self.likelihoods = []\n n_features = X.shape[1]\n \n with logging.getLogger() as logger:\n logger.info(\"Starting mixture model fit...\")\n\n for i in range(self.n_samples):\n x = X[i].copy().astype(np.float64)\n y_true = self.y[i]\n \n # Initialize weights to default class probabilities\n w = {\"A\": 0.5, \"B\": 0.5}\n \n # Iterate through all possible classes\n for k in [\"A\", \"B\"]:\n # Sample with replacement\n w[k] = np.random.choice(self.weights[k], size=1)\n \n # Calculate likelihood of the current sample given class k\n likelihoods, log_likelihoods = Chroptiks.fit(\n x, y_true, weights=w\n )\n \n self.likelihoods.append(likelihoods.log_prob)\n self.likelihoods.append(log_likelihoods)\n \n # Store data and initialize weights for this iteration\n self.data[\"X\"] = X[i]\n self.data[\"y\"] = y_true\n self.weights = w\n\n logging.getLogger().info(f\"Model fit completed with {len(self.likelihoods)} likelihood values.\")\n\n def predict(self, X):\n \"\"\"\n Predict class labels for new samples using trained model.\n\n Args:\n X (np.ndarray): Feature matrix of length n_samples containing features for each sample. Shape: (n_samples, n_features).\n\n Returns:\n list: Prediction vector of length n_samples, where index i corresponds to label i.\n Each entry is either 'A' or 'B'.\n \"\"\"\n predictions = np.array([])\n # Create array with all A labels first, then append B labels for each sample\n predictions = np.concatenate([np.ones(self.n_samples), self.y])\n\n return Chroptiks.predict(X, predictions)\n\n def save_model(self):\n \"\"\"\n Save current state to the checkpoint file.\n\n Returns:\n bool: True if successful, False otherwise.\n \"\"\"\n path = Path(CHECKPOINT_PATH)\n \n try:\n # Ensure directory exists (basic safety measure)\n if not path.exists():\n raise FileNotFoundError(f\"Checkpoint path does not exist: {path}\")\n\n # Save weights as a dictionary\n self.weights_to_save = {}\n for k, v in self.weights.items():\n self.weights_to_save[k] = float(v)\n \n with logging.getLogger() as logger:\n logger.info(\"Saving model to checkpoint...\")\n checkpoint_data = {\n \"weights\": self.weights_to_save,\n \"likelihoods\": self.likelihoods,\n \"X\": self.X.tolist(),\n \"y\": self.y.tolist()\n }\n \n # Save data to file using .to_csv\n data_path = path.parent / \"model_data.csv\"\n checkpoint_data.to_csv(data_path, index=False)\n \n logger.info(f\"Model saved to {data_path}\")\n return True\n \n except Exception as e:\n logging.getLogger().error(f\"Error saving model: {e}\")\n return False\n\n def load_checkpoint(self):\n \"\"\"\n Load previous state from the checkpoint file.\n\n Returns:\n Chroptiks: Model object with loaded weights and likelihoods.\n \"\"\"\n path = Path(CHECKPOINT_PATH)\n \n try:\n # Ensure directory exists\n if not path.exists():\n raise FileNotFoundError(f\"Checkpoint path does not exist: {path}\")\n\n # Open file to load data from CSV\n checkpoint_data = np.loadtxt(path, delimiter=',')\n\n # Convert dictionary keys to numpy arrays\n self.weights[\"A\"] = checkpoint_data[\"weights\"][\"A\"].astype(float)\n self.weights[\"B\"] = checkpoint_data[\"weights\"][\"B\"].astype(float)\n\n # Convert likelihoods lists to numpy arrays\n self.likelihoods = np.array([checkpoint_data[\"likelihoods\"][i] for i in range(len(checkpoint_data[\"likelihoods\"]))])\n \n # Reconstruct X and y from previous state\n self.X = checkpoint_data[\"X\"].astype(float)\n self.y = checkpoint_data[\"y\"]\n \n logging.getLogger().info(f\"Loaded model from {path}\")\n return Chroptiks(self.X, self.y)\n\n except Exception as e:\n logging.getLogger().error(f\"Error loading checkpoint: {e}\")\n raise\n\n def log_likelihood(self, label):\n \"\"\"\n Log likelihood value associated with a sample.\n\n Args:\n label (str): The true label for the sample ('A' or 'B').\n \"\"\"\n self.y.append(label)\n # Calculate current likelihood using Chroptiks\n likelihoods, _ = Chroptiks.fit(\n self.X, self.y, weights=self.weights\n )\n logging.getLogger().info(f\"Logged likelihood: {likelihoods.log_prob:.6f}\")\n\n# __main__ guard\nif __name__ == \"__main__\":\n # Initialize the model with default parameters\n model = MixtureFitter(max_iterations=1000)\n\n # Sample training data (replace with actual dataset if available)\n X_train = np.random.randn(100, 5)\n y_train = np.array(['A'] * 100 + ['B'] * 0)\n\n try:\n model.fit(X_train, y_train)\n print(\"Model training completed successfully.\")\n except Exception as e:\n logging.getLogger().error(f\"Training failed: {e}\")", "rejected": "import logging\nimport os\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nfrom datetime import timedelta\n\n# Setup logging to simulate production environment\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s [%(levelname)s] %(message)s',\n handlers=[\n logging.FileHandler('model_training.log'),\n logging.StreamHandler()\n ]\n)\n\nclass MixtureFitter:\n \"\"\"\n A flexible mixture model fitter with checkpointing support.\n Handles data loading, fitting, evaluation, and periodic saving.\n \"\"\"\n\n def __init__(self, n_components=3):\n self.n_components = np.array(n_components).astype(int)\n self.components = {i: 0 for i in range(len(self.n_components))}\n \n # Path to current directory\n self.current_path = Path(\".\").resolve()\n \n def load_data(self, filename=None, chunk_size=None):\n \"\"\"\n Load data from file or URL.\n \n Args:\n filename (str or None): Name of the CSV file. None means read from current working directory.\n chunk_size (int): Number of rows per chunk for parallel loading.\n \n Returns:\n pd.DataFrame: Loaded data\n \"\"\"\n if filename is None and os.path.isfile(self.current_path / \"data.csv\"):\n df = pd.read_csv(self.current_path / \"data.csv\")\n elif filename is None or not os.path.exists(filename):\n raise ValueError(f\"Data file not found at {filename}\")\n \n # Determine load strategy: batch or chunk\n if chunk_size and isinstance(chunk_size, int) and chunk_size > 0:\n chunks = [chunk_size] * len(df)\n elif chunk_size and isinstance(chunk_size, str):\n try:\n chunks = [int(chunk_size)] * len(df)\n except ValueError:\n raise ValueError(f\"Chunk size {chunk_size} is not an integer\")\n \n data = []\n for i in range(len(df)):\n start = i * chunk_size if chunk_size else 0\n end = min(start + chunk_size, df.shape[0])\n data.append(df.iloc[start:end])\n \n self.data = pd.concat(data)\n return self.data\n\n def fit(self, X_train, y_train=None):\n \"\"\"\n Train mixture model.\n \n Args:\n X_train (pd.DataFrame): Training data.\n y_train (array, optional): Target labels for binary classification or prediction.\n If None, treats all classes as binary.\n \n Returns:\n MixtureFitter: The fitted model instance\n \"\"\"\n # Initialize components\n self.components = np.array([0] * len(self.n_components))\n \n # Handle target variable if provided\n if y_train is not None and isinstance(y_train, (list, tuple)):\n labels = np.array(y_train)\n n_classes = len(labels)\n \n for i in range(len(self.components)):\n self.components[i] = int(np.mean(labels))\n \n y = labels.flatten() if len(y_train) > 1 else 0\n \n elif y_train is not None and isinstance(y_train, pd.Series):\n y = y_train.values\n \n elif y_train is not None and hasattr(y_train, 'values'):\n y = y_train.values\n \n elif y_train is not None:\n raise ValueError(\"y_train must be an array or Series object\")\n \n else:\n # Binary classification default\n n_classes = 2\n for i in range(len(self.components)):\n self.components[i] = int(np.mean(labels)) if len(labels) > 1 else 0\n \n y = np.array([0, 1]) if len(y_train) == 2 else np.array([0])\n \n # Train Mixture Model (Multinomial)\n n_samples = X_train.shape[0]\n \n self.mixture_model = np.zeros(n_components)\n \n for i in range(len(self.components)):\n data_points = X_train[self.data.index.where(self.components[i] > 0)]\n \n if len(data_points) == 0:\n continue\n \n counts = np.bincount(self.components[i])\n self.mixture_model[:, i] = counts\n \n for j in range(len(self.components)):\n count = int(np.sum(counts))\n # Ensure correct label by assigning the correct class\n if count > 0 and (j == i or (self.components[j] != i) and np.abs(i - j) < self.mixture_model[i, :]) and (i != j):\n self.mixture_model[:, i] = count\n \n # Store training data for later processing\n self.data = pd.concat([self.data, data_points]).reset_index(drop=True)\n \n return self\n\n def evaluate(self, X_test=None, y_test=None):\n \"\"\"\n Evaluate the model.\n \n Args:\n X_test (pd.DataFrame): Test data if provided.\n y_test (array or pd.Series): Target labels if provided.\n \n Returns:\n dict: Model metrics including accuracy and entropy\n \"\"\"\n metrics = {}\n \n # Ensure inputs are valid arrays\n if isinstance(y_test, list) and not np.isscalar(y_test[0]):\n y_test = np.array(y_test)\n elif not hasattr(y_test, 'values') or len(y_test) == 2:\n y_test = np.array([y_test])\n else:\n raise ValueError(\"y_test must be an array of shape (n_samples,)\")\n \n # Check if test data exists\n if X_test is None and hasattr(self.data, 'values'):\n X_test = self.data.values.copy()\n \n X_train, X_test, y_train, y_test = self.data.iloc[0:2].values\n \n # Get component probabilities for training data to calculate entropy\n prob = np.sum(self.mixture_model, axis=1)\n if len(prob) > 0:\n entropy = -np.bincount(prob, minlength=len(self.components))\n else:\n entropy = 0.0\n \n metrics[\"accuracy\"] = (y_test == 0).mean()\n metrics[\"entropy\"] = float(entropy.mean())\n \n # Save model state periodically\n save_path = self.current_path / \"mixture_model_state.json\"\n with open(save_path, 'w') as f:\n json.dump(self.model_dump(), f)\n os.chmod(save_path, 0o644)\n \n return metrics\n\n def save_checkpoint(self):\n \"\"\"Save the model state to a JSON file.\"\"\"\n if not hasattr(self.data, 'values'):\n self.data = pd.DataFrame()\n \n state = {\n \"n_components\": self.n_components.tolist(),\n \"components\": self.components.tolist(),\n \"data_shape\": list(self.data.shape),\n \"model_dump_json\": self.model_dump_json() if hasattr(self.model_dump, 'json') else None,\n \"metrics\": {\n \"accuracy\": float(metrics[\"accuracy\"]),\n \"entropy\": float(metrics[\"entropy\"])\n }\n }\n \n # Save to JSON with pickle for robustness\n path = self.current_path / \"mixture_model_state.pkl\"\n with open(path, 'wb') as f:\n pickle.dump(state, f)\n\n def load_checkpoint(self):\n \"\"\"Load a saved model checkpoint.\"\"\"\n if os.path.exists(self.current_path / \"mixture_model_state.pkl\"):\n path = self.current_path / \"mixture_model_state.pkl\"\n with open(path, 'rb') as f:\n state = pickle.load(f)\n \n # Restore components from JSON file (handles non-pickle versions)\n if hasattr(state, 'components'):\n self.components = np.array(state['components'])\n else:\n self.components = np.array([0] * len(self.n_components))\n \n return state\n\n def get_state(self):\n \"\"\"Return the current model state dictionary.\"\"\"\n return self.model_dump()\n\n# Main entry point with guard\nif __name__ == \"__main__\":\n import sys\n \n # Load sample data for demonstration\n try:\n from sklearn.datasets import make_blobs\n \n X, y = make_blobs(n_samples=200, n_features=5, centers=3, cluster_std=1.2)\n \n # Create fitted model instance\n fitter = MixtureFitter(n_components=3)\n fitter.load_data()\n \n # Train\n fitter.fit(X, y)\n \n # Evaluate\n metrics = fitter.evaluate()\n print(\"Model Evaluation:\")\n print(f\" Accuracy: {metrics['accuracy']:.4f}\")\n print(f\" Entropy: {metrics['entropy']:.4f}\")\n \n # Save state periodically\n save_path = self.current_path / \"model_training.log\"\n checkpoint_dir = self.current_path / \"checkpoints\"\n checkpoint_dir.mkdir(parents=True, exist_ok=True)\n \n for i in range(0, 15):\n fitter.save_checkpoint()\n print(f\" Checked after {i} epochs\")\n \n fitter.load_checkpoint()\n except ImportError:\n # Fallback if sklearn not available\n pass\n \n print(\"Checkpoint saved to checkpoint_dir/checkpoints/model_training_state.pkl\")", "chosen_reward": 0.23076923076923078, "rejected_reward": 0.07692307692307693, "gap": 0.1538, "meta": {"source_model": "qwen3.5:0.8b", "task_id": 5}}
|
traces/fixed2560/datasets/sft_pairs.jsonl
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a data loader that reads a CSV of galaxy properties, filters by redshift, and writes the filtered subset to disk with intermittent checkpointing.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a data loader that reads a CSV of galaxy properties, filters by redshift, and writes the filtered subset to disk with intermittent checkpointing."}, {"role": "assistant", "content": "import logging\nimport os\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nfrom datetime import timedelta\n\n# Configure logging to redirect to a file for inspection (as per best practices)\nlogging.basicConfig(level=logging.INFO, format=\"%(asctime)s - %(levelname)s - %(message)s\")\nlogger = logging.getLogger(__name__)\n\ndef check_save_directory() -> bool:\n \"\"\"Check if the save directory exists and is writable.\"\"\"\n save_dir = Path(os.environ.get(\"SAVE_DIR\", \"output\"))\n return save_dir.exists() and os.access(save_dir, os.W_OK)\n\ndef checkpoint_data(df: pd.DataFrame, progress: float, chunk_size: int, max_chunks: int) -> tuple:\n \"\"\"\n Perform random sampling of rows to avoid OOM on large datasets.\n \n Args:\n df: The DataFrame to process (assumed already sorted by 'redshift' if available).\n progress: Current percentage completed for this chunk.\n chunk_size: Number of rows sampled per iteration.\n max_chunks: Maximum number of chunks to sample before stopping.\n \n Returns:\n Tuple containing the sampled dataframe, total rows processed, and current chunk index.\n \"\"\"\n if not check_save_directory():\n logger.error(\"Save directory not found or not writable.\")\n return None, 0, 0\n \n # Calculate how many chunks to sample based on progress\n n_rows = len(df)\n num_samples = min(n_rows * chunk_size / 100.0, max_chunks)\n \n if num_samples <= 1:\n return df.copy(), 0, 0\n\n # Perform random sampling\n indices = np.random.choice(range(len(df)), size=num_samples, replace=False)\n sampled_indices = indices.flatten()\n \n logger.info(f\"Processed {len(df)} rows. Sampling {num_samples} rows. Chunks={num_samples}\")\n \n return df[sorted(sampled_indices)]\n\ndef write_filtered_results(df: pd.DataFrame, output_path: str, chunk_size: int, max_chunks: int) -> bool:\n \"\"\"\n Write filtered galaxy properties to CSV with checkpointing.\n \n Args:\n df: The DataFrame containing galaxy properties after redshift filtering.\n output_path: Path where the results will be saved.\n chunk_size: Number of rows sampled per iteration for logging.\n max_chunks: Maximum number of chunks to sample before stopping.\n \n Returns:\n True if successful, False otherwise.\n \"\"\"\n # Ensure directory exists and is writable\n save_dir = Path(output_path) / \"results\"\n save_dir.mkdir(parents=True, exist_ok=True)\n \n logger.info(f\"Starting write to {output_path}\")\n \n # Initialize log file\n log_file = output_path / \"checkpoint.log\"\n with open(log_file, \"a\") as f:\n f.write(\"Start of checkpoint sequence\\n\")\n f.write(\"Total rows processed: {}\\n\".format(len(df)))\n \n # Prepare data for sampling\n sampled_df = checkpoint_data(df, 100.0, chunk_size, max_chunks)\n \n if sampled_df is None:\n logger.error(\"Failed to process data or save directory was not writable.\")\n return False\n \n # Process and write to output file\n total_rows = len(sampled_df)\n chunks = []\n for i in range(0, total_rows, chunk_size):\n chunk = sampled_df.iloc[i : i + chunk_size]\n logger.info(f\"Processing chunk {i // chunk_size} of {total_rows} rows\")\n \n # Check if we need to save this checkpoint before writing the main file\n if i == 0:\n f.write(\"Checkpoint saved\\n\")\n \n df_chunk = pd.DataFrame(chunk)\n df_chunk.to_csv(save_dir / \"checkpoints/checkpoint_\" + str(i // chunk_size), index=False)\n chunks.append(df_chunk)\n \n # Append the main output file at the end\n logger.info(f\"Writing final result to {output_path}\")\n \n with open(output_path, \"a\") as f:\n f.write(\"Final result written.\\n\")\n \n return True"}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 0, "total_reward": 0.5384615384615384, "rater": "static", "code_source": "fence"}}
|
| 2 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a function that computes the pairwise cosine similarity between rows of a sparse matrix and saves results incrementally to a feather file.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a function that computes the pairwise cosine similarity between rows of a sparse matrix and saves results incrementally to a feather file."}, {"role": "assistant", "content": "import logging\nfrom pathlib import Path\nfrom chroptiks import plot, scatter, line\n\n\ndef compute_cosine_similarities(data: dict[str, list[float]]) -> list[tuple[list[float], list[float]]]:\n \"\"\"Compute pairwise cosine similarities between rows of the input data.\n \n Args:\n data: Dictionary mapping row names to lists of values for each column.\n \n Returns:\n List of tuples containing (row1_row2, similarity_score) for all unique pairs\n of rows in the input data.\n \"\"\"\n rows = list(data.keys())\n n_rows = len(rows)\n \n if n_rows < 3:\n return []\n \n # Ensure column names are consistent and sorted (optional optimization)\n if set(data.keys())[0] != set(data.values())[0]:\n for name in sorted(set(data)):\n data[name] = [v for v in data[name]]\n \n all_values = list(data.items())\n n_cols = len(all_values[0])\n values_dict = {name: values_dict[i][i] if i < len(values_dict) else []\n for name, values_dict in all_values}\n \n similarities = []\n unique_rows = set()\n \n for i in range(n_rows):\n row1 = list(all_values[i])\n for j in range(i + 1, n_rows):\n row2 = list(all_values[j])\n # Normalize values to 0-1 range before cosine similarity calculation\n def normalize(val_list):\n min_val = min(val for v in val_list)\n max_val = max(val for v in val_list)\n if max_val == 0:\n return [v / max_val for v in val_list]\n else:\n return [v / (max_val + 1e-9) for v in val_list]\n \n norm_row1 = normalize(row1)\n norm_row2 = normalize(row2)\n \n dot_product = sum(v * w for v, w in zip(norm_row1, norm_row2))\n n_samples = len(norm_row1)\n \n if n_samples == 0:\n continue\n \n # Cosine similarity calculation\n cosine_sim = (dot_product / (n_samples * n_samples))\n \n # Ensure non-negative similarity score\n if cosine_sim < 0:\n cosine_sim = 0\n \n similarities.append((row1, row2, cosine_sim))\n unique_rows.add(i)\n \n return similarities\n\n\ndef save_cosine_results(file_path: str, similarities: list[tuple[list[float], list[float]]]) -> None:\n \"\"\"Save computed cosine similarities to a feather file using chroptiks.\n \n Args:\n file_path: Path to the output feather file.\n similarities: List of tuples (row1_row2, similarity_score) in the order \n rows should be processed.\n \"\"\"\n # Ensure path exists\n if not Path(file_path).exists():\n logging.warning(f\"Output file {file_path} does not exist\")\n \n # Determine unique rows based on input data\n seen_rows = set()\n for i in range(len(similarities)):\n row1, row2, score = similarities[i]\n \n if i == 0:\n first_row = [float(row1)]\n else:\n first_row = [float(row1[0])]\n \n if not seen_rows.add(row1):\n logging.warning(f\"Duplicate row {row1} encountered at index {i}\")\n \n # Create scatter plot for similarity distribution\n n_similarities = len(similarities)\n max_val = float(max(s for _, _, s in similarities))\n if max_val > 0:\n x_coords = [float(i / (n_similarities + 1e-9)) for i in range(n_similarities)]\n y_coords = [float(abs(s - max_val) * 1e8) for s in similarities]\n \n scatter(\n \"similarity_matrix\",\n x=x_coords,\n y=y_coords,\n data=similarities,\n figsize=(5, 3.5),\n dpi=100,\n legend=\"On\" if len(similarities) > 2 else None,\n label_col=\"similarity_score\"\n )\n else:\n plot(\"similarities\", data=similarities, size=20, color='blue')\n \n # Export to CSV with metadata in first row\n data_to_csv = {k: list(v) for k, v in similarities}\n data_to_csv[\"file_path\"] = file_path\n \n logging.info(f\"Saved {len(similarities)} similarity results to {file_path}\")\n try:\n data.to_csv(file_path, index=False)\n except Exception as e:\n logging.error(f\"Error writing CSV: {e}\")\n raise\n\n\nif __name__ == \"__main__\":\n # Define test data\n test_data = {\n \"A\": [1.0, 2.0],\n \"B\": [3.0, 4.0],\n \"C\": [5.0, 6.0],\n \"D\": [7.0, 8.0]\n }\n \n # Compute similarities\n similarities = compute_cosine_similarities(test_data)\n \n if not similarities:\n raise ValueError(\"No valid pairs found in test data\")\n \n # Save results\n file_path = Path(__file__).parent / \"cosine_simulations\" / \"results.csv\"\n save_cosine_results(str(file_path), similarities)"}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 1, "total_reward": 0.2692307692307692, "rater": "static", "code_source": "fence"}}
|
| 3 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a knowledge graph embedding trainer that saves entity/relation checkpoints every N batches and resumes from the latest checkpoint.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a knowledge graph embedding trainer that saves entity/relation checkpoints every N batches and resumes from the latest checkpoint."}, {"role": "assistant", "content": "import json\nimport logging\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass BatchResult:\n batch_id: str\n samples_processed: int\n model_state: dict = field(default_factory=dict)\n error: Optional[str] = None\n\ndef init_logging(cfg=None):\n if cfg is None:\n cfg = {\n \"log_dir\": \"./model_checkpoint_logs\",\n \"batch_size\": 100,\n \"num_batches\": 1000,\n \"checkpoint_interval\": 25,\n \"output_dir\": \"./model_output\"\n }\n logger = logging.getLogger(\"Guac-Embed\")\n # Ensure only this log level is set (info) to avoid cluttering system logs\n if \"info\" not in logger.handlers:\n for handler in logger.handlers[:]:\n handler.setLevel(logging.INFO)\n new_handler = logging.StreamHandler()\n new_handler.setLevel(logging.INFO)\n new_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))\n logger.addHandler(new_handler)\n return logger\n\n@dataclass\nclass Entity:\n id: str\n name: str\n type: str\n entities: list = field(default_factory=list)\n\n@dataclass\nclass Relation:\n id: str\n source: str\n target: str\n score: float\n entity_ids: list = field(default_factory=list)\n\n@dataclass\nclass ModelState:\n embedding_weights: dict\n relations: list = field(default_factory=list)\n\ndef setup_logging(logger):\n logger.setLevel(logging.INFO)\n return logger\n\ndef load_checkpoint(checkpoint_path: str, logger: logging.Logger) -> ModelState:\n with open(checkpoint_path, 'r') as f:\n data = json.load(f)\n model_state = {**data.get(\"model\", {}), **{\"embeddings\": {\"embedding_weights\": data.get(\"embeddings\", {}).get(\"embedding_weights\", {})}},\n \"entities\": [{\"id\": e[\"id\"], \"name\": e[\"name\"], \"type\": e[\"type\"]} for e in data.get(\"entities\", [])],\n \"relations\": [r for r in data.get(\"relations\", []) if r[\"entity_id\"] in [\"user\", \"assistant\"]]\n }\n return model_state\n\ndef save_model(model_state: dict, logger: logging.Logger):\n with open(\"./model_output/model.pt\", 'wb') as f:\n json.dump(model_state, f)\n logger.info(f\"Model saved to ./model_output/model.pt\")\n\nclass EntityEmbedder:\n def __init__(self, config):\n self.config = config\n self.logger = setup_logging(config.get(\"logger\", None))\n \n def train_batch(self, model_state: dict, batch_size: int, logger: logging.Logger) -> BatchResult:\n n_docs = len(model_state[\"embeddings\"][\"embedding_weights\"])\n \n # Initialize empty embeddings if not present\n if \"embedding_weights\" not in model_state or model_state[\"embedding_weights\"].keys().length == 0:\n model_state[\"embeddings\"][\"embedding_weights\"] = {str(i).upper(): [] for i in range(n_docs)}\n \n current_id = 0\n results = [BatchResult(batch_id=f\"batch_{current_id}\", samples_processed=0, model_state=model_state)]\n \n # Load previous state for resume logic (optional)\n if \"checkpoint_id\" in model_state:\n prev_state = load_checkpoint(model_state[\"checkpoint_id\"], self.logger)\n prev_model_state = {\"embeddings\": {\"embedding_weights\": prev_state.get(\"embeddings\", {}).get(\"embedding_weights\", {})}}\n current_embedding_weights = [prev_model_state[\"embeddings\"][\"embedding_weights\"][next_key] for key in prev_model_state[\"embeddings\"][\"embedding_weights\"].keys()]\n else:\n current_embedding_weights = list(model_state[\"embeddings\"][\"embedding_weights\"].values())[1:]\n \n for doc_id in range(n_docs):\n # Shuffle docs based on id to ensure random order if needed, though we don't need shuffle here\n \n # Get current embedding weights\n weights = current_embedding_weights[doc_id]\n \n # Build relations list\n rels = []\n for i in range(len(weights)):\n entity_id = next_key(i)\n weight = weights[i]\n \n if not entity_id or entity_id == \"\":\n continue\n \n # Find relation from user/assistant to this entity\n for r_id, r_data in model_state[\"relations\"].items():\n source = r_data.get(\"source\", \"\").lower()\n target = r_data.get(\"target\", \"\").lower()\n \n if entity_id.lower() == source and target.lower() in [\"user\", \"assistant\"]:\n rels.append({\n \"id\": f\"rel_{doc_id}_{i}\",\n \"source\": entity_id,\n \"target\": target,\n \"score\": float(weight),\n \"entity_ids\": [entity_id]\n })\n \n # Normalize and save embeddings\n current_embeddings = {str(i).upper(): [] for i in range(n_docs)}\n current_embeddings[\"embedding_weights\"] = current_embedding_weights\n \n for doc_id in range(n_docs):\n entity_id = next_key(doc_id)\n weight = weights[doc_id]\n \n for r_id, r_data in rels:\n if not entity_id:\n break\n \n # Calculate score and update relation\n score = float(weight) * (1 - r_data.get(\"score\", 0))\n current_embeddings[r_id][\"id\"] = entity_id\n current_embeddings[r_id][\"entities\"].append(entity_id)\n current_embeddings[r_id][\"score\"] = max(0.0, min(1.0, score))\n \n # Update weights for next batch\n current_embedding_weights[doc_id] = []\n \n model_state[\"embeddings\"][\"embedding_weights\"][doc_id] = {k: v for k, v in current_embeddings.items() if k != \"embedding_weights\"}\n model_state[\"embeddings\"][\"embedding_weights\"].setdefault(doc_id, {}).append(str(next_key(doc_id)))\n \n return results\n\ndef main():\n # Initialize and log\n logger = init_logging({\"batch_size\": 100, \"num_batches\": 1000})\n \n checkpoint_path = \"./model_checkpoint/model.pt\"\n logger.info(f\"Loading checkpoint from {checkpoint_path}...\")\n model_state = load_checkpoint(checkpoint_path, logger)\n \n # Training configuration\n config = {\n \"embedding_dim\": 256,\n \"entity_ids\": [\"user\", \"assistant\"],\n \"entity_type_names\": [\"user\", \"assistant\"],\n \"batch_size\": 100,\n \"num_batches\": 1000,\n \"epoch_count\": 2,\n \"checkpoint_interval\": 25,\n \"save_every\": 25,\n \"resume_from\": checkpoint_path\n }\n \n logger.info(f\"Starting training with {config['batch_size']} batches...\")\n \n results = []\n for batch_id in range(config[\"num_batches\"]):\n batch_start = min(batch_start + config[\"checkpoint_interval\"], len(model_state))\n batch_end = max(batch_start + config[\"checkpoint_interval\"], len(model_state))\n \n logger.info(f\"Processing batch {batch_id}...\")\n \n # Create new embedding weights for this batch\n if \"embedding_weights\" not in model_state or model_state[\"embedding_weights\"].keys().length == 0:\n model_state[\"embeddings\"][\"embedding_weights\"] = {str(i).upper(): [] for i in range(len(model_state[\"embeddings\"][\"embedding_weights\"]))}\n \n results.append(BatchResult(batch_id=batch_id, samples_processed=len(model_state[\"embeddings\"][\"embedding_weights\"]), \n model_state=model_state))\n \n # Train batch\n logger.info(f\"Training batch {batch_id}: {len(model_state['embeddings']['embedding_weights'])} docs\")\n new_embeddings = EntityEmbedder(config).train_batch(model_state, config[\"batch_size\"], logger)\n \n # Resume and save if at checkpoint interval\n if len(new_embeddings[\"model_state\"][\"embeddings\"][\"embedding_weights\"]) == 0:\n model_state[\"checkpoint_id\"] = batch_start\n if len(model_state[\"embeddings\"][\"embedding_weights\"]) > 0:\n new_embeddings[\"model_state\"][\"embeddings\"][\"embedding_weights\"].pop(0)\n \n # Save to disk periodically\n save_model(model_state, logger)\n \n logger.info(\"Training complete.\")\n logger.info(f\"Final checkpoint saved at batch {len(results)-1}\")\n logger.info(f\"Results saved to ./model_output/results.json\")\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 2, "total_reward": 0.2692307692307692, "rater": "static", "code_source": "fence"}}
|
| 4 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a plotting utility that visualizes a 2D embedding space using chroptiks, with no grid, no title, and proper color mapping.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a plotting utility that visualizes a 2D embedding space using chroptiks, with no grid, no title, and proper color mapping."}, {"role": "assistant", "content": "import logging\nfrom typing import Any, Dict\n\n# Logging configuration - objective and concise\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s [%(levelname)s] %(message)s'\n)\n\ndef init_logging() -> None:\n \"\"\"Initialize the logger for centralized output.\"\"\"\n logging.getLogger().setLevel(logging.WARNING)\n\nclass DataManager:\n \"\"\"Manages data loading and visualization metadata.\"\"\"\n \n def __init__(self):\n self.data: Dict[str, Any] = {}\n self.metadata: Dict[str, str] = {\n 'embedding_dim': 100,\n 'color_map': 'viridis',\n 'plot_type': 'scatter'\n }\n\n def _load_from_file(self, filename: str) -> None:\n \"\"\"Load data from a CSV file.\"\"\"\n path = f'data/{filename}'\n try:\n df = pd.read_csv(path, names=self.metadata['embedding_dim'])\n self.data['x'] = df['embedding_dim']['x']\n self.data['y'] = df['embedding_dim']['y']\n self.metadata.update({\n 'source': 'data_loader',\n 'file': filename,\n 'shape': len(df)\n })\n except Exception as e:\n logging.warning(f'Failed to load data from {filename}: {e}')\n\n def _build_metadata(self) -> Dict[str, str]:\n \"\"\"Build the metadata dictionary from current state.\"\"\"\n return self.metadata.copy()\n\n def plot_data(self) -> None:\n \"\"\"Create a scatter plot of the 2D embedding space.\"\"\"\n if not self.data or len(self.data) == 0:\n logging.info('No data to visualize.')\n return\n\n fig, ax = chroptiks.scatter(\n x=self.data['x'],\n y=self.data['y'],\n size=12,\n linewidths=1.5,\n label='Embedding Space Visualization',\n color=self.metadata['color_map']\n )\n\n # Add metadata labels for reproducibility (without title)\n ax.set_xlabel('Coordinate 1')\n ax.set_ylabel('Coordinate 2')\n \n ax.legend(loc='upper right')\n ax.set_title('2D Embedding Space')\n\n def save_results(self, filename: str = 'visualizations.json') -> None:\n \"\"\"Save visualization metadata and results to CSV.\"\"\"\n output_path = f'data/{filename}'\n if not os.path.exists(output_path):\n logging.info(f'Saved visualization to {output_path}')\n return\n\n df = pd.DataFrame({\n 'embedding_dim': self.data['x'],\n 'y': self.data['y']\n })\n \n # Build metadata for CSV output\n csv_metadata = {\n 'type': 'scatter',\n 'file': filename,\n 'dimensions': 2,\n 'color_map': self.metadata['color_map'],\n 'colors': [self.metadata['color_map']] * (len(self.data) // 2 if len(self.data) > 1 else 1),\n 'title': f'Embedding Space: {self.metadata[\"embedding_dim\"]}',\n 'x': self.data['x'].tolist(),\n 'y': self.data['y'].tolist()\n }\n\n try:\n output_path = f'data/{filename}'\n df.to_csv(output_path, index=False)\n logging.info(f'Saved results to {output_path}')\n except Exception as e:\n logging.error(f'Failed to save CSV: {e}')\n\ndef main() -> None:\n \"\"\"Main entry point for the plotting utility.\"\"\"\n init_logging()\n \n # Initialize manager with default file if not specified\n manager = DataManager()\n \n # Load data from specific file if provided\n if 'data' in os.environ.get('INPUT_FILE', ''):\n manager._load_from_file(os.environ['INPUT_FILE'])\n\n # Ensure metadata is populated before plotting\n manager._build_metadata()\n print(f\"Loaded {len(manager.data)} data points into visualization.\")\n\n # Execute plot\n manager.plot_data()\n \n # Save results to CSV\n manager.save_results('results.json')\n\nif __name__ == '__main__':\n main()"}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 3, "total_reward": -0.038461538461538464, "rater": "static", "code_source": "fence"}}
|
| 5 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a scientific paper metadata scraper that writes parsed metadata to CSV incrementally with logging at each stage.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a scientific paper metadata scraper that writes parsed metadata to CSV incrementally with logging at each stage."}, {"role": "assistant", "content": "import os\nimport sys\nimport logging\nimport pandas as pd\nfrom datetime import datetime\n\n# Configure logging without print output\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s | %(levelname)s | %(message)s\"\n)\nlogger = logging.getLogger(__name__)\n\ndef load_metadata_from_csv(filepath):\n \"\"\"Load metadata from a CSV file. Returns DataFrame with columns: 'date', 'type', 'value'.\"\"\"\n df = pd.read_csv(filepath)\n if df.empty:\n logger.warning(f\"No data found in {filepath}\")\n return None\n return df\n\ndef save_metadata_to_csv(df, filepath):\n \"\"\"Save dataframe to CSV file with metadata columns. Writes incrementally.\"\"\"\n if len(df.columns) != 3 or any(col == \"date\" and col == \"value\" for col in df.columns) or df[\"value\"].dtype == object:\n logger.warning(f\"Not valid metadata format: expected column 'date', 'type', 'value'. Got columns {df.columns.tolist()}\")\n \n if len(df.columns) < 3:\n pd.DataFrame({\"date\": pd.to_datetime(df.get(\"date\", None)), \"type\": pd.to_categorical(df.get(\"type\", 0), num_categories=3)})\n df = pd.DataFrame({\"date\": pd.to_datetime(df.get(\"date\", None)), \"type\": df[\"value\"].map(lambda x: x if not pd.isna(x) else 0)})\n \n logger.info(f\"Writing {len(df)} records to {filepath}\")\n df.to_csv(filepath, index=False)\n\ndef process_single_data_point(data_point):\n \"\"\"Process a single data point from the CSV.\"\"\"\n if len(data_point) < 2:\n return None\n \n date = str(data_point.get(\"date\", \"N/A\"))\n type_val = data_point.get(\"type\", \"unknown\")\n value_str = data_point.get(\"value\", \"\")\n \n if isinstance(type_val, pd.Series):\n try:\n type_map = {0: 'low', 1: 'medium', 2: 'high'}\n type = type_map[type_val]\n except KeyError as e:\n type = \"unknown\"\n elif type_val in (\"null\", \"N/A\"):\n type = \"unknown\"\n else:\n type = type_val\n\n # Handle numeric values by converting string to float if needed\n try:\n value = float(value_str)\n except (ValueError, TypeError):\n value = 0.0\n\n return {\n \"date\": date,\n \"type\": type,\n \"value\": value\n }\n\ndef process_batch(data_list):\n \"\"\"Process a list of data points and extract metadata.\"\"\"\n if not isinstance(data_list, list) or len(data_list) == 0:\n raise ValueError(\"Data list must contain at least one valid point\")\n \n results = []\n for item in data_list:\n result = process_single_data_point(item)\n if result is None:\n continue\n results.append(result)\n \n logger.info(f\"Processing {len(results)} records from batch\")\n\ndef main():\n input_file = \"./metadata.json\"\n output_file = \"./metadata.csv\"\n \n # Ensure directory exists for write operations\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n \n try:\n logger.info(\"Loading metadata from JSON file...\")\n with open(input_file, \"r\") as f:\n data_list = json.load(f)\n \n process_batch(data_list)\n logger.info(f\"Writing to CSV: {output_file}\")\n \n except FileNotFoundError as e:\n logger.error(f\"Input file not found: {e}\")\n sys.exit(1)\n except Exception as e:\n logger.error(f\"Error processing data: {e}\")\n sys.exit(1)\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 4, "total_reward": 0.34615384615384615, "rater": "static", "code_source": "fence"}}
|
| 6 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a mixture model fitter that logs likelihood values and saves model state periodically for resumable training.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a mixture model fitter that logs likelihood values and saves model state periodically for resumable training."}, {"role": "assistant", "content": "import logging\nimport numpy as np\nfrom chroptiks import Chroptiks\nfrom pathlib import Path\nimport warnings\n\n# Configure logging to avoid warnings by default\nlogging.basicConfig(level=logging.INFO, format='%(message)s')\n\n# Global checkpoint state\nCHECKPOINT_PATH = \"model_checkpoint\"\n\nclass MixtureFitter:\n \"\"\"\n Fitter class for implementing a mixture model.\n \n Attributes:\n x_train (list): List of training samples.\n y_train (list): List of true labels for training samples.\n n_samples (int): Number of training samples.\n data (dict): Dictionary containing feature and label arrays.\n weights (dict): Dictionary storing hyperparameter values and their associated \n probabilities, initialized with defaults.\n likelihoods (list): List of calculated likelihood values during training.\n \n Methods:\n fit(self, X, y): Train the mixture model on the provided data.\n predict(self, X): Predict class labels for new samples using trained model.\n save_model(): Save current state to checkpoint file.\n load_checkpoint(): Load previous model state from checkpoint file.\n log_likelihood(self, label): Log likelihood value associated with a sample.\n \"\"\"\n\n def __init__(self, max_iterations=100000):\n \"\"\"\n Initialize the MixtureFitter.\n\n Args:\n max_iterations (int): Maximum number of iterations allowed before stopping training.\n \"\"\"\n self.X = np.array([])\n self.y = []\n self.n_samples = 0\n self.data = {}\n self.weights = {}\n self.likelihoods = []\n self.max_iterations = max_iterations\n\n def fit(self, X, y):\n \"\"\"\n Train the mixture model using maximum likelihood estimation.\n\n Args:\n X (np.ndarray): Feature matrix containing features for each sample. Shape: (n_samples, n_features).\n y (list): Label vector of length n_samples, where index i corresponds to label i in y.\n Each entry should be either 'A' or 'B'.\n\n Returns:\n Chroptiks: Trained model object with stored metrics and weights.\n \"\"\"\n # Initialize global state\n self.X = X\n self.y = y.copy()\n self.n_samples = len(y)\n\n # Initialize weights for all classes\n self.weights = {\"A\": 0.5, \"B\": 0.5}\n\n # Calculate initial likelihoods and log-likelihood\n self.likelihoods = []\n n_features = X.shape[1]\n \n with logging.getLogger() as logger:\n logger.info(\"Starting mixture model fit...\")\n\n for i in range(self.n_samples):\n x = X[i].copy().astype(np.float64)\n y_true = self.y[i]\n \n # Initialize weights to default class probabilities\n w = {\"A\": 0.5, \"B\": 0.5}\n \n # Iterate through all possible classes\n for k in [\"A\", \"B\"]:\n # Sample with replacement\n w[k] = np.random.choice(self.weights[k], size=1)\n \n # Calculate likelihood of the current sample given class k\n likelihoods, log_likelihoods = Chroptiks.fit(\n x, y_true, weights=w\n )\n \n self.likelihoods.append(likelihoods.log_prob)\n self.likelihoods.append(log_likelihoods)\n \n # Store data and initialize weights for this iteration\n self.data[\"X\"] = X[i]\n self.data[\"y\"] = y_true\n self.weights = w\n\n logging.getLogger().info(f\"Model fit completed with {len(self.likelihoods)} likelihood values.\")\n\n def predict(self, X):\n \"\"\"\n Predict class labels for new samples using trained model.\n\n Args:\n X (np.ndarray): Feature matrix of length n_samples containing features for each sample. Shape: (n_samples, n_features).\n\n Returns:\n list: Prediction vector of length n_samples, where index i corresponds to label i.\n Each entry is either 'A' or 'B'.\n \"\"\"\n predictions = np.array([])\n # Create array with all A labels first, then append B labels for each sample\n predictions = np.concatenate([np.ones(self.n_samples), self.y])\n\n return Chroptiks.predict(X, predictions)\n\n def save_model(self):\n \"\"\"\n Save current state to the checkpoint file.\n\n Returns:\n bool: True if successful, False otherwise.\n \"\"\"\n path = Path(CHECKPOINT_PATH)\n \n try:\n # Ensure directory exists (basic safety measure)\n if not path.exists():\n raise FileNotFoundError(f\"Checkpoint path does not exist: {path}\")\n\n # Save weights as a dictionary\n self.weights_to_save = {}\n for k, v in self.weights.items():\n self.weights_to_save[k] = float(v)\n \n with logging.getLogger() as logger:\n logger.info(\"Saving model to checkpoint...\")\n checkpoint_data = {\n \"weights\": self.weights_to_save,\n \"likelihoods\": self.likelihoods,\n \"X\": self.X.tolist(),\n \"y\": self.y.tolist()\n }\n \n # Save data to file using .to_csv\n data_path = path.parent / \"model_data.csv\"\n checkpoint_data.to_csv(data_path, index=False)\n \n logger.info(f\"Model saved to {data_path}\")\n return True\n \n except Exception as e:\n logging.getLogger().error(f\"Error saving model: {e}\")\n return False\n\n def load_checkpoint(self):\n \"\"\"\n Load previous state from the checkpoint file.\n\n Returns:\n Chroptiks: Model object with loaded weights and likelihoods.\n \"\"\"\n path = Path(CHECKPOINT_PATH)\n \n try:\n # Ensure directory exists\n if not path.exists():\n raise FileNotFoundError(f\"Checkpoint path does not exist: {path}\")\n\n # Open file to load data from CSV\n checkpoint_data = np.loadtxt(path, delimiter=',')\n\n # Convert dictionary keys to numpy arrays\n self.weights[\"A\"] = checkpoint_data[\"weights\"][\"A\"].astype(float)\n self.weights[\"B\"] = checkpoint_data[\"weights\"][\"B\"].astype(float)\n\n # Convert likelihoods lists to numpy arrays\n self.likelihoods = np.array([checkpoint_data[\"likelihoods\"][i] for i in range(len(checkpoint_data[\"likelihoods\"]))])\n \n # Reconstruct X and y from previous state\n self.X = checkpoint_data[\"X\"].astype(float)\n self.y = checkpoint_data[\"y\"]\n \n logging.getLogger().info(f\"Loaded model from {path}\")\n return Chroptiks(self.X, self.y)\n\n except Exception as e:\n logging.getLogger().error(f\"Error loading checkpoint: {e}\")\n raise\n\n def log_likelihood(self, label):\n \"\"\"\n Log likelihood value associated with a sample.\n\n Args:\n label (str): The true label for the sample ('A' or 'B').\n \"\"\"\n self.y.append(label)\n # Calculate current likelihood using Chroptiks\n likelihoods, _ = Chroptiks.fit(\n self.X, self.y, weights=self.weights\n )\n logging.getLogger().info(f\"Logged likelihood: {likelihoods.log_prob:.6f}\")\n\n# __main__ guard\nif __name__ == \"__main__\":\n # Initialize the model with default parameters\n model = MixtureFitter(max_iterations=1000)\n\n # Sample training data (replace with actual dataset if available)\n X_train = np.random.randn(100, 5)\n y_train = np.array(['A'] * 100 + ['B'] * 0)\n\n try:\n model.fit(X_train, y_train)\n print(\"Model training completed successfully.\")\n except Exception as e:\n logging.getLogger().error(f\"Training failed: {e}\")"}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 5, "total_reward": 0.23076923076923078, "rater": "static", "code_source": "fence"}}
|
| 7 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a text preprocessing pipeline for NLP experiments that reads raw text, tokenizes, and writes processed chunks to disk with checkpoint tracking.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a text preprocessing pipeline for NLP experiments that reads raw text, tokenizes, and writes processed chunks to disk with checkpoint tracking."}, {"role": "assistant", "content": "import os\nimport logging\nimport pandas as pd\nfrom chroptiks import plot\n\n# Setup logging\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s | %(levelname)-8s | %(message)s\",\n handlers=[\n logging.StreamHandler(),\n plot.HistogramChroptikaHandler(plot.FigureChroptika),\n ]\n)\n\n# Function to check if directory exists before starting pipeline\ndef ensure_directory_exists(path: str, parent_dir: str = \"root\") -> bool:\n \"\"\"Check if specified path exists and create parent directories recursively.\"\"\"\n try:\n os.makedirs(parent_dir, exist_ok=True)\n return True\n except PermissionError:\n logging.error(f\"Permission denied accessing {path}\")\n return False\n\ndef write_chunks_to_disk(\n chunk_data: dict,\n filename: str = \"processed_chunks.txt\",\n parent_dir: str = \"root\",\n max_chunk_size_mb: int = 50,\n min_chunk_size_mb: int = 10,\n skip_first_chunk: bool = True\n) -> pd.DataFrame:\n \"\"\"Write chunks to disk with incremental checkpoint tracking.\"\"\"\n # Ensure parent directory exists\n ensure_directory_exists(os.path.join(parent_dir, filename), parent_dir=parent_dir)\n\n current_file = os.path.join(parent_dir, filename)\n chunk_data_dict = {}\n\n if skip_first_chunk:\n first_chunk_data = {\"chunk_id\": 0, \"total_chunks\": 1}\n else:\n # Initialize with the current chunk data\n current_data = chunk_data\n\n with open(current_file, 'w', encoding='utf-8') as f:\n for i in range(1, chunk_data_dict[\"total_chunks\"] + 1):\n if i == chunk_data_dict[\"total_chunks\"]:\n # Write the last chunk after processing is complete\n df = pd.DataFrame(chunk_data_dict)\n logging.info(f\"Writing final chunk with {len(df)} chunks...\")\n \n # Format chunks for disk output (compact format for large files)\n rows_str = '\\n'.join([f\"{r[0]:-15} {r[2]:-15}\" for r in df.to_records(index=False)])\n lines = [str(current_file)] + [lines] if len(lines) > 1 else [rows_str]\n else:\n # Process the next chunk\n data = chunk_data_dict.pop(i, {})\n rows_str = '\\n'.join([f\"{r[0]:-15} {r[2]:-15}\" for r in df.to_records(index=False)])\n \n chunks = [\n (current_file, rows_str),\n (current_file + f\"/chunk-{i}\", data.get(\"chunk_text\", \"\"))\n ]\n lines.extend(chunks)\n\n # Update current chunk state for the next iteration\n if not skip_first_chunk:\n data = {\n \"chunk_id\": i,\n \"total_chunks\": len(df),\n **chunk_data_dict[i], # Add new key to previous dict\n }\n chunk_data_dict[\"current\"] = data\n else:\n chunk_data_dict[\"current\"] = data\n\n logging.info(f\"Written {len(chunks)} chunks to {current_file}\")\n return pd.DataFrame(df)\n\nif __name__ == \"__main__\":\n if len(os.listdir(\".\")) > 0:\n import sys\n script_dir = \".\"\n else:\n # Check for command-line argument or script location\n cmd_args = []\n for i in range(1, len(sys.argv)):\n if sys.argv[i] == \"-c\":\n cmd_args = sys.argv[i+1:]\n break\n \n if not cmd_args:\n print(\"Usage: python pipeline.py <command> [args]\")\n print(\"Commands:\", \"check\", \"process\")\n exit(1)\n \n script_dir = cmd_args[0]\n\n # Check and process directories\n for dirname, _, _ in os.walk(script_dir):\n if not os.path.isdir(dirname):\n continue\n \n filename = os.path.basename(dirname)\n check_cmd = f\"{dirname}/check {filename}\"\n try:\n os.system(check_cmd)\n except Exception as e:\n logging.error(f\"Error checking directory {dirname}: {e}\")\n\n # Process all chunks if a command was provided or script is in root\n cmd_args = sys.argv[1:] if len(sys.argv) > 1 else []\n if not cmd_args and \"process\" in cmd_args:\n cmd_args.append(\"check\")\n \n for dirname, _, _ in os.walk(script_dir):\n if not os.path.isdir(dirname):\n continue\n \n filename = os.path.basename(dirname)\n process_cmd = f\"{dirname}/process {filename}\"\n try:\n os.system(process_cmd)\n except Exception as e:\n logging.error(f\"Error processing directory {dirname}: {e}\")\n\n if len(cmd_args):\n cmd_args[0] = \"check\""}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 6, "total_reward": 0.2692307692307692, "rater": "static", "code_source": "fence"}}
|
| 8 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a benchmarking script that runs experiments, logs metrics via logging module, and appends results to a CSV after each trial.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a benchmarking script that runs experiments, logs metrics via logging module, and appends results to a CSV after each trial."}, {"role": "assistant", "content": "import csv\nimport os\nimport logging\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Any\nimport chroptiks\n\n@dataclass\nclass Experiments:\n experiment_name: str\n base_dir: str\n experiments_data: Dict[str, List[float]]\n\ndef setup_logging() -> logging.Logger:\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n \n handler = logging.StreamHandler()\n formatter = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n handler.setFormatter(formatter)\n \n logger.addHandler(handler)\n return logger\n\ndef append_to_csv(csv_path: str, data: Dict[str, List[float]]) -> None:\n with open(csv_path, 'w', newline='', encoding='utf-8') as f:\n writer = csv.DictWriter(f, fieldnames=data.keys())\n writer.writeheader()\n for k, v in data.items():\n if isinstance(v, (int, float)):\n writer.writerow({k: round(v, 4)})\n\ndef run_experiment(\n experiment_name: str,\n base_dir: str,\n experiments_data: Dict[str, List[float]]\n) -> Experiments:\n \"\"\"\n Runs an experiment and returns the result data.\n \n Args:\n experiment_name: Name of the experiment\n base_dir: Directory containing the experiment files\n experiments_data: Dictionary mapping experiment names to list of values\n \n Returns:\n A dataclass representing the complete experiment run with its metrics\n \"\"\"\n experiments = Experiments(\n experiment_name=experiment_name,\n base_dir=base_dir,\n experiments_data=experiments_data\n )\n \n # Ensure output directory exists\n os.makedirs(base_dir, exist_ok=True)\n \n for exp_data in experiments.experiments_data.values():\n if len(exp_data) == 0:\n continue\n \n name = list(exp_data.keys())[0]\n \n experiment_files = os.path.join(base_dir, 'experiments', name)\n if not os.path.exists(experiment_files):\n raise ValueError(f\"Experiment file '{name}' does not exist in {base_dir}\")\n \n # Get the last value for that experiment\n try:\n last_val = float(exp_data[name][-1])\n except (ValueError, IndexError):\n last_val = 0.0\n \n append_to_csv(os.path.join(base_dir, 'results.csv'), {\n 'name': name,\n 'last_value': round(last_val, 4)\n })\n\nif __name__ == '__main__':\n logger = setup_logging()\n \n # Initialize logging to capture all operations for debugging\n logger.info(\"Starting benchmarking script...\")\n \n # Check if base directory exists\n experiments_data = {}\n os.makedirs(os.path.join(__file__, '..', 'experiments'), exist_ok=True)\n \n # Load experiment data from a dictionary (simplification per task requirements)\n try:\n import json\n with open('experiment_data.json', 'r') as f:\n experiments_data = json.load(f)\n except FileNotFoundError:\n logger.warning(\"No experiment_data.json found. Creating default structure.\")\n # Create minimal example to avoid errors on missing file\n experiments_data = {\n \"a\": [10.5, 20.3, 30.0],\n \"b\": [5.0, 15.0, 25.0]\n }\n except Exception as e:\n logger.error(f\"Failed to load experiment data: {e}\")\n \n # Run the experiment\n result = run_experiment(\n experiment_name=\"baseline\",\n base_dir=os.path.join(__file__, '..', 'experiments'),\n experiments_data=experiments_data\n )\n \n logger.info(\"Experiment completed successfully.\")"}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 7, "total_reward": 0.23076923076923078, "rater": "static", "code_source": "fence"}}
|
| 9 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a function that generates synthetic tabular data for ML experiments and writes rows incrementally to parquet.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a function that generates synthetic tabular data for ML experiments and writes rows incrementally to parquet."}, {"role": "assistant", "content": "import logging\nfrom typing import Any, Dict\n\n# Logging configuration using chroptiks\ndef setup_logging(level: int = logging.INFO) -> logging.Logger:\n \"\"\"Create a chroptiks-based logger with specified level.\"\"\"\n if 'chroptiks' not in logging.config.get_config():\n logging.basicConfig(\n level=level,\n format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n return logging.getLogger('chroptiks')\n\n# Helper function to generate synthetic tabular data\ndef generate_synthetic_dataframe(\n n_samples: int,\n features: list[str],\n column_names: list[str],\n seed: int = 42\n) -> pd.DataFrame:\n \"\"\"Create a DataFrame for synthetic ML experiment data.\"\"\"\n if 'chroptiks' not in logging.get_config():\n # Ensure chroptiks is configured before calling this function\n if 'chroptiks' not in logging.config.get_config():\n from config import Config\n print(\"Config loaded successfully.\")\n\n rng = np.random.default_rng(seed)\n data = []\n\n for i in range(n_samples):\n x = rng.uniform(0, 10, len(features))\n y = rng.normal(0, 2)\n\n row = {col: x[i] for col in column_names} + [y]\n data.append(row)\n\n return pd.DataFrame(data)\n\n\n# Main function to generate synthetic tabular data\ndef main() -> None:\n \"\"\"Entry point for the experiment setup.\"\"\"\n # Setup logging\n logger = setup_logging(level=logging.INFO)\n\n # Generate DataFrame with specified parameters\n df = generate_synthetic_dataframe(\n n_samples=100,\n features=[\"x1\", \"x2\", \"y\"],\n column_names=[\"col1\", \"col2\", \"col3\"],\n seed=42\n )\n\n # Save to CSV with incremental writes\n df.to_csv('data.csv', index=False)\n\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 8, "total_reward": 0.23076923076923078, "rater": "static", "code_source": "fence"}}
|
| 10 |
+
{"messages": [{"role": "system", "content": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a model evaluation script that loads a checkpointed model, evaluates on a test set, and logs metrics to CSV using pandas.\n\nProvide the full Python implementation.\n"}, {"role": "user", "content": "Implement a model evaluation script that loads a checkpointed model, evaluates on a test set, and logs metrics to CSV using pandas."}, {"role": "assistant", "content": "import logging\nimport os\nimport json\nimport time\n\n# Setup logging\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s - %(levelname)s - %(message)s',\n handlers=[\n logging.FileHandler(os.path.join(os.path.dirname(__file__), 'log_metrics.csv'),\n encoding='utf-8'),\n logging.StreamHandler()\n ]\n)\n\ndef load_checkpoint():\n \"\"\"Load checkpoint file from directory.\"\"\"\n if not os.path.exists('checkpoints'):\n raise FileNotFoundError(\"Checkpoints directory does not exist\")\n \n checkpoint_path = 'checkpoints/model.pt'\n with open(checkpoint_path, 'r') as f:\n data = json.load(f)\n return data\n\n\ndef save_checkpoint(data):\n \"\"\"Save model checkpoint to file.\"\"\"\n output_path = 'checkpoints/model.pt'\n try:\n with open(output_path, 'w') as f:\n json.dump(data, f, indent=2)\n logging.info(f\"Checkpoint saved to {output_path}\")\n except Exception as e:\n logging.error(f\"Error saving checkpoint: {e}\", exc_info=True)\n\n\ndef evaluate(model_data):\n \"\"\"Evaluate model on test data and return metrics.\"\"\"\n X = model_data['features']\n y_true = model_data['target']\n \n # Prepare output dataframe (no column names, no titles)\n results = []\n for i in range(len(y_true)):\n prediction = model.predict(X[i])\n predictions = [p.item() for p in prediction]\n \n result_row = {\n 'input_id': X[i],\n 'true_label': y_true[i],\n 'predicted_label': predictions,\n 'accuracy': round(y_true[i].mean(), 4),\n 'confusion_matrix': evaluate_confusion_matrix(predictions, y_true)\n }\n results.append(result_row)\n \n # Save data as list of dicts (no dictionary writer, no grids)\n data_to_save = [row.to_dict() for row in results]\n save_checkpoint(data_to_save)\n return {\n 'metrics': {\n 'accuracy': 1.0,\n 'top_1_loss': None,\n 'top_5_loss': None,\n 'f1_score': None,\n 'precision': None,\n 'recall': None\n },\n 'results': results\n }\n\n\ndef evaluate_confusion_matrix(y_true, y_pred):\n \"\"\"Calculate confusion matrix using cross-entropy loss.\"\"\"\n tp = 0.0\n fp = 0.0\n tn = 0.0\n fn = 0.0\n \n for true_label in y_true:\n pred_idx = y_pred.index(true_label)\n if pred_idx < len(y_pred):\n tp += 1\n else:\n # Check if index is within bounds, otherwise ignore or handle appropriately\n pass\n \n pred_label = y_pred[pred_idx]\n if true_label == pred_label:\n tn += 1\n elif pred_label > true_label:\n fp += 1\n else:\n fn += 1\n\n cm = {\n 'tp': tp,\n 'fp': fp,\n 'tn': tn,\n 'fn': fn\n }\n return cm\n\n\ndef run_evaluation():\n \"\"\"Main entry point for the evaluation script.\"\"\"\n print(\"Starting model evaluation...\")\n \n # Load checkpoint\n data = load_checkpoint()\n \n # Evaluate on test set\n metrics = evaluate(data)\n \n # Log results\n logging.info(f\"Test set accuracy: {metrics['accuracy']:.4f}\")\n logging.info(f\"Confusion matrix summary:\")\n for key, val in metrics['confusion_matrix'].items():\n logging.info(f\"{key}: {val}\")\n \n return metrics\n\n\nif __name__ == \"__main__\":\n result = run_evaluation()"}], "meta": {"source_model": "qwen3.5:0.8b", "task_id": 9, "total_reward": 0.19230769230769232, "rater": "static", "code_source": "fence"}}
|
traces/fixed2560/summary_qwen3.5-0.8b.json
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"n_traces": 20,
|
| 3 |
+
"models": {
|
| 4 |
+
"qwen3.5:0.8b": {
|
| 5 |
+
"n": 20,
|
| 6 |
+
"n_scored": 20,
|
| 7 |
+
"code_sources": {
|
| 8 |
+
"fence": 19,
|
| 9 |
+
"fence_unterminated": 1
|
| 10 |
+
},
|
| 11 |
+
"empty_reasons": {},
|
| 12 |
+
"mean_reward": -0.0327,
|
| 13 |
+
"std_reward": 0.5028,
|
| 14 |
+
"min_reward": -1.0,
|
| 15 |
+
"max_reward": 0.5385,
|
| 16 |
+
"mean_code_chars": 5306.9,
|
| 17 |
+
"rules": {
|
| 18 |
+
"chroptiks_preference_reward": {
|
| 19 |
+
"mean": -0.1,
|
| 20 |
+
"fired_frac": 0.3
|
| 21 |
+
},
|
| 22 |
+
"intermittent_writes_reward": {
|
| 23 |
+
"mean": -0.35,
|
| 24 |
+
"fired_frac": 0.55
|
| 25 |
+
},
|
| 26 |
+
"logging_over_print_reward": {
|
| 27 |
+
"mean": 0.0,
|
| 28 |
+
"fired_frac": 0.6
|
| 29 |
+
},
|
| 30 |
+
"no_bargraphs_reward": {
|
| 31 |
+
"mean": 0.125,
|
| 32 |
+
"fired_frac": 1.0
|
| 33 |
+
},
|
| 34 |
+
"no_classes_reward": {
|
| 35 |
+
"mean": -0.325,
|
| 36 |
+
"fired_frac": 1.0
|
| 37 |
+
},
|
| 38 |
+
"no_plot_grids_reward": {
|
| 39 |
+
"mean": 0.2,
|
| 40 |
+
"fired_frac": 1.0
|
| 41 |
+
},
|
| 42 |
+
"no_plot_titles_reward": {
|
| 43 |
+
"mean": 0.05,
|
| 44 |
+
"fired_frac": 1.0
|
| 45 |
+
},
|
| 46 |
+
"no_seaborn_reward": {
|
| 47 |
+
"mean": 0.2,
|
| 48 |
+
"fired_frac": 1.0
|
| 49 |
+
},
|
| 50 |
+
"no_try_except_reward": {
|
| 51 |
+
"mean": -0.625,
|
| 52 |
+
"fired_frac": 1.0
|
| 53 |
+
},
|
| 54 |
+
"not_bare_script_reward": {
|
| 55 |
+
"mean": 0.2,
|
| 56 |
+
"fired_frac": 1.0
|
| 57 |
+
},
|
| 58 |
+
"objective_comments_reward": {
|
| 59 |
+
"mean": 0.2,
|
| 60 |
+
"fired_frac": 1.0
|
| 61 |
+
},
|
| 62 |
+
"pandas_csv_preference_reward": {
|
| 63 |
+
"mean": 0.0,
|
| 64 |
+
"fired_frac": 0.7
|
| 65 |
+
},
|
| 66 |
+
"resumable_checkpoint_reward": {
|
| 67 |
+
"mean": 0.0,
|
| 68 |
+
"fired_frac": 1.0
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
"traces_path": "/home/caug/npcww/guac-coder/traces/fixed2560/traces_qwen3.5-0.8b.jsonl",
|
| 74 |
+
"new_traces_this_run": 20,
|
| 75 |
+
"rater": "static"
|
| 76 |
+
}
|
traces/fixed2560/traces_qwen3.5-0.8b.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|