| |
|
|
| """Implements the conjecture-prove bootstrapping learning loop.""" |
|
|
| import asyncio |
| import os |
| import json |
| import datetime |
| from pathlib import Path |
|
|
| import hydra |
| from omegaconf import DictConfig |
| import torch |
| import numpy as np |
| from tqdm import tqdm |
|
|
| import peano |
| import worker |
| from worker import StudentResult |
| from hindsight import HindsightExample |
| from util import format_blocks_with_indent, sample_batch, setup_wandb, value_color, save_json |
| from conjecture import AgentLM, Context, sample_conjecture |
| from proofsearch import make_agent |
|
|
|
|
| def load_fixed_statements(path: str) -> list[str]: |
| """Parse a benchmark file with 'name. statement' lines into a list of statements.""" |
| stmts = [] |
| for line in Path(path).read_text().splitlines(): |
| line = line.strip() |
| if not line: |
| continue |
| if "." in line: |
| _, stmt = line.split(".", 1) |
| stmt = stmt.strip() |
| else: |
| stmt = line |
| stmts.append(stmt) |
| return stmts |
|
|
|
|
| def now() -> str: |
| return '[' + datetime.datetime.now().isoformat() + ']' |
|
|
|
|
| FAIL = "fail" |
|
|
|
|
| def _get_logprob(student_result, normalize): |
| """Return logprob, optionally normalized by proof length.""" |
| lp = student_result.logprob |
| if normalize and lp is not None and student_result.solution_actions: |
| lp = lp / max(len(student_result.solution_actions), 1) |
| return lp |
|
|
|
|
| DISTRIBUTED = os.environ.get('DISTRIBUTED', False) |
|
|
|
|
| def submit_task(agent_path: str, theory: worker.BackgroundTheory, statement: str, timeout: float = None): |
| if DISTRIBUTED: |
| return worker.try_prove.apply_async(args=(agent_path, theory, statement), |
| kwargs={'timeout': timeout}) |
| else: |
| return worker.try_prove.run(agent_path, theory, statement, timeout=timeout) |
|
|
|
|
| def get_task_result(task, timeout=None): |
| if DISTRIBUTED: |
| return task.get(timeout=timeout) |
| else: |
| return task |
|
|
|
|
| async def teacher_loop(cfg: DictConfig): |
| print('Running in', 'distributed mode.' if DISTRIBUTED else 'single-process mode.') |
|
|
| agent = make_agent(cfg) |
|
|
| with open(os.path.join(os.path.dirname(__file__), 'theories', cfg.theory.name + '.p')) as f: |
| theory = f.read() |
|
|
| difficulty_buckets = sorted([list(cfg.difficulty_buckets[i].items())[0] |
| for i in range(len(cfg.difficulty_buckets))], |
| key=lambda kv: kv[1]) |
|
|
| premises = cfg.theory.premises |
|
|
| d = peano.PyDerivation() |
| d.incorporate(theory) |
| proven_conjectures = [] |
| seen_hindsight_goals = set() |
| proofs = [] |
| outcomes = [] |
|
|
| continue_dir = cfg.get('continue') |
| start_iteration = 0 |
|
|
| if continue_dir is not None: |
| os.chdir(continue_dir) |
| print('Continuing run from', continue_dir) |
| |
| i = 0 |
| while os.path.exists(f'{i}.pt'): |
| i += 1 |
| i -= 1 |
| start_iteration = i |
| agent = torch.load(f'{i}.pt', weights_only=False) |
| print('Loaded agent from', f'{i}.pt') |
| |
| if i > 0: |
| with open(f'outcomes_{i-1}.json', 'r') as f: |
| outcomes = json.load(f) |
| proven_conjectures = [o['problem'] for o in outcomes |
| if o['hindsight'] is False and |
| o['proof'] is not None] |
| seen_hindsight_goals = {o['problem'] for o in outcomes |
| if o['hindsight'] and o['proof'] is not None} |
|
|
| print('Loaded', len(proven_conjectures), 'proven conjectures from previous run.') |
|
|
|
|
| if cfg.get('freeze_conjecturer', False): |
| print('Ablation: Freezing conjecturer.') |
|
|
|
|
| with open('log.jsonl', 'w') as log: |
| for i in range(start_iteration, cfg.iterations): |
| torch.save(agent, f'{i}.pt') |
|
|
| fixed_path = cfg.get('fixed_statements_path', None) |
|
|
| if fixed_path is not None: |
| conjectures = load_fixed_statements(fixed_path) |
| print(now(), f'Iteration #{i}: using {len(conjectures)} fixed benchmark problems.') |
| else: |
| context = Context(d, None, []) |
| |
| print(now(), f'Iteration #{i}: making conjectures...') |
|
|
| progress_bar = tqdm(total=cfg.n_conjectures) |
|
|
| conjectures = [] |
|
|
| while len(conjectures) < cfg.n_conjectures: |
| proposal = sample_conjecture(AgentLM(agent, 'Conj:(hard) '), context) |
|
|
| if proposal and proposal not in conjectures + proven_conjectures: |
| |
| contracted_proposal = d.contract(proposal) |
| if contracted_proposal not in conjectures + proven_conjectures: |
| conjectures.append(contracted_proposal) |
| progress_bar.update(1) |
|
|
| progress_bar.close() |
|
|
|
|
| print(now(), 'done, have', len(conjectures), 'conjectures') |
| print(conjectures) |
|
|
| log.write(json.dumps({'iteration': i, |
| 'msg': f'It #{i}: posing {len(conjectures)} conjectures.', |
| 'conjectures': conjectures})) |
| log.write('\n') |
| log.flush() |
|
|
| |
| tasks = [] |
|
|
| |
| agent_path = os.path.abspath(f'{i}.pt') |
|
|
| proof_search_timeout = cfg.get('proof_search_timeout', None) |
| if proof_search_timeout: |
| print(f'Proof search timeout: {proof_search_timeout}s') |
|
|
| print('Submitting tasks...') |
| for conjecture in tqdm(conjectures, miniters=1): |
| tasks.append(submit_task( |
| agent_path, |
| worker.BackgroundTheory(theory, premises), |
| conjecture, |
| timeout=proof_search_timeout)) |
|
|
| |
| examples = [] |
| student_results = [] |
|
|
| inactivity_timeout = (proof_search_timeout + 60) if proof_search_timeout else 660 |
| print('Collecting', len(tasks), f'results from workers (inactivity timeout: {inactivity_timeout}s).') |
|
|
| if DISTRIBUTED: |
| import time as _time |
| pending = set(range(len(tasks))) |
| last_result_time = _time.time() |
| progress_bar = tqdm(total=len(tasks), miniters=1) |
|
|
| while pending and (_time.time() - last_result_time) < inactivity_timeout: |
| for idx in list(pending): |
| if tasks[idx].ready(): |
| pending.discard(idx) |
| progress_bar.update(1) |
| last_result_time = _time.time() |
| try: |
| student_result = tasks[idx].get(timeout=5) |
| if student_result.error: |
| print('Error in prover process!') |
| print(student_result.error) |
| continue |
| student_results.append(student_result) |
| except Exception as e: |
| print(f'Failed to get result for task {idx}: {e}') |
| _time.sleep(1) |
|
|
| progress_bar.close() |
| if pending: |
| print(f'Collection stopped after {inactivity_timeout}s of inactivity.') |
| print(f'Got {len(student_results)} results out of {len(tasks)} tasks.') |
| else: |
| for task in tqdm(tasks, miniters=1): |
| student_result = get_task_result(task) |
| if student_result.error: |
| print('Error in prover process!') |
| print(student_result.error) |
| continue |
| student_results.append(student_result) |
|
|
| success_logprobs = [] |
| n_timeouts = 0 |
| normalize_lp = cfg.get('normalize_logprob', False) |
|
|
| |
| for student_result in student_results: |
| if student_result.success: |
| success_logprobs.append(_get_logprob(student_result, normalize_lp)) |
|
|
| if getattr(student_result, 'timed_out', False): |
| n_timeouts += 1 |
|
|
| outcomes.append({'iteration': i, |
| 'problem': student_result.problem, |
| 'proof': student_result.proof, |
| 'logprob': student_result.logprob, |
| 'actions': student_result.solution_actions, |
| 'hindsight': False, |
| 'timed_out': getattr(student_result, 'timed_out', False), |
| 'proof_features': getattr(student_result, 'proof_features', None), |
| }) |
|
|
| for h in student_result.hindsight_examples: |
| outcomes.append({'iteration': i, |
| 'problem': h.statement, |
| 'proof': h.proof, |
| 'logprob': h.logprob, |
| 'actions': h.solution_actions, |
| 'hindsight': True |
| }) |
|
|
| if not success_logprobs: |
| print(f'No solutions found in iteration {i} - stopping learning loop...') |
| break |
|
|
| print(f'Iteration #{i}: {len(success_logprobs)} solved, {n_timeouts} timed out, ' |
| f'{len(student_results) - len(success_logprobs) - n_timeouts} failed.') |
|
|
| thresholds = [np.percentile(success_logprobs, p) |
| for _, p in difficulty_buckets] |
|
|
| print('Thresholds:', |
| list(zip([k for k, _ in difficulty_buckets], thresholds)), |
| 'min =', np.min(success_logprobs), |
| 'max =', np.max(success_logprobs)) |
|
|
| |
| for student_result in student_results: |
| |
| if student_result.success: |
| lp = _get_logprob(student_result, normalize_lp) |
| outcome = next(k |
| for i, (k, _) in enumerate(difficulty_buckets) |
| if (lp <= thresholds[i] or |
| i + 1 == len(difficulty_buckets))) |
| else: |
| outcome = FAIL |
|
|
| if not cfg.get('freeze_conjecturer', False): |
| examples.append(f'Conj:({outcome}) ' + d.elaborate(student_result.problem)) |
|
|
| if student_result.success: |
| proven_conjectures.append(student_result.problem) |
| proofs.append(student_result.proof) |
|
|
| examples.extend(student_result.extracted_examples) |
|
|
| if cfg.train_policy_on_hindsight_examples: |
| for h in student_result.hindsight_examples: |
| if h.goal not in seen_hindsight_goals: |
| h_lp = h.logprob |
| if normalize_lp and h.solution_actions: |
| h_lp = h_lp / max(len(h.solution_actions), 1) |
| outcome = next(k |
| for i, (k, _) in enumerate(difficulty_buckets) |
| if h_lp <= thresholds[i] or i + 1 == len(difficulty_buckets)) |
|
|
| if not cfg.get('freeze_conjecturer', False): |
| examples.append(f'Conj:({outcome}) ' + d.elaborate(student_result.problem)) |
| examples.extend(h.examples) |
| seen_hindsight_goals.add(h.goal) |
|
|
| log.write(json.dumps({'iteration': i, |
| 'msg': f'Training on {len(examples)} examples.'})) |
| log.write('\n') |
|
|
| |
| if i + 1 < cfg.iterations: |
| print(len(examples), 'accumulated training examples.') |
| agent.train(examples) |
|
|
| save_json(examples, f'examples_{i}.json') |
| save_json(outcomes, f'outcomes_{i}.json') |
| torch.save(student_results, f'results_{i}.json') |
|
|
|
|
| @hydra.main(version_base="1.2", config_path="config", config_name="bootstrap") |
| def main(cfg: DictConfig): |
| print('Running from:', os.getcwd()) |
| setup_wandb(cfg) |
| if cfg.task == 'teacher': |
| asyncio.run(teacher_loop(cfg)) |
|
|
| if __name__ == '__main__': |
| main() |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
|
|
| |
| |
| |
|
|