88 points · by nopro · 2y ago · 102 comments
When it clicked in my head that "knowing a fact" is nearly synonymous with predicting a word (or series of words), I wanted to put it to the test, because it seemed so simple. I chose JavaScript because I can exploit the way it structures objects to aid in the modeling of language.
For example:
"I want to be at the beach", "I will do it later", "I want to know the answer", ...
becomes:
{
I: {
want: {
to: {
be: { ... },
know: { ... }
}
},
will: { ... }
},
...
}
in JavaScript. You can exploit the language's fast object lookup speed to find known sentences this way, rather than recursively searching text - which is the convention and would take forever or not work at all considering there are several full books loaded in by default (and it could support many more).Accompanying research yielded learnings about what "tokens" and "embeddings" are, what is meant by "training", and most of the rest - though I'm still learning jargon. I wrote a script to iterate over every single word of every single book to rank how likely it is that word will appear next, if given a cursor, and extended that to rank entire phrases. The base decoder started out what I'll call "token-agnostic" - didn't care if you were looking for the next letter... word... pixel... it's the same logic. But actually it's not, and it soon evolved into a text (language) model. But I have plans to get into image generation next (next-pixel prediction), using this. Overall the concepts are similar, but there are differences primarily around extraction and formatting.
Goals of the project:
- Demystify LLMs for people, show that it's just regular code that does normal stuff
- Actually make a pretty good LLM in JavaScript, with a version at least capable of running in a browser tab
[1] https://towardsdatascience.com/text-generation-with-markov-c...
Also, I’m not sure I understand the explanation of why js objects are so great for this, you could do the same thing with a python dict for example or equivalent mapping types in any programming language.
This is also missing an attention mechanism which is very important to understand even for a toy LLM as it’s part of what makes the responses so accurate to the context, rather than it just predicting what word usually comes next to another word (or sequence of words)
Yes, any language with a hashmap of sorts with O(1) lookups should be equivalent.
Python - one nice thing is all the "keys" retain their primitive type, where as in JS they all turn into strings. If Python wasn't so slow compared to JS that would matter a lot and I might use it, but the speed comparison isn't even close.
Python dicts are actually different from JS objects, Python uses a hashmap behind the scenes while most fast js vms will apply some heuristics to decide whether to use a hashmap or to make the object as a static struct with a known offset for each key, this explains it better than I can: https://v8.dev/blog/fast-properties
Nevertheless, for your specific use-case I would be really surprised if there was any significant difference between the performance of python and js – hashmaps are fast enough for this – plus with js objects you might be trading insertion performance for access performance in some cases, as there is overhead creating a v8-style "fast property" object
But there are almost literally lookup tables actually!
The thing is they don't perform the lookup on a single word as a key, but on the entire context, which is what makes them special. But besides that it's “just” a lookup table.
{
I: {
want: {
to: {
be: { ... },
know: { ... }
}
},
will: { ... }
},
...
}
Every word of every sentence is modeled and ranked, and there are methods to perform operations on it. If you added a lot more words and phrases to the model, it would be a "large" language model. It also supports non-words though, so it's more accurately a "next token prediction library" that can be used to create language models.I recommend a read of symbolic ai, or better, just a generic ai book: I was raised on Norvig (90s) but no idea how up to date that is kept/still is.
https://github.com/bennyschmidt/next-token-prediction/blob/d...
Can you pls explain what you just said as if I were a 5-year-old?
Use cases include: Auto-completion, auto-correct, spell checking, search/lookup, conversation simulation (chatbot), and more.
"Trained" means that every word of every sentence of every book loaded in has an embedded score representing how likely it is to appear following a user-provided cursor. The more text you have trained on (see /training/embeddings/) the more scored words it has available, so the more robust and accurate it can be with language.
What would make your implementation a "Large" Language Model is if it has many, many, many words and phrases modeled and ranked, not just a small amount.
Chat Bots:
For something like a realistic conversation simulator (AKA a chat bot) you usually need a Large Language Model (LLM) so that any user-provided cursor yields relevant responses. To filter out the noise of less relevant responses, a good LLM-based chatbot will also use parts-of-speech and sentiment analysis ("attention") to match to the most relevant one.
Example cursor: "Paris is", you might get "in France" or "really nice" as equally ranked predictions, what would make a Chat-specific model choose one or the other would be analyzing the input - example if the question was "Where is Paris?" the Chat model would be biased toward answers that mention locations, and respond with "in France".
User: "Where is Paris?"
Convert to cursor: "Paris is"
Get completions: "in France", "really nice", "a first name", etc.
Analyze input: "Where is" refers to a location
Analyze completions: "in France" refers to a location
Answer: "Paris is in France"
Hope this helps!
Many people have already answered this here [1], so there's no point in me explaining it again.
Dropping some pointers that will be helpful for you:
- https://karpathy.ai/zero-to-hero.html
- Highly recommend this one https://www.youtube.com/watch?v=PaCmpygFfXo
- https://github.com/karpathy/llm.c
- https://ig.ft.com/generative-ai
1: ex: https://news.ycombinator.com/reply?id=40007096&goto=item%3Fi...> With enough training data and a good chat interface, this can be used instead of well-known decoder-only models like GPT, Mistral, etc.
Seems to be very misleading...
I'm going to try to do that here: https://github.com/bennyschmidt/llimo
I totally understand your skepticism, and am also surprised it works so well as a sentence-finisher, even with hardly any data (a handful of books). Think about it like this:
If you had a file with billions of sentences:
"Paris is in France" "Apples grow on trees" "Gold is worth more than silver" "I know where to go!" etc...
Then you can complete virtually any sentence. Say the user enters "Paris" - you can easily find and return "is in France" by simply searching for "Paris" in the text then slicing out the rest of the sentence, "is in France" -- or just give the next word "is" for more of an auto-suggest feel.
But if there were 4 sentences starting with "Paris", it gets slightly more complex, now I have to rank them to know which one is the best suggestion:
"Paris is in France." "Paris is nice this time of year." "Paris Hilton liked my post!" "Paris was my favorite city overall."
In this case, "is" is still the best because it scores higher than "Hilton" and "was" - because it follows "Paris" more frequently. So in addition to the text file of billions of sentences, I need to make a ranking system to give a point score to every possible word in the file at every possible position it might be in.
To make it all faster (because a super massive text file is not feasible), the billions of sentences are not actually represented in a single text file, but as a deeply nested JavaScript object our computers are more optimized to traverse and lookup, along with the point values for each word.
At this point, _with enough sentences on file_ with ranked suggestions and fast lookups, you can complete almost anything a user could input. This is what I shared today.
> good chat interface
To put the sentence-finisher to use as a chat bot, all you need to do is convert the user's question or "prompt" into the beginning of a sentence. For example:
"Where is Paris?" -> "Paris is" and let the completer give you "in France". So the answer is: "Paris is in France."
Does this make sense?
More accurately, it's literally a language model:
{
I: {
want: {
to: {
be: { ... },
know: { ... }
}
},
will: { ... }
},
...
}
Every word of every sentence is modeled and ranked, and there are methods to perform operations on it. If you added a lot more words and phrases to the model, it would be a "large" language model. It also supports non-words though, so it's more accurately a "next token prediction library" that can be used to create language models.This is unoptimised, naïve implementation of ngram language model, idea from seven decades ago [0].
[0] "A Mathematical Theory of Communications" CE SHANNON, 1948
Personal recommendation: https://web.stanford.edu/~jurafsky/slp3/ Chapters 6-10 should give you a good understanding of these concepts, also from the mathematical point of view!
Agree regarding videos for learning technical concepts - strangely when things are over-simplified they can become harder to understand on a technical level, I guess just being so abstracted. Example: The embeddings in the video I mentioned were always visualized spatially, where I simply think about it in terms of numerical point values. Like in the movie Hackers where they're traveling through 3D "cities" of "data" or whatever is going on. On one hand it simplifies the domain for a wider audience, yet it turns it into something else entirely!
Appreciate you sharing these.
It's used for autocomplete, but it's a bad way to represent large amounts of text because the fanout is insane. Markov chains would be an improvement on this.
// Predict the next word
agent.getTokenPrediction('what');
// Predict the next 5 words
agent.getTokenSequencePrediction('what is', 5);
// Complete the phrase
agent.complete('hopefully');
// Get a top k sample of completion predictions
agent.getCompletions('The sun');
Hope this helps!I based it off a Ruby module called “Twitter Ebooks”, which I believe was based on a Python module called “horsey books”, which could create a bot that would make posts using Markov chains, given a corpus of text. [2]
(I’m not dropping the date to be a jerk, more to point out that Markov chains / n-grams are an interesting concept for experimenting with language models and have been around for a while.)
In my case, I fed a corpus of data (my Twitter history at the point, which was something like 20K tweets) and tried to create a Twitter bot to make intelligent sounding posts.
It worked out, sometimes. But, it was a lot of fun to figure out!
[1] “Building intelligent robots using Node.js that can conquer Twitter” - https://www.youtube.com/watch?v=rMmXdiUGsr4
http://cotty.16x16.com/compress/peppm.htm
https://compressions.sourceforge.net/PPM.html
https://en.m.wikipedia.org/wiki/Prediction_by_partial_matchi...
In swift https://github.com/kdv123/PPMLM
In C https://github.com/money6g/ppm
Someone’s done a JS version but I can’t find it right now
https://github.com/google-research/google-research/tree/mast...
Constructing 7-gram LM ...
Created trie with 21,502,513 nodes.
People on here will be happy to say that I do a similar thing, however my sequence length is dynamic because I also use a 2nd data structure - I'll use pretentious academic speak: I use a simple bigram LM (2-gram) for single next-word likeliness and separately a trie that models all words and phrases (so, n-gram). Not sure how many total nodes because sentence lengths vary in training data, but there are about 200,000 entry points (keys) so probably about 2-10 million total nodes in the default setup."Constructing 7-gram LM": They likely started with bigrams (what I use) which only tells you the next word based on 1 word given, and thought to increase accuracy by modeling out more words in a sequence, and eventually let the user (developer) pass in any amount they want to model (https://github.com/google-research/google-research/blob/5c87...). I thought of this too at first, but I actually got more accuracy (and speed) out of just keeping them as bigrams and making a totally separate structure that models out an n-gram of all phrases (e.g. could be a 24-token long sequence or 100+ tokens etc. I model it all) and if that phrase is found, then I just get the bigram assumption of the last token of the phrase. This works better when the training data is more diverse (for a very generic model), but theirs would probably outperform mine on accuracy when the training data has a lot of nearly identical sentences that only change wildly toward the end - I don't find this pattern in typical data though, maybe for certain coding and other tasks there are those patterns though. But because it's not dynamic and they make you provide that number, even a low number (any phrase longer than 2 words) - theirs will always have to do more lookup work than with simple bigrams and they're also limited by that fixed number as far as accuracy. I wonder how scalable that is - if I need to train on occasional ~100-word long sentences but also (and mostly) just ~3-word long sentences, I guess I set this to 100 and have a mostly "undefined" trie.
I also thought of the name "LMJS", theirs is "jslm" :) but I went with simply "next-token-prediction" because that's what it ultimately does as a library. I don't know what theirs is really designed for other than proving a concept. Most of their code files are actually comments and hypothetical scenarios.
I recently added a browser example showing simple autocomplete using my library: https://github.com/bennyschmidt/next-token-prediction/tree/m... (video)
And next I'm implementing 8-dimensional embeddings that are converted to normalized vectors between 0-1 to see if doing math on them does anything useful beyond similarity, right now they look like this:
[nextFrequency, prevalence, specificity, length, firstLetter, lastLetter, firstVowel, lastVowel]
For example, here's the embedding for "dog": [0.6666666666666666, 0.6, 0.45714285714285713, 0.15, 0.12, 0.24, 0.56, 0.56]
where it used to just be 1D: { dog: 23 }
Up until now I've only effectively used nextFrequency to predict the next word, but with these other 7 metrics I'm able to store more info about each word and being vectors am able to store it efficiently, and do what all the smart people keep saying like dot product similarity index etc. The big boys are using like 1536D arrays etc. but with just 7 it still works, and it's weird that it works.Thanks again for sharing!
News to me - can you tell me what principle you think an LLM works on?
Now, I haven't gone through your code, I'm relying mainly on your description, so what you've said may have confused me and be different from what you've done, but what you seem to be calling an 'embedding' is a trie storing a dataset of sentences. The actual embedding used in LLMs is a mapping from words (a word/token list is effectively a 1 dimensional space) into a much higher dimensional space that captures aspects of the meaning of the words being embedded (e.g. similar concepts may map to similar vectors in the space, or you might be able to do classic word arithmetic like king - man + woman = queen with the vectors that each word maps to).
Then the neural network works, ultimately resulting in a vector in that space, which we map into the next token.
This is a very different process to looking up a set of options in a trie, and I would expect it to outperform the trie method by an enormous amount on longer outputs, or where outputs that are not in the training data are needed.
A couple people have basically said "but what does it do?", "what value does it add?"
So I am planning a series of examples with videos for use cases like: Auto-completion, auto-correct, spell checking, search/lookup, and if I can get around to making an ImageDecoder, could get into "next-pixel prediction".
Beyond prediction, I want to make a YouTube video when I can show a working example of a really good chatbot than anyone can just npm install and use, would be funny to give some of the open models a run for their money - but you're right, it's just a hobby project for now. Working on that in a separate project: https://github.com/bennyschmidt/llimo
Thanks for the comment and motivation to write about it!
A Markov chain is a much looser concept than next token prediction, and would apply to any finite state machine where you can predict the next state. The React state management library XState is a Markov chain.
If you want to call a token-prediction library that trains on .txt files Markovian you can - sounds cool! But token prediction is more specific to what the library does.
Use cases include: Auto-completion, auto-correct, spell checking, search/lookup, conversation simulation (chatbot), and more.
I appreciate all the comments! Especially from those who watched the video and get it.
At most, your project is a simple language model, but definitely not a large language model.
After looking at your code, you also seem to have a wrong understanding of embeddings. Other people in this thread have already shared great resources that offer good explanations on these topics.
You seem to be very dismissive of Markov chains (or HMMs) while they've been used in NLP for years and produce really great results. Your project seems to use some concepts of Markov chains but more simplified. Here [1] is a random article that does next-token prediction using Markov chains. It's basically what your project does but in a more scalable and probabilistic way.
>Use cases include: Auto-completion, auto-correct, spell checking, search/lookup, conversation simulation (chatbot), and more.
These use cases are not possible using the concepts used in your project.
[1] https://bespoyasov.me/blog/text-generation-with-markov-chain...
I see a lot of parallels to this exercise and what I did - their use of generators is exceptionally slick. I bet theirs is way slower though. Mine has 1 dep (lodash) just for its deep merge function. I didn't even use Wink NLP for text splitting and other tasks because it was 10x or 20x slower than my simpler stuff from Stack Overflow. I actually like your description of "Markov chains but simplified". But really think the devx of `npm i simple-markov-chain` is worse than `npm i next-token-prediction`. I want people to actually use it for fast prediction.
AFAIK the only difference between a language model and a "large" one is the amount of data it's trained on. Because that translates into a much larger model.
Yeah this concept of embeddings is different than, say OpenAI's. They capture a broad spectrum of semantics, where mine only focuses on frequency and structure. However, I find that very often frequency and structure allows you to bypass semantic analysis and just get to the answer. The frequency method I'm using is I guess a bastardization of tf-IDF vectorization, let's call it "tf-IDF JSON.stringify!"
"These use cases are not possible using the concepts used in your project."
^ not sure what you mean by this one, feel free to try it yourself or watch the video demo
If entire models come to weights and big a%√ json, whose to say this isn't useful.
Usefulness: My goal by next week is to share a decent AI chat bot like ChatGPT using this library. I'm working with dang right now over email - who is one of the most cool and helpful moderators of all time - to get it unflagged, or at the very least to un-ruin my account so I can actually share future progress.
Turns out people really hate any definition of LLM that doesn't involve a black box of magic.
Thanks!
And it definitely isn't a Marcov model (https://en.wikipedia.org/wiki/Hidden_Markov_model) like you implied it is.
As far as the "emergent" apparent intelligence of SoTA LLM goes, it's not just counting the number of words that appear after a phrase. I don't think anyone has a good explanation of how it works so far, only that empirically a bunch of techniques combined together seems to do the trick and LLMs do seem to acquire intelligence far beyond what a Marcov model could acquire after the training process.
Therefore, see eg. https://www.reddit.com/r/LocalLLaMA/comments/1bgh9h4/the_tru...
A joke, but it's the truth as we know it.
> Of course I do, who doesn't?
Implying you (who apparently just watched a single video) are as ignorant as people who has read extensively on the subject (not me, but presumably many others here) isn't helpful. I mean, there's nothing stopping you from believing you know enough to explain what LLMs are to other people, but the GP is honestly telling you what you need to hear IMHO.
I don't appreciate you calling me ignorant, but I think the source of your projection is this phrase: "I don't think anyone has a good explanation of how it works so far" which translates to you don't know the basics. I get it, makes you mad for some reason lol But maybe it's you that needs to read up on what a language model actually is - what next token prediction means, and how it applies to LLMs you know and love. It really is not rocket science :)
Thanks for your comment!
"build fast LLMs from scratch!"