File size: 2,152 Bytes
7f1e014 | 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 | """Load the published weights (model.safetensors) and generate a sample.
Requires torch + safetensors + tiktoken. Run from the repo root:
python scripts/load_pretrained.py --prompt "Once upon a time"
The architecture is custom, so the model is built from the included `src/`
package (not `transformers.AutoModelForCausalLM`).
"""
import argparse
import json
import sys
from pathlib import Path
import torch
from safetensors.torch import load_file
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from src.config import ModelConfig # noqa: E402
from src.model import GPT # noqa: E402
from src.tokenizer import Tokenizer # noqa: E402
def load_model(weights_path: str, config_path: str, device: torch.device):
raw = json.load(open(config_path, encoding="utf-8"))["model"]
raw.pop("d_head", None) # derived in ModelConfig.__post_init__
model = GPT(ModelConfig(**raw))
model.load_state_dict(load_file(weights_path))
model.to(device)
model.eval()
if device.type == "cuda":
model = model.to(torch.bfloat16)
return model
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--weights", default=str(ROOT / "model.safetensors"))
ap.add_argument("--train-config", default=str(ROOT / "training_config.json"))
ap.add_argument("--prompt", default="Once upon a time")
ap.add_argument("--max-new-tokens", type=int, default=200)
ap.add_argument("--temperature", type=float, default=0.8)
ap.add_argument("--top-k", type=int, default=40)
ap.add_argument("--seed", type=int, default=42)
args = ap.parse_args()
torch.manual_seed(args.seed)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = load_model(args.weights, args.train_config, device)
tokenizer = Tokenizer()
input_ids = torch.tensor([tokenizer.encode(args.prompt)], device=device)
output_ids = model.generate(
input_ids,
max_new_tokens=args.max_new_tokens,
temperature=args.temperature,
top_k=args.top_k,
)
print(tokenizer.decode(output_ids[0].tolist()))
if __name__ == "__main__":
main()
|