File size: 10,363 Bytes
2e30a77 | 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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | import argparse
import random
from pathlib import Path
import torch
from model.sutra import SutraModel
from tokenizer import SutraTokenizerFast
# ============================================================
# NeemSutra-125M-Python-Instruct
# Reproducible inference script
# ============================================================
ROOT = Path(__file__).resolve().parent
CHECKPOINT = ROOT / "neemsutra_125m_python_instruct.pt"
TOKENIZER_DIR = ROOT
# Exact architecture of the released model
VOCAB_SIZE = 8000
CONTEXT_LENGTH = 256
D_MODEL = 768
N_LAYERS = 16
N_HEADS = 12
# Training used dropout, but inference must disable it.
DROPOUT = 0.0
def get_device(requested):
if requested == "cpu":
return torch.device("cpu")
if requested == "cuda":
if not torch.cuda.is_available():
raise RuntimeError("CUDA was requested but is not available.")
return torch.device("cuda")
if requested == "mps":
if not (
hasattr(torch.backends, "mps")
and torch.backends.mps.is_available()
):
raise RuntimeError("MPS was requested but is not available.")
return torch.device("mps")
# auto
if torch.cuda.is_available():
return torch.device("cuda")
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
def set_seed(seed):
random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def load_model(device):
if not CHECKPOINT.exists():
raise FileNotFoundError(
f"Checkpoint not found:\n{CHECKPOINT}"
)
model = SutraModel(
vocab_size=VOCAB_SIZE,
context_length=CONTEXT_LENGTH,
d_model=D_MODEL,
n_layers=N_LAYERS,
n_heads=N_HEADS,
dropout=DROPOUT,
)
checkpoint = torch.load(
CHECKPOINT,
map_location="cpu",
weights_only=False,
)
# --------------------------------------------------------
# Support common checkpoint formats
# --------------------------------------------------------
if isinstance(checkpoint, dict):
if "model_state_dict" in checkpoint:
state_dict = checkpoint["model_state_dict"]
elif "state_dict" in checkpoint:
state_dict = checkpoint["state_dict"]
elif "model" in checkpoint and isinstance(
checkpoint["model"], dict
):
state_dict = checkpoint["model"]
else:
# The checkpoint itself may be a state_dict.
state_dict = checkpoint
else:
raise RuntimeError(
f"Unsupported checkpoint type: {type(checkpoint)}"
)
# --------------------------------------------------------
# Remove DDP "module." prefix if present
# --------------------------------------------------------
cleaned_state_dict = {}
for key, value in state_dict.items():
if key.startswith("module."):
key = key[len("module."):]
cleaned_state_dict[key] = value
missing, unexpected = model.load_state_dict(
cleaned_state_dict,
strict=False,
)
if missing:
raise RuntimeError(
"Missing model parameters:\n"
+ "\n".join(missing)
)
if unexpected:
print(
"Warning: unexpected checkpoint parameters:"
)
for key in unexpected:
print(f" {key}")
model = model.to(device)
model.eval()
return model
def sample_top_k(logits, top_k):
if top_k <= 0:
return logits
k = min(top_k, logits.size(-1))
values, _ = torch.topk(logits, k)
threshold = values[..., -1, None]
return torch.where(
logits < threshold,
torch.full_like(logits, float("-inf")),
logits,
)
def sample_top_p(logits, top_p):
if top_p >= 1.0:
return logits
if top_p <= 0.0:
return logits
sorted_logits, sorted_indices = torch.sort(
logits,
descending=True,
)
probabilities = torch.softmax(
sorted_logits,
dim=-1,
)
cumulative_probabilities = torch.cumsum(
probabilities,
dim=-1,
)
remove = cumulative_probabilities > top_p
# Always retain the highest-probability token.
remove[..., 0] = False
sorted_logits = sorted_logits.masked_fill(
remove,
float("-inf"),
)
filtered = torch.full_like(logits, float("-inf"))
filtered.scatter_(
-1,
sorted_indices,
sorted_logits,
)
return filtered
@torch.no_grad()
def generate(
model,
tokenizer,
prompt,
max_new_tokens=40,
temperature=0.0,
top_k=0,
top_p=1.0,
seed=42,
):
set_seed(seed)
input_ids = tokenizer.encode(prompt)
if not input_ids:
raise ValueError("Prompt produced no tokens.")
if len(input_ids) > CONTEXT_LENGTH:
print(
f"Warning: prompt contains {len(input_ids)} tokens. "
f"Truncating to the last {CONTEXT_LENGTH} tokens."
)
input_ids = input_ids[-CONTEXT_LENGTH:]
tokens = torch.tensor(
[input_ids],
dtype=torch.long,
device=next(model.parameters()).device,
)
generated = list(input_ids)
eos_id = tokenizer.eos_token_id
for _ in range(max_new_tokens):
# Keep only the model's available context.
context = tokens[:, -CONTEXT_LENGTH:]
logits = model(context)
# Prediction for the final input position.
next_token_logits = logits[:, -1, :]
# ----------------------------------------------------
# Greedy / deterministic generation
# ----------------------------------------------------
if temperature <= 0.0:
next_token = torch.argmax(
next_token_logits,
dim=-1,
keepdim=True,
)
else:
scaled_logits = (
next_token_logits / temperature
)
scaled_logits = sample_top_k(
scaled_logits,
top_k,
)
scaled_logits = sample_top_p(
scaled_logits,
top_p,
)
probabilities = torch.softmax(
scaled_logits,
dim=-1,
)
next_token = torch.multinomial(
probabilities,
num_samples=1,
)
token_id = next_token.item()
generated.append(token_id)
# Append token for next iteration.
tokens = torch.cat(
[tokens, next_token],
dim=1,
)
if eos_id is not None and token_id == eos_id:
break
# Decode only the generated continuation.
continuation = generated[len(input_ids):]
return tokenizer.decode(
continuation,
skip_special_tokens=True,
)
def main():
parser = argparse.ArgumentParser(
description="NeemSutra-125M-Python-Instruct inference"
)
parser.add_argument(
"--prompt",
type=str,
required=True,
help="Input prompt.",
)
parser.add_argument(
"--max-new-tokens",
type=int,
default=40,
help="Maximum number of generated tokens.",
)
parser.add_argument(
"--temperature",
type=float,
default=0.0,
help="Sampling temperature. 0 = greedy/deterministic.",
)
parser.add_argument(
"--top-k",
type=int,
default=0,
help="Top-k sampling. 0 disables top-k.",
)
parser.add_argument(
"--top-p",
type=float,
default=1.0,
help="Nucleus sampling threshold.",
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="Random seed.",
)
parser.add_argument(
"--device",
choices=["auto", "cpu", "cuda", "mps"],
default="auto",
help="Inference device.",
)
args = parser.parse_args()
if args.max_new_tokens < 1:
raise ValueError(
"--max-new-tokens must be greater than 0."
)
if args.temperature < 0:
raise ValueError(
"--temperature cannot be negative."
)
if not 0 < args.top_p <= 1:
raise ValueError(
"--top-p must be in the range (0, 1]."
)
device = get_device(args.device)
print("=" * 70)
print(f"Checkpoint : {CHECKPOINT.name}")
print(f"Device : {device}")
print(f"Parameters : {sum(p.numel() for p in SutraModel(
VOCAB_SIZE, CONTEXT_LENGTH, D_MODEL, N_LAYERS, N_HEADS,
DROPOUT
).parameters()):,}")
print(f"Temperature: {args.temperature}")
print(f"Seed : {args.seed}")
print("=" * 70)
tokenizer = SutraTokenizerFast(
TOKENIZER_DIR
)
model = load_model(device)
parameter_count = sum(
p.numel() for p in model.parameters()
)
print("=" * 70)
print("NeemSutra-125M-Python-Instruct")
print("=" * 70)
print(f"Checkpoint : {CHECKPOINT.name}")
print(f"Device : {device}")
print(f"Parameters : {parameter_count:,}")
print(f"Temperature: {args.temperature}")
print(f"Seed : {args.seed}")
print("=" * 70)
print("\nPrompt:")
print(args.prompt)
output = generate(
model=model,
tokenizer=tokenizer,
prompt=args.prompt,
max_new_tokens=args.max_new_tokens,
temperature=args.temperature,
top_k=args.top_k,
top_p=args.top_p,
seed=args.seed,
)
print("\nGenerated:")
print("-" * 70)
print(output)
print("-" * 70)
if __name__ == "__main__":
main() |