coderofpears commited on
Commit
f800bfe
·
verified ·
1 Parent(s): 25848bb

publish portable stage runner + frozen sources

Browse files
Files changed (1) hide show
  1. scripts/run_dataset_stage_v3.py +213 -0
scripts/run_dataset_stage_v3.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit own-weight initialization into an expanded-data, faster training stage.
2
+
3
+ Parent history is recorded separately from this stage's local counters. No saved
4
+ fingerprints are rewritten. The original trainer remains byte-identical; its
5
+ factory identity binds this initializer source and the immutable stage lineage.
6
+ """
7
+ import argparse
8
+ from datetime import datetime, timezone
9
+ import gc
10
+ import hashlib
11
+ import json
12
+ import logging
13
+ import math
14
+ import os
15
+ from pathlib import Path
16
+ import shutil
17
+ import tempfile
18
+ import time
19
+ import uuid
20
+
21
+ PARENT_SHA = '3afe6849de8d4f216f7e95bca0ef60b41b7ca8ac1d3d5feb4dc00a6cc59b1395'
22
+ PARENT_STEP = 18666
23
+ PARENT_TOKENS = 1739227136
24
+ PARENT_CHECKPOINT_TOKENS = 305_823_744
25
+ DATA_FP = '03b6dc7f4e70ae679d84da9407dafaaf6b9e0abb79634ef9b95a34044397a553'
26
+ TARGET = 50_000_000_000
27
+
28
+
29
+ def canonical_hash(value):
30
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
31
+
32
+
33
+ def stage_config(parent_config):
34
+ cfg = dict(parent_config)
35
+ cfg.update(batch_size=16, sequence_length=1024, gradient_accumulation_steps=1,
36
+ gradient_checkpointing=False, loss_chunk_tokens=8192, precision='bf16',
37
+ total_steps=math.ceil((TARGET - PARENT_TOKENS) / 16384), warmup_steps=500,
38
+ checkpoint_interval_steps=0, checkpoint_interval_seconds=1800,
39
+ log_interval_steps=50, eval_interval_steps=2000, eval_targets=8192)
40
+ return {'training': cfg}
41
+
42
+
43
+ def campaign_tokens(stage_tokens):
44
+ if type(stage_tokens) is not int or stage_tokens < 0:
45
+ raise ValueError('Invalid stage exposure counter')
46
+ return PARENT_TOKENS + stage_tokens
47
+
48
+
49
+ def write_json(path, value):
50
+ with Path(path).open('w', encoding='utf-8') as stream:
51
+ json.dump(value, stream, indent=2, sort_keys=True)
52
+ stream.flush()
53
+ os.fsync(stream.fileno())
54
+
55
+
56
+ def make_factory(parent_weights, lineage_sha, source_sha, builder):
57
+ def initialize(raw_config):
58
+ model = builder(raw_config, attention_backend='sdpa')
59
+ model.load_state_dict(parent_weights, strict=True)
60
+ return model
61
+ initialize.__module__ = 'pear15_owned_stage'
62
+ initialize.__qualname__ = 'parent_' + lineage_sha + '_initializer_' + source_sha
63
+ return initialize
64
+
65
+
66
+ def run(parent_root, stage_root, data, *, seconds=7200, smoke_first=False,
67
+ smoke_only=False, release_runtime=False):
68
+ if not 0 < seconds <= 7200:
69
+ raise ValueError('Stage session must be bounded to at most two hours')
70
+ import torch
71
+ from pear15 import scratch_train as core
72
+ from pear15.cloud_checkpoint import load_latest, _root
73
+ from pear15.scratch_data import manifest_fingerprint
74
+
75
+ if not torch.cuda.is_available() or 'A100' not in torch.cuda.get_device_name(0):
76
+ raise RuntimeError('Use the validated A100 configuration')
77
+ parent_loaded = load_latest(parent_root)
78
+ if parent_loaded is None:
79
+ raise ValueError('No verified parent checkpoint')
80
+ parent, parent_checkpoint = parent_loaded
81
+ if (parent_checkpoint['manifest']['sha256'] != PARENT_SHA or parent['step'] != PARENT_STEP
82
+ or parent['token_count'] != PARENT_CHECKPOINT_TOKENS
83
+ or parent['identity']['implementation_fingerprint'] != core._implementation_fingerprint()):
84
+ raise ValueError('Wrong parent or original trainer implementation')
85
+ manifest = json.loads((Path(data) / 'manifest.json').read_text())
86
+ if manifest_fingerprint(manifest) != DATA_FP:
87
+ raise ValueError('Expanded dataset fingerprint mismatch')
88
+ config = stage_config(parent['training_config'])
89
+ source_sha = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
90
+ lineage = {'format': 'pear15-owned-pretraining-stage-v1',
91
+ 'parent_checkpoint_sha256': PARENT_SHA, 'parent_step': PARENT_STEP,
92
+ 'parent_campaign_token_count': PARENT_TOKENS,
93
+ 'parent_identity': parent['identity'], 'dataset_fingerprint': DATA_FP,
94
+ 'model_config': parent['model_config'],
95
+ 'semantic_training': {k: v for k, v in config['training'].items() if k not in core._OPERATIONAL},
96
+ 'target_campaign_exposures': TARGET, 'initializer_source_sha256': source_sha,
97
+ 'initialization': 'Own trained model weights; fresh AdamW, scheduler, RNG seed and expanded-data cursor.',
98
+ 'counter_policy': 'campaign = parent_campaign_token_count + stage_local_token_count'}
99
+ lineage_sha = canonical_hash(lineage)
100
+ root = _root(stage_root, create=True)
101
+ info = root / 'info'
102
+ info.mkdir(exist_ok=True)
103
+ lineage_path = info / 'stage-lineage.json'
104
+ if lineage_path.exists():
105
+ if json.loads(lineage_path.read_text()) != lineage:
106
+ raise ValueError('Existing stage lineage differs')
107
+ else:
108
+ write_json(lineage_path, lineage)
109
+ factory = make_factory(parent['model'], lineage_sha, source_sha, core.build_model)
110
+ model_config = parent['model_config']
111
+ parent_bytes = parent_checkpoint['manifest']['bytes']
112
+ del parent_loaded, parent
113
+ logger = logging.getLogger('pear15.scratch_train')
114
+ logger.setLevel(logging.INFO)
115
+ logger.propagate = False
116
+ if not logger.handlers:
117
+ logger.addHandler(logging.StreamHandler())
118
+ phase = {'main': False}
119
+
120
+ class CampaignProgress(logging.Handler):
121
+ def emit(self, record):
122
+ try:
123
+ event = json.loads(record.getMessage())
124
+ if phase['main'] and event.get('event') in {'step', 'session_end'}:
125
+ total = campaign_tokens(event['token_count'])
126
+ print(json.dumps({'event': 'campaign_progress', 'stage_step': event['step'],
127
+ 'stage_tokens': event['token_count'], 'campaign_tokens': total,
128
+ 'remaining_campaign_tokens': max(0, TARGET - total)}), flush=True)
129
+ except (ValueError, KeyError, TypeError):
130
+ pass
131
+
132
+ progress = CampaignProgress()
133
+ logger.addHandler(progress)
134
+ print(json.dumps({'event': 'stage_lineage', 'lineage': lineage, 'lineage_sha256': lineage_sha,
135
+ 'factory_identity': factory.__module__ + '.' + factory.__qualname__}, indent=2), flush=True)
136
+ smoke = None
137
+ try:
138
+ if smoke_first or smoke_only:
139
+ smoke_root = Path(tempfile.mkdtemp(prefix='stage2-smoke-', dir='/content')) / 'run'
140
+ first = core.run_training(data, model_config, config, smoke_root, device='cuda',
141
+ model_factory=factory, max_session_steps=5, max_session_seconds=300)
142
+ second = core.run_training(data, model_config, config, smoke_root, device='cuda',
143
+ model_factory=factory, max_session_steps=5, max_session_seconds=300)
144
+ if (first['step'] != 5 or second['step'] != 10 or second['token_count'] != 163840
145
+ or second['resumed_from']['step'] != 5):
146
+ raise RuntimeError('Expanded-data/new-configuration smoke continuation failed')
147
+ smoke = {'status': 'passed', 'first': first, 'second': second,
148
+ 'campaign_exposures_added': 0, 'scope': 'Disposable real-data configuration/resume check.'}
149
+ write_json(info / 'stage-smoke.json', smoke)
150
+ print(json.dumps({'event': 'stage_smoke', **smoke}, indent=2), flush=True)
151
+ gc.collect()
152
+ torch.cuda.empty_cache()
153
+ if smoke_only:
154
+ return smoke
155
+ snapshots = math.ceil(seconds / 1800) + 1
156
+ required = snapshots * (parent_bytes + 16 * 1024**2) + 1024**3
157
+ free = shutil.disk_usage(root).free
158
+ if free < required:
159
+ raise RuntimeError(f'Insufficient cumulative-write quota: need {required}, free {free}')
160
+ session_id = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') + '-' + uuid.uuid4().hex[:12]
161
+ write_json(info / ('stage-intent-' + session_id + '.json'),
162
+ {'session_id': session_id, 'lineage_sha256': lineage_sha,
163
+ 'session_bound_seconds': seconds, 'required_write_bytes': required, 'free_bytes': free})
164
+ phase['main'] = True
165
+ started = time.perf_counter()
166
+ summary = core.run_training(data, model_config, config, root, device='cuda',
167
+ model_factory=factory, max_session_seconds=seconds, allow_environment_change=False)
168
+ final = load_latest(root)
169
+ if final is None or final[0]['step'] != summary['step']:
170
+ raise RuntimeError('Final stage checkpoint did not reload')
171
+ total = campaign_tokens(final[0]['token_count'])
172
+ backup = Path(tempfile.mkdtemp(prefix='stage2-final-', dir='/content'))
173
+ for name in ('checkpoint.pt', 'manifest.json', 'READY'):
174
+ shutil.copyfile(Path(final[1]['path']) / name, backup / name)
175
+ receipt = {'format': 'pear15-stage-session-completion-v1', 'session_id': session_id,
176
+ 'timestamp': datetime.now(timezone.utc).isoformat(), 'lineage': lineage,
177
+ 'lineage_sha256': lineage_sha, 'summary': summary, 'checkpoint': final[1],
178
+ 'campaign_token_count': total, 'remaining_campaign_tokens': max(0, TARGET - total),
179
+ 'campaign_complete': total >= TARGET,
180
+ 'training_session_completed': summary['status'] in {'session_seconds', 'completed'},
181
+ 'wall_seconds': time.perf_counter() - started, 'ssd_backup': str(backup)}
182
+ write_json(info / ('stage-completion-' + session_id + '.json'), receipt)
183
+ write_json(info / 'stage-latest-completion.json', receipt)
184
+ write_json(backup / 'stage-receipt.json', receipt)
185
+ print(json.dumps(receipt, indent=2), flush=True)
186
+ del final
187
+ from google.colab import drive
188
+ drive.flush_and_unmount(timeout_ms=600000)
189
+ print('STAGE_DRIVE_FLUSH_ACKNOWLEDGED', flush=True)
190
+ if release_runtime:
191
+ from google.colab import runtime
192
+ runtime.unassign()
193
+ return receipt
194
+ finally:
195
+ logger.removeHandler(progress)
196
+
197
+
198
+ def main():
199
+ parser = argparse.ArgumentParser(description=__doc__)
200
+ parser.add_argument('--parent-root', type=Path, required=True)
201
+ parser.add_argument('--stage-root', type=Path, required=True)
202
+ parser.add_argument('--data', type=Path, required=True)
203
+ parser.add_argument('--seconds', type=int, default=7200)
204
+ parser.add_argument('--smoke-first', action='store_true')
205
+ parser.add_argument('--smoke-only', action='store_true')
206
+ parser.add_argument('--release-runtime', action='store_true')
207
+ args = parser.parse_args()
208
+ run(args.parent_root, args.stage_root, args.data, seconds=args.seconds,
209
+ smoke_first=args.smoke_first, smoke_only=args.smoke_only, release_runtime=args.release_runtime)
210
+
211
+
212
+ if __name__ == '__main__':
213
+ main()