Carol_JITAI / scripts /prepare_huggingface_release.py
AnuCaro's picture
Publish verified Qwen3 experimental adapter and measured limitations
61d5a60 verified
Raw History Blame Contribute Delete
15.1 kB
"""Build an allowlisted, scanned source-only Hub release. Never loads Qwen."""
import ast
import hashlib
import json
import re
import shutil
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
RELEASE = ROOT / 'release' / 'huggingface'
def sha(data):
return hashlib.sha256(data).hexdigest()
def scan(name, data):
"""Fail closed on common credentials and personal identifiers, including ZIP members."""
findings = []
patterns = {
'huggingface_token': r'\bhf_[A-Za-z0-9]{20,}\b',
'github_token': r'\b(?:ghp_|github_pat_)[A-Za-z0-9_]{20,}\b',
'cloud_access_key': r'\b(?:AKIA|ASIA)[A-Z0-9]{16}\b',
'private_key': r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----',
'email_address': r'[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}',
'personal_home_path': r'(?i)(?:[a-z]:[\\/]+Users[\\/]|/' r'Users/|/' r'home/)[^\s"\']+',
'workspace_path': r'(?i)[a-z]:[\\/]+VSC[\\/]',
'local_user_name': r'(?i)\banusha\b',
'credential_assignment': r'''(?i)(?:api_key|access_token|password|secret)\s*[=:]\s*["'][^"'\s]{8,}["']''',
'jwt': r'\beyJ[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}',
}
text = data.decode('utf-8-sig')
for category, pattern in patterns.items():
for match in re.finditer(pattern, text):
findings.append({'file': name, 'category': category,
'line': text[:match.start()].count('\n') + 1})
return findings
def main():
if RELEASE.exists():
raise SystemExit('Release already exists; preserve it and review changes before rebuilding.')
bundle = ROOT / 'colab/experimental-stage-c.zip'
expected = (ROOT / 'colab/experimental-stage-c.sha256').read_text().split()[0]
if sha(bundle.read_bytes()) != expected:
raise ValueError('Experimental bundle checksum mismatch')
with zipfile.ZipFile(bundle) as archive:
if archive.testzip() is not None:
raise ValueError('Invalid experimental ZIP')
for member in archive.infolist():
path = Path(member.filename)
if path.is_absolute() or '..' in path.parts or '\\' in member.filename:
raise ValueError('Unsafe bundle member')
if member.file_size > 50 * 1024**2:
raise ValueError('Unexpected bundle member size')
for name in ('stage_c_runtime.py', 'experimental_data.py'):
if archive.read('colab/' + name) != (ROOT / 'colab' / name).read_bytes():
raise ValueError('Bundled runtime differs from local runtime')
artifacts = []
checked_archives = []
# Exclude environments/caches, inspect all other project directories and ZIPs.
import os
for folder, directories, files in os.walk(ROOT):
directories[:] = [d for d in directories if d not in {'.git', '__pycache__', 'release'}
and not d.startswith('.venv')]
for name in files:
path = Path(folder) / name
rel = path.relative_to(ROOT).as_posix()
if name.endswith(('.safetensors', '.bin', '.pt', '.pth')) or name in {
'adapter_config.json', 'tiny_test_report.json', 'artifact_manifest.json'}:
artifacts.append(rel)
if path.suffix == '.zip':
with zipfile.ZipFile(path) as archive:
matches = [n for n in archive.namelist() if
n.endswith(('.safetensors', '.bin', '.pt', '.pth',
'adapter_config.json', 'tiny_test_report.json'))]
checked_archives.append({'path': rel, 'training_artifact_members': matches})
if artifacts or any(a['training_artifact_members'] for a in checked_archives):
raise ValueError('Training artifacts found: inspect them before creating a source-only card')
selected = [ROOT / 'requirements-stage-b.txt']
for folder, glob in [('src/jitai_training', '*.py'), ('schemas', '*.json'),
('data/candidates/v3', '*')]:
selected += [p for p in (ROOT / folder).rglob(glob)
if p.is_file() and '__pycache__' not in p.parts]
selected += [ROOT / 'colab' / name for name in (
'experimental_data.py', 'stage_c_runtime.py', 'requirements-stage-c.txt',
'stage_c_qwen3_experimental.ipynb', 'experimental-stage-c.zip',
'experimental-stage-c.sha256')]
findings = []
for path in selected:
if path.is_symlink():
raise ValueError('Symlinks are not allowed')
rel = path.relative_to(ROOT).as_posix()
if path.suffix == '.zip':
with zipfile.ZipFile(path) as archive:
for member in archive.namelist():
findings += scan(rel + ':' + member, archive.read(member))
else:
findings += scan(rel, path.read_bytes())
if findings:
raise ValueError('Potential sensitive content requires review: ' + json.dumps(findings))
RELEASE.mkdir(parents=True)
for path in selected:
target = RELEASE / path.relative_to(ROOT)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(path, target)
# Preserve every checksum-bound input exactly; document historical instructions separately.
card = '''---
language:
- en
tags:
- jitai
- qwen3
- experimental
- synthetic-data
- training-code
- no-trained-weights
model-index: []
---
# JITAI Qwen3 experimental training project — no trained weights
This repository shares code, validation schemas, 300 authored synthetic candidates,
and a Google Colab QLoRA smoke-test notebook targeting **Qwen/Qwen3-1.7B**.
**No trained LoRA adapter, merged model, tokenizer export, or training results are
included.** Local inspection found no adapter weights/configuration or saved
training report, including inside the project's three ZIP archives. A separate
Colab run outside this project cannot be verified from these local files.
This repository cannot be loaded as a trained model with `from_pretrained`.
## Data and intended use
All 300 candidates remain **synthetic and unreviewed**. Automated validation is
not human approval. Stage B has not been accepted. Splits contain 198 training,
52 validation, and 50 test candidates. The smoke test selects six training and
six separate validation examples, one per decision class. Test examples are
validated for dataset integrity but never fitted or scored by the smoke test.
No claims about clinical safety, model quality, or generalization are supported.
Use for research and teammate inspection; this is not a production or medical system.
Host applications must independently enforce consent, safety, and tool execution.
Safety/security examples include synthetic distress and adversarial requests.
## Prepared experiment
The current notebook is configured for an explicitly acknowledged unreviewed-data
experiment: eight optimizer steps, seed 20261015, 4-bit NF4 QLoRA, rank 8,
alpha 16, q_proj/v_proj targets, and assistant-only loss. Read the actual notebook
for the sequence cap. It rejects overlength examples rather than truncating.
If a sequence check fails, no weight download or training proceeds; inspect the
failure in Colab rather than treating a prepared notebook as a completed run.
The base model commit is resolved and recorded at execution time; no executed
base revision or GPU environment can be claimed here. GPU determinism is not guaranteed.
The source contains no executed training evidence or measured training metrics.
## Reproduce and collaborate
See [REPRODUCING.md](REPRODUCING.md) for CPU validation, Colab steps, and artifact
handling. Review source changes with teammates through Hub discussions and pull
requests. An organization administrator should grant your teammate repository
write access, or an appropriate resource-group role if your organization uses one.
No credentials, personal Drive contents, human-review working files, environments,
model caches, or submission snapshots are part of this release.
The input ZIP is preserved byte-for-byte to match its preconfigured checksum.
Its embedded notebooks/README are historical; use the **top-level
colab/stage_c_qwen3_experimental.ipynb** and these reproduction instructions.
Historical dataset-card warnings remain intact: experimental acknowledgement does
not approve the dataset for an approved pilot or production use.
## License and provenance
The existing project has no explicit project/data license. This release does not
invent one; the team must decide a license before granting broader reuse rights.
The base model has its own terms at https://huggingface.co/Qwen/Qwen3-1.7B.
No base-model weights are redistributed. See PUBLICATION_STATUS.json for the local
artifact inventory and SHA256SUMS for hashes of the release files.
'''
(RELEASE / 'README.md').write_text(card, encoding='utf-8')
instructions = '''# Reproduce the source-only experimental project
## CPU validation (no model downloads)
From this repository's root, create a virtual environment and install
`python -m pip install -r requirements-stage-b.txt`.
Set `PYTHONPATH` to `src` and `colab` using your OS path separator
(PowerShell: `$env:PYTHONPATH = 'src;colab'`; POSIX: `export PYTHONPATH=src:colab`).
Run:
```sh
python -c "from experimental_data import validate_experimental; print(validate_experimental('data/candidates/v3')['split_counts'])"
```
Verify `colab/experimental-stage-c.zip` against its SHA-256 sidecar before upload.
All input candidates and manifests are copied without modification. Source hashes
and observed historical generator dependencies are in source_manifest.json.
To generate new candidates, use `python -m jitai_training.cli --help` and a fresh
run version; never overwrite the original splits or present a regeneration as
the original export. This release does not ship private review sessions.
## Google Colab browser actions
1. Open `colab/stage_c_qwen3_experimental.ipynb` in Google Colab.
2. Select a remote NVIDIA GPU runtime; do not use a local runtime.
3. Upload `colab/experimental-stage-c.zip` through the Files sidebar to
`/content/experimental-stage-c.zip`.
4. Run the current top-level notebook from top to bottom. Training and the exact
experimental acknowledgement are prefilled. No configuration edits or personal
Drive access are required. GPU availability and compatibility remain runtime
checks; no actual Colab execution is asserted by this release.
5. Check preflight, dataset, token-length/masking, memory, and training results.
Failures must remain failures; never infer success from saved adapter files alone.
6. Run the final packaging cell, then download the actual ZIP and SHA-256 through
the Files sidebar before the ephemeral runtime disappears. Outputs are confined
to `/content/jitai-stage-c-experimental/`.
The model runtime repeats acknowledgement, dataset, GPU, output-path and step-limit
gates. It uses the pinned `colab/requirements-stage-c.txt` while retaining Colab's
CUDA PyTorch. A loaded-package mismatch can require a runtime restart and rerun.
The tokenizer may be downloaded for sequence validation before model weights.
No silent truncation, CPU fallback, automatic Hub upload, or Google Drive mount
is used by the experimental notebook.
## Publishing real adapter artifacts later
This release contains none. After an actual Colab run, retain the original
`tiny_test_report.json`, `artifact_manifest.json`, `adapter/adapter_config.json`,
`adapter/adapter_model.safetensors`, tokenizer files and the output archive checksum.
Verify archive/manifest hashes and review outputs for personal data and credentials.
Inspect the actual base-model revision, package versions, experimental provenance,
test-use flag, finite losses, changed adapter parameters, and smoke-test outcome.
Retain failed-run reports as diagnostics; never describe them as passed training.
Update the model card using actual evidence before a separately reviewed upload.
Do not add fake configs or placeholder weights to make this repository loadable.
## Team workflow
Use the confirmed organization repository, not an unconfirmed personal namespace.
Each teammate authenticates with their own account; never share an access token.
An organization administrator controls teammate write access. Use Hub pull requests
for proposed changes and review the public diff before merging. Keep private
feedback, contact details, secrets and human-review session exports outside the repo.
'''
(RELEASE / 'REPRODUCING.md').write_text(instructions, encoding='utf-8')
(RELEASE / '.gitignore').write_text('''.env
.env.*
*.pem
*.key
.venv*/
venv/
__pycache__/
*.py[cod]
.cache/
.huggingface/
.aws/
.codex/
.agents/
data/reviews/
submission/
checkpoints/
wandb/
''', encoding='utf-8')
(RELEASE / 'PUBLICATION_STATUS.json').write_text(json.dumps({
'release_kind': 'source-only-experimental-training-project',
'base_model_target': 'Qwen/Qwen3-1.7B',
'adapter_weights_present': False, 'adapter_config_present': False,
'training_report_present': False, 'training_execution_verified': False,
'human_approved': False, 'stage_b_accepted': False,
'experimental_bundle_sha256': expected,
'project_training_artifacts': artifacts, 'checked_archives': checked_archives,
'privacy_scan': 'Passed pattern scan of all release text and embedded ZIP members; not proof of absence of all sensitive data.',
'excluded': ['credentials', 'virtual environments', 'caches', 'review sessions',
'submission snapshots', 'private workspace metadata'],
'project_license': 'not specified in existing project',
}, indent=2) + '\n', encoding='utf-8')
for path in RELEASE.rglob('*'):
if path.is_file() and path.suffix != '.zip':
findings += scan(path.relative_to(RELEASE).as_posix(), path.read_bytes())
if path.suffix == '.py':
ast.parse(path.read_text(encoding='utf-8-sig'))
if path.suffix == '.ipynb':
book = json.loads(path.read_text(encoding='utf-8'))
for cell in book['cells']:
if cell['cell_type'] == 'code':
if cell['execution_count'] is not None or cell['outputs']:
raise ValueError('Notebook has outputs or execution evidence to review')
ast.parse(''.join(cell['source']))
if findings:
raise ValueError('Generated content requires privacy review: ' + json.dumps(findings))
manifest = ''.join(sha(p.read_bytes()) + ' ' + p.relative_to(RELEASE).as_posix() + '\n'
for p in sorted(RELEASE.rglob('*')) if p.is_file())
(RELEASE / 'SHA256SUMS').write_text(manifest, encoding='utf-8')
print(json.dumps({'release_folder': str(RELEASE), 'files': len(manifest.splitlines()) + 1,
'adapter_found': False, 'privacy_findings': findings}, indent=2))
if __name__ == '__main__':
main()