File size: 3,727 Bytes
7f50cd1 | 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 | """Cache all visible train.jsonl descriptors; never read practice query labels."""
import argparse
import hashlib
import json
import time
from pathlib import Path
from runtime import HERE, feature_version, featurize, record_id, worker_count
from interface.data import read_records
import numpy as np
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('data_dir', type=str)
parser.add_argument('--workers', type=int, default=8)
parser.add_argument('--exclude-cohort', action='append', default=[],
help='Exclude a whole cohort for external validation.')
parser.add_argument('--limit-per-cohort', type=int, default=None,
help='Small smoke fixture only; production leaves this unset.')
args = parser.parse_args()
if args.limit_per_cohort is not None and args.limit_per_cohort < 1:
parser.error('--limit-per-cohort must be positive')
start = time.monotonic()
files = sorted(Path(args.data_dir).glob('*/train.jsonl'))
if not files:
raise FileNotFoundError(f'No cohort train.jsonl files in {args.data_dir}')
unknown = set(args.exclude_cohort) - {path.parent.name for path in files}
if unknown:
raise ValueError(f'Unknown excluded cohorts: {sorted(unknown)}')
matrices, responses, identities, cohorts = [], [], [], []
manifest = {
'data_policy': 'Only visible train.jsonl responses; no query.jsonl or practice answers.',
'feature_version': feature_version(),
'excluded_cohorts': sorted(args.exclude_cohort),
'limit_per_cohort': args.limit_per_cohort,
'workers': worker_count(args.workers),
'cohorts': [],
}
for path in files:
if path.parent.name in args.exclude_cohort:
continue
rows = read_records(path)
available = len(rows)
if args.limit_per_cohort is not None:
rows = rows[:args.limit_per_cohort]
if not rows:
continue
print(f'preparing {path.parent.name}: {len(rows)} training rows', flush=True)
x = featurize(rows, args.workers)
y = np.array([row['response'] for row in rows], dtype=np.float64)
if not np.isfinite(y).all():
raise ValueError(f'Nonfinite training responses in {path}')
matrices.append(x)
responses.append(y)
identities.extend(record_id(row) for row in rows)
cohorts.extend([path.parent.name] * len(rows))
manifest['cohorts'].append({
'name': path.parent.name, 'file': path.relative_to(args.data_dir).as_posix(),
'sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
'available_records': available, 'prepared_records': len(rows),
'rows_with_missing_features': int(np.isnan(x).any(axis=1).sum()),
})
if not matrices:
raise ValueError('No training rows remain after cohort exclusions.')
target = HERE / 'prepared'
target.mkdir(parents=True, exist_ok=True)
pending = target / 'training_pool.pending.npz'
np.savez_compressed(pending, features=np.concatenate(matrices),
responses=np.concatenate(responses),
record_ids=np.asarray(identities), cohorts=np.asarray(cohorts),
feature_version=np.asarray(feature_version()))
pending.replace(target / 'training_pool.npz')
manifest['prepared_records'] = len(identities)
manifest['seconds'] = time.monotonic() - start
(target / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
print(f'prepared {len(identities)} rows in {manifest["seconds"]:.3f}s', flush=True)
if __name__ == '__main__':
main()
|