"""Prepare local Colab support now; include approved data only after real review.""" import argparse import hashlib import json import sys import zipfile from pathlib import Path ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/'src')) from jitai_training import review def support_files(): files={} for folder,pattern in [('src/jitai_training','*.py'),('schemas','*.json')]: for p in (ROOT/folder).rglob(pattern): if '__pycache__' not in p.parts: files[p.relative_to(ROOT).as_posix()]=p.read_bytes() for name in ['colab/final_training_runtime.py','colab/stage_c_runtime.py', 'colab/requirements-stage-c.txt','requirements-stage-b.txt']: files[name]=(ROOT/name).read_bytes() return files def make_zip(path,files): if path.exists(): with zipfile.ZipFile(path) as archive: if set(archive.namelist())==set(files) and all(archive.read(k)==v for k,v in files.items()): return raise ValueError('Existing bundle differs; preserve it and choose a new version') path.parent.mkdir(parents=True,exist_ok=True) with zipfile.ZipFile(path,'x',zipfile.ZIP_DEFLATED) as archive: for name,content in sorted(files.items()): entry=zipfile.ZipInfo(name,date_time=(2026,10,23,0,0,0)) entry.compress_type=zipfile.ZIP_DEFLATED archive.writestr(entry,content) path.with_suffix('.sha256').write_text(hashlib.sha256(path.read_bytes()).hexdigest()+' '+path.name+'\n') def make_notebook(): cells=[] def cell(kind,text): result=dict(cell_type=kind,metadata={},id='final-'+str(len(cells)),source=text.splitlines(keepends=True)) if kind=='code':result.update(execution_count=None,outputs=[]) cells.append(result) cell('markdown','''# Approved-data Qwen3-1.7B QLoRA training candidate Prepared and unexecuted. This is separate from the eight-step unreviewed experiment. Run only after genuine individual human decisions allow the local final-input builder to export a complete, balanced approved subset. Three epochs are a reproducible initial training profile, not evidence of convergence, production readiness or Stage B acceptance. Train/validation/test remain in their original family splits. No Google Drive, OAuth, automatic public upload or CPU fallback is used. Before running: select a **remote Colab NVIDIA GPU** and upload the locally generated `jitai-final-input.zip` plus `jitai-final-input.sha256` through the Files sidebar. The support-only ZIP cannot pass the approved-data gate. Colab free allocation and T4 memory compatibility must be verified at execution; never ignore OOM/length errors. ''') cell('code','''from pathlib import Path import sys, subprocess, json, hashlib, zipfile, os, shutil import google.colab if not Path('/content').is_dir(): raise RuntimeError('Remote Colab required') gpu=subprocess.run(['nvidia-smi'],capture_output=True,text=True) if gpu.returncode: raise RuntimeError('Select a remote Colab GPU; no CPU fallback') print(gpu.stdout) if shutil.disk_usage('/content').free < 12*1024**3: raise RuntimeError('Need 12 GiB free disk') os.environ['HF_HUB_DISABLE_TELEMETRY']='1' os.environ['WANDB_DISABLED']='true' os.environ['HF_HOME']='/content/jitai-hf-cache' ''') cell('code','''# Trust the checksum supplied by the local reviewed-input builder, not a URL. bundle=Path('/content/jitai-final-input.zip') sidecar=Path('/content/jitai-final-input.sha256') if not bundle.is_file() or not sidecar.is_file(): raise RuntimeError('Upload jitai-final-input.zip and jitai-final-input.sha256 from the local approved-data builder') expected=sidecar.read_text().split()[0] if len(expected)!=64 or hashlib.sha256(bundle.read_bytes()).hexdigest()!=expected: raise RuntimeError('Approved input checksum mismatch') INPUT=Path('/content/jitai-final-input')/expected[:16] INPUT.mkdir(parents=True,exist_ok=True) with zipfile.ZipFile(bundle) as archive: if sum(i.file_size for i in archive.infolist())>100*1024**2: raise RuntimeError('Oversized input ZIP') for member in archive.infolist(): target=(INPUT/member.filename).resolve() if not target.is_relative_to(INPUT.resolve()) or '\\\\' in member.filename: raise RuntimeError('Unsafe ZIP path') if member.is_dir(): continue content=archive.read(member) if target.exists() and target.read_bytes()!=content: raise RuntimeError('Changed input; use a fresh runtime') target.parent.mkdir(parents=True,exist_ok=True) if not target.exists(): target.write_bytes(content) requirements=INPUT/'colab/requirements-stage-c.txt' subprocess.check_call([sys.executable,'-m','pip','install','--quiet','-r',str(requirements)]) import importlib.metadata as metadata for spec in requirements.read_text(encoding='utf-8-sig').splitlines(): if not spec.strip() or spec.startswith('#'): continue name,version=spec.split('==') if metadata.version(name)!=version: raise RuntimeError('Dependency mismatch: '+name) loaded=sys.modules.get(name.replace('-','_')) if loaded is not None and getattr(loaded,'__version__',version)!=version: raise RuntimeError('Restart the runtime and rerun: loaded package version differs for '+name) sys.path[:0]=[str(INPUT/'src'),str(INPUT/'colab')] from final_training_runtime import validate_final_dataset, run_final, package_outputs print(validate_final_dataset(INPUT/'approved')['split_counts']) ''') cell('markdown','''## Optional resume backup To resume across runtime loss, upload a previously generated `run-v1-backup.zip` and its checksum. It must be your own trusted output: Trainer checkpoint files contain optimizer/RNG serialization. The cell below restores it only when both files are present and verifies its manifest before extraction. Otherwise it starts a fresh run. Within the same runtime, complete epoch checkpoints are selected automatically. Back up before Colab disconnects; ephemeral files do not survive a deleted runtime. Never restore someone else's untrusted checkpoints. ''') cell('code','''OUTPUT=Path('/content/jitai-final-approved/run-v1') backup=Path('/content/run-v1-backup.zip') backup_hash=Path('/content/run-v1-backup.zip.sha256') if backup.exists() or backup_hash.exists(): if not backup.is_file() or not backup_hash.is_file(): raise RuntimeError('Resume requires ZIP and checksum') if hashlib.sha256(backup.read_bytes()).hexdigest()!=backup_hash.read_text().split()[0]: raise RuntimeError('Resume ZIP checksum mismatch') if OUTPUT.exists(): raise RuntimeError('Destination already exists; resume it without restoring again') with zipfile.ZipFile(backup) as archive: if sum(i.file_size for i in archive.infolist())>4*1024**3: raise RuntimeError('Oversized resume backup') manifest=json.loads(archive.read('run-v1/artifact_manifest.json')) if set(archive.namelist())!={'run-v1/'+n for n in manifest}|{'run-v1/artifact_manifest.json'}: raise RuntimeError('Unexpected resume backup members') for name,digest in manifest.items(): if hashlib.sha256(archive.read('run-v1/'+name)).hexdigest()!=digest: raise RuntimeError('Resume artifact checksum failed') for member in archive.infolist(): target=(OUTPUT.parent/member.filename).resolve() if not target.is_relative_to(OUTPUT.resolve()) or '\\\\' in member.filename: raise RuntimeError('Unsafe resume path') target.parent.mkdir(parents=True,exist_ok=True) target.write_bytes(archive.read(member)) print('Output/resume destination:',OUTPUT) ''') cell('code',"# This validates approved data and GPU before any model/tokenizer downloads.\nrun_final(INPUT/'approved',OUTPUT)\n") cell('markdown','''## Save actual results and checkpoints Run this cell even after a runtime error if diagnostics/checkpoints were saved. Download the printed ZIP and checksum through the Files sidebar. The ZIP can contain human-approved synthetic test outputs, adapter weights, diagnostics and complete checkpoints; inspect it before sharing. A completion file is created only after training and base/adapter held-out evaluations finish; it is not quality acceptance. ''') cell('code',"archive=package_outputs(OUTPUT)\nprint('Download manually:',archive)\nprint('Checksum:',archive.with_suffix('.zip.sha256'))\n") notebook=dict(cells=cells,metadata=dict(kernelspec=dict(display_name='Python 3',language='python',name='python3'), language_info=dict(name='python'),colab=dict(provenance=[])),nbformat=4,nbformat_minor=5) target=ROOT/'colab/final_qwen3_approved.ipynb' content=json.dumps(notebook,indent=2)+'\n' if not target.exists() or target.read_text()!=content: target.write_text(content,encoding='utf-8') def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--work',type=Path,default=review.DEFAULT_WORK) parser.add_argument('--approved-output',type=Path,default=ROOT/'data/final-approved/v1') parser.add_argument('--bundle',type=Path,default=ROOT/'colab/jitai-final-input.zip') args=parser.parse_args() make_notebook() make_zip(ROOT/'colab/jitai-final-support.zip',support_files()) report=review.pilot_report(args.work)[0] if not report['review_status']['human_review_complete'] or not report['tiny_training_ready']: print(json.dumps({'final_training_ready':False,'reason':'Genuine complete human review and balanced approved pairs required', 'status':report['review_status'],'approved_exportable':report['approved_exportable'], 'prepared_notebook':'colab/final_qwen3_approved.ipynb', 'support_only_bundle':'colab/jitai-final-support.zip'},indent=2)) return if not args.approved_output.exists(): review.export_pilot(args.work,args.approved_output) review.validate_pilot(args.approved_output) approved_hashes={event['example_id']:event['approved_sha256'] for event in review.read_jsonl(args.approved_output/'approval_evidence.jsonl')} _,_,approved_rows,_=review.approved_records(args.work) if approved_hashes!={row['example_id']:review.digest(row) for row in approved_rows}: raise ValueError('Existing approved export differs from current human decisions; choose a fresh version') readiness=dict(kind='human-approved-final-training-input-v1',human_review_complete=True, approved_exportable=report['approved_exportable'],stage_b_accepted=False, pilot_manifest_sha256=hashlib.sha256((args.approved_output/'manifest.json').read_bytes()).hexdigest(), approval_ledger_sha256=hashlib.sha256((args.work/'decisions.jsonl').read_bytes()).hexdigest()) target=args.approved_output/'final_readiness.json' if target.exists() and json.loads(target.read_text())!=readiness: raise ValueError('Readiness changed; choose a fresh approved export and bundle path') target.write_text(json.dumps(readiness,indent=2)+'\n') files=support_files() files.update({'approved/'+p.name:p.read_bytes() for p in args.approved_output.iterdir() if p.is_file()}) make_zip(args.bundle,files) print(json.dumps({'final_training_ready':True,'bundle':str(args.bundle),'approved_exportable':report['approved_exportable']},indent=2)) if __name__=='__main__':main()