dkumar15 commited on
Commit
a19b01b
·
verified ·
1 Parent(s): 5200189

Upload training_code/inference.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. training_code/inference.py +134 -0
training_code/inference.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference script for the 1B Transformer — Single GPU.
3
+
4
+ Usage:
5
+ python inference.py # auto-finds latest checkpoint
6
+ python inference.py /path/to/checkpoint.pt # specific checkpoint
7
+ """
8
+
9
+ import sys
10
+ import os
11
+ import glob
12
+ import time
13
+ import torch
14
+ import torch.nn.functional as F
15
+
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ from model.config import ModelConfig
18
+ from model.transformer import Transformer
19
+ from model.data import get_tokenizer
20
+
21
+
22
+ def find_latest_checkpoint(checkpoint_dir="/jfs/deepak-kumar/checkpoints"):
23
+ files = glob.glob(os.path.join(checkpoint_dir, "step_*.pt"))
24
+ if not files:
25
+ final = os.path.join(checkpoint_dir, "final.pt")
26
+ return final if os.path.exists(final) else None
27
+ return max(files, key=lambda f: int(os.path.basename(f).split("_")[1].split(".")[0]))
28
+
29
+
30
+ def load_model(checkpoint_path, device="cuda:0"):
31
+ config = ModelConfig()
32
+ model = Transformer(config)
33
+
34
+ print(f"Loading checkpoint: {checkpoint_path}")
35
+ ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
36
+ model.load_state_dict(ckpt["model"])
37
+ model = model.to(device).bfloat16().eval()
38
+
39
+ step = ckpt.get("step", "?")
40
+ loss = ckpt.get("loss", "?")
41
+ print(f" Step: {step} | Loss: {loss}")
42
+ print(f" Params: {sum(p.numel() for p in model.parameters()):,}")
43
+ print(f" Device: {device}")
44
+ del ckpt
45
+ torch.cuda.empty_cache()
46
+ return model, config
47
+
48
+
49
+ @torch.no_grad()
50
+ def generate(model, tokenizer, prompt, max_new_tokens=200,
51
+ temperature=0.8, top_k=50, top_p=0.9, device="cuda:0"):
52
+ input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)
53
+ t0 = time.time()
54
+
55
+ for i in range(max_new_tokens):
56
+ if input_ids.shape[1] >= model.config.max_seq_len:
57
+ break
58
+
59
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
60
+ logits, _ = model(input_ids)
61
+
62
+ logits = logits[:, -1, :] / temperature
63
+
64
+ if top_k > 0:
65
+ topk_vals, _ = torch.topk(logits, top_k)
66
+ logits[logits < topk_vals[:, -1:]] = float("-inf")
67
+
68
+ if top_p < 1.0:
69
+ sorted_logits, sorted_idx = torch.sort(logits, descending=True)
70
+ cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
71
+ mask = cum_probs - F.softmax(sorted_logits, dim=-1) >= top_p
72
+ sorted_logits[mask] = float("-inf")
73
+ logits = sorted_logits.scatter(1, sorted_idx, sorted_logits)
74
+
75
+ probs = F.softmax(logits, dim=-1)
76
+ next_token = torch.multinomial(probs, num_samples=1)
77
+
78
+ if next_token.item() == tokenizer.eos_token_id:
79
+ break
80
+
81
+ input_ids = torch.cat([input_ids, next_token], dim=1)
82
+
83
+ elapsed = time.time() - t0
84
+ gen_tokens = input_ids.shape[1] - len(tokenizer.encode(prompt))
85
+ tok_per_sec = gen_tokens / max(elapsed, 1e-9)
86
+
87
+ text = tokenizer.decode(input_ids[0], skip_special_tokens=True)
88
+ return text, gen_tokens, tok_per_sec
89
+
90
+
91
+ def main():
92
+ device = "cuda:0"
93
+ if len(sys.argv) > 1:
94
+ checkpoint = sys.argv[1]
95
+ else:
96
+ checkpoint = find_latest_checkpoint()
97
+ if checkpoint is None:
98
+ print("No checkpoint found!")
99
+ sys.exit(1)
100
+
101
+ model, config = load_model(checkpoint, device)
102
+ tokenizer = get_tokenizer()
103
+
104
+ prompts = [
105
+ "The meaning of life is",
106
+ "In machine learning, a neural network",
107
+ "The capital of France is",
108
+ "Once upon a time, there was a",
109
+ "To solve a quadratic equation, you need to",
110
+ "The theory of relativity explains that",
111
+ "Python is a programming language that",
112
+ "The sun rises in the east and",
113
+ ]
114
+
115
+ print("\n" + "=" * 70)
116
+ print(" INFERENCE — 1B Transformer (Single GPU)")
117
+ print("=" * 70)
118
+
119
+ for prompt in prompts:
120
+ print(f"\n{'─' * 60}")
121
+ print(f"PROMPT: {prompt}")
122
+ print(f"{'─' * 60}")
123
+ text, n_tok, tps = generate(model, tokenizer, prompt,
124
+ max_new_tokens=150, temperature=0.8,
125
+ top_k=50, device=device)
126
+ generated = text[len(prompt):]
127
+ print(f"OUTPUT:{generated}")
128
+ print(f" [{n_tok} tokens, {tps:.1f} tok/s]")
129
+
130
+ print("\n" + "=" * 70)
131
+
132
+
133
+ if __name__ == "__main__":
134
+ main()