File size: 14,511 Bytes
f1adc24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/usr/bin/env python3

"""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  # noqa
from hindsight import HindsightExample  # noqa
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)
        # Find largest iteration number such that i.pt exists.
        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')
        # Load examples and outcomes.
        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, [])
                # 1- Run conjecturing model to obtain N conjectures.
                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:
                        # Contract conjectures to make them Peano-parseable.
                        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()

            # 2- Try to prove each of the conjectures
            tasks = []

            # Reuse the checkpoint already saved above.
            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))

            # 3- Train model on proofs and outcome of conjectures (easy, hard, 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)

            # 3a- Look at all the success logprobs and compute the easy/hard threhsold.
            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))

            # 3b- Classify problems into easy/hard.
            for student_result in student_results:
                # Outcome is the name of the first difficulty bucket that is larger than the logprob.
                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')

            # 3c- Train model on conjecturing and proof search examples.
            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()

#DISTRIBUTED=1 python bootstrap.py --config-name bootstrap_NoHER
#DISTRIBUTED=1 python bootstrap.py --config-name bootstrap_nat_mul
#CUDA_VISIBLE_DEVICES=0 celery -A worker.app worker --loglevel=info --concurrency=5 -n gpu0@%h
#CUDA_VISIBLE_DEVICES=1 celery -A worker.app worker --loglevel=info --concurrency=5 -n gpu1@%h
#CUDA_VISIBLE_DEVICES=2 celery -A worker.app worker --loglevel=info --concurrency=5 -n gpu2@%h
#CUDA_VISIBLE_DEVICES=3 celery -A worker.app worker --loglevel=info --concurrency=5 -n gpu3@%h
#redis-server --port 6379
#DISTRIBUTED=1 python bootstrap.py --config-name bootstrap_800_moreupdates.yaml
#DISTRIBUTED=1 python bootstrap.py --config-name bootstrap_nat_mul_800.yaml

#DISTRIBUTED=1 python bootstrap.py --config-name bootstrap_fixed_benchmark +agent_path=/datadrive/ayush/home/minimoX/learning/outputs/bootstrap_bs_800_para/2026-03-12_23-41-21/2.pt


#DISTRIBUTED=1 python bootstrap.py --config-name bootstrap_fixed_benchmark +agent_path=/datadrive/ayush/home/minimoX/learning/outputs/bootstrap_fixed_bench_noHER/2026-03-19_18-44-53/9.pt
#DISTRIBUTED=1 python bootstrap.py --config-name bootstrap_nat_mul_800