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
Download colab/final_training_runtime.py from AnuCaro/Carol_JITAI: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/AnuCaro/Carol_JITAI/resolve/main/colab/final_training_runtime.py
- Command line
-
hf download hf://AnuCaro/Carol_JITAI/colab/final_training_runtime.py
-
curl -L -o final_training_runtime.py https://huggingface.co/AnuCaro/Carol_JITAI/resolve/main/colab/final_training_runtime.py
14.1 kB
| """Approved-data-only Colab training/evaluation. Importing never imports a model.""" | |
| import hashlib | |
| import json | |
| import math | |
| import re | |
| import zipfile | |
| from pathlib import Path | |
| MODEL_ID = 'Qwen/Qwen3-1.7B' | |
| OUTPUT_ROOT = Path('/content/jitai-final-approved') | |
| DEFAULTS = dict(seed=20261023, max_length=2048, epochs=3, learning_rate=2e-4, | |
| gradient_accumulation_steps=8, lora_rank=8, lora_alpha=16, | |
| max_new_tokens=384) | |
| def checksum(path): | |
| return hashlib.sha256(Path(path).read_bytes()).hexdigest() | |
| def validate_final_dataset(path): | |
| from jitai_training.review import validate_pilot | |
| path = Path(path) | |
| checks, ready = validate_pilot(path) | |
| evidence = json.loads((path/'final_readiness.json').read_text(encoding='utf-8')) | |
| if not ready or evidence.get('kind') != 'human-approved-final-training-input-v1': | |
| raise ValueError('Final training requires a balanced, genuinely approved dataset export') | |
| if evidence.get('human_review_complete') is not True: | |
| raise ValueError('Final preparation requires every source example to be adjudicated by a human') | |
| if evidence.get('pilot_manifest_sha256') != checksum(path/'manifest.json'): | |
| raise ValueError('Final readiness is not bound to this approved dataset') | |
| if evidence.get('approved_exportable') != sum(checks['split_counts'].values()): | |
| raise ValueError('Approved dataset counts differ from readiness') | |
| return checks | |
| def output_path(path): | |
| path = Path(path).resolve() | |
| if path == OUTPUT_ROOT.resolve() or not path.is_relative_to(OUTPUT_ROOT.resolve()): | |
| raise ValueError('Final outputs must use a run directory within /content/jitai-final-approved') | |
| return path | |
| def package_outputs(path): | |
| """Include checkpoints for manual backup/resume. No external uploads.""" | |
| path = output_path(path) | |
| manifest = {p.relative_to(path).as_posix(): checksum(p) for p in sorted(path.rglob('*')) | |
| if p.is_file() and p.name != 'artifact_manifest.json'} | |
| for p in path.rglob('*'): | |
| if p.is_symlink(): raise ValueError('Symlinks not allowed') | |
| if not manifest: raise ValueError('No actual output files to package') | |
| (path/'artifact_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') | |
| archive = path.parent/(path.name+'-backup.zip') | |
| if archive.exists(): raise ValueError('Backup already exists; preserve/download it before packaging again') | |
| with zipfile.ZipFile(archive,'x',zipfile.ZIP_DEFLATED) as z: | |
| for p in sorted(path.rglob('*')): | |
| if p.is_file(): z.write(p,path.name+'/'+p.relative_to(path).as_posix()) | |
| archive.with_suffix('.zip.sha256').write_text(checksum(archive)+' '+archive.name+'\n') | |
| return archive | |
| def resumable_checkpoint(output): | |
| candidates = [p for p in Path(output).glob('checkpoints/checkpoint-*') | |
| if p.is_dir() and re.fullmatch(r'checkpoint-\d+',p.name)] | |
| for p in sorted(candidates,key=lambda p:int(p.name.split('-')[-1]),reverse=True): | |
| if all((p/name).is_file() for name in ['trainer_state.json','optimizer.pt','scheduler.pt', | |
| 'adapter_model.safetensors','adapter_config.json']): | |
| if list(p.glob('rng_state*.pth')): return str(p) | |
| return None | |
| def run_final(dataset, output, config=None): | |
| # These checks happen before any model/tokenizer network access. | |
| import sys | |
| if 'google.colab' not in sys.modules or not Path('/content').is_dir(): | |
| raise RuntimeError('Colab remote runtime required. No local Qwen execution.') | |
| checks = validate_final_dataset(dataset) | |
| from stage_c_runtime import require_colab_gpu, assistant_example | |
| hardware = require_colab_gpu() | |
| from packaging.version import Version | |
| if Version(hardware['torch'].split('+')[0]) < Version('2.4'): | |
| raise RuntimeError('Colab CUDA PyTorch >=2.4 required; no CPU fallback') | |
| output = output_path(output) | |
| config = {**DEFAULTS, **(config or {})} | |
| if (config != DEFAULTS): | |
| raise ValueError('Use the reviewed fixed training profile; version the pipeline to change it') | |
| from jitai_training.reporting import read_jsonl | |
| dataset = Path(dataset) | |
| rows = {s:read_jsonl(dataset/(s+'.jsonl')) for s in ['train','validation','test']} | |
| binding = dict(config=config, approved_manifest_sha256=checksum(dataset/'manifest.json'), | |
| final_readiness_sha256=checksum(dataset/'final_readiness.json'),model_id=MODEL_ID) | |
| checkpoint = None | |
| previous = None | |
| if output.exists(): | |
| previous = json.loads((output/'run_config.json').read_text()) | |
| if any(previous.get(k)!=v for k,v in binding.items()): | |
| raise ValueError('Resume configuration/data changed; use a fresh run directory') | |
| if (output/'completion.json').exists(): | |
| raise ValueError('Training already completed; preserve it and use its evaluation outputs') | |
| checkpoint = resumable_checkpoint(output) | |
| if not checkpoint: raise ValueError('No complete resumable checkpoint; preserve this failed run') | |
| print(json.dumps({'preflight':'passed','split_counts':checks['split_counts'], | |
| 'output':str(output),'resume':checkpoint,'hardware':hardware},indent=2)) | |
| import torch | |
| from importlib.metadata import version | |
| from huggingface_hub import HfApi | |
| from transformers import (AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig, | |
| Trainer, TrainingArguments, TrainerCallback, set_seed) | |
| from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training | |
| revision = previous['model_revision'] if previous else HfApi().model_info(MODEL_ID).sha | |
| if not re.fullmatch(r'[0-9a-f]{40}',revision or ''): | |
| raise ValueError('Immutable base revision required') | |
| set_seed(config['seed']) | |
| torch.backends.cudnn.benchmark=False | |
| torch.backends.cudnn.deterministic=True | |
| torch.use_deterministic_algorithms(True,warn_only=True) | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID,revision=revision,trust_remote_code=False) | |
| if tokenizer.pad_token_id is None: tokenizer.pad_token=tokenizer.eos_token | |
| tokenizer.padding_side='right' | |
| # Only train/validation are tokenized for fitting/model selection. | |
| encoded = {s:[assistant_example(tokenizer,r,config['max_length']) for r in rows[s]] | |
| for s in ['train','validation']} | |
| if not output.exists(): | |
| output.mkdir(parents=True,exist_ok=False) | |
| metadata = {**binding,'model_revision':revision,'hardware':hardware, | |
| 'data_mode':'human-approved-synthetic-final-training', 'human_approved':True, | |
| 'stage_b_accepted':False,'configuration_recorded_before_training':True, | |
| 'packages':{k:version(k) for k in ['torch','transformers','peft','accelerate', | |
| 'bitsandbytes','tokenizers','huggingface-hub']}, | |
| 'sequence_lengths':{s:[len(e[0]['input_ids']) for e in encoded[s]] for s in encoded}, | |
| 'determinism':'seeded; CUDA deterministic warn_only; not bitwise guaranteed'} | |
| (output/'run_config.json').write_text(json.dumps(metadata,indent=2)+'\n') | |
| with (output/'execution_attempts.jsonl').open('a') as stream: | |
| stream.write(json.dumps({'hardware':hardware,'resume_checkpoint':checkpoint, | |
| 'packages':{k:version(k) for k in ['torch','transformers','peft','bitsandbytes']}})+'\n') | |
| try: | |
| bf16=torch.cuda.is_bf16_supported() | |
| dtype=torch.bfloat16 if bf16 else torch.float16 | |
| model=AutoModelForCausalLM.from_pretrained(MODEL_ID,revision=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=dtype), | |
| device_map={'':0},dtype=dtype,attn_implementation='sdpa') | |
| if not getattr(model,'is_loaded_in_4bit',False): raise RuntimeError('Refusing non-4-bit fallback') | |
| model.config.use_cache=False | |
| model=prepare_model_for_kbit_training(model,use_gradient_checkpointing=True, | |
| gradient_checkpointing_kwargs={'use_reentrant':False}) | |
| model=get_peft_model(model,LoraConfig(r=config['lora_rank'],lora_alpha=config['lora_alpha'], | |
| lora_dropout=0.05,bias='none',task_type='CAUSAL_LM',target_modules=['q_proj','v_proj'])) | |
| if not any(p.requires_grad for p in model.parameters()): raise RuntimeError('No trainable adapter parameters') | |
| class Examples(torch.utils.data.Dataset): | |
| def __init__(self,values): self.values=values | |
| def __len__(self): return len(self.values) | |
| def __getitem__(self,index): return self.values[index][0] | |
| def collate(examples): | |
| length=max(len(x['input_ids']) for x in examples) | |
| return {name:torch.tensor([x[name]+[pad]*(length-len(x[name])) for x in examples],dtype=torch.long) | |
| for name,pad in [('input_ids',tokenizer.pad_token_id),('attention_mask',0),('labels',-100)]} | |
| class FiniteLoss(TrainerCallback): | |
| def on_log(self,args,state,control,logs=None,**kwargs): | |
| for key in ['loss','eval_loss','grad_norm']: | |
| if key in (logs or {}) and not math.isfinite(float(logs[key])): | |
| raise RuntimeError('Nonfinite '+key+'; preserve checkpoints and diagnose') | |
| args=TrainingArguments(output_dir=str(output/'checkpoints'),num_train_epochs=config['epochs'], | |
| per_device_train_batch_size=1,per_device_eval_batch_size=1, | |
| gradient_accumulation_steps=config['gradient_accumulation_steps'], | |
| learning_rate=config['learning_rate'],lr_scheduler_type='linear',warmup_ratio=0.05, | |
| optim='adamw_torch',fp16=not bf16,bf16=bf16,gradient_checkpointing=True, | |
| gradient_checkpointing_kwargs={'use_reentrant':False},eval_strategy='epoch',save_strategy='epoch', | |
| save_total_limit=2,save_only_model=False,save_safetensors=True,load_best_model_at_end=True, | |
| metric_for_best_model='eval_loss',greater_is_better=False,logging_steps=1, | |
| logging_nan_inf_filter=False,report_to='none',push_to_hub=False, | |
| seed=config['seed'],data_seed=config['seed'],dataloader_num_workers=0, | |
| remove_unused_columns=False,label_names=['labels']) | |
| trainer=Trainer(model=model,args=args,train_dataset=Examples(encoded['train']), | |
| eval_dataset=Examples(encoded['validation']),data_collator=collate, | |
| processing_class=tokenizer,callbacks=[FiniteLoss()]) | |
| torch.cuda.reset_peak_memory_stats() | |
| trained=trainer.train(resume_from_checkpoint=checkpoint) | |
| if not math.isfinite(trained.training_loss): raise RuntimeError('Nonfinite training loss') | |
| model.save_pretrained(output/'adapter',safe_serialization=True) | |
| tokenizer.save_pretrained(output/'adapter') | |
| trainer.save_state() | |
| if not (output/'adapter/adapter_model.safetensors').is_file(): raise RuntimeError('Adapter not saved') | |
| (output/'training_result.json').write_text(json.dumps({ | |
| 'steps':trainer.state.global_step,'training_loss':trained.training_loss, | |
| 'best_checkpoint':trainer.state.best_model_checkpoint,'human_approved':True, | |
| 'stage_b_accepted':False,'peak_vram':torch.cuda.max_memory_allocated()},indent=2)+'\n') | |
| # Hold test untouched until training/model selection has finished. | |
| evaluate_held_out(model,tokenizer,rows['test'],output,config) | |
| (output/'completion.json').write_text(json.dumps({'training_completed':True, | |
| 'held_out_evaluation_completed':True,'human_approved_training_data':True, | |
| 'quality_accepted':False,'note':'Human assessment of measured results remains required.'},indent=2)+'\n') | |
| except Exception as error: | |
| (output/'failure.json').write_text(json.dumps({'exception_type':type(error).__name__, | |
| 'message':str(error),'resumable_checkpoint':resumable_checkpoint(output), | |
| 'training_or_evaluation_completed':False},indent=2)+'\n') | |
| raise | |
| return output | |
| def evaluate_held_out(model,tokenizer,rows,output,config): | |
| import torch | |
| from stage_c_runtime import assistant_example | |
| from jitai_training.evaluation import evaluate_predictions | |
| model.eval() | |
| model.gradient_checkpointing_disable() | |
| results={} | |
| # Evaluate unchanged base with adapters disabled, then the selected adapter. | |
| for variant in ['base','adapter']: | |
| predictions=[] | |
| from contextlib import nullcontext | |
| with model.disable_adapter() if variant=='base' else nullcontext(): | |
| for row in rows: | |
| _,prompt,_=assistant_example(tokenizer,row,config['max_length']) | |
| tokens=tokenizer(prompt,return_tensors='pt',add_special_tokens=False).to(model.device) | |
| with torch.inference_mode(): | |
| generated=model.generate(**tokens,do_sample=False,max_new_tokens=config['max_new_tokens'], | |
| pad_token_id=tokenizer.pad_token_id,eos_token_id=tokenizer.eos_token_id, | |
| use_cache=True) | |
| text=tokenizer.decode(generated[0,tokens['input_ids'].shape[1]:],skip_special_tokens=True) | |
| predictions.append(dict(example_id=row['example_id'],raw_output=text, | |
| generation_token_limit_hit=generated.shape[1]-tokens['input_ids'].shape[1]>=config['max_new_tokens'])) | |
| (output/(variant+'_test_predictions.jsonl')).write_text(''.join(json.dumps(p)+'\n' for p in predictions)) | |
| results[variant]=evaluate_predictions(rows,predictions) | |
| results[variant]['generation_token_limit_hit_count']=sum(p['generation_token_limit_hit'] for p in predictions) | |
| (output/'test_evaluation.json').write_text(json.dumps(results,indent=2)+'\n') | |