Kiritox07 commited on
Commit
c1b8df7
·
0 Parent(s):

Initial Deployment without large files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. .gitignore +2 -0
  3. Dockerfile +25 -0
  4. README.md +14 -0
  5. core/__init__.py +0 -0
  6. core/__pycache__/__init__.cpython-314.pyc +0 -0
  7. core/__pycache__/config.cpython-314.pyc +0 -0
  8. core/config.py +25 -0
  9. core/sandbox/__init__.py +1 -0
  10. core/sandbox/executor.py +186 -0
  11. main.py +69 -0
  12. masteries/__init__.py +0 -0
  13. masteries/coding/__init__.py +1 -0
  14. masteries/coding/__pycache__/__init__.cpython-314.pyc +0 -0
  15. masteries/coding/artifacts/critic_v1/config.json +43 -0
  16. masteries/coding/artifacts/critic_v1/tokenizer.json +0 -0
  17. masteries/coding/artifacts/critic_v1/tokenizer_config.json +13 -0
  18. masteries/coding/data/__pycache__/generate_critic_datasets.cpython-314.pyc +0 -0
  19. masteries/coding/data/check_langs.py +16 -0
  20. masteries/coding/data/continuous_learning.jsonl +1 -0
  21. masteries/coding/data/download.py +9 -0
  22. masteries/coding/data/explore_hf_dataset.py +23 -0
  23. masteries/coding/data/generate_codecontests_dataset.py +75 -0
  24. masteries/coding/data/generate_codeforces_dataset.py +72 -0
  25. masteries/coding/data/generate_critic_datasets.py +104 -0
  26. masteries/coding/data/generate_pyresbugs_dataset.py +60 -0
  27. masteries/coding/data/inspect_data.py +11 -0
  28. masteries/coding/data/test_sandbox.py +39 -0
  29. masteries/coding/inference/__init__.py +1 -0
  30. masteries/coding/inference/__pycache__/__init__.cpython-314.pyc +0 -0
  31. masteries/coding/inference/__pycache__/actor_generate.cpython-314.pyc +0 -0
  32. masteries/coding/inference/__pycache__/critic_predict.cpython-314.pyc +0 -0
  33. masteries/coding/inference/__pycache__/gpu_orchestrator.cpython-314.pyc +0 -0
  34. masteries/coding/inference/__pycache__/test_critic_brain.cpython-314.pyc +0 -0
  35. masteries/coding/inference/__pycache__/v2_orchestrator.cpython-314.pyc +0 -0
  36. masteries/coding/inference/__pycache__/v3_orchestrator.cpython-314.pyc +0 -0
  37. masteries/coding/inference/__pycache__/v4_orchestrator.cpython-314.pyc +0 -0
  38. masteries/coding/inference/actor_generate.py +80 -0
  39. masteries/coding/inference/critic_predict.py +84 -0
  40. masteries/coding/inference/test_critic_brain.py +35 -0
  41. masteries/coding/inference/v4_orchestrator.py +127 -0
  42. masteries/coding/inference/watchdog.py +63 -0
  43. masteries/coding/models/actor_v1/config.json +42 -0
  44. masteries/coding/models/actor_v1/generation_config.json +6 -0
  45. masteries/coding/models/actor_v1/tokenizer.json +0 -0
  46. masteries/coding/models/actor_v1/tokenizer_config.json +34 -0
  47. masteries/coding/models/critic_best/config.json +30 -0
  48. masteries/coding/models/critic_best/tokenizer.json +0 -0
  49. masteries/coding/models/critic_best/tokenizer_config.json +17 -0
  50. masteries/coding/models/critic_v1/config.json +30 -0
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
2
+ *.parquet filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.safetensors
2
+ *.parquet
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # Set working directory
4
+ WORKDIR /code
5
+
6
+ # Copy requirements and install
7
+ COPY ./requirements.txt /code/requirements.txt
8
+ RUN pip install --no-cache-dir -r /code/requirements.txt
9
+
10
+ # Create a non-root user (Hugging Face Spaces requirement)
11
+ RUN useradd -m -u 1000 user
12
+ USER user
13
+ ENV HOME=/home/user \
14
+ PATH=/home/user/.local/bin:$PATH
15
+
16
+ WORKDIR $HOME/app
17
+
18
+ # Copy the application code
19
+ COPY --chown=user . $HOME/app
20
+
21
+ # Expose port 7860
22
+ EXPOSE 7860
23
+
24
+ # Run the FastAPI server
25
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: PACE AI Inference
3
+ emoji: 🚀
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ ---
9
+
10
+ # PACE AI Inference Service
11
+
12
+ This repository powers the AI backend for the PACE (Pipelined Actor-Critic Ensemble) system.
13
+
14
+ It exposes a FastAPI backend via Docker running on port 7860, serving multiple specialized pipelines for coding, research, and literacy.
core/__init__.py ADDED
File without changes
core/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (195 Bytes). View file
 
core/__pycache__/config.cpython-314.pyc ADDED
Binary file (1.87 kB). View file
 
core/config.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+ from pydantic import Field
3
+ from pydantic_settings import BaseSettings, SettingsConfigDict
4
+
5
+
6
+ class Settings(
7
+ BaseSettings
8
+ ): # Renamed to 'Settings' following PEP 8 PascalCase conventions
9
+ gpu_device: str = Field("cuda:0")
10
+ max_vram_mb: int = Field(7500)
11
+ api_host: str = Field("0.0.0.0")
12
+ api_port: int = Field(8000)
13
+ models_dir: str = Field("./masteries")
14
+ max_sequence_length: int = Field(2048)
15
+ max_critic_iterations: int = Field(5)
16
+ log_level: str = Field("INFO")
17
+
18
+ # Tells Pydantic to read overrides from your .env file
19
+ model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
20
+
21
+
22
+ @lru_cache(maxsize=1)
23
+ def get_settings() -> Settings:
24
+
25
+ return Settings()
core/sandbox/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # sandbox package
core/sandbox/executor.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ executor.py — Sandbox Verification Engine (Stream B / Mastery 1: Coding)
3
+
4
+ Provides a secure, isolated Python subprocess executor that runs
5
+ LLM-generated code snippets against unit tests with strict timeouts.
6
+
7
+ The Coding Critic uses this to emit a binary reward signal:
8
+ PASS → the generated code is functionally correct (reward = +1)
9
+ FAIL → the code has runtime errors or test failures (reward = -1)
10
+
11
+ Security model:
12
+ - Code runs in a *child* subprocess — never eval()/exec() in the parent.
13
+ - stdout/stderr are captured; the parent process is never blocked beyond
14
+ ``timeout`` seconds.
15
+ - A minimal ``__builtins__`` restriction note is included in the harness
16
+ (full sandboxing requires OS-level isolation such as Docker; see
17
+ ``infra/docker/Dockerfile.sandbox``).
18
+ """
19
+
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import textwrap
24
+ import time
25
+ from pathlib import Path
26
+ from typing import Optional
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Defaults
31
+ # ---------------------------------------------------------------------------
32
+
33
+ DEFAULT_TIMEOUT: int = 10 # seconds before the subprocess is killed
34
+ MAX_OUTPUT_CHARS: int = 8_000 # truncate stdout/stderr beyond this
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Public API
39
+ # ---------------------------------------------------------------------------
40
+
41
+ def run_code(
42
+ code: str,
43
+ test_code: Optional[str] = None,
44
+ timeout: int = DEFAULT_TIMEOUT,
45
+ python_executable: str = sys.executable,
46
+ ) -> dict:
47
+ """
48
+ Execute *code* in an isolated subprocess, optionally appending *test_code*.
49
+
50
+ The combined script is written to a temporary file, executed by the
51
+ *python_executable* interpreter, and the results are returned as a dict.
52
+
53
+ Args:
54
+ code: The LLM-generated Python source to execute.
55
+ test_code: Optional unit-test source appended after *code*.
56
+ Should use ``assert`` statements or ``unittest``/
57
+ ``pytest`` style. If provided, any ``AssertionError``
58
+ is treated as a FAIL.
59
+ timeout: Maximum wall-clock seconds allowed for execution.
60
+ python_executable: Path to the Python interpreter (defaults to the
61
+ running interpreter so the same environment is used).
62
+
63
+ Returns:
64
+ A dict with keys:
65
+ - ``"status"`` : ``"pass"`` | ``"fail"`` | ``"timeout"`` | ``"error"``
66
+ - ``"stdout"`` : captured standard output (str, truncated)
67
+ - ``"stderr"`` : captured standard error (str, truncated)
68
+ - ``"return_code"`` : process exit code (int), or ``None`` on timeout
69
+ - ``"elapsed_ms"`` : wall-clock milliseconds spent
70
+ - ``"label"`` : 1 = pass, 0 = fail (for Critic reward)
71
+ """
72
+ # Build the harness script
73
+ harness_parts = [textwrap.dedent(code)]
74
+ if test_code:
75
+ harness_parts.append("\n\n# --- TEST HARNESS ---\n")
76
+ harness_parts.append(textwrap.dedent(test_code))
77
+ full_script = "\n".join(harness_parts)
78
+
79
+ # Write to a temp file (auto-deleted after execution)
80
+ with tempfile.NamedTemporaryFile(
81
+ mode="w",
82
+ suffix=".py",
83
+ prefix="pace_sandbox_",
84
+ delete=False,
85
+ encoding="utf-8",
86
+ ) as tmp:
87
+ tmp.write(full_script)
88
+ tmp_path = Path(tmp.name)
89
+
90
+ start = time.perf_counter()
91
+ try:
92
+ proc = subprocess.run(
93
+ [python_executable, str(tmp_path)],
94
+ capture_output=True,
95
+ text=True,
96
+ timeout=timeout,
97
+ )
98
+ elapsed_ms = int((time.perf_counter() - start) * 1000)
99
+
100
+ stdout = proc.stdout[:MAX_OUTPUT_CHARS]
101
+ stderr = proc.stderr[:MAX_OUTPUT_CHARS]
102
+ return_code = proc.returncode
103
+
104
+ if return_code == 0:
105
+ status = "pass"
106
+ label = 1
107
+ else:
108
+ status = "fail"
109
+ label = 0
110
+
111
+ except subprocess.TimeoutExpired:
112
+ elapsed_ms = timeout * 1000
113
+ stdout = ""
114
+ stderr = f"Execution timed out after {timeout}s."
115
+ return_code = None
116
+ status = "timeout"
117
+ label = 0
118
+
119
+ except Exception as exc:
120
+ elapsed_ms = int((time.perf_counter() - start) * 1000)
121
+ stdout = ""
122
+ stderr = str(exc)
123
+ return_code = -1
124
+ status = "error"
125
+ label = 0
126
+
127
+ finally:
128
+ tmp_path.unlink(missing_ok=True)
129
+
130
+ return {
131
+ "status": status,
132
+ "stdout": stdout,
133
+ "stderr": stderr,
134
+ "return_code": return_code,
135
+ "elapsed_ms": elapsed_ms,
136
+ "label": label,
137
+ }
138
+
139
+
140
+ def batch_run(
141
+ code_test_pairs: list[tuple[str, Optional[str]]],
142
+ timeout: int = DEFAULT_TIMEOUT,
143
+ ) -> list[dict]:
144
+ """
145
+ Run multiple (code, test_code) pairs sequentially and return a list of
146
+ result dicts. Useful for batch evaluation during Critic training.
147
+
148
+ Args:
149
+ code_test_pairs: List of (code, test_code) tuples.
150
+ timeout: Per-execution timeout in seconds.
151
+
152
+ Returns:
153
+ List of result dicts as returned by :func:`run_code`.
154
+ """
155
+ return [run_code(code, test, timeout=timeout) for code, test in code_test_pairs]
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # CLI smoke-test
160
+ # ---------------------------------------------------------------------------
161
+
162
+ if __name__ == "__main__":
163
+ print("=== Sandbox Executor — Smoke Test ===\n")
164
+
165
+ # Test 1: correct code
166
+ result = run_code(
167
+ code="def add(a, b): return a + b",
168
+ test_code="assert add(2, 3) == 5\nassert add(-1, 1) == 0\nprint('Tests passed.')",
169
+ )
170
+ print(f"[PASS expected] status={result['status']} label={result['label']}")
171
+ print(f" stdout: {result['stdout'].strip()}")
172
+
173
+ # Test 2: buggy code (assertion will fail)
174
+ result = run_code(
175
+ code="def add(a, b): return a - b", # bug: subtraction instead of addition
176
+ test_code="assert add(2, 3) == 5",
177
+ )
178
+ print(f"\n[FAIL expected] status={result['status']} label={result['label']}")
179
+ print(f" stderr: {result['stderr'].strip()[:200]}")
180
+
181
+ # Test 3: infinite loop → timeout
182
+ result = run_code(
183
+ code="while True: pass",
184
+ timeout=2,
185
+ )
186
+ print(f"\n[TIMEOUT expected] status={result['status']} label={result['label']}")
main.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import traceback
3
+ from pydantic import BaseModel
4
+ from typing import Optional
5
+ from fastapi import FastAPI, HTTPException
6
+ from fastapi.responses import StreamingResponse
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ import threading
9
+
10
+ app = FastAPI(
11
+ title="PACE AI Inference Service",
12
+ description="Hugging Face Deployment for PACE Actor-Critic Ensemble",
13
+ version="1.0.0"
14
+ )
15
+
16
+ app.add_middleware(
17
+ CORSMiddleware,
18
+ allow_origins=["*"],
19
+ allow_credentials=True,
20
+ allow_methods=["*"],
21
+ allow_headers=["*"],
22
+ )
23
+
24
+ class GenerateRequest(BaseModel):
25
+ text: str
26
+ mode: Optional[str] = "coding"
27
+ speed_mode: Optional[str] = "pro"
28
+
29
+ _generate_lock = threading.Lock()
30
+
31
+ @app.get("/")
32
+ def root():
33
+ return {"status": "PACE AI Service Running"}
34
+
35
+ @app.get("/health")
36
+ def health():
37
+ return {"status": "healthy"}
38
+
39
+ @app.post("/generate_stream")
40
+ def generate_stream(request: GenerateRequest):
41
+ def event_stream():
42
+ if not _generate_lock.acquire(blocking=False):
43
+ yield json.dumps({"type": "status", "content": "Server busy"}) + "\n"
44
+ yield json.dumps({"type": "done"}) + "\n"
45
+ return
46
+
47
+ try:
48
+ mode = request.mode
49
+ speed = request.speed_mode
50
+
51
+ if mode == "literacy":
52
+ from masteries.literacy.inference.v4_orchestrator import literacy_pipeline as active_pipeline
53
+ elif mode == "research":
54
+ from masteries.research.inference.v4_orchestrator import research_pipeline as active_pipeline
55
+ else:
56
+ from masteries.coding.inference.v4_orchestrator import v4_pipeline as active_pipeline
57
+
58
+ for event in active_pipeline(request.text, speed_mode=speed):
59
+ # The event is already a dictionary.
60
+ yield json.dumps(event) + "\n"
61
+
62
+ yield json.dumps({"type": "done"}) + "\n"
63
+ except Exception as e:
64
+ traceback.print_exc()
65
+ yield json.dumps({"type": "error", "content": str(e)}) + "\n"
66
+ finally:
67
+ _generate_lock.release()
68
+
69
+ return StreamingResponse(event_stream(), media_type="application/x-ndjson")
masteries/__init__.py ADDED
File without changes
masteries/coding/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # masteries.coding package
masteries/coding/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (207 Bytes). View file
 
masteries/coding/artifacts/critic_v1/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_num_labels": 1,
3
+ "activation_function": "gelu_new",
4
+ "add_cross_attention": false,
5
+ "architectures": [
6
+ "GPT2ForSequenceClassification"
7
+ ],
8
+ "attn_pdrop": 0.1,
9
+ "bos_token_id": 50256,
10
+ "dtype": "float32",
11
+ "embd_pdrop": 0.1,
12
+ "eos_token_id": 50256,
13
+ "initializer_range": 0.02,
14
+ "layer_norm_epsilon": 1e-05,
15
+ "model_type": "gpt2",
16
+ "n_ctx": 1024,
17
+ "n_embd": 768,
18
+ "n_head": 12,
19
+ "n_inner": null,
20
+ "n_layer": 6,
21
+ "n_positions": 1024,
22
+ "pad_token_id": 50256,
23
+ "problem_type": "single_label_classification",
24
+ "reorder_and_upcast_attn": false,
25
+ "resid_pdrop": 0.1,
26
+ "scale_attn_by_inverse_layer_idx": false,
27
+ "scale_attn_weights": true,
28
+ "summary_activation": null,
29
+ "summary_first_dropout": 0.1,
30
+ "summary_proj_to_labels": true,
31
+ "summary_type": "cls_index",
32
+ "summary_use_proj": true,
33
+ "task_specific_params": {
34
+ "text-generation": {
35
+ "do_sample": true,
36
+ "max_length": 50
37
+ }
38
+ },
39
+ "tie_word_embeddings": true,
40
+ "transformers_version": "5.13.0",
41
+ "use_cache": true,
42
+ "vocab_size": 50257
43
+ }
masteries/coding/artifacts/critic_v1/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
masteries/coding/artifacts/critic_v1/tokenizer_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "eos_token": "<|endoftext|>",
6
+ "errors": "replace",
7
+ "is_local": false,
8
+ "local_files_only": false,
9
+ "model_max_length": 1024,
10
+ "pad_token": "<|endoftext|>",
11
+ "tokenizer_class": "GPT2Tokenizer",
12
+ "unk_token": "<|endoftext|>"
13
+ }
masteries/coding/data/__pycache__/generate_critic_datasets.cpython-314.pyc ADDED
Binary file (3.66 kB). View file
 
masteries/coding/data/check_langs.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+
3
+ def main():
4
+ ds = datasets.load_dataset("ByteDance-Seed/Code-Contests-Plus", split="train", streaming=True)
5
+ langs = set()
6
+ for i, item in enumerate(ds):
7
+ for sub in item.get('correct_submissions', []):
8
+ langs.add(sub.get('language', ''))
9
+ for sub in item.get('incorrect_submissions', []):
10
+ langs.add(sub.get('language', ''))
11
+ if i >= 100:
12
+ break
13
+ print("Available languages:", langs)
14
+
15
+ if __name__ == "__main__":
16
+ main()
masteries/coding/data/continuous_learning.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"prompt": "write a code for binary search", "target_code": "# Generated by Critic due to Actor failure\ndef binary_search(arr, target):\n low, high = 0, len(arr) - 1\n \n while low <= high:\n mid = (low + high) // 2\n if arr[mid] == target:\n return mid\n elif arr[mid] < target:\n low = mid + 1\n else:\n high = mid - 1\n \n return -1"}
masteries/coding/data/download.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+
3
+ dataset = load_dataset("nuprl/stack-dedup-python-testgen-starcoder-filter-v2")
4
+
5
+
6
+ print(dataset)
7
+ print("Saving dataset to disk... please wait a few seconds...")
8
+ dataset["train"].to_parquet("masteries/coding/data/raw/stack_python_157k.parquet")
9
+ print("SUCCESS: File permanently saved to disk!")
masteries/coding/data/explore_hf_dataset.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+
3
+ print("Exploring open-r1/codeforces-submissions...")
4
+ try:
5
+ ds1 = datasets.load_dataset("open-r1/codeforces-submissions", split="train", streaming=True)
6
+ for i, item in enumerate(ds1):
7
+ print("Codeforces Sample:", item.keys())
8
+ print(item)
9
+ break
10
+ except Exception as e:
11
+ print(f"Error loading Codeforces: {e}")
12
+
13
+ print("\nExploring ByteDance-Seed/Code-Contests-Plus...")
14
+ try:
15
+ ds2 = datasets.load_dataset("ByteDance-Seed/Code-Contests-Plus", split="train", streaming=True)
16
+ for i, item in enumerate(ds2):
17
+ print("CodeContests+ Sample:", item.keys())
18
+ # Truncate some large strings if necessary
19
+ keys_to_print = {k: v[:200] if isinstance(v, str) else v for k, v in item.items()}
20
+ print(keys_to_print)
21
+ break
22
+ except Exception as e:
23
+ print(f"Error loading CodeContests+: {e}")
masteries/coding/data/generate_codecontests_dataset.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import datasets
4
+
5
+
6
+ def main():
7
+ OUTPUT_DIR = "masteries/coding/data/raw"
8
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
9
+ OUTPUT_PATH = os.path.join(OUTPUT_DIR, "codecontests_fused_dataset.parquet")
10
+
11
+ print("Loading ByteDance-Seed/Code-Contests-Plus dataset (streaming mode)...")
12
+ ds = datasets.load_dataset(
13
+ "ByteDance-Seed/Code-Contests-Plus", split="train", streaming=True
14
+ )
15
+
16
+ clean_data = []
17
+ buggy_data = []
18
+
19
+ # Target dataset size: 50k clean, 50k buggy
20
+ TARGET_PER_CLASS = 50000
21
+
22
+ print(f"Extracting up to {TARGET_PER_CLASS} Python samples per class...")
23
+
24
+ for item in ds:
25
+ # Extract correct submissions (Clean / Label 0)
26
+ for sub in item.get("correct_submissions", []):
27
+ if (
28
+ "python" in str(sub.get("language", "")).lower()
29
+ and len(clean_data) < TARGET_PER_CLASS
30
+ ):
31
+ clean_data.append(
32
+ {"mutated_code": sub.get("code", ""), "label": "CLEAN"}
33
+ )
34
+
35
+ # Extract incorrect submissions (Buggy / Label 1)
36
+ for sub in item.get("incorrect_submissions", []):
37
+ if (
38
+ "python" in str(sub.get("language", "")).lower()
39
+ and len(buggy_data) < TARGET_PER_CLASS
40
+ ):
41
+ buggy_data.append({"mutated_code": sub.get("code", ""), "label": "BUG"})
42
+
43
+ # Stop early if we have enough data
44
+ if len(clean_data) >= TARGET_PER_CLASS and len(buggy_data) >= TARGET_PER_CLASS:
45
+ break
46
+
47
+ print(f"Extracted {len(clean_data)} CLEAN samples.")
48
+ print(f"Extracted {len(buggy_data)} BUGGY samples.")
49
+
50
+ df_clean = pd.DataFrame(clean_data)
51
+ df_bugs = pd.DataFrame(buggy_data)
52
+
53
+ print("Fusing and randomizing dataset...")
54
+ df_fused = pd.concat([df_clean, df_bugs], ignore_index=True)
55
+
56
+ # Remove completely duplicated snippets
57
+ df_fused = df_fused.drop_duplicates(
58
+ subset=["mutated_code"], keep="first"
59
+ ).reset_index(drop=True)
60
+
61
+ # Final deep shuffle
62
+ df_fused = df_fused.sample(frac=1, random_state=42).reset_index(drop=True)
63
+
64
+ print(f"Saving to {OUTPUT_PATH}...")
65
+ df_fused.to_parquet(OUTPUT_PATH)
66
+
67
+ print(f"SUCCESS! Dataset saved to {OUTPUT_PATH}")
68
+ print(f"Total Rows: {len(df_fused)}")
69
+ print(
70
+ f"Clean Data: {(df_fused['label'] == 'CLEAN').sum()} | Bug Data: {(df_fused['label'] == 'BUG').sum()}"
71
+ )
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()
masteries/coding/data/generate_codeforces_dataset.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import datasets
4
+
5
+
6
+ def main():
7
+ OUTPUT_DIR = "masteries/coding/data/raw"
8
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
9
+ OUTPUT_PATH = os.path.join(OUTPUT_DIR, "codeforces_fused_dataset.parquet")
10
+
11
+ print("Loading open-r1/codeforces-submissions dataset (streaming mode)...")
12
+ ds = datasets.load_dataset(
13
+ "open-r1/codeforces-submissions", split="train", streaming=True
14
+ )
15
+
16
+ clean_data = []
17
+ buggy_data = []
18
+
19
+ # Target dataset size: 50k clean, 50k buggy
20
+ TARGET_PER_CLASS = 50000
21
+
22
+ print(f"Extracting up to {TARGET_PER_CLASS} Python samples per class...")
23
+
24
+ for item in ds:
25
+ lang = str(item.get("programmingLanguage", "")).lower()
26
+ if "python" not in lang and "pypy" not in lang:
27
+ continue
28
+
29
+ verdict = item.get("verdict", "")
30
+ code = item.get("source", "")
31
+
32
+ if verdict == "OK" and len(clean_data) < TARGET_PER_CLASS:
33
+ clean_data.append({"mutated_code": code, "label": "CLEAN"})
34
+ elif (
35
+ verdict in ["WRONG_ANSWER", "TIME_LIMIT_EXCEEDED", "RUNTIME_ERROR"]
36
+ and len(buggy_data) < TARGET_PER_CLASS
37
+ ):
38
+ buggy_data.append({"mutated_code": code, "label": "BUG"})
39
+
40
+ # Stop early if we have enough data
41
+ if len(clean_data) >= TARGET_PER_CLASS and len(buggy_data) >= TARGET_PER_CLASS:
42
+ break
43
+
44
+ print(f"Extracted {len(clean_data)} CLEAN samples.")
45
+ print(f"Extracted {len(buggy_data)} BUGGY samples.")
46
+
47
+ df_clean = pd.DataFrame(clean_data)
48
+ df_bugs = pd.DataFrame(buggy_data)
49
+
50
+ print("Fusing and randomizing dataset...")
51
+ df_fused = pd.concat([df_clean, df_bugs], ignore_index=True)
52
+
53
+ # Remove completely duplicated snippets
54
+ df_fused = df_fused.drop_duplicates(
55
+ subset=["mutated_code"], keep="first"
56
+ ).reset_index(drop=True)
57
+
58
+ # Final deep shuffle
59
+ df_fused = df_fused.sample(frac=1, random_state=42).reset_index(drop=True)
60
+
61
+ print(f"Saving to {OUTPUT_PATH}...")
62
+ df_fused.to_parquet(OUTPUT_PATH)
63
+
64
+ print(f"SUCCESS! Dataset saved to {OUTPUT_PATH}")
65
+ print(f"Total Rows: {len(df_fused)}")
66
+ print(
67
+ f"Clean Data: {(df_fused['label'] == 'CLEAN').sum()} | Bug Data: {(df_fused['label'] == 'BUG').sum()}"
68
+ )
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
masteries/coding/data/generate_critic_datasets.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import numpy as np
4
+
5
+ # 1. Define paths
6
+ RAW_PARQUET_PATH = "masteries/coding/data/raw/stack_python_157k.parquet"
7
+ OUTPUT_DIR = "masteries/coding/data/raw"
8
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
9
+
10
+ print("Loading the master dataset...")
11
+ df_master = pd.read_parquet(RAW_PARQUET_PATH)
12
+
13
+ # 2. SHUFFLE FIRST: Destroy any original order in the dataset
14
+ print("Performing initial shuffle...")
15
+ df_master = df_master.sample(frac=1, random_state=42).reset_index(drop=True)
16
+
17
+ # 3. THE ROUND-ROBIN ALLOCATOR
18
+ # We use modulo 6 to perfectly zipper the data (50% Clean, 50% Bugs spread across 3 types)
19
+ # Pattern: 0=Clean, 1=Flip, 2=Clean, 3=Constant, 4=Clean, 5=Deletion
20
+ print("Slicing into mutually exclusive categories...")
21
+ conditions = [
22
+ (df_master.index % 6 == 0) | (df_master.index % 6 == 2) | (df_master.index % 6 == 4), # 50% Clean
23
+ (df_master.index % 6 == 1), # 16.6% Flip
24
+ (df_master.index % 6 == 3), # 16.6% Constant
25
+ (df_master.index % 6 == 5) # 16.6% Deletion
26
+ ]
27
+ choices = ['CLEAN', 'FLIP', 'CONSTANT', 'DELETION']
28
+ df_master['assigned_type'] = np.select(conditions, choices, default='UNKNOWN')
29
+
30
+ # Isolate the slices
31
+ df_clean = df_master[df_master['assigned_type'] == 'CLEAN'].copy()
32
+ df_flips = df_master[df_master['assigned_type'] == 'FLIP'].copy()
33
+ df_constants = df_master[df_master['assigned_type'] == 'CONSTANT'].copy()
34
+ df_deletions = df_master[df_master['assigned_type'] == 'DELETION'].copy()
35
+
36
+ # ==========================================
37
+ # APPLY MUTATIONS (Safely isolated)
38
+ # ==========================================
39
+ print(f"Applying mutations (Zero Overlap Guaranteed)...")
40
+
41
+ # FLIPS
42
+ df_flips["mutated_code"] = (
43
+ df_flips["content"]
44
+ .str.replace(" == ", " != ", regex=False)
45
+ .str.replace(" < ", " > ", regex=False)
46
+ .str.replace(" + ", " - ", regex=False)
47
+ )
48
+ df_flips["bug_type"] = "OPERATOR_FLIP"
49
+ df_flips["label"] = "BUG"
50
+ df_flips = df_flips[df_flips["mutated_code"] != df_flips["content"]].copy()
51
+
52
+ # CONSTANTS
53
+ df_constants["mutated_code"] = (
54
+ df_constants["content"]
55
+ .str.replace(" 0", " 1", regex=False)
56
+ .str.replace("True", "False", regex=False)
57
+ .str.replace("False", "True", regex=False)
58
+ )
59
+ df_constants["bug_type"] = "CONSTANT_SHIFT"
60
+ df_constants["label"] = "BUG"
61
+ df_constants = df_constants[df_constants["mutated_code"] != df_constants["content"]].copy()
62
+
63
+ # DELETIONS
64
+ def drop_return_statement(code_str):
65
+ lines = str(code_str).split("\n")
66
+ surviving_lines = [line for line in lines if "return " not in line]
67
+ return "\n".join(surviving_lines)
68
+
69
+ df_deletions["mutated_code"] = df_deletions["content"].apply(drop_return_statement)
70
+ df_deletions["bug_type"] = "STATEMENT_DELETION"
71
+ df_deletions["label"] = "BUG"
72
+ df_deletions = df_deletions[df_deletions["mutated_code"] != df_deletions["content"]].copy()
73
+
74
+ # CLEAN
75
+ df_clean["mutated_code"] = df_clean["content"]
76
+ df_clean["bug_type"] = "CLEAN"
77
+ df_clean["label"] = "CLEAN"
78
+
79
+ # ==========================================
80
+ # BALANCE THE CLASSES (50/50 MATCH)
81
+ # ==========================================
82
+ total_surviving_bugs = len(df_flips) + len(df_constants) + len(df_deletions)
83
+ print(f"Trimming clean data from {len(df_clean)} down to {total_surviving_bugs}...")
84
+ df_clean = df_clean.sample(n=total_surviving_bugs, random_state=42).copy()
85
+
86
+ # ==========================================
87
+ # RECOMBINE & FINAL SHUFFLE
88
+ # ==========================================
89
+ print("Fusing and randomizing final dataset...")
90
+ df_fused = pd.concat([df_clean, df_flips, df_constants, df_deletions], ignore_index=True)
91
+
92
+ # Remove rows sharing identical code logic (duplicates)
93
+ df_fused = df_fused.drop_duplicates(subset=["mutated_code"], keep="first").reset_index(drop=True)
94
+
95
+ # Final deep shuffle so the Critic learns no sequential patterns
96
+ df_fused = df_fused.sample(frac=1, random_state=99).reset_index(drop=True)
97
+
98
+ # Save
99
+ fused_path = os.path.join(OUTPUT_DIR, "critic_fused_dataset.parquet")
100
+ df_fused.to_parquet(fused_path)
101
+
102
+ print(f"SUCCESS! Dataset saved to {fused_path}")
103
+ print(f"Total Rows: {len(df_fused)}")
104
+ print(f"Clean Data: {(df_fused['label'] == 'CLEAN').sum()} | Bug Data: {(df_fused['label'] == 'BUG').sum()}")
masteries/coding/data/generate_pyresbugs_dataset.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ from datasets import load_dataset
4
+
5
+ # 1. Define paths
6
+ OUTPUT_DIR = "masteries/coding/data/raw"
7
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
8
+ OUTPUT_PATH = os.path.join(OUTPUT_DIR, "pyresbugs_fused_dataset.parquet")
9
+
10
+ print("Downloading OSS-forge/PyResBugs dataset...")
11
+ dataset = load_dataset("OSS-forge/PyResBugs")
12
+
13
+ # PyResBugs only has a train split
14
+ df_master = pd.DataFrame(dataset['train'])
15
+
16
+ print(f"Loaded {len(df_master)} raw bugs from PyResBugs.")
17
+
18
+ # 2. Extract CLEAN data (Fault Free Code)
19
+ df_clean = pd.DataFrame({
20
+ "mutated_code": df_master["Fault Free Code"],
21
+ "bug_type": "CLEAN",
22
+ "label": "CLEAN"
23
+ })
24
+
25
+ # 3. Extract BUG data (Faulty Code)
26
+ df_bugs = pd.DataFrame({
27
+ "mutated_code": df_master["Faulty Code"],
28
+ "bug_type": df_master["Fault_Acronym"].fillna("UNKNOWN_BUG"),
29
+ "label": "BUG"
30
+ })
31
+
32
+ # 4. Remove rows where Faulty and Fault Free code are identical (just in case)
33
+ # We can do this by merging and comparing
34
+ invalid_mask = df_master["Fault Free Code"] == df_master["Faulty Code"]
35
+ num_invalid = invalid_mask.sum()
36
+ if num_invalid > 0:
37
+ print(f"Warning: Found {num_invalid} rows where Faulty Code == Fault Free Code. Dropping them.")
38
+ df_clean = df_clean[~invalid_mask]
39
+ df_bugs = df_bugs[~invalid_mask]
40
+
41
+ # Drop NaNs just in case
42
+ df_clean = df_clean.dropna(subset=["mutated_code"])
43
+ df_bugs = df_bugs.dropna(subset=["mutated_code"])
44
+
45
+ # 5. Recombine & Shuffle
46
+ print("Fusing and randomizing dataset...")
47
+ df_fused = pd.concat([df_clean, df_bugs], ignore_index=True)
48
+
49
+ # Remove completely duplicated snippets
50
+ df_fused = df_fused.drop_duplicates(subset=["mutated_code"], keep="first").reset_index(drop=True)
51
+
52
+ # Final deep shuffle
53
+ df_fused = df_fused.sample(frac=1, random_state=42).reset_index(drop=True)
54
+
55
+ # Save
56
+ df_fused.to_parquet(OUTPUT_PATH)
57
+
58
+ print(f"SUCCESS! Dataset saved to {OUTPUT_PATH}")
59
+ print(f"Total Rows: {len(df_fused)}")
60
+ print(f"Clean Data: {(df_fused['label'] == 'CLEAN').sum()} | Bug Data: {(df_fused['label'] == 'BUG').sum()}")
masteries/coding/data/inspect_data.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+ df = pd.read_parquet("masteries/coding/data/raw/stack_python_157k.parquet")
4
+
5
+
6
+ print("\n--- Here is Row 0: The First Code Example! ---")
7
+ print("FUNCTION CODE:")
8
+ print(df["content"].iloc[0]) # iloc[0] means "Index Location 0" (the first row)
9
+
10
+ print("\nAUTOMATED UNIT TESTS:")
11
+ print(df["tests"].iloc[0])
masteries/coding/data/test_sandbox.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+
4
+ # 1. Let's create a sample code string with a DELIBERATE bug (2 + 2 = 5!)
5
+ buggy_code = """
6
+ def add_numbers(a, b):
7
+ return a + b + 1 # BUG: Flipped logic / off-by-one error!
8
+ """
9
+
10
+ # 2. Let's attach an objective unit test assertion
11
+ unit_test = """
12
+ assert add_numbers(2, 2) == 4, "Math failed: 2 + 2 should be 4!"
13
+ print("ALL TESTS PASSED!")
14
+ """
15
+
16
+ # We combine them into a single executable payload
17
+ full_payload = buggy_code + "\n" + unit_test
18
+
19
+ print("Launching isolated child subprocess to verify code...")
20
+
21
+ try:
22
+ # 3. We spawn a child python process to execute the payload with a 2-second timeout!
23
+ result = subprocess.run(
24
+ [sys.executable, "-c", full_payload],
25
+ capture_output=True, # Capture what prints to screen
26
+ text=True, # Decode output as strings, not raw bytes
27
+ timeout=2.0, # Kill process if it loops for more than 2 seconds
28
+ )
29
+
30
+ # 4. Evaluate the Exit Code (0 = Success, anything else = Crash/Test Failure)
31
+ if result.returncode == 0:
32
+ print("SANDBOX RESULT: CLEAN (All unit tests passed!)")
33
+ print("Output:", result.stdout.strip())
34
+ else:
35
+ print("SANDBOX RESULT: BUG DETECTED (Unit test failed!)")
36
+ print("Error Traceback:\n", result.stderr.strip())
37
+
38
+ except subprocess.TimeoutExpired:
39
+ print("SANDBOX RESULT: INFINITE LOOP TERMINATED (Exceeded 2.0s limit!)")
masteries/coding/inference/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # masteries.coding.inference package
masteries/coding/inference/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (217 Bytes). View file
 
masteries/coding/inference/__pycache__/actor_generate.cpython-314.pyc ADDED
Binary file (2.91 kB). View file
 
masteries/coding/inference/__pycache__/critic_predict.cpython-314.pyc ADDED
Binary file (3.02 kB). View file
 
masteries/coding/inference/__pycache__/gpu_orchestrator.cpython-314.pyc ADDED
Binary file (2.8 kB). View file
 
masteries/coding/inference/__pycache__/test_critic_brain.cpython-314.pyc ADDED
Binary file (1.89 kB). View file
 
masteries/coding/inference/__pycache__/v2_orchestrator.cpython-314.pyc ADDED
Binary file (7.05 kB). View file
 
masteries/coding/inference/__pycache__/v3_orchestrator.cpython-314.pyc ADDED
Binary file (2.12 kB). View file
 
masteries/coding/inference/__pycache__/v4_orchestrator.cpython-314.pyc ADDED
Binary file (4.3 kB). View file
 
masteries/coding/inference/actor_generate.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PACE Actor Inference Node
3
+ Task LE-1: Loads the trained Actor Model, generates multiple code fixes based on a prompt.
4
+ """
5
+
6
+ import os
7
+ import torch
8
+ import gc
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+
11
+
12
+ def generate_fixes(
13
+ prompt: str,
14
+ model_dir: str = "masteries/coding/models/actor_v1",
15
+ num_return_sequences: int = 3,
16
+ fallback_model: str = "bigcode/tiny_starcoder_py",
17
+ ) -> list[str]:
18
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
+
20
+ target_dir = model_dir if os.path.exists(model_dir) else fallback_model
21
+
22
+ try:
23
+ tokenizer = AutoTokenizer.from_pretrained(target_dir)
24
+ except Exception:
25
+ tokenizer = None
26
+
27
+ if tokenizer is None and target_dir != fallback_model:
28
+ try:
29
+ tokenizer = AutoTokenizer.from_pretrained(fallback_model)
30
+ except Exception:
31
+ tokenizer = None
32
+
33
+ if tokenizer is None:
34
+ raise ValueError(
35
+ f"Failed to load tokenizer from '{target_dir}' or fallback '{fallback_model}'."
36
+ )
37
+
38
+ if getattr(tokenizer, "pad_token", None) is None:
39
+ tokenizer.pad_token = tokenizer.eos_token
40
+
41
+ # Load the custom 164M fine-tuned Actor (or fallback base model)
42
+ try:
43
+ model = AutoModelForCausalLM.from_pretrained(target_dir).to(device)
44
+ except Exception:
45
+ model = AutoModelForCausalLM.from_pretrained(fallback_model).to(device)
46
+
47
+ inputs = tokenizer(
48
+ prompt,
49
+ return_tensors="pt",
50
+ truncation=True,
51
+ )
52
+ inputs = {k: v.to(device) for k, v in inputs.items()}
53
+
54
+ with torch.no_grad():
55
+ generated_ids = model.generate(
56
+ **inputs,
57
+ max_new_tokens=256,
58
+ temperature=0.7,
59
+ do_sample=True,
60
+ num_return_sequences=num_return_sequences,
61
+ )
62
+
63
+ decoded_texts = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
64
+
65
+ # VRAM PURGE: Destroy tensors and clear cache
66
+ del model, tokenizer, inputs, generated_ids
67
+ gc.collect()
68
+ if device.type == "cuda":
69
+ torch.cuda.empty_cache()
70
+ print(
71
+ f"[VRAM] Actor Purged. Idling Footprint: {torch.cuda.memory_allocated() / (1024**2):.2f} MB"
72
+ )
73
+
74
+ return decoded_texts
75
+
76
+
77
+ if __name__ == "__main__":
78
+ print("[SYSTEM] Testing Actor Inference Engine")
79
+ test_prompt = "def linear_search(arr):"
80
+ print(generate_fixes(test_prompt, num_return_sequences=1))
masteries/coding/inference/critic_predict.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PACE Critic Inference Node
3
+ Task LE-2: Loads the trained 125M CodeBERT Critic, evaluates a batch of code strings.
4
+ """
5
+
6
+ import os
7
+ import torch
8
+ import gc
9
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
10
+
11
+
12
+ def evaluate_syntax_batch(
13
+ code_snippets: list[str],
14
+ model_dir: str = "masteries/coding/models/critic_v3",
15
+ fallback_model: str = "microsoft/codebert-base",
16
+ ) -> list[float]:
17
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
+
19
+ target_dir = model_dir if os.path.exists(model_dir) else fallback_model
20
+
21
+ try:
22
+ tokenizer = AutoTokenizer.from_pretrained(target_dir)
23
+ except Exception:
24
+ tokenizer = None
25
+
26
+ if tokenizer is None and target_dir != fallback_model:
27
+ try:
28
+ tokenizer = AutoTokenizer.from_pretrained(fallback_model)
29
+ except Exception:
30
+ tokenizer = None
31
+
32
+ if tokenizer is None:
33
+ raise ValueError(
34
+ f"Failed to load tokenizer from '{target_dir}' or fallback '{fallback_model}'."
35
+ )
36
+
37
+ if getattr(tokenizer, "pad_token", None) is None:
38
+ tokenizer.pad_token = tokenizer.eos_token
39
+
40
+ # Initialize with num_labels=2 for binary classification
41
+ try:
42
+ model = AutoModelForSequenceClassification.from_pretrained(
43
+ target_dir, num_labels=2
44
+ ).to(device)
45
+ except Exception:
46
+ model = AutoModelForSequenceClassification.from_pretrained(
47
+ fallback_model, num_labels=2
48
+ ).to(device)
49
+
50
+ inputs = tokenizer(
51
+ code_snippets,
52
+ truncation=True,
53
+ max_length=512,
54
+ padding="max_length",
55
+ return_tensors="pt",
56
+ )
57
+ inputs = {k: v.to(device) for k, v in inputs.items()}
58
+
59
+ with torch.no_grad():
60
+ outputs = model(**inputs)
61
+
62
+ # Convert raw logits to percentages (0.0 to 1.0)
63
+ probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
64
+
65
+ # Extract the probability of Class 1 (Bug). Lower is better (closer to 0 / Clean).
66
+ bug_probs = probabilities[:, 1].tolist()
67
+
68
+ # VRAM PURGE: Destroy tensors and clear cache
69
+ del model, tokenizer, inputs, outputs, probabilities
70
+ gc.collect()
71
+ if device.type == "cuda":
72
+ torch.cuda.empty_cache()
73
+ print(
74
+ f"[VRAM] Critic Purged. Idling Footprint: {torch.cuda.memory_allocated() / (1024**2):.2f} MB"
75
+ )
76
+
77
+ return bug_probs
78
+
79
+
80
+ if __name__ == "__main__":
81
+ print("[SYSTEM] Testing Critic Inference Engine...")
82
+ bad_code = ["def calculate_sum(a, b) return a + b"]
83
+ print("Testing Critic Inference Engine...")
84
+ print(evaluate_syntax_batch(bad_code))
masteries/coding/inference/test_critic_brain.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+
4
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
5
+ model_dir = "masteries/coding/models/critic_best"
6
+
7
+ print("Loading Critic...")
8
+ tokenizer = AutoTokenizer.from_pretrained(model_dir)
9
+ model = AutoModelForSequenceClassification.from_pretrained(model_dir).to(device)
10
+ model.eval()
11
+
12
+ clean_code = """
13
+ def multiply(a, b):
14
+ return a * b
15
+ """
16
+
17
+ buggy_code = """
18
+ def multiply(a, b):
19
+ return a + b
20
+ """
21
+
22
+
23
+ def predict_bug(code_str):
24
+ inputs = tokenizer(
25
+ code_str, return_tensors="pt", truncation=True, max_length=512
26
+ ).to(device)
27
+ with torch.no_grad():
28
+ logits = model(**inputs).logits
29
+ probs = torch.softmax(logits, dim=1)
30
+ # Class 1 is "BUG"
31
+ return probs[0][1].item()
32
+
33
+
34
+ print(f"\n[CLEAN CODE] Bug Probability: {predict_bug(clean_code):.4f}")
35
+ print(f"[BUGGY CODE] Bug Probability: {predict_bug(buggy_code):.4f}")
masteries/coding/inference/v4_orchestrator.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import sys
3
+ import torch
4
+
5
+ from masteries.coding.training.actor.alt_actor_model import ActorModel
6
+ from masteries.coding.training.critic.alt_critic_model import QwenCritic
7
+
8
+ # Global instances to avoid reloading models on every request
9
+ _actor = None
10
+ _critic = None
11
+
12
+
13
+ def get_actor():
14
+ global _actor
15
+ if _actor is None:
16
+ print("Initializing Actor Model...")
17
+ _actor = ActorModel()
18
+ return _actor
19
+
20
+
21
+ def get_critic():
22
+ global _critic
23
+ if _critic is None:
24
+ print("Initializing Critic Model...")
25
+ _critic = QwenCritic()
26
+ return _critic
27
+
28
+
29
+ def flush_vram():
30
+ """Forces PyTorch to release memory back to the OS."""
31
+ gc.collect()
32
+ if torch.cuda.is_available():
33
+ torch.cuda.empty_cache()
34
+
35
+
36
+ def v4_pipeline(user_prompt, max_iterations=1, speed_mode="pro"):
37
+ """
38
+ PACE Dual-Engine Orchestrator.
39
+ Uses the Actor (3B) to generate code and Critic (1.5B) to review and revise.
40
+ """
41
+ yield {
42
+ "type": "status",
43
+ "content": f"Initializing Actor-Critic Ensemble (v4 - {speed_mode} mode)...",
44
+ }
45
+
46
+ # Load models
47
+ actor = get_actor()
48
+ if speed_mode == "pro":
49
+ critic = get_critic()
50
+
51
+ yield {"type": "status", "content": "Actor is generating initial code..."}
52
+
53
+ # Generate initial code
54
+ code_snippet = ""
55
+ for token in actor.generate_code(user_prompt):
56
+ code_snippet += token
57
+ yield {"type": "token", "content": token}
58
+
59
+ # Clear CUDA cache after Actor completes generation
60
+ flush_vram()
61
+
62
+ if speed_mode == "pro":
63
+ for i in range(max_iterations):
64
+ yield {
65
+ "type": "status",
66
+ "content": f"Critic is analyzing the code (Iteration {i+1})...",
67
+ }
68
+
69
+ # Critique the generated code
70
+ print(f"\n--- CRITIQUE (Iteration {i+1}) ---")
71
+ critique = ""
72
+ for token in critic.critique(code_snippet, context=user_prompt):
73
+ critique += token
74
+ print(token, end="", flush=True)
75
+ print("\n-----------------------------\n")
76
+
77
+ # Clear CUDA cache after Critic completes analysis
78
+ flush_vram()
79
+
80
+ # Check if critic is satisfied (basic heuristic)
81
+ lower_critique = critique.lower()
82
+ if (
83
+ "looks good" in lower_critique
84
+ or "no issues" in lower_critique
85
+ or "no bugs" in lower_critique
86
+ or "is correct" in lower_critique
87
+ ):
88
+ yield {"type": "status", "content": "Critic approved the code!"}
89
+ break
90
+
91
+ yield {
92
+ "type": "status",
93
+ "content": f"Critic found issues. Actor is revising (Iteration {i+1})...",
94
+ }
95
+ yield {"type": "clear"} # Clear the chat window for the revised code
96
+
97
+ new_code_snippet = ""
98
+ for token in actor.revise_code(user_prompt, code_snippet, critique):
99
+ new_code_snippet += token
100
+ yield {"type": "token", "content": token}
101
+
102
+ code_snippet = new_code_snippet
103
+
104
+ # Clear CUDA cache after Actor completes revision
105
+ flush_vram()
106
+
107
+ yield {"type": "status", "content": "Ensemble Pipeline Complete."}
108
+
109
+
110
+ # Alias for backward compatibility / streaming callers
111
+ v4_stream_pipeline = v4_pipeline
112
+
113
+ if __name__ == "__main__":
114
+ print("Testing v4_pipeline directly...")
115
+ test_prompt = "Write a Python function to calculate the factorial of a number."
116
+
117
+ for event in v4_pipeline(test_prompt):
118
+ if event["type"] == "token":
119
+ import sys
120
+
121
+ sys.stdout.write(event["content"])
122
+ sys.stdout.flush()
123
+ elif event["type"] == "status":
124
+ print(f"\n[STATUS] {event['content']}")
125
+ elif event["type"] == "clear":
126
+ print("\n[CLEAR] (Actor is revising...)")
127
+ print("\n\nTest execution finished.")
masteries/coding/inference/watchdog.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import time
3
+
4
+ MAX_TEMP = 83
5
+
6
+
7
+ def get_gpu_temp():
8
+ try:
9
+ output = subprocess.check_output(
10
+ [
11
+ "nvidia-smi",
12
+ "--query-gpu=temperature.gpu",
13
+ "--format=csv,noheader,nounits",
14
+ ],
15
+ text=True,
16
+ )
17
+ temps = [
18
+ int(x.strip()) for x in output.strip().split("\n") if x.strip().isdigit()
19
+ ]
20
+ return max(temps) if temps else 0
21
+ except Exception as e:
22
+ print("Could not read GPU temp:", e)
23
+ return 0
24
+
25
+
26
+ def kill_training_script():
27
+ print(f"CRITICAL: GPU Temp exceeded {MAX_TEMP}°C! Taking emergency action.")
28
+ try:
29
+ # Find train.py process and kill it
30
+ output = subprocess.check_output(
31
+ "wmic process where \"commandline like '%masteries/coding/training/critic/train.py%' and name='python.exe'\" get processid",
32
+ shell=True,
33
+ text=True,
34
+ )
35
+ lines = [line.strip() for line in output.split("\n") if line.strip()]
36
+ killed = False
37
+ for line in lines[1:]: # skip header 'ProcessId'
38
+ if line.isdigit():
39
+ pid = line
40
+ print(f"Killing Train Script PID {pid}...")
41
+ subprocess.call(f"taskkill /F /PID {pid}", shell=True)
42
+ killed = True
43
+
44
+ if not killed:
45
+ print(
46
+ "Could not find specific train.py process. Not killing all python just in case."
47
+ )
48
+
49
+ except Exception as e:
50
+ print("Error while trying to kill process:", e)
51
+
52
+
53
+ print(
54
+ f"Starting Hardware Watchdog. Monitoring GPU Temp every 60 seconds. Max Temp: {MAX_TEMP}°C"
55
+ )
56
+ while True:
57
+ temp = get_gpu_temp()
58
+ print(f"Current GPU Temp: {temp}°C")
59
+ if temp >= MAX_TEMP:
60
+ kill_training_script()
61
+ print("Watchdog emergency triggered. Exiting watchdog.")
62
+ break
63
+ time.sleep(60)
masteries/coding/models/actor_v1/config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_function": "gelu_pytorch_tanh",
3
+ "add_cross_attention": false,
4
+ "architectures": [
5
+ "GPTBigCodeForCausalLM"
6
+ ],
7
+ "attention_softmax_in_fp32": true,
8
+ "attn_pdrop": 0.1,
9
+ "bos_token_id": 0,
10
+ "dtype": "float32",
11
+ "embd_pdrop": 0.1,
12
+ "eos_token_id": 0,
13
+ "inference_runner": 0,
14
+ "initializer_range": 0.02,
15
+ "layer_norm_epsilon": 1e-05,
16
+ "max_batch_size": null,
17
+ "max_sequence_length": null,
18
+ "model_type": "gpt_bigcode",
19
+ "multi_query": true,
20
+ "n_embd": 768,
21
+ "n_head": 12,
22
+ "n_inner": 3072,
23
+ "n_layer": 20,
24
+ "n_positions": 8192,
25
+ "num_key_value_heads": 1,
26
+ "pad_key_length": true,
27
+ "pad_token_id": null,
28
+ "pre_allocate_kv_cache": false,
29
+ "resid_pdrop": 0.1,
30
+ "scale_attention_softmax_in_fp32": true,
31
+ "scale_attn_weights": true,
32
+ "summary_activation": null,
33
+ "summary_first_dropout": 0.1,
34
+ "summary_proj_to_labels": true,
35
+ "summary_type": "cls_index",
36
+ "summary_use_proj": true,
37
+ "tie_word_embeddings": true,
38
+ "transformers_version": "5.13.0",
39
+ "use_cache": true,
40
+ "validate_runner_input": true,
41
+ "vocab_size": 49152
42
+ }
masteries/coding/models/actor_v1/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 0,
5
+ "transformers_version": "5.13.0"
6
+ }
masteries/coding/models/actor_v1/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
masteries/coding/models/actor_v1/tokenizer_config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "eos_token": "<|endoftext|>",
6
+ "extra_special_tokens": [
7
+ "<|endoftext|>",
8
+ "<fim_prefix>",
9
+ "<fim_middle>",
10
+ "<fim_suffix>",
11
+ "<fim_pad>",
12
+ "<filename>",
13
+ "<gh_stars>",
14
+ "<issue_start>",
15
+ "<issue_comment>",
16
+ "<issue_closed>",
17
+ "<jupyter_start>",
18
+ "<jupyter_text>",
19
+ "<jupyter_code>",
20
+ "<jupyter_output>",
21
+ "<empty_output>",
22
+ "<commit_before>",
23
+ "<commit_msg>",
24
+ "<commit_after>",
25
+ "<reponame>"
26
+ ],
27
+ "is_local": false,
28
+ "local_files_only": false,
29
+ "model_max_length": 1000000000000000019884624838656,
30
+ "pad_token": "<|endoftext|>",
31
+ "tokenizer_class": "TokenizersBackend",
32
+ "unk_token": "<|endoftext|>",
33
+ "vocab_size": 49152
34
+ }
masteries/coding/models/critic_best/config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_cross_attention": false,
3
+ "architectures": [
4
+ "RobertaForSequenceClassification"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": 0,
8
+ "classifier_dropout": null,
9
+ "dtype": "float32",
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 768,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 3072,
16
+ "is_decoder": false,
17
+ "layer_norm_eps": 1e-05,
18
+ "max_position_embeddings": 514,
19
+ "model_type": "roberta",
20
+ "num_attention_heads": 12,
21
+ "num_hidden_layers": 12,
22
+ "output_past": true,
23
+ "pad_token_id": 1,
24
+ "problem_type": "single_label_classification",
25
+ "tie_word_embeddings": true,
26
+ "transformers_version": "5.13.0",
27
+ "type_vocab_size": 1,
28
+ "use_cache": true,
29
+ "vocab_size": 50265
30
+ }
masteries/coding/models/critic_best/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
masteries/coding/models/critic_best/tokenizer_config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<s>",
5
+ "cls_token": "<s>",
6
+ "eos_token": "</s>",
7
+ "errors": "replace",
8
+ "is_local": false,
9
+ "local_files_only": false,
10
+ "mask_token": "<mask>",
11
+ "model_max_length": 512,
12
+ "pad_token": "</s>",
13
+ "sep_token": "</s>",
14
+ "tokenizer_class": "RobertaTokenizer",
15
+ "trim_offsets": true,
16
+ "unk_token": "<unk>"
17
+ }
masteries/coding/models/critic_v1/config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_cross_attention": false,
3
+ "architectures": [
4
+ "RobertaForSequenceClassification"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": 0,
8
+ "classifier_dropout": null,
9
+ "dtype": "float32",
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 768,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 3072,
16
+ "is_decoder": false,
17
+ "layer_norm_eps": 1e-05,
18
+ "max_position_embeddings": 514,
19
+ "model_type": "roberta",
20
+ "num_attention_heads": 12,
21
+ "num_hidden_layers": 12,
22
+ "output_past": true,
23
+ "pad_token_id": 1,
24
+ "problem_type": "single_label_classification",
25
+ "tie_word_embeddings": true,
26
+ "transformers_version": "5.13.0",
27
+ "type_vocab_size": 1,
28
+ "use_cache": true,
29
+ "vocab_size": 50265
30
+ }