Carol_JITAI / scripts /assemble_trained_ai_release.py
AnuCaro's picture
Publish verified Qwen3 experimental adapter and measured limitations
61d5a60 verified
Raw History Blame Contribute Delete
22.1 kB
"""Assemble an actual verified experimental run locally. Never publishes."""
import argparse
import hashlib
import importlib.util
import json
import shutil
import sys
import zipfile
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT/'src'),str(ROOT/'scripts')]
from verify_ai_run import inspect
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()
def render_metrics(metrics):
lines=['# Measured held-out experimental results','',
'AI-reviewed synthetic data; no human approval or Stage B acceptance.',
'The baseline is the same NF4-quantized base with adapters disabled.',
'Invalid outputs remain in the denominator; test did not select the checkpoint.','',
'| Variant | N | Accuracy | Macro F1 | Weighted F1 | Schema/finite-policy violations |',
'|---|---:|---:|---:|---:|---:|']
for variant in ['base','adapter']:
r=metrics[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']} |")
for variant in ['base','adapter']:
r=metrics[variant]
lines+=['',f'## {variant}: per-class results','',
'| 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 are truth, columns are predictions.','',
'| 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 counts: `'+json.dumps(r['safety_counts'])+'`',
'Generation token-limit hits: '+str(r['generation_token_limit_hit_count']),
'Invalid JSON/decision count: '+str(r['invalid_json_or_decision_count'])]
lines+=['','## Limits','',
'Small authored synthetic tests have no human-approved ground truth. Finite policy rules and label-based safety counts cannot certify clinical safety, semantic independence, unrestricted policy compliance or production readiness. Exact-output accuracy is a strict target match, not a human judgment of equivalent wording.']
return '\n'.join(lines)+'\n'
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('archive',type=Path)
parser.add_argument('--version',default='v1')
parser.add_argument('--output-name',default='JITAI-Qwen3-trained-experimental-project.zip')
args=parser.parse_args()
if Path(args.output_name).name != args.output_name or not args.output_name.endswith('.zip'):
raise ValueError('Output name must be a ZIP filename without directories')
result=inspect(args.archive)
out=ROOT/'artifacts/ai-experiment-v1'
recovered=out/('verified-run-'+args.version)
stage=ROOT/'release'/('ai-experimental-trained-'+args.version)
if recovered.exists() or stage.exists():raise ValueError('Preserve existing verified artifacts; choose another version')
recovered.mkdir(parents=True)
with zipfile.ZipFile(args.archive) as archive:
for name in archive.namelist():
rel=Path(*Path(name).parts[1:])
target=(recovered/rel).resolve()
if not target.is_relative_to(recovered.resolve()):raise ValueError('Unsafe extraction path')
target.parent.mkdir(parents=True,exist_ok=True)
target.write_bytes(archive.read(name))
# Start from reviewed preparation contents, retaining all reproduction inputs.
shutil.copytree(ROOT/'release/huggingface',stage)
shutil.copytree(ROOT/'release/ai-experimental-prepared-v1',stage,dirs_exist_ok=True)
# Standard Hub model layout: adapter/config/tokenizer at repository root.
# The original run layout remains intact in the verified backup archive.
shutil.copytree(recovered/'adapter',stage,dirs_exist_ok=True)
for name in ['src','schemas','colab']:
source=recovered/'project'/name
if source.exists():shutil.copytree(source,stage/name,dirs_exist_ok=True,ignore=shutil.ignore_patterns('__pycache__'))
for name in ['run_config.json','training_result.json','adapter_verification.json','completion.json',
'test_evaluation.json','test_evaluation.md','base_test_predictions.jsonl',
'adapter_test_predictions.jsonl']:
shutil.copyfile(recovered/name,stage/name)
for name in ['execution_attempts.jsonl','evaluation_execution.json','evaluation_attempts.jsonl','training_console.log']:
if (recovered/name).is_file():
shutil.copyfile(recovered/name,stage/name)
logs=stage/'training_logs';logs.mkdir(exist_ok=True)
if (recovered/'checkpoints/trainer_state.json').is_file():
shutil.copyfile(recovered/'checkpoints/trainer_state.json',logs/'trainer_state.json')
optimizer_recovered=any((recovered/'checkpoints').glob('checkpoint-*/optimizer.pt'))
# Runtime inference example expects the raw run layout. Adapt paths only for
# this packaged project layout; adapter bytes and measured outputs are unchanged.
inference=(recovered/'inference_example.py').read_text()
inference=inference.replace("ROOT/'project/src'","ROOT/'src'").replace("ROOT/'project/colab'","ROOT/'colab'")
inference=inference.replace("ROOT/'project/experimental/test.jsonl'","ROOT/'data/experimental/ai-reviewed-v1/test.jsonl'")
inference=inference.replace("ROOT/'adapter'","ROOT")
(stage/'inference_example.py').write_text(inference)
shutil.copyfile(ROOT/'scripts/verify_ai_run.py',stage/'scripts/verify_ai_run.py')
shutil.copyfile(ROOT/'scripts/assemble_trained_ai_release.py',stage/'scripts/assemble_trained_ai_release.py')
if (ROOT/'scripts/verify_final_project.py').is_file():
shutil.copyfile(ROOT/'scripts/verify_final_project.py',stage/'scripts/verify_final_project.py')
license_receipt=ROOT/'artifacts/resume-audit-20261026/upstream-license.json'
if license_receipt.is_file():
shutil.copyfile(license_receipt,stage/'UPSTREAM_LICENSE_CHECK.json')
(stage/'VERIFIED_RUN.json').write_text(json.dumps(result,indent=2)+'\n')
config=json.loads((stage/'run_config.json').read_text())
training=json.loads((stage/'training_result.json').read_text())
metrics=json.loads((stage/'test_evaluation.json').read_text())
# Fix the presentation of the original Markdown summary without altering any
# raw predictions, JSON metrics, saved weights, or the original run archive.
(stage/'test_evaluation.md').write_text(render_metrics(metrics),encoding='utf-8')
(stage/'REPORT_PROVENANCE.json').write_text(json.dumps({
'metric_source':'test_evaluation.json, independently recomputed from raw predictions',
'raw_run_markdown_sha256':sha(recovered/'test_evaluation.md'),
'packaged_markdown_sha256':sha(stage/'test_evaluation.md'),
'change':'Formatting of the human-readable summary only; measurements unchanged.'},indent=2)+'\n')
card='''---
language:
- en
library_name: peft
pipeline_tag: text-generation
base_model: Qwen/Qwen3-1.7B
tags:
- qwen3
- lora
- experimental
- synthetic-data
model-index: []
---
# JITAI Qwen3-1.7B experimental LoRA adapter
Actual QLoRA adapter weights and configuration are included at repository root. The run used
AI-reviewed synthetic data with **no human approval**. Original Stage B acceptance
is false. This is a small experimental training run, not a production/clinical
model or a human-approved final model. The original eight-step experiment is
separate; the measurements here come from the actual run described below.
'''
card+=f"Base revision: `{config['model_revision']}`. GPU: {config['hardware']['gpu']}. Optimizer steps: {training['steps']}.\n\n"
card+='The dataset contains 194 training, 52 validation, and 50 test examples. Four uncertain repeat-outreach examples were excluded as complete pairs; 48 emergency messages lose implementation prose. All labels and original family splits were preserved. Full curation decisions and both original/derived gate reports accompany the data.\n\n'
card+='The source passes 18/18 gates. The derived experimental subset passes 17/18: authored-inventory completeness intentionally fails after exclusion. Every other original gate is required. This is not original Stage B acceptance.\n\n'
card+='## Measured held-out results\n\n| Variant | Test N | Accuracy | Macro F1 | Weighted F1 | Policy/schema violations |\n|---|---:|---:|---:|---:|---:|\n'
for variant in ['base','adapter']:
r=metrics[variant]
card+=f"| {variant} | {r['n']} | {r['accuracy']:.4f} | {r['macro_f1']:.4f} | {r['weighted_f1']:.4f} | {r['contract_or_finite_policy_violation_count']} |\n"
card+='\nThe baseline is the same NF4-quantized base with adapters disabled, not full-precision inference. Both use greedy decoding on the same held-out test rows. Validation loss selected the checkpoint; test was not used for fitting or model selection. Per-class precision, recall, F1, support, confusion matrices including INVALID, safety counts and limitations are in [test_evaluation.md](test_evaluation.md). Raw predictions and machine-readable results are included. Invalid outputs remain in the denominator.\n\n'
card+='## Reproduce and infer\n\nUse the existing self-contained notebook `colab/qwen3_ai_experimental_autorun.ipynb` on a remote Colab T4. Pin the recorded base revision, consult run_config.json for actual packages/configuration, and retain the original split files. `inference_example.py` loads the saved adapter onto that immutable base in an authorized GPU runtime. It does not execute tools. This is an adapter, not a merged standalone model; load the root adapter onto the pinned base explicitly. No credentials or personal Google Drive access are needed for the public base model.\n\n'
card+='## Verification and limitations\n\nAdapter tensor layout, finiteness, config, manifest hashes, training evidence and every reported metric were checked against the actual saved files and raw predictions. See VERIFIED_RUN.json, adapter_verification.json and SHA256SUMS. '
card+=('The local handoff retains optimizer checkpoints, excluded from public files.\n\n' if optimizer_recovered else 'Original optimizer/RNG checkpoints were not recovered after the Colab server disappeared. Evaluation reused the verified adapter without repeating training; see evaluation_execution.json for the actual recovery protocol. Optimizer-state resumption is unavailable.\n\n')
card+='Small authored synthetic test sets and finite oracles cannot establish human label correctness, clinical safety, unrestricted policy compliance, semantic independence or production readiness. Class supports are small. No human approval or quality acceptance is implied by successful training. Seeded GPU results are not guaranteed bitwise reproducible. Human-review and approved-data workflows remain unchanged.\n\n'
card+='## Licensing\n\nThe upstream Qwen/Qwen3-1.7B model card declares Apache-2.0; comply with its terms. The existing project/data license is unspecified; this release invents no license or broader reuse grant. No base-model weights are redistributed.\n'
(stage/'README.md').write_text(card,encoding='utf-8')
(stage/'REPRODUCING.md').write_text('''# Reproduce the completed experimental adapter
The original human-approved-data path remains unchanged. This completed run uses
AI-reviewed synthetic data with no human approval and no Stage B acceptance.
Use colab/qwen3_ai_experimental_autorun.ipynb on a remote Colab T4, including
through the official Google Colab VS Code extension. The notebook embeds inputs,
pins the base revision, trains, evaluates, verifies weights and packages outputs.
Consult run_config.json, training_result.json and VERIFIED_RUN.json for this run.
The original eight-step notebook/bundle are retained as historical inputs; they
are separate from these measured three-epoch results.
For inference, install the pinned colab/requirements-stage-c.txt in a remote
Colab GPU runtime and run inference_example.py from this project root. It loads
the immutable base revision and the local root adapter. No tools execute.
Test scores and limitations are in test_evaluation.md/json. Keep test out of model
selection. The local handoff includes a private run backup, excluded from public
files. Optimizer-state resumption is possible only when original optimizer/RNG
checkpoints are actually present. Otherwise reuse the saved weights for inference
or evaluation; see evaluation_execution.json. Nothing is published automatically.
''',encoding='utf-8')
handoff=stage/'docs/ai-experiment-handoff.md'
original_handoff=handoff.read_text(encoding='utf-8')
handoff.write_text('# Completed experimental run update\n\n'
'Actual training and both held-out evaluations completed on a remote Colab T4 through VS Code. '
'Adapter tensors and measured metrics were verified from saved files and raw predictions. '
'See the root README, VERIFIED_RUN.json and test_evaluation.md/json for current results. '
'The preparation notes below are retained as historical reproduction instructions; their '
'pre-execution status statements describe preparation, not this completed run. '
'No human approval or Stage B acceptance is claimed. Nothing has been published.\n\n'
+original_handoff,encoding='utf-8')
status=json.loads((stage/'PROJECT_STATUS.json').read_text())
status.update(actual_model_trained=True,adapter_weights_saved=True,model_evaluation_measured=True,
accuracy=metrics['adapter']['accuracy'],precision={k:v['precision'] for k,v in metrics['adapter']['per_class'].items()},
recall={k:v['recall'] for k,v in metrics['adapter']['per_class'].items()},
f1=metrics['adapter']['macro_f1'],base_model_results=result['base'],adapter_results=result['adapter'],
reason=None,runtime_start='Completed on a remote Colab T4 through the VS Code extension',
public_upload_performed=False,full_project_complete=True,
original_optimizer_checkpoints_recovered=optimizer_recovered)
(stage/'PROJECT_STATUS.json').write_text(json.dumps(status,indent=2)+'\n')
(stage/'PUBLICATION_STATUS.json').write_text(json.dumps(status,indent=2)+'\n')
report=['# Final JITAI Qwen3 experimental project report','',
'## Dataset preparation','',
'AI-reviewed synthetic data, without human approval: 296 examples, split into '
'194 training, 52 validation and 50 held-out test examples. Original family splits '
'were preserved. Four uncertain repeat-outreach examples were excluded as complete '
'counterfactual pairs; 48 emergency messages had implementation prose removed. '
'Curation decisions and original/derived gate reports accompany the data. '
'Original data passes 18/18 gates; the experimental subset passes 17/18 because '
'authored-inventory completeness fails after the exclusions. Stage B acceptance remains false.','',
'## Training configuration and actual results','',
f"Base: {config['model_id']}, immutable revision `{config['model_revision']}`. "
'NF4 QLoRA with double quantization, FP16 compute, rank 8/alpha 16, q/v targets, '
'batch size 1, accumulation 8, learning rate 0.0002, seed 20261023, token cap 2048. '
'No input truncation. Three epochs and 75 optimizer steps completed on Tesla T4. '
f"Recorded average training loss: {training['training_loss']:.9f}. "
'Console-reported final validation loss: 0.658717. Validation loss selected '
'the saved adapter; the held-out test did not select it. '
'The original optimizer/RNG checkpoints were not recovered. Evaluation reused '
'the verified saved adapter and did not repeat training.','',
'## Measured held-out evaluation','',
'Both variants use the same 50 test examples, immutable base revision and '
'NF4 quantization. Baseline disables adapters. Recovery uses greedy decoding, '
'left padding, batch size 4 and at most 384 generated tokens. Invalid outputs '
'remain in the denominator. Precision and recall below are macro averages '
'over the six decision classes.','',
'| Variant | N | Accuracy | Macro precision | Macro recall | Macro F1 |',
'|---|---:|---:|---:|---:|---:|']
for variant in ['base','adapter']:
measured=metrics[variant]
precision=sum(v['precision'] for v in measured['per_class'].values())/len(measured['per_class'])
recall=sum(v['recall'] for v in measured['per_class'].values())/len(measured['per_class'])
report.append(f"| {variant} | {measured['n']} | {measured['accuracy']:.6f} | {precision:.6f} | {recall:.6f} | {measured['macro_f1']:.6f} |")
for variant in ['base','adapter']:
measured=metrics[variant]
report+=['',f"{variant}: {measured['invalid_json_or_decision_count']}/{measured['n']} invalid JSON/decision outputs; "
f"{measured['generation_token_limit_hit_count']} generation-cap hits; "
f"{measured['contract_or_finite_policy_violation_count']}/{measured['n']} schema/finite-policy violations. "
f"Safety counts: {json.dumps(measured['safety_counts'])}."]
report+=['','The baseline receives the same compact prompt used during training, '
'without an additional full output schema, few-shot examples or output repair. '
'Its score measures strict output-contract performance under this fixed protocol, '
'not general reasoning ability. The adapter results do not support production use.']
report+=['','Per-class precision/recall/F1, confusion matrices, exact-output accuracy, '
'safety counts and per-example reference/predicted labels are in '
'`test_evaluation.json` and `test_evaluation.md`. Raw generated text is in '
'`base_test_predictions.jsonl` and `adapter_test_predictions.jsonl`. '
'`evaluation_execution.json` records actual evaluation hardware and packages.','',
'## Reproduction and use','',
'See `REPRODUCING.md`, the existing Colab notebook, `run_config.json` and '
'`evaluation_execution.json`. Load the root adapter onto the pinned original '
'Qwen base with PEFT; `inference_example.py` demonstrates this without executing '
'tools. The evaluation-only recovery code is `colab/evaluate_saved_ai_adapter.py`. '
'The verified raw run backup is retained only in the local ZIP, outside the '
'public staging directory. No new public upload has occurred.','',
'## Limitations and licensing','',
'Small authored synthetic test sets without human-approved labels cannot '
'establish clinical safety, unrestricted policy compliance, semantic '
'independence or production readiness. Finite schema/policy violations are '
'rule-screen results. Seeded CUDA execution is not bitwise guaranteed. '
'Upstream Qwen declares Apache-2.0; project code/data licensing remains '
'unspecified. No additional license or reuse grant is invented. Public '
'publication requires explicit authorization.','']
(stage/'FINAL_PROJECT_REPORT.md').write_text('\n'.join(report),encoding='utf-8')
# Verify public candidates, including the decoded notebook input ZIP, without
# including private control capabilities or complete optimizer/RNG checkpoints.
spec=importlib.util.spec_from_file_location('privacy',ROOT/'scripts/prepare_huggingface_release.py')
privacy=importlib.util.module_from_spec(spec);spec.loader.exec_module(privacy)
findings=[]
for p in stage.rglob('*'):
if p.is_file() and p.suffix!='.safetensors':
if p.suffix=='.zip':
with zipfile.ZipFile(p) as archive:
for name in archive.namelist():
findings+=privacy.scan(p.relative_to(stage).as_posix()+':'+name,archive.read(name))
else:
findings+=privacy.scan(p.relative_to(stage).as_posix(),p.read_bytes())
(out/'trained-publication-scan.json').write_text(json.dumps({'findings':findings,
'weights_verified':True,'project_data_license':'unspecified','publication_performed':False},indent=2)+'\n')
if findings:raise ValueError('Public contents need privacy review; raw verified run preserved: '+json.dumps(findings))
manifest=''.join(sha(p)+' '+p.relative_to(stage).as_posix()+'\n' for p in sorted(stage.rglob('*'))
if p.is_file() and p.name!='SHA256SUMS')
(stage/'SHA256SUMS').write_text(manifest)
proposed=[dict(path=p.relative_to(stage).as_posix(),sha256=sha(p),bytes=p.stat().st_size)
for p in sorted(stage.rglob('*')) if p.is_file()]
(out/'trained-proposed-public-files.json').write_text(json.dumps({'destination':'AnuCaro/Carol_JITAI',
'confirmation_required':True,'upload_performed':False,'files':proposed},indent=2)+'\n')
final=out/args.output_name
with zipfile.ZipFile(final,'x',zipfile.ZIP_DEFLATED) as archive:
for p in sorted(stage.rglob('*')):
if p.is_file():archive.write(p,p.relative_to(stage).as_posix())
archive.write(args.archive,'private-run-backup/'+args.archive.name)
final.with_suffix('.zip.sha256').write_text(sha(final)+' '+final.name+'\n')
receipt={'project_zip':str(final),'sha256':sha(final),'verified_adapter':True,
'evaluation_recomputed':True,'public_upload_performed':False,'run':result}
(out/'trained-handoff-receipt.json').write_text(json.dumps(receipt,indent=2)+'\n')
print(json.dumps(receipt,indent=2))
if __name__=='__main__':main()