Text Generation
PyTorch
English
Supernova-tinyArc / src /generate.py
Supernova11c's picture
Publish Supernova-tinyArc Base v1
2d1f5a4 verified
Raw History Blame Contribute Delete
4.01 kB
import argparse
import json
from pathlib import Path
import torch
from tokenizers import Tokenizer
from model import SupernovaTinyArc
def sample_next_token(logits, temperature=0.8, top_k=50, top_p=0.9):
if temperature <= 0:
return torch.argmax(logits, dim=-1, keepdim=True)
logits = logits / temperature
if top_k > 0:
k = min(top_k, logits.size(-1))
threshold = torch.topk(logits, k).values[..., -1, None]
logits = logits.masked_fill(logits < threshold, float("-inf"))
if 0 < top_p < 1:
sorted_logits, sorted_indices = torch.sort(
logits, descending=True, dim=-1
)
cumulative_probs = torch.softmax(
sorted_logits, dim=-1
).cumsum(dim=-1)
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[..., 1:] = (
sorted_indices_to_remove[..., :-1].clone()
)
sorted_indices_to_remove[..., 0] = False
indices_to_remove = torch.zeros_like(
logits, dtype=torch.bool
)
indices_to_remove.scatter_(
-1, sorted_indices, sorted_indices_to_remove
)
logits = logits.masked_fill(
indices_to_remove, float("-inf")
)
probabilities = torch.softmax(logits, dim=-1)
return torch.multinomial(probabilities, num_samples=1)
def generate(
model,
tokenizer,
prompt,
device,
max_new_tokens=200,
temperature=0.8,
top_k=50,
top_p=0.9,
):
input_ids = tokenizer.encode(prompt).ids
if not input_ids:
raise ValueError("The prompt produced no tokens.")
ids = torch.tensor(
[input_ids], dtype=torch.long, device=device
)
eos_id = tokenizer.token_to_id("[EOS]")
max_seq_len = model.config["max_seq_len"]
model.eval()
with torch.no_grad():
for _ in range(max_new_tokens):
context = ids[:, -max_seq_len:]
logits, _ = model(context)
next_token = sample_next_token(
logits[:, -1, :],
temperature=temperature,
top_k=top_k,
top_p=top_p,
)
ids = torch.cat([ids, next_token], dim=1)
if eos_id is not None and next_token.item() == eos_id:
break
return tokenizer.decode(
ids[0].tolist(),
skip_special_tokens=True
)
def main():
parser = argparse.ArgumentParser(
description="Generate text with Supernova-tinyArc."
)
parser.add_argument("--prompt", required=True)
parser.add_argument("--checkpoint", default="checkpoints/base/best.pt")
parser.add_argument("--max-new-tokens", type=int, default=200)
parser.add_argument("--temperature", type=float, default=0.8)
parser.add_argument("--top-k", type=int, default=50)
parser.add_argument("--top-p", type=float, default=0.9)
parser.add_argument("--device", default=None)
args = parser.parse_args()
root = Path(__file__).resolve().parent
device = args.device or (
"cuda" if torch.cuda.is_available() else "cpu"
)
with open(root / "config/model.json", encoding="utf-8") as f:
config = json.load(f)
tokenizer = Tokenizer.from_file(
str(root / "tokenizer/tokenizer.json")
)
checkpoint_path = Path(args.checkpoint)
if not checkpoint_path.is_absolute():
checkpoint_path = root / checkpoint_path
checkpoint = torch.load(
checkpoint_path,
map_location="cpu",
weights_only=False,
)
model = SupernovaTinyArc(config)
model.load_state_dict(checkpoint["model"], strict=True)
model.to(device)
model.eval()
print(generate(
model=model,
tokenizer=tokenizer,
prompt=args.prompt,
device=device,
max_new_tokens=args.max_new_tokens,
temperature=args.temperature,
top_k=args.top_k,
top_p=args.top_p,
))
if __name__ == "__main__":
main()