Downloads Β· 30 days
0
cosmicshubham/next-word-predictor-lstm
next-word-predictor-lstm is a text generation model from cosmicshubham. Use it when you need the model to write or continue text. It is set up for pytorch. The card lists the license as mit.
π― A next word prediction model trained on WikiText-2 using LSTM architecture. Given a sequence of words, this model predicts the most likely next word.
Downloads Β· 30 days
0
Access
Public
Updated Jan 24, 2026
Repo size
137 MB
Likes
0
Public
Click a slice to open those files.
.pth136 MB Β· 100%
From the Hugging Face model README
π― A next word prediction model trained on WikiText-2 using LSTM architecture. Given a sequence of words, this model predicts the most likely next word.
| Metric | Score | Rank |
|---|---|---|
| Test Perplexity | 88.31 | π’ Good |
| BLEU Score | 0.2900 | π’ Competitive |
| Top-1 Accuracy | 0.2595 (25.95%) | π’ Strong |
| Top-5 Accuracy | 0.4857 (48.57%) | π’ Excellent |
| Top-10 Accuracy | 0.5677 (56.77%) | π’ Very Good |
| Mean Reciprocal Rank | 0.3643 | π’ Strong |
pip install torch huggingface_hub
import torch
import pickle
from huggingface_hub import hf_hub_download
# Download model files
model_path = hf_hub_download(
repo_id="cosmicshubham/next-word-predictor-lstm",
filename="best_model.pth"
)
tokenizer_path = hf_hub_download(
repo_id="cosmicshubham/next-word-predictor-lstm",
filename="tokenizer.pkl"
)
# Load tokenizer
with open(tokenizer_path, 'rb') as f:
tokenizer = pickle.load(f)
# Define model architecture
import torch.nn as nn
class NextWordLSTM(nn.Module):
def __init__(self, vocab_size, embedding_dim=256, hidden_dim=512,
num_layers=2, dropout=0.5):
super(NextWordLSTM, self).__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0)
self.embedding_dropout = nn.Dropout(0.2)
self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers,
batch_first=True,
dropout=dropout if num_layers > 1 else 0)
self.dropout = nn.Dropout(dropout)
self.fc = nn.Linear(hidden_dim, vocab_size)
def forward(self, x):
embedded = self.embedding(x)
embedded = self.embedding_dropout(embedded)
lstm_out, _ = self.lstm(embedded)
last_output = lstm_out[:, -1, :]
dropped = self.dropout(last_output)
output = self.fc(dropped)
return output
# Load model
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = NextWordLSTM(vocab_size=len(tokenizer.word2idx))
checkpoint = torch.load(model_path, map_location=device, weights_only=False)
model.load_state_dict(checkpoint['model_state_dict'])
model.to(device)
model.eval()
# Prediction function
def predict_next_word(text, top_k=5):
SEQ_LENGTH = 20
tokens = tokenizer.encode(text)
if len(tokens) < SEQ_LENGTH:
tokens = [0] * (SEQ_LENGTH - len(tokens)) + tokens
else:
tokens = tokens[-SEQ_LENGTH:]
input_tensor = torch.tensor([tokens], dtype=torch.long).to(device)
with torch.no_grad():
output = model(input_tensor)
probs = torch.softmax(output, dim=1)
top_probs, top_indices = probs.topk(top_k * 3, dim=1)
predictions = []
for prob, idx in zip(top_probs[0], top_indices[0]):
word = tokenizer.idx2word.get(idx.item(), '<UNK>')
# Filter special tokens
if word in ['<PAD>', '<UNK>', '<EOS>', '.', ',', '!', '?']:
continue
predictions.append((word, prob.item()))
if len(predictions) >= top_k:
break
return predictions
# Example usage
text = "I am going to the"
predictions = predict_next_word(text, top_k=5)
print(f"Input: '{text}'\nPredictions:")
for i, (word, prob) in enumerate(predictions, 1):
print(f" {i}. {word:.<20} {prob*100:5.2f}%")
Input: 'I am going to the'
Predictions:
1. right............... 0.93%
2. city................ 0.85%
3. north............... 0.74%
4. end................. 0.71%
5. new................. 0.70%
NextWordLSTM(
(embedding): Embedding(10000, 256, padding_idx=0)
(embedding_dropout): Dropout(p=0.2)
(lstm): LSTM(256, 512, num_layers=2, batch_first=True, dropout=0.5)
(dropout): Dropout(p=0.5)
(fc): Linear(in_features=512, out_features=10000)
)
Total Parameters: ~13 Million
The model was trained for 20 epochs with the following progression:
<UNK>The model predicts words based on Wikipedia writing patterns:
Input: "I am going to the"
Input: "The weather today is"
best_model.pth - Model checkpoint with best validation performancetokenizer.pkl - Vocabulary and tokenization mappingsevaluation_metrics.json - Complete training metrics and historyREADME.md - This documentationThe model was trained using custom LSTM implementation with:
| Model | Test PPL | Top-1 Acc | Notes |
|---|---|---|---|
| Random Baseline | ~10000 | 0.01% | Random guessing |
| N-gram (5-gram) | ~200 | 15% | Traditional approach |
| This Model | 88.31 | 25.95% | LSTM-based |
| GPT-2 Small | ~35 | 45% | Much larger (117M params) |
If you use this model in your research or application, please cite:
@misc{next-word-predictor-lstm-2026,
author = {Shubham Kumar (cosmicshubham)},
title = {Next Word Predictor: LSTM-based Language Model},
year = {2025},
month = {January},
publisher = {Hugging Face},
howpublished = {\url{https://huggingface.co/cosmicshubham/next-word-predictor-lstm}},
note = {Trained on WikiText-2 dataset}
}
MIT License - Free to use for commercial and non-commercial purposes.
Last Updated: 2026-01-24
Model Version: 1.0
Framework: PyTorch 1.9+