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86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#!/usr/bin/env python3
"""Hardware-agnostic Pear1.5 training script.

Auto-detects hardware (CUDA/TPU/CPU), configures optimal settings,
and runs training. Can resume from ANY checkpoint regardless of origin hardware.

Usage:
    python train_agnostic.py --data-path /path/to/data --output-dir /path/to/checkpoints
    python train_agnostic.py --data-path /path/to/data --output-dir /path/to/checkpoints --resume-from step_88587
    python train_agnostic.py --data-path /path/to/data --output-dir /path/to/checkpoints --resume-from /path/to/checkpoint.pt
"""
import argparse
import json
import math
import os
import sys
import time
import hashlib
from pathlib import Path
from typing import Optional, Dict, Any

import torch
import torch.nn as nn
from torch.utils.data import DataLoader

# Import hardware detection
sys.path.insert(0, str(Path(__file__).parent))
from hardware import get_hardware_info, get_training_config, HardwareInfo, DeviceType

# Constants
PARENT_STEP = 18666
PARENT_TOKENS = 1_739_227_136
TOKENS_PER_STEP = 16_384
TARGET = 50_000_000_000
DATA_FP = '03b6dc7f4e70ae679d84da9407dafaaf6b9e0abb79634ef9b95a34044397a553'
IMPLEMENTATION_FP = 'ef9af3b58d70b42a123ba689f4d88de267cbac4c2ba1eae2838bdb57d2b8a36d'

# Model constants (for reference)
VOCAB = 49152
HIDDEN = 576
LAYERS = 30
HEADS = 9
KV_HEADS = 3


def build_model(config: Dict[str, Any]) -> nn.Module:
    """Build Llama model from config dict."""
    from transformers import LlamaConfig, LlamaForCausalLM
    
    llama_config = LlamaConfig(
        vocab_size=config["vocab_size"],
        hidden_size=config["hidden_size"],
        num_hidden_layers=config["num_hidden_layers"],
        num_attention_heads=config["num_attention_heads"],
        num_key_value_heads=config["num_key_value_heads"],
        max_position_embeddings=config["max_position_embeddings"],
        rope_theta=config.get("rope_theta", 10000.0),
        tie_word_embeddings=config.get("tie_word_embeddings", True),
        hidden_act="silu",
        initializer_range=0.02,
        rms_norm_eps=1e-5,
        use_cache=False,  # Required for gradient checkpointing
    )
    model = LlamaForCausalLM(llama_config)
    return model


def load_checkpoint(model: nn.Module, optimizer, scheduler, ckpt_path: Path, device) -> Dict:
    """Load checkpoint from any hardware origin. Returns training state."""
    print(f"Loading checkpoint from {ckpt_path}")
    payload = torch.load(ckpt_path, map_location="cpu", weights_only=True)
    
    # Load model weights
    model.load_state_dict(payload["model"], strict=True)
    
    # Load optimizer/scheduler if present
    if optimizer and "optimizer" in payload:
        optimizer.load_state_dict(payload["optimizer"])
    if scheduler and "scheduler" in payload and payload["scheduler"]:
        scheduler.load_state_dict(payload["scheduler"])
    
    # Move model to device
    model.to(device)
    
    # Extract training state
    state = {
        "step": payload.get("step", 0),
        "token_count": payload.get("token_count", 0),
        "data_cursor": payload.get("data_cursor", {"epoch": 0, "offset_tokens": 0}),
    }
    
    print(f"Resumed from step {state['step']}, tokens {state['token_count']:,}")
    return state


def save_checkpoint(model, optimizer, scheduler, step: int, token_count: int, 
                    data_cursor: Dict, config: Dict, output_dir: Path, 
                    is_final: bool = False, hw: HardwareInfo = None) -> Path:
    """Save checkpoint in hardware-agnostic format."""
    output_dir.mkdir(parents=True, exist_ok=True)
    
    payload = {
        "model": model.state_dict(),
        "optimizer": optimizer.state_dict() if optimizer else None,
        "scheduler": scheduler.state_dict() if scheduler else None,
        "step": step,
        "token_count": token_count,
        "data_cursor": data_cursor,
        "model_config": {
            "model_type": config["model_type"],
            "vocab_size": config["vocab_size"],
            "hidden_size": config["hidden_size"],
            "num_hidden_layers": config["num_hidden_layers"],
            "num_attention_heads": config["num_attention_heads"],
            "num_key_value_heads": config["num_key_value_heads"],
            "max_position_embeddings": config["max_position_embeddings"],
            "tie_word_embeddings": config.get("tie_word_embeddings", True),
        },
        "training_config": {k: v for k, v in config.items() 
                           if k not in ["model_type", "vocab_size", "hidden_size", 
                                       "num_hidden_layers", "num_attention_heads", 
                                       "num_key_value_heads", "max_position_embeddings",
                                       "tie_word_embeddings"]},
        "hardware_origin": {
            "device_type": hw.device_type.value if hw else "unknown",
            "variant": hw.variant if hw else "unknown",
            "num_devices": hw.num_devices if hw else 1,
        } if hw else {},
        "identity": {
            "implementation_fingerprint": IMPLEMENTATION_FP,
            "dataset_fingerprint": DATA_FP,
            "model_fingerprint": "",  # TODO: compute
        },
        "rng": {
            "torch": torch.get_rng_state(),
            "cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None,
        },
    }
    
    step_str = f"step_{step:012d}"
    ckpt_dir = output_dir / step_str
    ckpt_dir.mkdir(parents=True, exist_ok=True)
    
    ckpt_path = ckpt_dir / "checkpoint.pt"
    torch.save(payload, ckpt_path)
    
    # Manifest
    manifest = {
        "format": "pear15.cloud_checkpoint.v1",
        "file": "checkpoint.pt",
        "sha256": hashlib.sha256(ckpt_path.read_bytes()).hexdigest(),
        "bytes": ckpt_path.stat().st_size,
        "step": step,
        "created_ns": time.time_ns(),
        "id": hashlib.sha256(f"{step}{time.time_ns()}".encode()).hexdigest()[:32],
    }
    (ckpt_dir / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True))
    
    # READY marker
    ready = b"pear15.cloud_checkpoint.v1\n" + manifest["sha256"].encode() + b"\n"
    (ckpt_dir / "READY").write_bytes(ready)
    
    print(f"Saved checkpoint: {ckpt_dir}")
    return ckpt_dir


def get_dataloader(data_path: Path, config: Dict, device, hw: HardwareInfo):
    """Get DataLoader for the detected hardware.
    
    REPLACE THIS with your actual data loader from pear15.scratch_data
    """
    # For now, use a dummy loader - REPLACE WITH REAL DATA
    from torch.utils.data import DataLoader, TensorDataset, IterableDataset
    
    class DummyIterableDataset(IterableDataset):
        def __iter__(self):
            while True:
                input_ids = torch.randint(0, VOCAB, (config["batch_size"], config["sequence_length"]), dtype=torch.long)
                labels = input_ids.clone()
                yield input_ids, labels
    
    dataset = DummyIterableDataset()
    loader = DataLoader(dataset, batch_size=None, num_workers=0)
    
    if hw.device_type == DeviceType.TPU:
        import torch_xla.distributed.parallel_loader as pl
        return pl.MpDeviceLoader(loader, device)
    elif hw.device_type == DeviceType.CUDA and hw.num_devices > 1:
        # DDP handled separately
        return loader
    return loader


def train_loop(model, optimizer, scheduler, dataloader, device, config, 
               start_state, output_dir, hw, max_steps=None):
    """Main training loop."""
    model.train()
    
    step = start_state["step"]
    token_count = start_state["token_count"]
    data_cursor = start_state["data_cursor"]
    
    total_steps = config["total_steps"] if max_steps is None else min(config["total_steps"], start_state["step"] + max_steps)
    grad_accum = config["gradient_accumulation_steps"]
    log_interval = config["log_interval_steps"]
    ckpt_interval = config["checkpoint_interval_steps"]
    ckpt_interval_sec = config["checkpoint_interval_seconds"]
    
    optimizer.zero_grad()
    accumulated_loss = 0.0
    last_ckpt_time = time.time()
    
    print(f"Starting training from step {step} to {total_steps}")
    print(f"Device: {device}, Hardware: {hw.variant}, Effective batch: {hw.effective_batch}")
    
    # For TPU
    is_tpu = hw.device_type == DeviceType.TPU
    if is_tpu:
        import torch_xla.core.xla_model as xm
    
    for epoch in range(10000):  # Large number, controlled by total_steps
        for batch_idx, (input_ids, labels) in enumerate(dataloader):
            if step >= total_steps:
                break
            
            input_ids = input_ids.to(device, non_blocking=True)
            labels = labels.to(device, non_blocking=True)
            
            # Forward
            outputs = model(input_ids=input_ids, labels=labels)
            loss = outputs.loss / grad_accum
            
            # Backward
            loss.backward()
            accumulated_loss += loss.item()
            
            # Optimizer step
            if (batch_idx + 1) % grad_accum == 0:
                # Gradient clipping
                torch.nn.utils.clip_grad_norm_(model.parameters(), config["max_grad_norm"])
                
                if is_tpu:
                    import torch_xla.core.xla_model as xm
                    xm.optimizer_step(optimizer)
                else:
                    optimizer.step()
                
                scheduler.step()
                optimizer.zero_grad()
                
                step += 1
                token_count += TOKENS_PER_STEP
                
                # Logging
                if step % log_interval == 0:
                    avg_loss = accumulated_loss / log_interval
                    lr = scheduler.get_last_lr()[0]
                    print(f"step {step:,} | tokens {token_count:,} | loss {avg_loss:.4f} | lr {lr:.2e}")
                    accumulated_loss = 0.0
                
                # Checkpoint (step-based)
                if step % ckpt_interval == 0:
                    data_cursor = {"epoch": epoch, "offset_tokens": token_count % 997_885_340}
                    save_checkpoint(model, optimizer, scheduler, step, token_count,
                                   data_cursor, config, output_dir, hw=hw)
                    last_ckpt_time = time.time()
                
                # Checkpoint (time-based)
                if time.time() - last_ckpt_time >= ckpt_interval_sec:
                    data_cursor = {"epoch": epoch, "offset_tokens": token_count % 997_885_340}
                    save_checkpoint(model, optimizer, scheduler, step, token_count,
                                   data_cursor, config, output_dir, hw=hw)
                    last_ckpt_time = time.time()
        
        if step >= total_steps:
            break
    
    # Final checkpoint
    data_cursor = {"epoch": epoch, "offset_tokens": token_count % 997_885_340}
    save_checkpoint(model, optimizer, scheduler, step, token_count,
                   data_cursor, config, output_dir, is_final=True, hw=hw)
    
    if is_tpu:
        import torch_xla.core.xla_model as xm
        xm.wait_device_ops()
    
    return step, token_count


def setup_device(hw: HardwareInfo):
    """Setup device for training."""
    if hw.device_type == DeviceType.CUDA:
        if hw.num_devices > 1:
            # DDP setup
            import torch.distributed as dist
            dist.init_process_group(backend="nccl")
            local_rank = int(os.environ.get("LOCAL_RANK", 0))
            device = torch.device(f"cuda:{local_rank}")
            torch.cuda.set_device(device)
        else:
            device = torch.device("cuda:0")
        # Enable TF32 for Ampere+
        if hw.supports_bf16:
            torch.backends.cuda.matmul.allow_tf32 = True
            torch.backends.cudnn.allow_tf32 = True
    
    elif hw.device_type == DeviceType.TPU:
        import torch_xla.core.xla_model as xm
        device = xm.xla_device()
        os.environ["PJRT_DEVICE"] = "TPU"
        os.environ["XLA_USE_BF16"] = "1"
    
    else:
        device = torch.device("cpu")
    
    return device


def setup_optimizer(model, config):
    """Setup optimizer and scheduler."""
    optimizer = torch.optim.AdamW(
        model.parameters(),
        lr=config["learning_rate"],
        betas=(config["adam_beta1"], config["adam_beta2"]),
        eps=config["adam_epsilon"],
        weight_decay=config["weight_decay"],
    )
    
    total_steps = config["total_steps"]
    warmup_steps = config["warmup_steps"]
    min_lr_ratio = config["min_lr_ratio"]
    
    def lr_lambda(current_step):
        if current_step < warmup_steps:
            return float(current_step + 1) / float(max(1, warmup_steps))
        progress = float(current_step - warmup_steps) / float(max(1, total_steps - warmup_steps))
        return max(min_lr_ratio, 1.0 - progress * (1.0 - min_lr_ratio))
    
    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
    return optimizer, scheduler


def main():
    parser = argparse.ArgumentParser(description="Hardware-agnostic Pear1.5 training")
    parser.add_argument("--data-path", type=Path, required=True, help="Path to expanded dataset")
    parser.add_argument("--output-dir", type=Path, required=True, help="Checkpoint output directory")
    parser.add_argument("--resume-from", type=str, default=None, 
                        help="Resume from checkpoint (step number, 'latest', or path)")
    parser.add_argument("--max-steps", type=int, default=None, help="Max steps to run")
    parser.add_argument("--hf-model-path", type=Path, default=None, 
                        help="HF model path for fresh init (if not resuming)")
    parser.add_argument("--seed", type=int, default=0)
    args = parser.parse_args()
    
    torch.manual_seed(args.seed)
    
    # Detect hardware
    hw = get_hardware_info()
    config = get_training_config(hw)
    
    # Setup device
    device = setup_device(hw)
    
    # Build or load model
    if args.resume_from:
        # Resume from checkpoint
        model = build_model(config)
        optimizer, scheduler = setup_optimizer(model, config)
        
        if args.resume_from == "latest":
            # Find latest checkpoint in output_dir
            ckpts = sorted(args.output_dir.glob("step_*/checkpoint.pt"))
            if not ckpts:
                raise ValueError("No checkpoints found to resume from")
            ckpt_path = ckpts[-1]
        elif args.resume_from.isdigit():
            # Step number
            step = int(args.resume_from)
            ckpt_path = args.output_dir / f"step_{step:012d}" / "checkpoint.pt"
        else:
            ckpt_path = Path(args.resume_from)
        
        start_state = load_checkpoint(model, optimizer, scheduler, ckpt_path, device)
    
    else:
        # Fresh init from HF model or scratch
        if args.hf_model_path:
            from transformers import AutoModelForCausalLM
            print(f"Loading from HF model: {args.hf_model_path}")
            model = AutoModelForCausalLM.from_pretrained(
                args.hf_model_path, torch_dtype=torch.bfloat16 if hw.supports_bf16 else torch.float32, use_cache=False
            )
        else:
            model = build_model(config)
        
        model.gradient_checkpointing_enable()
        model.to(device)
        
        optimizer, scheduler = setup_optimizer(model, config)
        start_state = {"step": 0, "token_count": 0, "data_cursor": {"epoch": 0, "offset_tokens": 0}}
    
    # DDP wrap for multi-GPU
    if hw.device_type == DeviceType.CUDA and hw.num_devices > 1:
        model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[device.index])
    
    # Data loader
    dataloader = get_dataloader(args.data_path, config, device, hw)
    
    # Train
    final_step, final_tokens = train_loop(
        model, optimizer, scheduler, dataloader, device, config,
        start_state, args.output_dir, hw, max_steps=args.max_steps
    )
    
    print(f"Training complete: step {final_step}, tokens {final_tokens:,}")


if __name__ == "__main__":
    main()