"""Freeze scientific recipe and implementation only after readiness checks."""
import json,pathlib,hashlib,datetime
ROOT=pathlib.Path(__file__).resolve().parents[1]
def sha(p):return hashlib.sha256((ROOT/p).read_bytes()).hexdigest()
for name in ['contextual_dense_operator_cpu_audit','contextual_rl_update_cpu_audit','contextual_training_state_cpu_audit','contextual_dense_preflight']:
 assert json.loads((ROOT/f'notes/{name}.json').read_text())['status']=='PASS'
split=json.loads((ROOT/'notes/contextual_rl_split.json').read_text())
assert len(split['train_indices'])==256 and len(split['development_indices'])==512 and len(split['confirmation_indices'])==700
assert not set(split['train_indices'])&(set(split['development_indices'])|set(split['confirmation_indices']))
paths=['code/contextual_dense_operator.py','code/contextual_rl_common.py','code/train_contextual_rl.py','code/eval_contextual_native.py','code/analyze_contextual_rl.py','code/freeze_contextual_rl.py','code/prepare_contextual_split.py','run_contextual_rl_queue.py','code/latent_deliberation.py','code/generate_native_policy.py','code/generate_latent_answers.py','code/run_baseline.py','code/compressed_checkpoint.py','code/broad_latent_common.py','code/prefix_teacher_spec.py','code/extract_latent_teacher.py','code/batched_latent_acquisition.py','code/microbatch_latent_acquisition.py','code/train_latent_acquisition_pilot.py','code/audit_latent_source_boundary.py','code/run_with_isolated_grader.py','code/isolated_grade_worker.py','code/certified_integer_grade.py','code/run_with_certified_grader.py','code/vendor/reasoning_from_scratch/qwen3.py','code/vendor/reasoning_from_scratch/qwen3_batched.py','code/vendor/reasoning_from_scratch/ch03.py','code/vendor/reasoning_from_scratch/ch04.py','notes/contextual_rl_split.json','notes/contextual_dense_operator_cpu_audit.json','notes/contextual_rl_update_cpu_audit.json','notes/contextual_training_state_cpu_audit.json','notes/contextual_dense_preflight.json','notes/native_policy_generation_cpu_audit.json','notes/latent_rl_restart_readiness_result.md','code/results/baseline_s17041_u50/model.pth','code/data/math_train.json','code/data/tokenizer-base.json','notes/latent_feature_source_development_1958/holdout/targets.jsonl']
c={'status':'FROZEN_CONTEXTUAL_DENSE_RL','frozen_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'name':'contextual_dense_rl_w17041_s18641202','output':'code/results/contextual_dense_rl_w17041_s18641202','queue_state':'notes/contextual_rl_queue.json','parent':'code/results/baseline_s17041_u50/model.pth','split':'notes/contextual_rl_split.json','retention_source':'notes/latent_feature_source_development_1958/holdout/targets.jsonl','seed':18641202,'bootstrap_seed':19641202,'arms':['G','C','E','H'],'updates':64,'batch_questions':4,'samples':8,'chunks':4,'updates_per_chunk':16,'prompt_limit':960,'train_tokens':512,'eval_batch':16,'eval_tokens':2048,'eval_questions':512,'learning_rate':1e-6,'weight_decay':.01,'clip_norm':1.,'topk':100,'head_chunk':64,'dense_weight':.1,'replay_weight':.1,'gradient_diagnostic_updates':[1,33],
'parameters':'all751632384 original untied FP32, no added parameters; TF32 disabled',
'ordinary_objective':'pergroup mean/sample-std advantages eps1e-4 on binary rewards, then EOSmask; full-softmax raw summed logscore, averaged over8samples and4questions. BehaviorT.8/top-p.9. Skip optimizer iff entirebatch has no backward calls.',
'dense_objective':'C/E add .1 times summed student-top100+pooled-tail JSD, denominator32. Current pre-update teacher detached; support from pre-update student. First correctEOS draw supplies own context to all incorrectEOS draws only. E uses the same template with empty solution. Missing context/dense paths contribute0 without renormalization. No cap or allcorrect dense updates.',
'replay_objective':'H adds .1 times summed negative logprob of first correctEOS draw, denominator4, including allcorrect groups; no donor contributes0. Same current-state model, no persistent replay bank.',
'gradient_diagnostics':'At scheduledupdates1/33, recompute separate weighted objective gradients on actual32draws; CPU-save and restore actual combined gradient bitwise before optimizer. Does not change weights or coefficient. Count all extra work.',
'retention':'first64 historical holdout source targets, excluded from training; fixed before/after ordinary trace NLL only, no selection.',
'primary':'All5native512 endpoints complete before anynativegrading; C-W>=16net and paired95lower(C-W)>0 and lower(C-G)>0. C-E/C-H planned secondary; a context/dense-specific benefit requires superiority over these controls, not merely Warm.',
'uncertainty':'100000 paireditemresamples, numpydefault_rng19641202 reset eachcontrast; one start/seed, reused512development, no seeduncertainty or finalbenchmarkclaim.',
'next':'Positive requires independentwarm/trainingseed andcomparablework strongerordinary control before reserved700/MATH500/secondbenchmark, then fresh secondroundfast+deliberative test. Failedfixedtest prompts strongestremainingconversion; no gate relaxation.',
'restart':'Verifiedcompressed exactstate restore; independently seeded eachgroup; CPU exactnextupdate check and priorfullsize exactstate/boundedGPUexecution evidence, NOT bitwiseGPUupdates. Delete intermediate restart only after verifiedsuccessor. Any failedjob stops queue; no automatic retries.',
'work':'Generation and support/teacher forward positions, heads and dense attention pairs separately; gradient paths count logical forward/backward positions, block/head checkpoint recomputation adds one forward pass. Diagnostic and source-retention work separately. Queue logs allocated GPUtime distinct fromwaiting. Not an equal-compute factorial.',
'scope':'Established SDPO contextual distribution primitive adapted to allowed own-model feedback. No larger-model demonstrations/logits/judgments. No native outcomes yet.',
'input_sha256':{p:sha(p) for p in paths}}
p=ROOT/'notes/contextual_rl_contract.json';assert not p.exists();p.write_text(json.dumps(c,indent=2));print(json.dumps({'name':c['name'],'seed':c['seed'],'sha256':sha(str(p.relative_to(ROOT))),'files':len(paths)},indent=2))
