Download masked.py from Valeztiro/Micro-llm: direct link, hf CLI and curl.
- Browser
- Download file 7.48 kB
-
https://huggingface.co/Valeztiro/Micro-llm/resolve/main/masked.py
- Command line
-
hf download hf://Valeztiro/Micro-llm/masked.py
-
curl -L -o masked.py https://huggingface.co/Valeztiro/Micro-llm/resolve/main/masked.py
7.48 kB
| """Run optional masked-token adaptation on the existing No Robots checkpoint.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| import torch | |
| from tokenizers import Tokenizer | |
| from tqdm import tqdm | |
| from model import GPT, GPTConfig | |
| from train import ( | |
| MemmapBatchLoader, | |
| append_training_note, | |
| autocast_context, | |
| make_masked_batch, | |
| make_optimizer, | |
| save_checkpoint, | |
| ) | |
| PROJECT_DIR = Path(__file__).resolve().parent | |
| def estimate_masked_loss( | |
| model: GPT, | |
| loader: MemmapBatchLoader, | |
| device: torch.device, | |
| iterations: int, | |
| mask_token_id: int, | |
| mask_probability: float, | |
| ) -> float: | |
| model.eval() | |
| losses = torch.empty(iterations, device="cpu") | |
| with torch.no_grad(): | |
| for index in range(iterations): | |
| inputs, _ = loader.next_batch() | |
| corrupted, labels = make_masked_batch( | |
| inputs, mask_token_id, model.config.vocab_size, mask_probability | |
| ) | |
| with autocast_context(device): | |
| _, loss = model(corrupted, labels, causal=False) | |
| losses[index] = loss.item() | |
| model.train() | |
| return losses.mean().item() | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--checkpoint", type=Path, default=PROJECT_DIR / "agent-checkpoints" / "latest.pt") | |
| parser.add_argument("--data-dir", type=Path, default=PROJECT_DIR / "agent-data") | |
| parser.add_argument("--tokenizer", type=Path, default=PROJECT_DIR / "agent-tokenizer.json") | |
| parser.add_argument("--steps", type=int, default=500, help="additional masked updates") | |
| parser.add_argument("--batch-size", type=int, default=4) | |
| parser.add_argument("--gradient-accumulation", type=int, default=4) | |
| parser.add_argument("--mask-probability", type=float, default=0.15) | |
| parser.add_argument("--learning-rate", type=float, default=1e-5) | |
| parser.add_argument("--eval-every", type=int, default=100) | |
| parser.add_argument("--eval-batches", type=int, default=10) | |
| parser.add_argument("--device", choices=("auto", "cuda", "cpu"), default="auto") | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| for name in ("checkpoint", "data_dir", "tokenizer"): | |
| path = getattr(args, name) | |
| if not path.is_absolute(): | |
| setattr(args, name, (Path.cwd() / path).resolve()) | |
| if args.steps < 1 or args.batch_size < 1 or args.gradient_accumulation < 1: | |
| raise SystemExit("steps, batch-size, and gradient-accumulation must be positive") | |
| if args.eval_every < 1 or args.eval_batches < 1: | |
| raise SystemExit("eval-every and eval-batches must be positive") | |
| if not 0.0 < args.mask_probability < 1.0 or args.learning_rate <= 0: | |
| raise SystemExit("mask-probability must be between 0 and 1 and learning-rate must be positive") | |
| if args.device == "cuda" and not torch.cuda.is_available(): | |
| raise SystemExit("CUDA was requested but is not available") | |
| if not args.checkpoint.is_file(): | |
| raise FileNotFoundError(f"Checkpoint not found: {args.checkpoint}; run train.py first") | |
| if not args.tokenizer.is_file(): | |
| raise FileNotFoundError(f"Tokenizer not found: {args.tokenizer}") | |
| manifest_path = args.data_dir / "dataset.json" | |
| try: | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| except (OSError, json.JSONDecodeError): | |
| manifest = None | |
| expected_manifest = { | |
| "dataset": "HuggingFaceH4/no_robots", | |
| "train_split": "train", | |
| "validation_split": "test", | |
| } | |
| if ( | |
| manifest != expected_manifest | |
| or not (args.data_dir / "train.bin").is_file() | |
| or not (args.data_dir / "val.bin").is_file() | |
| ): | |
| subprocess.run( | |
| [ | |
| sys.executable, | |
| str(PROJECT_DIR / "prepare_data.py"), | |
| "--tokenizer", | |
| str(args.tokenizer), | |
| "--output-dir", | |
| str(args.data_dir), | |
| "--dataset", | |
| "HuggingFaceH4/no_robots", | |
| "--train-split", | |
| "train", | |
| "--validation-split", | |
| "test", | |
| ], | |
| cwd=PROJECT_DIR, | |
| check=True, | |
| ) | |
| device = torch.device( | |
| "cuda" if args.device == "cuda" or (args.device == "auto" and torch.cuda.is_available()) else "cpu" | |
| ) | |
| checkpoint = torch.load(args.checkpoint, map_location=device, weights_only=False) | |
| config = GPTConfig(**checkpoint["config"]) | |
| model = GPT(config).to(device) | |
| model.load_state_dict(checkpoint["model"]) | |
| optimizer = make_optimizer(model, weight_decay=0.1) | |
| if checkpoint.get("optimizer"): | |
| optimizer.load_state_dict(checkpoint["optimizer"]) | |
| for group in optimizer.param_groups: | |
| group["lr"] = args.learning_rate | |
| scaler = torch.amp.GradScaler("cuda", enabled=device.type == "cuda") | |
| if checkpoint.get("scaler"): | |
| scaler.load_state_dict(checkpoint["scaler"]) | |
| start_step = int(checkpoint.get("step", 0)) | |
| best_val_loss = float(checkpoint.get("best_val_loss", float("inf"))) | |
| tokenizer = Tokenizer.from_file(str(args.tokenizer)) | |
| mask_token_id = tokenizer.token_to_id("<|unk|>") | |
| if mask_token_id is None: | |
| raise ValueError("Tokenizer must contain <|unk|> as the mask placeholder") | |
| train_loader = MemmapBatchLoader( | |
| args.data_dir / "train.bin", args.batch_size, config.context_length, device | |
| ) | |
| val_loader = MemmapBatchLoader( | |
| args.data_dir / "val.bin", args.batch_size, config.context_length, device | |
| ) | |
| notes_path = args.checkpoint.parent / "training-notes.md" | |
| append_training_note( | |
| notes_path, | |
| "Masked adaptation", | |
| f"- Starting checkpoint: `{args.checkpoint}` at step {start_step:,}\n" | |
| f"- Dataset: `HuggingFaceH4/no_robots`\n" | |
| f"- Additional updates: {args.steps:,}; mask probability: {args.mask_probability:.0%}\n" | |
| f"- Learning rate: {args.learning_rate:.2g}; device: `{device}`\n" | |
| "- The existing checkpoint is loaded and `latest.pt` is overwritten; no fresh initialization.", | |
| ) | |
| model.train() | |
| progress = tqdm(range(1, args.steps + 1), total=args.steps, desc="Masked adaptation") | |
| completed_step = start_step | |
| try: | |
| for update in progress: | |
| optimizer.zero_grad(set_to_none=True) | |
| loss_value = 0.0 | |
| for _ in range(args.gradient_accumulation): | |
| inputs, _ = train_loader.next_batch() | |
| corrupted, labels = make_masked_batch( | |
| inputs, mask_token_id, config.vocab_size, args.mask_probability | |
| ) | |
| with autocast_context(device): | |
| _, loss = model(corrupted, labels, causal=False) | |
| loss_value += loss.detach().float().item() / args.gradient_accumulation | |
| scaler.scale(loss / args.gradient_accumulation).backward() | |
| scaler.unscale_(optimizer) | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| scaler.step(optimizer) | |
| scaler.update() | |
| completed_step = start_step + update | |
| progress.set_postfix(loss=f"{loss_value:.4f}", step=completed_step) | |
| if update % args.eval_every == 0 or update == args.steps: | |
| val_loss = estimate_masked_loss( | |
| model, | |
| val_loader, | |
| device, | |
| args.eval_batches, | |
| mask_token_id, | |
| args.mask_probability, | |
| ) | |
| save_checkpoint( | |
| args.checkpoint, model, optimizer, scaler, completed_step, best_val_loss | |
| ) | |
| append_training_note( | |
| notes_path, | |
| f"Masked step {completed_step:,}", | |
| f"- Training loss: {loss_value:.6f}\n" | |
| f"- Masked validation loss: {val_loss:.6f}\n" | |
| f"- Checkpoint overwritten: `{args.checkpoint.name}`", | |
| ) | |
| except KeyboardInterrupt: | |
| save_checkpoint(args.checkpoint, model, optimizer, scaler, completed_step, best_val_loss) | |
| append_training_note( | |
| notes_path, | |
| "Masked adaptation interrupted", | |
| f"- Saved step: {completed_step:,}\n- Checkpoint overwritten: `{args.checkpoint.name}`", | |
| ) | |
| print(f"Interrupted; saved {args.checkpoint} at step {completed_step:,}") | |
| finally: | |
| progress.close() | |
| if __name__ == "__main__": | |
| main() | |