Instructions to use AnuCaro/Carol_JITAI with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use AnuCaro/Carol_JITAI with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-1.7B") model = PeftModel.from_pretrained(base_model, "AnuCaro/Carol_JITAI") - Notebooks
- Google Colab
- Kaggle
File size: 20,586 Bytes
61d5a60 | 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 | """Build a self-contained Colab experiment and honest local handoff. No upload."""
import ast
import base64
import hashlib
import io
import json
import sys
import zipfile
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT/'src'),str(ROOT/'colab')]
from jitai_training.ai_experiment import build_dataset,validate_ai_dataset,ACK
DATA=ROOT/'data/experimental/ai-reviewed-v1'
OUT=ROOT/'artifacts/ai-experiment-v1'
def make_runtime():
"""Create a separate reviewable module; do not modify approved runtime."""
text=(ROOT/'colab/final_training_runtime.py').read_text(encoding='utf-8')
text=text.replace('Approved-data-only Colab training/evaluation.','AI-reviewed synthetic experimental Colab training/evaluation; no human approval.')
text=text.replace("Path('/content/jitai-final-approved')","Path('/content/jitai-ai-experimental')")
start=text.index('def validate_final_dataset(');end=text.index('\ndef output_path(',start)
text=text[:start]+'''def validate_experimental_dataset(path):
from jitai_training.ai_experiment import validate_ai_dataset
return validate_ai_dataset(path)
'''+text[end:]
text=text.replace('def run_final(dataset, output, config=None):',f'def run_experiment(dataset, output, config=None, acknowledgement=""):\n if acknowledgement != {ACK!r}:\n raise RuntimeError("Explicit no-human-approval experimental acknowledgement required")')
text=text.replace('checks = validate_final_dataset(dataset)','checks = validate_experimental_dataset(dataset)')
text=text.replace('approved_manifest_sha256','experimental_manifest_sha256').replace('final_readiness_sha256','ai_review_decisions_sha256').replace("dataset/'final_readiness.json'","dataset/'review_decisions.json'")
text=text.replace('human-approved-synthetic-final-training','ai-reviewed-synthetic-experimental')
text=text.replace("'human_approved':True","'human_approved':False").replace("'human_approved_training_data':True","'human_approved_training_data':False")
text=text.replace('Human assessment of measured results remains required.','Experimental measured results do not establish human approval, Stage B acceptance, or production readiness.')
text=text.replace('Final outputs','Experimental outputs')
# The pinned Trainer's secure optimizer/RNG resume path requires PyTorch >=2.6.
text=text.replace("Version('2.4')","Version('2.6')").replace('PyTorch >=2.4','PyTorch >=2.6')
text=text.replace("'bitsandbytes','tokenizers','huggingface-hub'","'bitsandbytes','tokenizers','huggingface-hub','numpy','safetensors'")
token_report=OUT/'tokenizer-preflight.json'
if token_report.exists():
revision=json.loads(token_report.read_text())['model_revision']
text=text.replace('HfApi().model_info(MODEL_ID).sha',repr(revision))
text=text.replace(" class Examples(torch.utils.data.Dataset):", " initial = {name:p.detach().cpu().clone() for name,p in model.named_parameters() if p.requires_grad}\n\n class Examples(torch.utils.data.Dataset):")
text=text.replace(" model.save_pretrained(output/'adapter',safe_serialization=True)"," changed = any(not torch.equal(initial[name],p.detach().cpu()) for name,p in model.named_parameters() if name in initial)\n if not changed: raise RuntimeError('No adapter parameter changes detected')\n model.save_pretrained(output/'adapter',safe_serialization=True)")
text=text.replace(" (output/'training_result.json').write_text", " weights_check = verify_adapter(output/'adapter')\n (output/'adapter_verification.json').write_text(json.dumps(weights_check,indent=2)+'\\n')\n (output/'training_result.json').write_text")
text=text.replace("'steps':trainer.state.global_step,'training_loss':trained.training_loss,","'steps':trainer.state.global_step,'training_loss':trained.training_loss,'adapter_parameters_changed':changed,")
# A completion record is written only after verified weights and both evaluations.
text=text.replace(" 'held_out_evaluation_completed':True,", " 'held_out_evaluation_completed':True,'adapter_weights_verified':True,")
text=text.replace(" (output/'completion.json').write_text", " assemble_run_project(dataset,output)\n (output/'completion.json').write_text")
text=text.replace(" (output/'test_evaluation.json').write_text(json.dumps(results,indent=2)+'\\n')", " results['metadata']={'data_mode':'ai-reviewed-synthetic-experimental','human_approved':False,'stage_b_accepted':False,\n 'baseline':'same NF4-quantized base model with LoRA adapters disabled','decoding':'greedy',\n 'test_used_for_training_or_selection':False,'max_new_tokens':config['max_new_tokens']}\n (output/'test_evaluation.json').write_text(json.dumps(results,indent=2)+'\\n')\n write_evaluation_report(results,output/'test_evaluation.md')")
text+='''
def verify_adapter(path):
import torch
from safetensors import safe_open
path=Path(path)
config=json.loads((path/'adapter_config.json').read_text())
if config.get('peft_type')!='LORA' or config.get('base_model_name_or_path')!=MODEL_ID:
raise ValueError('Saved adapter config/base mismatch')
count=0
with safe_open(path/'adapter_model.safetensors',framework='pt',device='cpu') as archive:
keys=list(archive.keys())
if not keys or not all('lora_' in k for k in keys):raise ValueError('Missing LoRA tensor payloads')
for key in keys:
tensor=archive.get_tensor(key)
if tensor.numel()==0 or not torch.isfinite(tensor).all():raise ValueError('Invalid/nonfinite adapter tensor')
count+=tensor.numel()
return dict(verified=True,tensor_count=len(keys),parameters=count,
weights_sha256=checksum(path/'adapter_model.safetensors'),
config_sha256=checksum(path/'adapter_config.json'),human_approved=False)
def write_evaluation_report(results,path):
lines=['# Measured experimental evaluation','',
'AI-reviewed synthetic data; no human approval. Stage B is not accepted.',
'Both variants use the same NF4-quantized base and held-out test examples.',
'The baseline disables adapters. Test is not used for fitting or model selection.','',
'| Variant | N | Accuracy | Macro F1 | Weighted F1 | Finite policy/schema violations |',
'|---|---:|---:|---:|---:|---:|']
for variant in ['base','adapter']:
r=results[variant]
lines.append(f"| {variant} | {r['n']} | {r['accuracy']:.4f} | {r['macro_f1']:.4f} | {r['weighted_f1']:.4f} | {r['contract_or_finite_policy_violation_count']} |")
lines+=['',f'## {variant}: per-class metrics','',
'| Class | Precision | Recall | F1 | Support |','|---|---:|---:|---:|---:|']
for label,m in r['per_class'].items():
lines.append(f"| {label} | {m['precision']:.4f} | {m['recall']:.4f} | {m['f1']:.4f} | {m['support']} |")
lines+=['','Confusion matrix (rows = truth; columns = predictions including INVALID):','',
'| Truth | '+' | '.join(r['confusion_columns'])+' |',
'|---|'+'---:|'*len(r['confusion_columns'])]
for label,counts in r['confusion_matrix'].items():
lines.append('| '+label+' | '+' | '.join(str(counts[c]) for c in r['confusion_columns'])+' |')
lines+=['','Safety screen counts: '+json.dumps(r['safety_counts']),
'Token-limit hits: '+str(r.get('generation_token_limit_hit_count',0)),'']
lines+=['## Limitations','',
'Small authored synthetic data and finite rules do not establish clinical safety, human label correctness, semantic independence, or production readiness. Invalid outputs remain in the denominator. No human approval is implied.']
Path(path).write_text('\\n'.join(lines)+'\\n')
def assemble_run_project(dataset,output):
import shutil
source_root=Path(dataset).parent
project=Path(output)/'project'
project.mkdir(exist_ok=True)
for name in ['src','schemas','experimental','colab']:
source=source_root/name
if source.exists():
shutil.copytree(source,project/name,dirs_exist_ok=True,ignore=shutil.ignore_patterns('__pycache__'))
model_card=''' + '"""' + '''---
language:
- en
tags:
- qwen3
- lora
- experimental
- synthetic-data
base_model: Qwen/Qwen3-1.7B
---
# Qwen3-1.7B AI-reviewed synthetic EXPERIMENT
Actual adapter files and measured base/adapter test results accompany this run.
All data remains synthetic and unreviewed by humans. No human approval or original
Stage B acceptance is claimed. See test_evaluation.md/json for measured metrics,
raw predictions for each test example, run_config.json for the immutable base
revision and actual package/GPU metadata, and adapter_verification.json for hashes.
The baseline uses the same NF4-quantized base with adapters disabled. Test results
were computed after model selection. They must not be treated as deployment or
clinical safety certification; the small authored dataset has no human-approved
ground truth. The project/data license is unspecified; no reuse grant is invented.
Qwen/Qwen3-1.7B has its own Apache-2.0 terms. Nothing is automatically published.
''' + '"""' + '''
(output/'README.md').write_text(model_card)
(output/'REPRODUCE.md').write_text('Run project/colab/requirements-stage-c.txt in a fresh remote Colab GPU environment. Add project/src and project/colab to sys.path. Call ai_experimental_runtime.run_experiment on project/experimental and a new output run directory, passing the ACK from jitai_training.ai_experiment. Pin the base revision recorded in run_config.json. This is experimental and never requires or creates human approval. Test is evaluation-only. Retain the original output and hashes.\\n')
(output/'inference_example.py').write_text(INFERENCE_EXAMPLE)
INFERENCE_EXAMPLE = r''' + '"""' + '''# Run only in an authorized remote Colab GPU runtime after installing pinned dependencies.
import google.colab
import json,sys
from pathlib import Path
ROOT=Path(__file__).resolve().parent
sys.path[:0]=[str(ROOT/'project/src'),str(ROOT/'project/colab')]
from stage_c_runtime import require_colab_gpu,assistant_example
require_colab_gpu()
import torch
from transformers import AutoModelForCausalLM,AutoTokenizer,BitsAndBytesConfig
from peft import PeftModel
meta=json.loads((ROOT/'run_config.json').read_text())
tokenizer=AutoTokenizer.from_pretrained(ROOT/'adapter',trust_remote_code=False)
base=AutoModelForCausalLM.from_pretrained(meta['model_id'],revision=meta['model_revision'],trust_remote_code=False,
quantization_config=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.float16),
device_map={'':0},dtype=torch.float16)
model=PeftModel.from_pretrained(base,ROOT/'adapter');model.eval()
row=json.loads((ROOT/'project/experimental/test.jsonl').read_text().splitlines()[0])
_,prompt,_=assistant_example(tokenizer,row,meta['config']['max_length'])
inputs=tokenizer(prompt,return_tensors='pt',add_special_tokens=False).to(model.device)
with torch.inference_mode():generated=model.generate(**inputs,do_sample=False,max_new_tokens=384,pad_token_id=tokenizer.eos_token_id)
print(tokenizer.decode(generated[0,inputs['input_ids'].shape[1]:],skip_special_tokens=True))
''' + '"""' + '''
'''
ast.parse(text)
(ROOT/'colab/ai_experimental_runtime.py').write_text(text,encoding='utf-8')
def payload_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 p in DATA.iterdir():
if p.is_file():files['experimental/'+p.name]=p.read_bytes()
for name in ['colab/ai_experimental_runtime.py','colab/stage_c_runtime.py','colab/requirements-stage-c.txt']:
files[name]=(ROOT/name).read_bytes()
return files
def deterministic_zip(files):
buffer=io.BytesIO()
with zipfile.ZipFile(buffer,'w',zipfile.ZIP_DEFLATED) as z:
for name,data in sorted(files.items()):
entry=zipfile.ZipInfo(name,date_time=(2026,10,23,0,0,0));entry.compress_type=zipfile.ZIP_DEFLATED
z.writestr(entry,data)
return buffer.getvalue()
def make_notebook(payload):
cells=[]
def cell(kind,text):
item=dict(cell_type=kind,id='ai-experiment-'+str(len(cells)),metadata={},source=text.splitlines(keepends=True))
if kind=='code':item.update(execution_count=None,outputs=[])
cells.append(item)
cell('markdown','''# Qwen3-1.7B: AI-reviewed synthetic EXPERIMENT (no human approval)
**Prepared, not executed.** Run all cells on a remote Colab T4 GPU. The input data
and runtime are embedded: no separate upload, configuration editing, Google Drive,
OAuth, or public publishing is needed. This is a three-epoch training candidate,
not the prior eight-step test. Human approval is explicitly waived by the user for
this experiment only. Original approved-data safeguards remain unchanged.
296 examples remain in their original family splits. Four uncertain ignored-reminder
retry examples were excluded as complete pairs; emergency implementation prose was
removed from 48 messages. All original 18 checks run. The subset fails authored
inventory completeness by design; the other 17 gates must pass. No Stage B acceptance
is claimed. Small synthetic data cannot establish production or clinical safety.
The final cell packages verified weights, raw predictions, measured evaluation,
logs, configuration and checkpoints, then requests a browser download. Save the
ZIP before the ephemeral Colab runtime disappears. The notebook never publishes.
''')
cell('code','''import sys,os,json,hashlib,base64,io,zipfile,subprocess,shutil
from pathlib import Path
import google.colab
if not Path('/content').is_dir():raise RuntimeError('Remote Colab required; no local Qwen execution')
gpu=subprocess.run(['nvidia-smi'],capture_output=True,text=True)
if gpu.returncode:raise RuntimeError('Colab did not assign an NVIDIA GPU; select a T4 GPU and rerun')
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'
''')
encoded=base64.b64encode(payload).decode()
cell('code',f"# Embedded, hash-bound source and AI-reviewed synthetic inputs.\nPAYLOAD = {encoded!r}\nEXPECTED_SHA256 = {hashlib.sha256(payload).hexdigest()!r}\n"+'''data=base64.b64decode(PAYLOAD,validate=True)
if hashlib.sha256(data).hexdigest()!=EXPECTED_SHA256:raise RuntimeError('Embedded input hash mismatch')
INPUT=Path('/content/jitai-ai-input')/EXPECTED_SHA256[:16]
INPUT.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(io.BytesIO(data)) as archive:
if sum(i.file_size for i in archive.infolist())>100*1024**2:raise RuntimeError('Oversized embedded input')
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 embedded archive path')
if member.is_dir():continue
content=archive.read(member)
if target.exists() and target.read_bytes()!=content:raise RuntimeError('Input changed; 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,expected=spec.split('==')
if metadata.version(name)!=expected:raise RuntimeError('Unexpected package version: '+name)
loaded=sys.modules.get(name.replace('-','_'))
if loaded is not None and getattr(loaded,'__version__',expected)!=expected:
raise RuntimeError('Restart the session and Run all: loaded package mismatch for '+name)
sys.path[:0]=[str(INPUT/'src'),str(INPUT/'colab')]
from jitai_training.ai_experiment import ACK,validate_ai_dataset
from ai_experimental_runtime import run_experiment,package_outputs,verify_adapter
checks=validate_ai_dataset(INPUT/'experimental')
print(json.dumps({'split_counts':checks['split_counts'],'all_18_gates':checks['automated_checks'],
'human_approved':False,'stage_b_accepted':False},indent=2))
''')
cell('code',f"EXPERIMENT_ACKNOWLEDGEMENT = {ACK!r}\n"+'''if EXPERIMENT_ACKNOWLEDGEMENT!=ACK:raise RuntimeError('Explicit experimental acknowledgement required')
OUTPUT=Path('/content/jitai-ai-experimental/run-v1')
# Optional recovery: upload ONLY your own trusted prior backup and checksum.
backup=Path('/content/run-v1-backup.zip');sidecar=Path('/content/run-v1-backup.zip.sha256')
if backup.exists() and not OUTPUT.exists():
if not sidecar.is_file() or hashlib.sha256(backup.read_bytes()).hexdigest()!=sidecar.read_text().split()[0]:
raise RuntimeError('Resume backup requires a matching trusted checksum')
with zipfile.ZipFile(backup) as archive:
if sum(i.file_size for i in archive.infolist())>4*1024**3:raise RuntimeError('Oversized resume ZIP')
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 members')
for name,digest in manifest.items():
if hashlib.sha256(archive.read('run-v1/'+name)).hexdigest()!=digest:raise RuntimeError('Resume artifact checksum mismatch')
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))
# GPU, consent, dataset, no-truncation, output binding and step configuration gates are repeated inside.
run_experiment(INPUT/'experimental',OUTPUT,acknowledgement=EXPERIMENT_ACKNOWLEDGEMENT)
''')
cell('markdown','''## Actual output packaging
Run this cell after a training error too if diagnostics/checkpoints exist. A saved
adapter alone is not a passed experiment: completion requires actual weight
verification and base/adapter held-out evaluation. Check completion.json and the
measured test_evaluation reports. The browser may ask permission for the download.
Within this runtime complete epoch checkpoints resume automatically. Across runtime
loss, retain your trusted backup and checksum; see the handoff resume instructions.
''')
cell('code','''if not OUTPUT.exists():raise RuntimeError('No actual run artifacts exist')
archive=package_outputs(OUTPUT)
print('Actual output archive:',archive)
print('Checksum:',archive.with_suffix('.zip.sha256').read_text())
from google.colab import files
files.download(str(archive))
files.download(str(archive.with_suffix('.zip.sha256')))
''')
book=dict(cells=cells,nbformat=4,nbformat_minor=5,metadata={
'kernelspec':dict(display_name='Python 3',language='python',name='python3'),
'language_info':dict(name='python'),'accelerator':'GPU','colab':{'gpuType':'T4','provenance':[]}})
for c in cells:
if c['cell_type']=='code':ast.parse(''.join(c['source']))
(ROOT/'colab/qwen3_ai_experimental_autorun.ipynb').write_text(json.dumps(book,indent=2)+'\n',encoding='utf-8')
def main():
OUT.mkdir(parents=True,exist_ok=True)
if not DATA.exists():build_dataset(ROOT/'data/candidates/v3',DATA)
report=validate_ai_dataset(DATA)
make_runtime()
payload=deterministic_zip(payload_files())
(OUT/'embedded-training-input.zip').write_bytes(payload)
make_notebook(payload)
print(json.dumps({'dataset':str(DATA),'split_counts':report['split_counts'],
'original_gates_passed':sum(report['automated_checks'].values()),'checks_run':18,
'notebook':str(ROOT/'colab/qwen3_ai_experimental_autorun.ipynb'),
'embedded_input_sha256':hashlib.sha256(payload).hexdigest(),'training_executed':False},indent=2))
if __name__=='__main__':main()
|