{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Dhruv Matani",
  "title_listed": "Language Models for Sentence Completion",
  "keywords": "",
  "domain": "文本处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/",
  "publish_date": "2023-09-15",
  "corpus_stage": "",
  "notes": "",
  "id": "e748a8462f00",
  "collected_at": "2026-10-02T10:39:21",
  "title": "Language Models for Sentence Completion | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n# Language Models for Sentence Completion\nA practical application of a language model that picks the most likely candidate word that extends an English sentence by a single word\n[Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\nSeptember 15, 202314 min read\n![Photo by Brett Jordan on Unsplash](../images/000.jpg)\nPhoto by [Brett Jordan](https://unsplash.com/@brett_jordan?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\nCo-authored with [Naresh Singh](https://medium.com/@brocolishbroxoli).\n## Table of contents\n[**Introduction**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#6d2d) [**Problem Statement**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#93ee) [**Brainstorming a solution**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#7fa3)\n  * [Algorithms and Data Structures](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#9890)\n  * [NLP (Natural Language Processing)](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#d107)\n  * [Deep Learning (Neural Networks)](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#e846)\n\n\n[**An LSTM model**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#2ecd)\n  * [Tokenization](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#4a4c)\n  * [The PyTorch Model](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#75ba)\n  * [Using the model to prune invalid suggestions](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#7ad8)\n  * [Computing the next word probability](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#1049)\n\n\n[**A Transformer model**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#9241)\n[**Conclusion**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#597e)\n* * *\n## Introduction\nLanguage models such as GPT have become very popular recently and are being used for a variety of text generation tasks, such as in ChatGPT or other conversational AI systems. These language models are huge, often exceeding tens of billions of parameters, and need a lot of computing resources and money to run.\nIn the context of English language models, these massive models are [over-parameterized](https://www.reddit.com/r/MachineLearning/comments/ib4rth/d_why_does_models_like_gpt3_or_bert_dont_have/) since they use the model's parameters to memorize and learn aspects of our world instead of just modeling the English language. We can likely use a much smaller model if we have an application that requires the model to understand just the language and its constructs.\nThe complete code for running inference on the trained model can be found [in this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/next_word_probability/inference-next-word-probability.ipynb).\n* * *\n## Problem Statement\nLet's assume we're building a swipe keyboard system that tries to predict the word you type in next on your mobile phone. Based on the pattern traced by the swipe pattern, there are many possibilities for the user's intended word. However, many of these possible words aren't actual words in English and can be eliminated. Even after this initial pruning and elimination step, many candidates remain, and we need to pick one as a suggestion for the user.\nTo further prune this list of candidates, we can use a deep-learning-based language model that looks at the provided context and tells us which candidate is most likely to complete the sentence.\nFor example, if the user has typed the sentence _\"I've scheduled this\"_ and then swipes a pattern as shown below\n![](../images/001.png)\nThen, some possible English language words that the user could have meant are:\n  1. messing\n  2. meeting\n\n\nHowever, if we think about it, it's probably more likely that the user meant \"meeting\" and not \"messing\" because of the word \"scheduled\" in the earlier part of the sentence.\nGiven everything we know so far, what options do we have for doing this pruning programmatically? Let's brainstorm some solutions in the section below.\n* * *\n## Brainstorming a solution\n### Algorithms and Data Structures\nUsing first principles, it seems reasonable to start with a corpus of data, find pairs of words that come together, and train a [Markov model](https://en.wikipedia.org/wiki/Markov_model) that predicts the probability of the pair occurring in a sentence. You'll notice two significant issues with this approach.\n  1. **Space utilization** : There are anywhere [between 250k to 1 million words in the English language](https://www.merriam-webster.com/help/faq-how-many-english-words), which don't include the numerous proper nouns that are constantly growing in volume. Hence, any traditional software solution modeling the probability of a pair of words occurring together must maintain a lookup table with 250k*250k = 62.5 billion word pairs, which is somewhat excessive. It seems likely that many pairs don't occur very often and can be pruned. Even after pruning, there are a lot of pairs to worry about.\n  2. **Completeness** : Encoding the probability of a pair of words doesn't do justice to the problem at hand. For example, the earlier sentence context is completely lost when you're looking at just the most recent pair of words. In the sentence _\"How is your day coming\"_ if you want to check the word after \"coming\", you'd have a lot of pairs starting with \"coming\". This misses the entire sentence context before that word. One can imagine using word triplets, etc.... but this exacerbates the problem of space utilization mentioned above.\n\n\nLet's shift our focus to a solution that leverages the nature of the English language and see if that can help us here.\n### NLP (Natural Language Processing)\nHistorically, the area of [NLP (natural language processing)](https://en.wikipedia.org/wiki/Natural_language_processing) involved understanding the [parts of speech (POS)](https://www.englishclub.com/grammar/parts-of-speech.php) of a sentence and using that information to perform such pruning and prediction decisions. One can imagine using a POS tag associated with each word to determine if the following word in a sentence is valid.\nHowever, the process of computing the parts of speech for a sentence is a complex process in itself, and requires specialized understanding of language as evidenced in [this page on NLTK's parts of speech tagging](https://www.nltk.org/book/ch05.html).\nNext, let's take a look at a deep-learning-based approach that requires a lot more tagged data, but not as much language expertise to build.\n### Deep Learning (Neural Networks)\nThe area of NLP has been upended by the advent of deep learning. With the invention of LSTM and Transformer based language models, the solution more often than not involves throwing some high-quality data at a model and training it to predict the next word.\nIn essence, this is what the GPT model is doing. GPT (Generative Pre-Trained Transformer) models are trained to predict the next word (token) given a prefix of a sentence.\nGiven the sentence prefix _\"It is such a wonderful\"_ , it's likely for the model to provide the following as high-probability predictions for the word following the sentence.\n  1. day\n  2. experience\n  3. world\n  4. life\n\n\nIt's also likely that the following words will have a lower probability of completing the sentence prefix.\n  1. red\n  2. mouse\n  3. line\n\n\nThe [Transformer model architecture](https://en.wikipedia.org/wiki/Transformer_\\(machine_learning_model\\)) is at the heart of systems such as ChatGPT. However, for the more restricted use case of learning English language semantics, we can use a cheaper-to-run model architecture such as an [LSTM (long short-term memory)](https://en.wikipedia.org/wiki/Long_short-term_memory) model.\n* * *\n## An LSTM model\nLet's build a simple LSTM model and train it to predict the next token given a prefix of tokens. Now, you might ask what a token is.\n### Tokenization\nTypically for language models, a token can mean\n  1. A single character (or a single byte)\n  2. An entire word in the target language\n  3. Something in between 1 and 2. This is usually called a sub-word\n\n\nMapping a single character (or byte) to a token is very restrictive since we're overloading that token to hold a lot of context about where it occurs. This is because the character \"c\" for example, occurs in many different words, and to predict the next character after we see the character \"c\" requires us to really look hard at the leading context.\nMapping a single word to a token is also problematic since English itself has anywhere between 250k and 1 million words. In addition, what happens when a new word is added to the language? Do we need to go back and re-train the entire model to account for this new word?\nSub-word tokenization is considered the industry standard in the year 2023. It assigns substrings of bytes frequently occurring together to unique tokens. Typically, language models have anywhere from a few thousand (say 4,000) to tens of thousands (say 60,000) of unique tokens. The algorithm to determine what constitutes a token is determined by the[ BPE (Byte pair encoding) algorith](https://huggingface.co/learn/nlp-course/chapter6/5?fw=pt)m.\nTo choose the number of unique tokens in our vocabulary (called the vocabulary size), we need to be mindful of a few things:\n  1. If we choose too few tokens, we're back in the regime of a token per character, and it's hard for the model to learn anything useful.\n  2. If we choose too many tokens, we end up in a situation where the model's embedding tables over-shadow the rest of the model's weight and it becomes hard to deploy the model in a constrained environment. The size of the embedding table will depend on the number of dimensions we use for each token. It's not uncommon to use a size of 256, 512, 786, etc... If we use a token embedding dimension of 512, and we have 100k tokens, we end up with an embedding table that uses 200MiB in memory.\n\n\nHence, we need to strike a balance when choosing the vocabulary size. In this example, we pick 6600 tokens and train our tokenizer with a vocabulary size of 6600. Next, let's take a look at the model definition itself.\n### The PyTorch Model\nThe model itself is pretty straightforward. We have the following layers:\n  1. Token Embedding (vocab size=6600, embedding dim=512), for a total size of about 15MiB (assuming 4 byte float32 as the embedding table's data type)\n  2. LSTM (num layers=1, hidden dimension=786) for a total size of about 16MiB\n  3. Multi-Layer Perceptron (786 to 3144 to 6600 dimensions) for a total size of about 93MiB\n\n\nThe complete model has about 31M trainable parameters for a total size of about 120MiB.\n![](../images/body-8c4aa0fc6e16d186aa87.png)\nHere's the PyTorch code for the model.\npython\n\n```\nclass WordPredictionLSTMModel(nn.Module):\n    def __init__(self, num_embed, embed_dim, pad_idx, lstm_hidden_dim, lstm_num_layers, output_dim, dropout):\n        super().__init__()\n        self.vocab_size = num_embed\n        self.embed = nn.Embedding(num_embed, embed_dim, pad_idx)\n        self.lstm = nn.LSTM(embed_dim, lstm_hidden_dim, lstm_num_layers, batch_first=True, dropout=dropout)\n        self.fc = nn.Sequential(\n            nn.Linear(lstm_hidden_dim, lstm_hidden_dim * 4),\n            nn.LayerNorm(lstm_hidden_dim * 4),\n            nn.LeakyReLU(),\n            nn.Dropout(p=dropout),\n\n            nn.Linear(lstm_hidden_dim * 4, output_dim),\n        )\n    #\n\n    def forward(self, x):\n        x = self.embed(x)\n        x, _ = self.lstm(x)\n        x = self.fc(x)\n        x = x.permute(0, 2, 1)\n        return x\n    #\n#\n```\n\nHere's the model summary using torchinfo.\nLSTM Model Summary\ntext\n\n```\n=================================================================\nLayer (type:depth-idx) Param #\n=================================================================\nWordPredictionLSTMModel - \n├─Embedding: 1–1 3,379,200\n├─LSTM: 1–2 4,087,200\n├─Sequential: 1–3 - \n│ └─Linear: 2–1 2,474,328\n│ └─LayerNorm: 2–2 6,288\n│ └─LeakyReLU: 2–3 - \n│ └─Dropout: 2–4 - \n│ └─Linear: 2–5 20,757,000\n=================================================================\nTotal params: 30,704,016\nTrainable params: 30,704,016\nNon-trainable params: 0\n=================================================================\n```\n\n**Interpreting the accuracy** : After training this model on 12M English language sentences for about 8 hours on a P100 GPU, we achieved a loss of 4.03, a top-1 accuracy of 29% and a top-5 accuracy of 49%. This means that 29% of the time, the model was able to correctly predict the next token, and 49% of the time, the next token in the training set was one of the top 5 predictions by the model.\n**What should our success metric be?** While the top-1 and top-5 accuracy numbers for our model aren't impressive, they aren't as important for our problem. Our candidate words are a small set of possible words that fit the swipe pattern. What we want from our model is to be able to select an ideal candidate to complete the sentence such that it is syntactically and semantically coherent. Since our model learns the _nature_ of language through the training data, we expect it to assign a higher probability to coherent sentences. For example, if we have the sentence _\"The baseball player\"_ and possible completion candidates (\"ran\", \"swam\", \"hid\"), then the word \"ran\" is a better follow-up word than the other two. So, if our model predicts the word _ran_ with a higher probability than the rest, it works for us.\n**Interpreting the loss** : A loss of 4.03 means that the negative log-likelihood of the prediction is 4.03, which means that the probability of predicting the next token correctly is e^-4.03 = 0.0178 or 1/56. A randomly initialized model typically has a loss of about 8.8 which is -log_e(1/6600), since the model randomly predicts 1/6600 tokens (6600 being the vocabulary size). While a loss of 4.03 may not seem great, it's important to remember that the trained model is about 120x better than an untrained (or randomly initialized) model.\nNext, let's take a look at how we can use this model to improve suggestions from our swipe keyboard.\n### Using the model to prune invalid suggestions\nLet's take a look at a real example. Suppose we have a partial sentence _\"I think\"_ , and the user makes the swipe pattern shown in blue below, starting at \"o\", going between the letters \"c\" and \"v\", and ending between the letters \"e\" and \"v\".\n![](../images/body-cbf398de52d07b8fabc5.png)\nSome possible words that could be represented by this swipe pattern are\n  1. Over\n  2. Oct (short for October)\n  3. Ice\n  4. I've (with the apostrophe implied)\n\n\nOf these suggestions, the most likely one is probably going to be _\"I've\"_. Let's feed these suggestions into our model and see what it spits out.\ntext\n\n```\n[I think] [I've] = 0.00087\n[I think] [over] = 0.00051\n[I think] [ice] = 0.00001\n[I think] [Oct] = 0.00000\n```\n\nThe value after the = sign is the probability of the word being a valid completion of the sentence prefix. In this case, we see that the word \"I've\" has been assigned the highest probability. Hence, it is the most likely word to follow the sentence prefix \"I think\".\nThe next question you might have is how we can compute these next-word probabilities. Let's take a look.\n### Computing the next word probability\nTo compute the probability that a word is a valid completion of a sentence prefix, we run the model in eval (inference) mode and feed in the tokenized sentence prefix. We also tokenize the word after adding a whitespace prefix to the word. This is done because the HuggingFace pre-tokenizer splits words with spaces at the beginning of the word, so we want to make sure that our inputs are consistent with the tokenization strategy used by HuggingFace Tokenizers.\nLet's assume that the candidate word is made up of 3 tokens T0, T1, and T2.\n  1. We first run the model with the original tokenized sentence prefix. For the last token, we check the probability of predicting token T0. We add this to the \"probs\" list.\n  2. Next, we run a prediction on the prefix+T0 and check the probability of token T1. We add this probability to the \"probs\" list.\n  3. Next, we run a prediction on the prefix+T0+T1 and check the probability of token T2. We add this probability to the \"probs\" list.\n\n\nThe \"probs\" list contains the individual probabilities of generating the tokens T0, T1, and T2 in sequence. Since these tokens correspond to the tokenization of the candidate word, we can multiply these probabilities to get the combined probability of the candidate being a completion of the sentence prefix.\nThe code for computing the completion probabilities is shown below.\npython\n\n```\n def get_completion_probability(self, input, completion, tok):\n      self.model.eval()\n      ids = tok.encode(input).ids\n      ids = torch.tensor(ids, device=self.device).unsqueeze(0)\n      completion_ids = torch.tensor(tok.encode(completion).ids, device=self.device).unsqueeze(0)\n      probs = []\n      for i in range(completion_ids.size(1)):\n          y = self.model(ids)\n          y = y[0,:,-1].softmax(dim=0)\n          # prob is the probability of this completion.\n          prob = y[completion_ids[0,i]]\n          probs.append(prob)\n          ids = torch.cat([ids, completion_ids[:,i:i+1]], dim=1)\n      #\n      return torch.tensor(probs)\n  #\n```\n\nWe can see some more examples below.\ntext\n\n```\n[That ice-cream looks] [really] = 0.00709\n[That ice-cream looks] [delicious] = 0.00264\n[That ice-cream looks] [absolutely] = 0.00122\n[That ice-cream looks] [real] = 0.00031\n[That ice-cream looks] [fish] = 0.00004\n[That ice-cream looks] [paper] = 0.00001\n[That ice-cream looks] [atrocious] = 0.00000\n\n[Since we're heading] [toward] = 0.01052\n[Since we're heading] [away] = 0.00344\n[Since we're heading] [against] = 0.00035\n[Since we're heading] [both] = 0.00009\n[Since we're heading] [death] = 0.00000\n[Since we're heading] [bubble] = 0.00000\n[Since we're heading] [birth] = 0.00000\n\n[Did I make] [a] = 0.22704\n[Did I make] [the] = 0.06622\n[Did I make] [good] = 0.00190\n[Did I make] [food] = 0.00020\n[Did I make] [color] = 0.00007\n[Did I make] [house] = 0.00006\n[Did I make] [colour] = 0.00002\n[Did I make] [pencil] = 0.00001\n[Did I make] [flower] = 0.00000\n\n[We want a candidate] [with] = 0.03209\n[We want a candidate] [that] = 0.02145\n[We want a candidate] [experience] = 0.00097\n[We want a candidate] [which] = 0.00094\n[We want a candidate] [more] = 0.00010\n[We want a candidate] [less] = 0.00007\n[We want a candidate] [school] = 0.00003\n\n[This is the definitive guide to the] [the] = 0.00089\n[This is the definitive guide to the] [complete] = 0.00047\n[This is the definitive guide to the] [sentence] = 0.00006\n[This is the definitive guide to the] [rapper] = 0.00001\n[This is the definitive guide to the] [illustrated] = 0.00001\n[This is the definitive guide to the] [extravagant] = 0.00000\n[This is the definitive guide to the] [wrapper] = 0.00000\n[This is the definitive guide to the] [miniscule] = 0.00000\n\n[Please can you] [check] = 0.00502\n[Please can you] [confirm] = 0.00488\n[Please can you] [cease] = 0.00002\n[Please can you] [cradle] = 0.00000\n[Please can you] [laptop] = 0.00000\n[Please can you] [envelope] = 0.00000\n[Please can you] [options] = 0.00000\n[Please can you] [cordon] = 0.00000\n[Please can you] [corolla] = 0.00000\n\n[I think] [I've] = 0.00087\n[I think] [over] = 0.00051\n[I think] [ice] = 0.00001\n[I think] [Oct] = 0.00000\n\n[Please] [can] = 0.00428\n[Please] [cab] = 0.00000\n\n[I've scheduled this] [meeting] = 0.00077\n[I've scheduled this] [messing] = 0.00000\n```\n\nThese examples show the probability of the word completing the sentence before it. The candidates are sorted in decreasing order of probability.\nSince Transformers are slowly replacing LSTM and RNN models for sequence-based tasks, let's take a look at what a Transformer model for the same objective would look like.\n* * *\n## A Transformer model\nTransformer-based models are a very popular architecture for training language models to predict the next word in a sentence. The specific technique we'll use is the causal attention mechanism. We'll train just the [transformer encoder layer in PyTorch](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html#torch.nn.TransformerEncoder) using causal attention. Causal attention means we'll allow every token in the sequence to only look at the tokens before it. This resembles the information that a unidirectional LSTM layer uses when trained only in the forward direction.\n![](../images/body-7f6d5ef29582e412f527.png)\nThe Transformer model we'll see here is based directly on the [nn.TransformerEncoder](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html#torch.nn.TransformerEncoder) and [nn.TransformerEncoderLayer](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html#torch.nn.TransformerEncoderLayer) in PyTorch.\npython\n\n```\nimport math\n\ndef generate_src_mask(sz, device):\n    return torch.triu(torch.full((sz, sz), True, device=device), diagonal=1)\n#\n\nclass PositionalEmbedding(nn.Module):\n    def __init__(self, sequence_length, embed_dim):\n        super().__init__()\n        self.sqrt_embed_dim = math.sqrt(embed_dim)\n        self.pos_embed = nn.Parameter(torch.empty((1, sequence_length, embed_dim)))\n        nn.init.uniform_(self.pos_embed, -1.0, 1.0)\n    #\n\n    def forward(self, x):\n        return x * self.sqrt_embed_dim + self.pos_embed[:,:x.size(1)]\n    #\n#\n\nclass WordPredictionTransformerModel(nn.Module):\n    def __init__(self, sequence_length, num_embed, embed_dim, pad_idx, num_heads, num_layers, output_dim, dropout, norm_first, activation):\n        super().__init__()\n        self.vocab_size = num_embed\n        self.sequence_length = sequence_length\n        self.embed_dim = embed_dim\n        self.sqrt_embed_dim = math.sqrt(embed_dim)\n        self.embed = nn.Sequential(\n            nn.Embedding(num_embed, embed_dim, pad_idx),\n            PositionalEmbedding(sequence_length, embed_dim),\n            nn.LayerNorm(embed_dim),\n            nn.Dropout(p=0.1),\n        )\n\n        encoder_layer = nn.TransformerEncoderLayer(\n            d_model=embed_dim, nhead=num_heads, dropout=dropout, batch_first=True, norm_first=norm_first, activation=activation,\n        )\n        self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)\n        self.fc = nn.Sequential(\n            nn.Linear(embed_dim, embed_dim * 4),\n            nn.LayerNorm(embed_dim * 4),\n            nn.LeakyReLU(),\n            nn.Dropout(p=dropout),\n\n            nn.Linear(embed_dim * 4, output_dim),\n        )\n    #\n\n    def forward(self, x):\n        src_attention_mask = generate_src_mask(x.size(1), x.device)\n        x = self.embed(x)\n        x = self.encoder(x, is_causal=True, mask=src_attention_mask)\n        x = self.fc(x)\n        x = x.permute(0, 2, 1)\n        return x\n    #\n#\n```\n\nWe can plug this model in place of the LSTM model that we used before since it's API is compatible. This model takes longer to train for the same amount of training data and has comparable performance.\nTransformer models are better for long sequences. In our case, we have sequences of length 256. Most of the context needed to perform next-word completion tends to be local, so we don't really need the power of Transformers here.\n* * *\n## Conclusion\nWe saw how we can solve very practical NLP problems using deep learning techniques based on LSTM (RNN) and Transformer models. Not every language task requires the use of models with billions of parameters. Specialized applications that require modeling language itself, and not memorizing large volumes of information can be handled using much smaller models that can be deployed easily and more efficiently than the massive language models that we are used to seeing these days.\nAll the image(s) except for the first one were created by the author(s).\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-a3403563a948ce1eab7b.jpeg)\nWritten By\n## [Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[See all from Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[Hands On Tutorials](https://towardsdatascience.com/tag/hands-on-tutorials/)[Language Model](https://towardsdatascience.com/tag/language-model/)[Llm](https://towardsdatascience.com/tag/llm/)[Next Word Prediction](https://towardsdatascience.com/tag/next-word-prediction/)[Transformers](https://towardsdatascience.com/tag/transformers/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Flanguage-models-for-sentence-completion-6a5298a85e43%2F&title=Language%20Models%20for%20Sentence%20Completion)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Flanguage-models-for-sentence-completion-6a5298a85e43%2F&title=Language%20Models%20for%20Sentence%20Completion)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Flanguage-models-for-sentence-completion-6a5298a85e43%2F&text=Language%20Models%20for%20Sentence%20Completion)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/002.jpg)](https://towardsdatascience.com/mastering-prompt-engineering-with-functional-testing-a-systematic-guide-to-reliable-llm-outputs/)\n## [Mastering Prompt Engineering with Functional Testing: A Systematic Guide to Reliable LLM Outputs](https://towardsdatascience.com/mastering-prompt-engineering-with-functional-testing-a-systematic-guide-to-reliable-llm-outputs/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nHow prompt evaluation with a systematic approach composed of algorithmic testing with input/output data fixtures can make prompt engineering for complex AI tasks more reliable.\n[Ugo Pradère](https://towardsdatascience.com/author/ugopradere/)\nMarch 14, 202513 min read\n  * [![](../images/003.png)](https://towardsdatascience.com/prompt-like-a-data-scientist-auto-prompt-optimization-and-testing-with-dspy-ff699f030cb7/)\n## [Prompt Like a Data Scientist: Auto Prompt Optimization and Testing with DSPy](https://towardsdatascience.com/prompt-like-a-data-scientist-auto-prompt-optimization-and-testing-with-dspy-ff699f030cb7/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nApplying machine learning methodology to prompt building\n[Julian Yip](https://towardsdatascience.com/author/jyipkl/)\nMay 5, 202443 min read\n  * [![](../images/004.jpg)](https://towardsdatascience.com/are-language-models-benchmark-savants-or-real-world-problem-solvers-725a7e1524e1/)\n## [Are Language Models Benchmark Savants or Real-World Problem Solvers?](https://towardsdatascience.com/are-language-models-benchmark-savants-or-real-world-problem-solvers-725a7e1524e1/)\n[](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/)\nEvaluating the evolution and application of language models on real world tasks\n[Tula Masterman](https://towardsdatascience.com/author/tula.masterman/)\nMarch 23, 20247 min read\n  * [![](../images/005.jpeg)](https://towardsdatascience.com/dragin-dynamic-retrieval-augmented-generation-based-on-the-information-needs-of-large-language-dbdb9aabc1ef/)\n## [DRAGIN: Dynamic Retrieval Augmented Generation based on the Information Needs of Large Language...](https://towardsdatascience.com/dragin-dynamic-retrieval-augmented-generation-based-on-the-information-needs-of-large-language-dbdb9aabc1ef/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nTraditional RAG vs. dynamic RAG\n[Atisha Rajpurohit](https://towardsdatascience.com/author/atisharajpurohit/)\nDecember 5, 20249 min read\n  * [![](../images/006.png)](https://towardsdatascience.com/integrating-llm-agents-with-langchain-into-vica-d18a5c8583c6/)\n## [Integrating LLM Agents with LangChain into VICA](https://towardsdatascience.com/integrating-llm-agents-with-langchain-into-vica-d18a5c8583c6/)\n[](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/)\nLearn how we use LLM Agents to improve and customise transactions in a chatbot!\n[Ng Wei Cheng](https://towardsdatascience.com/author/weichengac2/)\nAugust 20, 202414 min read\n  * [![](../images/007.png)](https://towardsdatascience.com/using-llms-to-evaluate-llms-ce390ae575c6/)\n## [Using LLMs to evaluate LLMs](https://towardsdatascience.com/using-llms-to-evaluate-llms-ce390ae575c6/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nTechniques and dangers of using LLMs to evaluate LLM outputs.\n[Maksym Petyak](https://towardsdatascience.com/author/petyak.mi/)\nNovember 10, 20237 min read\n  * [![](../images/008.jpg)](https://towardsdatascience.com/visualizing-spotify-songs-with-python-an-exploratory-data-analysis-fc3fae3c2c09/)\n## [Visualizing Spotify Songs with Python: an exploratory data analysis](https://towardsdatascience.com/visualizing-spotify-songs-with-python-an-exploratory-data-analysis-fc3fae3c2c09/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nSome questions to answer: What makes popular music popular? How is today's music different from that of over 30 years ago?\n[Dea Bardhoshi](https://towardsdatascience.com/author/deabardhoshi/)\nJune 9, 20218 min read\n  * [![](../images/009.png)](https://towardsdatascience.com/the-savant-syndrome-is-pattern-recognition-equivalent-to-intelligence-242aab928152/)\n## [The Savant Syndrome: Is Pattern Recognition Equivalent to Intelligence?](https://towardsdatascience.com/the-savant-syndrome-is-pattern-recognition-equivalent-to-intelligence-242aab928152/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nExploring the limits of artificial intelligence: why mastering patterns may not equal genuine reasoning\n[Salvatore Raieli](https://towardsdatascience.com/author/salvatore-raieli/)\nOctober 31, 202413 min read\n  * [![](../images/body-63beb50f664a055ed739.jpg)](https://towardsdatascience.com/leveraging-machine-learning-for-effective-marketing-strategy-development-99b1b887f2f5/)\n## [Leveraging Machine Learning for Effective Marketing Strategy Development](https://towardsdatascience.com/leveraging-machine-learning-for-effective-marketing-strategy-development-99b1b887f2f5/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nTips and tricks for successful building of a marketing strategy using ML\n[Elena K.](https://towardsdatascience.com/author/elenek/)\nAugust 1, 20238 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "Language Models for Sentence Completion | Towards Data Science",
    "description": "A practical application of a language model that picks the most likely candidate word that extends an English sentence by a single word",
    "keywords": null,
    "author": "Dhruv Matani",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Language Models for Sentence Completion",
    "og:description": "A practical application of a language model that picks the most likely candidate word that extends an English sentence by a single word",
    "og:url": "https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/0GCVKIOPDnMM1XI5Z-scaled.jpg",
    "og:image:width": "2560",
    "og:image:height": "1920",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Dhruv Matani",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "14 min read",
    "article:published_time": "2023-09-15T05:54:32.000Z",
    "article:modified_time": "2023-09-15T05:54:32.000Z",
    "article:author": "https://towardsdatascience.com/author/dhruvbird/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/e748a8462f00/code/block_000.txt",
      "chars": 825
    },
    {
      "language": "txt",
      "file": "attachments/e748a8462f00/code/block_001.txt",
      "chars": 590
    },
    {
      "language": "txt",
      "file": "attachments/e748a8462f00/code/block_002.txt",
      "chars": 106
    },
    {
      "language": "txt",
      "file": "attachments/e748a8462f00/code/block_003.txt",
      "chars": 648
    },
    {
      "language": "txt",
      "file": "attachments/e748a8462f00/code/block_004.txt",
      "chars": 2183
    },
    {
      "language": "txt",
      "file": "attachments/e748a8462f00/code/block_005.txt",
      "chars": 1958
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:06:18Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:06:18Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:06:18Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:06:18Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/dhruvbird/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/hands-on-tutorials/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/language-model/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/llm/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/next-word-prediction/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/transformers/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/mastering-prompt-engineering-with-functional-testing-a-systematic-guide-to-reliable-llm-outputs/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/large-language-models/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/ugopradere/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/prompt-like-a-data-scientist-auto-prompt-optimization-and-testing-with-dspy-ff699f030cb7/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/jyipkl/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/are-language-models-benchmark-savants-or-real-world-problem-solvers-725a7e1524e1/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@brett_jordan"
    },
    {
      "type": "external",
      "href": "https://unsplash.com"
    },
    {
      "type": "external",
      "href": "https://medium.com/@brocolishbroxoli"
    },
    {
      "type": "external",
      "href": "https://www.reddit.com/r/MachineLearning/comments/ib4rth/d_why_does_models_like_gpt3_or_bert_dont_have/"
    },
    {
      "type": "external",
      "href": "https://github.com/dhruvbird/ml-notebooks/blob/main/next_word_probability/inference-next-word-probability.ipynb"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Markov_model"
    },
    {
      "type": "external",
      "href": "https://www.merriam-webster.com/help/faq-how-many-english-words"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Natural_language_processing"
    },
    {
      "type": "external",
      "href": "https://www.englishclub.com/grammar/parts-of-speech.php"
    },
    {
      "type": "external",
      "href": "https://www.nltk.org/book/ch05.html"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Transformer_(machine_learning_model)"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Long_short-term_memory"
    },
    {
      "type": "external",
      "href": "https://huggingface.co/learn/nlp-course/chapter6/5?fw=pt"
    },
    {
      "type": "external",
      "href": "https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html"
    },
    {
      "type": "external",
      "href": "https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Language+Models+for+Sentence+Completion&u=https%3A%2F%2Ftowardsdatascience.com%2Flanguage-models-for-sentence-completion-6a5298a85e43%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Language+Models+for+Sentence+Completion&url=https%3A%2F%2Ftowardsdatascience.com%2Flanguage-models-for-sentence-completion-6a5298a85e43%2F"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:32:36Z",
  "source_url": "https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n# Language Models for Sentence Completion\nA practical application of a language model that picks the most likely candidate word that extends an English sentence by a single word\n[Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\nSeptember 15, 202314 min read\n![Photo by Brett Jordan on Unsplash](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/0GCVKIOPDnMM1XI5Z-scaled.jpg)\nPhoto by [Brett Jordan](https://unsplash.com/@brett_jordan?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\nCo-authored with [Naresh Singh](https://medium.com/@brocolishbroxoli).\n## Table of contents\n[**Introduction**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#6d2d) [**Problem Statement**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#93ee) [**Brainstorming a solution**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#7fa3)\n  * [Algorithms and Data Structures](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#9890)\n  * [NLP (Natural Language Processing)](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#d107)\n  * [Deep Learning (Neural Networks)](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#e846)\n\n\n[**An LSTM model**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#2ecd)\n  * [Tokenization](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#4a4c)\n  * [The PyTorch Model](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#75ba)\n  * [Using the model to prune invalid suggestions](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#7ad8)\n  * [Computing the next word probability](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#1049)\n\n\n[**A Transformer model**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#9241)\n[**Conclusion**](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/#597e)\n* * *\n## Introduction\nLanguage models such as GPT have become very popular recently and are being used for a variety of text generation tasks, such as in ChatGPT or other conversational AI systems. These language models are huge, often exceeding tens of billions of parameters, and need a lot of computing resources and money to run.\nIn the context of English language models, these massive models are [over-parameterized](https://www.reddit.com/r/MachineLearning/comments/ib4rth/d_why_does_models_like_gpt3_or_bert_dont_have/) since they use the model's parameters to memorize and learn aspects of our world instead of just modeling the English language. We can likely use a much smaller model if we have an application that requires the model to understand just the language and its constructs.\nThe complete code for running inference on the trained model can be found [in this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/next_word_probability/inference-next-word-probability.ipynb).\n* * *\n## Problem Statement\nLet's assume we're building a swipe keyboard system that tries to predict the word you type in next on your mobile phone. Based on the pattern traced by the swipe pattern, there are many possibilities for the user's intended word. However, many of these possible words aren't actual words in English and can be eliminated. Even after this initial pruning and elimination step, many candidates remain, and we need to pick one as a suggestion for the user.\nTo further prune this list of candidates, we can use a deep-learning-based language model that looks at the provided context and tells us which candidate is most likely to complete the sentence.\nFor example, if the user has typed the sentence _\"I've scheduled this\"_ and then swipes a pattern as shown below\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/0kntJcWP0dbvnbuNG.png)\nThen, some possible English language words that the user could have meant are:\n  1. messing\n  2. meeting\n\n\nHowever, if we think about it, it's probably more likely that the user meant \"meeting\" and not \"messing\" because of the word \"scheduled\" in the earlier part of the sentence.\nGiven everything we know so far, what options do we have for doing this pruning programmatically? Let's brainstorm some solutions in the section below.\n* * *\n## Brainstorming a solution\n### Algorithms and Data Structures\nUsing first principles, it seems reasonable to start with a corpus of data, find pairs of words that come together, and train a [Markov model](https://en.wikipedia.org/wiki/Markov_model) that predicts the probability of the pair occurring in a sentence. You'll notice two significant issues with this approach.\n  1. **Space utilization** : There are anywhere [between 250k to 1 million words in the English language](https://www.merriam-webster.com/help/faq-how-many-english-words), which don't include the numerous proper nouns that are constantly growing in volume. Hence, any traditional software solution modeling the probability of a pair of words occurring together must maintain a lookup table with 250k*250k = 62.5 billion word pairs, which is somewhat excessive. It seems likely that many pairs don't occur very often and can be pruned. Even after pruning, there are a lot of pairs to worry about.\n  2. **Completeness** : Encoding the probability of a pair of words doesn't do justice to the problem at hand. For example, the earlier sentence context is completely lost when you're looking at just the most recent pair of words. In the sentence _\"How is your day coming\"_ if you want to check the word after \"coming\", you'd have a lot of pairs starting with \"coming\". This misses the entire sentence context before that word. One can imagine using word triplets, etc.... but this exacerbates the problem of space utilization mentioned above.\n\n\nLet's shift our focus to a solution that leverages the nature of the English language and see if that can help us here.\n### NLP (Natural Language Processing)\nHistorically, the area of [NLP (natural language processing)](https://en.wikipedia.org/wiki/Natural_language_processing) involved understanding the [parts of speech (POS)](https://www.englishclub.com/grammar/parts-of-speech.php) of a sentence and using that information to perform such pruning and prediction decisions. One can imagine using a POS tag associated with each word to determine if the following word in a sentence is valid.\nHowever, the process of computing the parts of speech for a sentence is a complex process in itself, and requires specialized understanding of language as evidenced in [this page on NLTK's parts of speech tagging](https://www.nltk.org/book/ch05.html).\nNext, let's take a look at a deep-learning-based approach that requires a lot more tagged data, but not as much language expertise to build.\n### Deep Learning (Neural Networks)\nThe area of NLP has been upended by the advent of deep learning. With the invention of LSTM and Transformer based language models, the solution more often than not involves throwing some high-quality data at a model and training it to predict the next word.\nIn essence, this is what the GPT model is doing. GPT (Generative Pre-Trained Transformer) models are trained to predict the next word (token) given a prefix of a sentence.\nGiven the sentence prefix _\"It is such a wonderful\"_ , it's likely for the model to provide the following as high-probability predictions for the word following the sentence.\n  1. day\n  2. experience\n  3. world\n  4. life\n\n\nIt's also likely that the following words will have a lower probability of completing the sentence prefix.\n  1. red\n  2. mouse\n  3. line\n\n\nThe [Transformer model architecture](https://en.wikipedia.org/wiki/Transformer_\\(machine_learning_model\\)) is at the heart of systems such as ChatGPT. However, for the more restricted use case of learning English language semantics, we can use a cheaper-to-run model architecture such as an [LSTM (long short-term memory)](https://en.wikipedia.org/wiki/Long_short-term_memory) model.\n* * *\n## An LSTM model\nLet's build a simple LSTM model and train it to predict the next token given a prefix of tokens. Now, you might ask what a token is.\n### Tokenization\nTypically for language models, a token can mean\n  1. A single character (or a single byte)\n  2. An entire word in the target language\n  3. Something in between 1 and 2. This is usually called a sub-word\n\n\nMapping a single character (or byte) to a token is very restrictive since we're overloading that token to hold a lot of context about where it occurs. This is because the character \"c\" for example, occurs in many different words, and to predict the next character after we see the character \"c\" requires us to really look hard at the leading context.\nMapping a single word to a token is also problematic since English itself has anywhere between 250k and 1 million words. In addition, what happens when a new word is added to the language? Do we need to go back and re-train the entire model to account for this new word?\nSub-word tokenization is considered the industry standard in the year 2023. It assigns substrings of bytes frequently occurring together to unique tokens. Typically, language models have anywhere from a few thousand (say 4,000) to tens of thousands (say 60,000) of unique tokens. The algorithm to determine what constitutes a token is determined by the[ BPE (Byte pair encoding) algorith](https://huggingface.co/learn/nlp-course/chapter6/5?fw=pt)m.\nTo choose the number of unique tokens in our vocabulary (called the vocabulary size), we need to be mindful of a few things:\n  1. If we choose too few tokens, we're back in the regime of a token per character, and it's hard for the model to learn anything useful.\n  2. If we choose too many tokens, we end up in a situation where the model's embedding tables over-shadow the rest of the model's weight and it becomes hard to deploy the model in a constrained environment. The size of the embedding table will depend on the number of dimensions we use for each token. It's not uncommon to use a size of 256, 512, 786, etc... If we use a token embedding dimension of 512, and we have 100k tokens, we end up with an embedding table that uses 200MiB in memory.\n\n\nHence, we need to strike a balance when choosing the vocabulary size. In this example, we pick 6600 tokens and train our tokenizer with a vocabulary size of 6600. Next, let's take a look at the model definition itself.\n### The PyTorch Model\nThe model itself is pretty straightforward. We have the following layers:\n  1. Token Embedding (vocab size=6600, embedding dim=512), for a total size of about 15MiB (assuming 4 byte float32 as the embedding table's data type)\n  2. LSTM (num layers=1, hidden dimension=786) for a total size of about 16MiB\n  3. Multi-Layer Perceptron (786 to 3144 to 6600 dimensions) for a total size of about 93MiB\n\n\nThe complete model has about 31M trainable parameters for a total size of about 120MiB.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/0aIaX1HtNih4GRtlG.png)\nHere's the PyTorch code for the model.\npython\n\n```\nclass WordPredictionLSTMModel(nn.Module):\n    def __init__(self, num_embed, embed_dim, pad_idx, lstm_hidden_dim, lstm_num_layers, output_dim, dropout):\n        super().__init__()\n        self.vocab_size = num_embed\n        self.embed = nn.Embedding(num_embed, embed_dim, pad_idx)\n        self.lstm = nn.LSTM(embed_dim, lstm_hidden_dim, lstm_num_layers, batch_first=True, dropout=dropout)\n        self.fc = nn.Sequential(\n            nn.Linear(lstm_hidden_dim, lstm_hidden_dim * 4),\n            nn.LayerNorm(lstm_hidden_dim * 4),\n            nn.LeakyReLU(),\n            nn.Dropout(p=dropout),\n\n            nn.Linear(lstm_hidden_dim * 4, output_dim),\n        )\n    #\n\n    def forward(self, x):\n        x = self.embed(x)\n        x, _ = self.lstm(x)\n        x = self.fc(x)\n        x = x.permute(0, 2, 1)\n        return x\n    #\n#\n```\n\nHere's the model summary using torchinfo.\nLSTM Model Summary\ntext\n\n```\n=================================================================\nLayer (type:depth-idx) Param #\n=================================================================\nWordPredictionLSTMModel - \n├─Embedding: 1–1 3,379,200\n├─LSTM: 1–2 4,087,200\n├─Sequential: 1–3 - \n│ └─Linear: 2–1 2,474,328\n│ └─LayerNorm: 2–2 6,288\n│ └─LeakyReLU: 2–3 - \n│ └─Dropout: 2–4 - \n│ └─Linear: 2–5 20,757,000\n=================================================================\nTotal params: 30,704,016\nTrainable params: 30,704,016\nNon-trainable params: 0\n=================================================================\n```\n\n**Interpreting the accuracy** : After training this model on 12M English language sentences for about 8 hours on a P100 GPU, we achieved a loss of 4.03, a top-1 accuracy of 29% and a top-5 accuracy of 49%. This means that 29% of the time, the model was able to correctly predict the next token, and 49% of the time, the next token in the training set was one of the top 5 predictions by the model.\n**What should our success metric be?** While the top-1 and top-5 accuracy numbers for our model aren't impressive, they aren't as important for our problem. Our candidate words are a small set of possible words that fit the swipe pattern. What we want from our model is to be able to select an ideal candidate to complete the sentence such that it is syntactically and semantically coherent. Since our model learns the _nature_ of language through the training data, we expect it to assign a higher probability to coherent sentences. For example, if we have the sentence _\"The baseball player\"_ and possible completion candidates (\"ran\", \"swam\", \"hid\"), then the word \"ran\" is a better follow-up word than the other two. So, if our model predicts the word _ran_ with a higher probability than the rest, it works for us.\n**Interpreting the loss** : A loss of 4.03 means that the negative log-likelihood of the prediction is 4.03, which means that the probability of predicting the next token correctly is e^-4.03 = 0.0178 or 1/56. A randomly initialized model typically has a loss of about 8.8 which is -log_e(1/6600), since the model randomly predicts 1/6600 tokens (6600 being the vocabulary size). While a loss of 4.03 may not seem great, it's important to remember that the trained model is about 120x better than an untrained (or randomly initialized) model.\nNext, let's take a look at how we can use this model to improve suggestions from our swipe keyboard.\n### Using the model to prune invalid suggestions\nLet's take a look at a real example. Suppose we have a partial sentence _\"I think\"_ , and the user makes the swipe pattern shown in blue below, starting at \"o\", going between the letters \"c\" and \"v\", and ending between the letters \"e\" and \"v\".\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/0ZxYzvXUsJCyNIack.png)\nSome possible words that could be represented by this swipe pattern are\n  1. Over\n  2. Oct (short for October)\n  3. Ice\n  4. I've (with the apostrophe implied)\n\n\nOf these suggestions, the most likely one is probably going to be _\"I've\"_. Let's feed these suggestions into our model and see what it spits out.\ntext\n\n```\n[I think] [I've] = 0.00087\n[I think] [over] = 0.00051\n[I think] [ice] = 0.00001\n[I think] [Oct] = 0.00000\n```\n\nThe value after the = sign is the probability of the word being a valid completion of the sentence prefix. In this case, we see that the word \"I've\" has been assigned the highest probability. Hence, it is the most likely word to follow the sentence prefix \"I think\".\nThe next question you might have is how we can compute these next-word probabilities. Let's take a look.\n### Computing the next word probability\nTo compute the probability that a word is a valid completion of a sentence prefix, we run the model in eval (inference) mode and feed in the tokenized sentence prefix. We also tokenize the word after adding a whitespace prefix to the word. This is done because the HuggingFace pre-tokenizer splits words with spaces at the beginning of the word, so we want to make sure that our inputs are consistent with the tokenization strategy used by HuggingFace Tokenizers.\nLet's assume that the candidate word is made up of 3 tokens T0, T1, and T2.\n  1. We first run the model with the original tokenized sentence prefix. For the last token, we check the probability of predicting token T0. We add this to the \"probs\" list.\n  2. Next, we run a prediction on the prefix+T0 and check the probability of token T1. We add this probability to the \"probs\" list.\n  3. Next, we run a prediction on the prefix+T0+T1 and check the probability of token T2. We add this probability to the \"probs\" list.\n\n\nThe \"probs\" list contains the individual probabilities of generating the tokens T0, T1, and T2 in sequence. Since these tokens correspond to the tokenization of the candidate word, we can multiply these probabilities to get the combined probability of the candidate being a completion of the sentence prefix.\nThe code for computing the completion probabilities is shown below.\npython\n\n```\n def get_completion_probability(self, input, completion, tok):\n      self.model.eval()\n      ids = tok.encode(input).ids\n      ids = torch.tensor(ids, device=self.device).unsqueeze(0)\n      completion_ids = torch.tensor(tok.encode(completion).ids, device=self.device).unsqueeze(0)\n      probs = []\n      for i in range(completion_ids.size(1)):\n          y = self.model(ids)\n          y = y[0,:,-1].softmax(dim=0)\n          # prob is the probability of this completion.\n          prob = y[completion_ids[0,i]]\n          probs.append(prob)\n          ids = torch.cat([ids, completion_ids[:,i:i+1]], dim=1)\n      #\n      return torch.tensor(probs)\n  #\n```\n\nWe can see some more examples below.\ntext\n\n```\n[That ice-cream looks] [really] = 0.00709\n[That ice-cream looks] [delicious] = 0.00264\n[That ice-cream looks] [absolutely] = 0.00122\n[That ice-cream looks] [real] = 0.00031\n[That ice-cream looks] [fish] = 0.00004\n[That ice-cream looks] [paper] = 0.00001\n[That ice-cream looks] [atrocious] = 0.00000\n\n[Since we're heading] [toward] = 0.01052\n[Since we're heading] [away] = 0.00344\n[Since we're heading] [against] = 0.00035\n[Since we're heading] [both] = 0.00009\n[Since we're heading] [death] = 0.00000\n[Since we're heading] [bubble] = 0.00000\n[Since we're heading] [birth] = 0.00000\n\n[Did I make] [a] = 0.22704\n[Did I make] [the] = 0.06622\n[Did I make] [good] = 0.00190\n[Did I make] [food] = 0.00020\n[Did I make] [color] = 0.00007\n[Did I make] [house] = 0.00006\n[Did I make] [colour] = 0.00002\n[Did I make] [pencil] = 0.00001\n[Did I make] [flower] = 0.00000\n\n[We want a candidate] [with] = 0.03209\n[We want a candidate] [that] = 0.02145\n[We want a candidate] [experience] = 0.00097\n[We want a candidate] [which] = 0.00094\n[We want a candidate] [more] = 0.00010\n[We want a candidate] [less] = 0.00007\n[We want a candidate] [school] = 0.00003\n\n[This is the definitive guide to the] [the] = 0.00089\n[This is the definitive guide to the] [complete] = 0.00047\n[This is the definitive guide to the] [sentence] = 0.00006\n[This is the definitive guide to the] [rapper] = 0.00001\n[This is the definitive guide to the] [illustrated] = 0.00001\n[This is the definitive guide to the] [extravagant] = 0.00000\n[This is the definitive guide to the] [wrapper] = 0.00000\n[This is the definitive guide to the] [miniscule] = 0.00000\n\n[Please can you] [check] = 0.00502\n[Please can you] [confirm] = 0.00488\n[Please can you] [cease] = 0.00002\n[Please can you] [cradle] = 0.00000\n[Please can you] [laptop] = 0.00000\n[Please can you] [envelope] = 0.00000\n[Please can you] [options] = 0.00000\n[Please can you] [cordon] = 0.00000\n[Please can you] [corolla] = 0.00000\n\n[I think] [I've] = 0.00087\n[I think] [over] = 0.00051\n[I think] [ice] = 0.00001\n[I think] [Oct] = 0.00000\n\n[Please] [can] = 0.00428\n[Please] [cab] = 0.00000\n\n[I've scheduled this] [meeting] = 0.00077\n[I've scheduled this] [messing] = 0.00000\n```\n\nThese examples show the probability of the word completing the sentence before it. The candidates are sorted in decreasing order of probability.\nSince Transformers are slowly replacing LSTM and RNN models for sequence-based tasks, let's take a look at what a Transformer model for the same objective would look like.\n* * *\n## A Transformer model\nTransformer-based models are a very popular architecture for training language models to predict the next word in a sentence. The specific technique we'll use is the causal attention mechanism. We'll train just the [transformer encoder layer in PyTorch](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html#torch.nn.TransformerEncoder) using causal attention. Causal attention means we'll allow every token in the sequence to only look at the tokens before it. This resembles the information that a unidirectional LSTM layer uses when trained only in the forward direction.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/0CB7TzptLF3rkPu2t.png)\nThe Transformer model we'll see here is based directly on the [nn.TransformerEncoder](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html#torch.nn.TransformerEncoder) and [nn.TransformerEncoderLayer](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html#torch.nn.TransformerEncoderLayer) in PyTorch.\npython\n\n```\nimport math\n\ndef generate_src_mask(sz, device):\n    return torch.triu(torch.full((sz, sz), True, device=device), diagonal=1)\n#\n\nclass PositionalEmbedding(nn.Module):\n    def __init__(self, sequence_length, embed_dim):\n        super().__init__()\n        self.sqrt_embed_dim = math.sqrt(embed_dim)\n        self.pos_embed = nn.Parameter(torch.empty((1, sequence_length, embed_dim)))\n        nn.init.uniform_(self.pos_embed, -1.0, 1.0)\n    #\n\n    def forward(self, x):\n        return x * self.sqrt_embed_dim + self.pos_embed[:,:x.size(1)]\n    #\n#\n\nclass WordPredictionTransformerModel(nn.Module):\n    def __init__(self, sequence_length, num_embed, embed_dim, pad_idx, num_heads, num_layers, output_dim, dropout, norm_first, activation):\n        super().__init__()\n        self.vocab_size = num_embed\n        self.sequence_length = sequence_length\n        self.embed_dim = embed_dim\n        self.sqrt_embed_dim = math.sqrt(embed_dim)\n        self.embed = nn.Sequential(\n            nn.Embedding(num_embed, embed_dim, pad_idx),\n            PositionalEmbedding(sequence_length, embed_dim),\n            nn.LayerNorm(embed_dim),\n            nn.Dropout(p=0.1),\n        )\n\n        encoder_layer = nn.TransformerEncoderLayer(\n            d_model=embed_dim, nhead=num_heads, dropout=dropout, batch_first=True, norm_first=norm_first, activation=activation,\n        )\n        self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)\n        self.fc = nn.Sequential(\n            nn.Linear(embed_dim, embed_dim * 4),\n            nn.LayerNorm(embed_dim * 4),\n            nn.LeakyReLU(),\n            nn.Dropout(p=dropout),\n\n            nn.Linear(embed_dim * 4, output_dim),\n        )\n    #\n\n    def forward(self, x):\n        src_attention_mask = generate_src_mask(x.size(1), x.device)\n        x = self.embed(x)\n        x = self.encoder(x, is_causal=True, mask=src_attention_mask)\n        x = self.fc(x)\n        x = x.permute(0, 2, 1)\n        return x\n    #\n#\n```\n\nWe can plug this model in place of the LSTM model that we used before since it's API is compatible. This model takes longer to train for the same amount of training data and has comparable performance.\nTransformer models are better for long sequences. In our case, we have sequences of length 256. Most of the context needed to perform next-word completion tends to be local, so we don't really need the power of Transformers here.\n* * *\n## Conclusion\nWe saw how we can solve very practical NLP problems using deep learning techniques based on LSTM (RNN) and Transformer models. Not every language task requires the use of models with billions of parameters. Specialized applications that require modeling language itself, and not memorizing large volumes of information can be handled using much smaller models that can be deployed easily and more efficiently than the massive language models that we are used to seeing these days.\nAll the image(s) except for the first one were created by the author(s).\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657076238_edr3rv.jpeg)\nWritten By\n## [Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[See all from Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[Hands On Tutorials](https://towardsdatascience.com/tag/hands-on-tutorials/)[Language Model](https://towardsdatascience.com/tag/language-model/)[Llm](https://towardsdatascience.com/tag/llm/)[Next Word Prediction](https://towardsdatascience.com/tag/next-word-prediction/)[Transformers](https://towardsdatascience.com/tag/transformers/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Flanguage-models-for-sentence-completion-6a5298a85e43%2F&title=Language%20Models%20for%20Sentence%20Completion)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Flanguage-models-for-sentence-completion-6a5298a85e43%2F&title=Language%20Models%20for%20Sentence%20Completion)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Flanguage-models-for-sentence-completion-6a5298a85e43%2F&text=Language%20Models%20for%20Sentence%20Completion)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Prompt-engineering-scientific-approach.jpg)](https://towardsdatascience.com/mastering-prompt-engineering-with-functional-testing-a-systematic-guide-to-reliable-llm-outputs/)\n## [Mastering Prompt Engineering with Functional Testing: A Systematic Guide to Reliable LLM Outputs](https://towardsdatascience.com/mastering-prompt-engineering-with-functional-testing-a-systematic-guide-to-reliable-llm-outputs/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nHow prompt evaluation with a systematic approach composed of algorithmic testing with input/output data fixtures can make prompt engineering for complex AI tasks more reliable.\n[Ugo Pradère](https://towardsdatascience.com/author/ugopradere/)\nMarch 14, 202513 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1s_Xn52jw2opmaN0mm3lDxA.png)](https://towardsdatascience.com/prompt-like-a-data-scientist-auto-prompt-optimization-and-testing-with-dspy-ff699f030cb7/)\n## [Prompt Like a Data Scientist: Auto Prompt Optimization and Testing with DSPy](https://towardsdatascience.com/prompt-like-a-data-scientist-auto-prompt-optimization-and-testing-with-dspy-ff699f030cb7/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nApplying machine learning methodology to prompt building\n[Julian Yip](https://towardsdatascience.com/author/jyipkl/)\nMay 5, 202443 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/0hWi6DirZ7v0hLmQC.jpg)](https://towardsdatascience.com/are-language-models-benchmark-savants-or-real-world-problem-solvers-725a7e1524e1/)\n## [Are Language Models Benchmark Savants or Real-World Problem Solvers?](https://towardsdatascience.com/are-language-models-benchmark-savants-or-real-world-problem-solvers-725a7e1524e1/)\n[](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/)\nEvaluating the evolution and application of language models on real world tasks\n[Tula Masterman](https://towardsdatascience.com/author/tula.masterman/)\nMarch 23, 20247 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/12/1J-OSRrmHJNcyWAbp1QOARg-scaled.jpeg)](https://towardsdatascience.com/dragin-dynamic-retrieval-augmented-generation-based-on-the-information-needs-of-large-language-dbdb9aabc1ef/)\n## [DRAGIN: Dynamic Retrieval Augmented Generation based on the Information Needs of Large Language...](https://towardsdatascience.com/dragin-dynamic-retrieval-augmented-generation-based-on-the-information-needs-of-large-language-dbdb9aabc1ef/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nTraditional RAG vs. dynamic RAG\n[Atisha Rajpurohit](https://towardsdatascience.com/author/atisharajpurohit/)\nDecember 5, 20249 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/08/1HTULJI9sLlOrIHytzAx4wQ.png)](https://towardsdatascience.com/integrating-llm-agents-with-langchain-into-vica-d18a5c8583c6/)\n## [Integrating LLM Agents with LangChain into VICA](https://towardsdatascience.com/integrating-llm-agents-with-langchain-into-vica-d18a5c8583c6/)\n[](https://towardsdatascience.com/language-models-for-sentence-completion-6a5298a85e43/)\nLearn how we use LLM Agents to improve and customise transactions in a chatbot!\n[Ng Wei Cheng](https://towardsdatascience.com/author/weichengac2/)\nAugust 20, 202414 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/11/17MonaLlO4zTNeFQT0ATKbw.png)](https://towardsdatascience.com/using-llms-to-evaluate-llms-ce390ae575c6/)\n## [Using LLMs to evaluate LLMs](https://towardsdatascience.com/using-llms-to-evaluate-llms-ce390ae575c6/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nTechniques and dangers of using LLMs to evaluate LLM outputs.\n[Maksym Petyak](https://towardsdatascience.com/author/petyak.mi/)\nNovember 10, 20237 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/06/0ABnUFIFgqNKL2Cjz-scaled.jpg)](https://towardsdatascience.com/visualizing-spotify-songs-with-python-an-exploratory-data-analysis-fc3fae3c2c09/)\n## [Visualizing Spotify Songs with Python: an exploratory data analysis](https://towardsdatascience.com/visualizing-spotify-songs-with-python-an-exploratory-data-analysis-fc3fae3c2c09/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nSome questions to answer: What makes popular music popular? How is today's music different from that of over 30 years ago?\n[Dea Bardhoshi](https://towardsdatascience.com/author/deabardhoshi/)\nJune 9, 20218 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1DEROz5k61T_8wf-I6515HA.png)](https://towardsdatascience.com/the-savant-syndrome-is-pattern-recognition-equivalent-to-intelligence-242aab928152/)\n## [The Savant Syndrome: Is Pattern Recognition Equivalent to Intelligence?](https://towardsdatascience.com/the-savant-syndrome-is-pattern-recognition-equivalent-to-intelligence-242aab928152/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nExploring the limits of artificial intelligence: why mastering patterns may not equal genuine reasoning\n[Salvatore Raieli](https://towardsdatascience.com/author/salvatore-raieli/)\nOctober 31, 202413 min read\n  * [![](https://towardsdatascience.com/images/fallback-image.jpg)](https://towardsdatascience.com/leveraging-machine-learning-for-effective-marketing-strategy-development-99b1b887f2f5/)\n## [Leveraging Machine Learning for Effective Marketing Strategy Development](https://towardsdatascience.com/leveraging-machine-learning-for-effective-marketing-strategy-development-99b1b887f2f5/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nTips and tricks for successful building of a marketing strategy using ML\n[Elena K.](https://towardsdatascience.com/author/elenek/)\nAugust 1, 20238 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/e748a8462f00/pages/",
  "body_markdown_path": "attachments/e748a8462f00/pages/archived-body.md",
  "local_html": "attachments/e748a8462f00/pages/archived-body.html",
  "body_source": "prior_capture"
}