Upload generate.py with huggingface_hub
Browse files- generate.py +45 -0
generate.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from train import TinyTransformerLM
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@torch.no_grad()
|
| 10 |
+
def generate(model, idx, max_new_tokens, temperature, itos):
|
| 11 |
+
model.eval()
|
| 12 |
+
for _ in range(max_new_tokens):
|
| 13 |
+
idx_cond = idx[:, -model.block_size :]
|
| 14 |
+
logits, _ = model(idx_cond)
|
| 15 |
+
logits = logits[:, -1, :] / temperature
|
| 16 |
+
probs = torch.softmax(logits, dim=-1)
|
| 17 |
+
next_id = torch.multinomial(probs, num_samples=1)
|
| 18 |
+
idx = torch.cat((idx, next_id), dim=1)
|
| 19 |
+
return "".join(itos[int(i)] for i in idx[0])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
parser = argparse.ArgumentParser()
|
| 24 |
+
parser.add_argument("--model", default="runs/tiny-char-model.pt")
|
| 25 |
+
parser.add_argument("--prompt", default="hello")
|
| 26 |
+
parser.add_argument("--tokens", type=int, default=400)
|
| 27 |
+
parser.add_argument("--temperature", type=float, default=0.8)
|
| 28 |
+
args = parser.parse_args()
|
| 29 |
+
|
| 30 |
+
checkpoint = torch.load(Path(args.model), map_location="cpu")
|
| 31 |
+
config = checkpoint["config"]
|
| 32 |
+
stoi = checkpoint["stoi"]
|
| 33 |
+
itos = {int(k): v for k, v in checkpoint["itos"].items()}
|
| 34 |
+
|
| 35 |
+
model = TinyTransformerLM(**config)
|
| 36 |
+
model.load_state_dict(checkpoint["model"])
|
| 37 |
+
|
| 38 |
+
fallback = next(iter(stoi.values()))
|
| 39 |
+
encoded = [stoi.get(ch, fallback) for ch in args.prompt]
|
| 40 |
+
idx = torch.tensor([encoded], dtype=torch.long)
|
| 41 |
+
print(generate(model, idx, args.tokens, args.temperature, itos))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
main()
|