35 min read

Natural Language Processing

Turning text into useful predictions involves several connected problems: representing words, modeling sequences, finding structure, and generating responses. This article follows those ideas from text features and probabilistic models to attention, transformers, and retrieval-augmented generation.

Tokenization and text features

Begin with the text itself: the patterns we can match, the units we split it into, and the features we extract from those units.

re.findall(regex, text)Returns a list of all matches of regex
re.search(regex, text)Looks for first location where regex matches
re.split(regex, text)splits text at the occurrence of pattern defined by regex
re.sub(regex, replacement, text)Replaces occurrence of regex in text with replacement string

Regular expression Meta Characters

Meta CharacterMatches
.Any character except newline
^negation
$end of string
*0 or more repetition of prev element
+1 or more repetition of prev element
?0 or 1 repetition of preceding element
{n}exactly n repetitions of prev element
{n,}n or more repetitions of prev element
{n.m}Between n and m repetitions of prev element
( )Matches poora ka poora regex inside
[ ]Matches any character from [ ]
|or
\Allows us to use metacharacters in regex
\dAny digit
\DAny non-digit
\wAny alphanumeric chars and underscores (a-z, A-Z, 0-9, _)
\WAny non-alphanumeric chars
\sAny whitespace chars (spaces, tabs, newlines)
\SAny non-whitespace chars
!Logical not sign
Tokenization and text features — illustration

Byte pair encodings

data compression technique used to reduce the size of a dataset by replacing the most frequent pairs of adjacent bytes (or characters) with a single byte (or character) that does not appear in the data.

is considered a data-driven approach because it adapts its tokenization or compression process based on the actual statistics of the data it is applied to. Instead of using a predefined set of rules

Tokenization and text features — illustration

Edit distance

Measure of how different two strings are from each other.

Applications:

  1. Spell Checkers: To find the closest correct word to a misspelled word.
  2. DNA Sequence Comparison: To measure the similarity between two DNA sequences.
  3. Natural Language Processing: To compare text similarity.

Kinds:

NLP — 🥩Regular expressions*

Insert: 1

Delete: 1

Replace: 1

Tokenization and text features — illustration

TF (Term Frequency)

How frequently a term appears in a document relative to total number of terms in that document

Helps identify relevance of term in specific document, giving weight to terms that occur more frequently

\[Term\,Frequency=\,\frac{No.\,of\,reps\,of\,words\,in\,sentence}{No.\,of\,words\,in\,sentence}\]
Tokenization and text features — illustration

IDF (Inverse Document Frequency)

IDF measures how important a term is across multiple documents, decreasing the weight of common terms and increasing the weight of rare terms.

Used in conjunction with TF to evaluate the significance of a term across a collection of documents.

\[IDF=\operatorname{log}\left( \frac{No\,of\,sentences}{No\,of\,sentences\,containing\,words} \right)\]
IDF
good\[\operatorname{log}\left( \frac{3}{3} \right)=0\]
boy\[\operatorname{log}\left( \frac{3}{2} \right)=0.58\]
girl\[\operatorname{log}\left( \frac{3}{2} \right)=0.58\]

TF-IDF

\[TFIDF(t,d)=TF(t,d)×IDF(t)\]
F1F2F3
goodboygirl
S100.290.193
S2000.193
S300.290.193

Focus on Unique Terms: By combining TF and IDF, TF-IDF emphasizes terms that are frequent in a specific document (TF) but infrequent across all documents (IDF). This helps to highlight unique or relevant terms.

Dimensionality Reduction: Using TF-IDF scores can reduce the number of terms that need to be processed, focusing on the most relevant features for tasks such as document classification, clustering, and information retrieval.

Text classification

Text classification — illustration
Text classification — illustration

Make each word has a weight in whole 10,000 words vocabulary

Very slow training time

Text classification — illustration

Frequency table is given below

Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration

Naïve Bayes

It's called naive because this method makes the assumption that 

the features you're using for  classification are all independent. 

Which in reality is rarely the case. 

Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration
Text classification — illustration

Ensembles and XGBoost

Ensemble learning

Combining predictions from multiple models to improve overall accuracy

Types of ensemble models:

  1. Bagging

Multiple models are trained in parallel on random subsets of training data, each model makes predictions and the final decision is based on majority voting. Reduces overfitting and variance

  1. Boosting

Models are trained sequentially, each model focuses on correcting errors of previous ones. Reduces bias and increases accuracy

Single decision trees are sensitive to small changes in data.

A minor modification in a training example can lead to a completely different tree structure, making the model less robust.

tree ensemble consists of multiple decision trees that collectively make predictions.

In this approach, each tree is built from potentially different subsets of data, and when making predictions, they vote on the outcome

Sampling with Replacement: Involves drawing items from a set and returning them after each draw. Allows for duplicates in the selection process.

Used to create multiple random training sets from the original dataset.

Each set can contain repeated examples and may not include all original instances.

Promotes diversity in training data, which is essential for effective ensemble learning.

To further diversify trees, select a random subset of K features from N features at each node for splitting.

NLP — ✅XGBoost*

XGBoost Regression

ExpGapSalaryResidual 1
2yes40k-11
2.5yes41k-10
3no52k1
4no60k9
4.5yes62k10
Average:51k
Ensembles and XGBoost — illustration

Assume <= 2.5 and > 2.5 gives highest Gain

Ensembles and XGBoost — illustration
ExpGapSalaryResidual 1Base model O/PResidual 2
2yes40k-1146-6
2.5yes41k-1046-5
3no52k153.5-1.5
4no60k962-2
4.5yes62k10620
Average:51k
Ensembles and XGBoost — illustration
Ensembles and XGBoost — illustration

XGBoost Classification

Ensembles and XGBoost — illustration

Assume that using salary before credit as first split results in highest GAIN

Ensembles and XGBoost — illustration
Ensembles and XGBoost — illustration
Ensembles and XGBoost — illustration

Log(odds) = logit function

\[Odds=\,\frac{p}{1−p}\]

P is the probability of event occurring

SalaryCreditApprovalRes1Model outputRes2
<=50KB0-0.50.6-0.6
<=50KG10.5
<=50KG10.5
>50KB0-0.5
>50KG10.5
>50KN10.5
<=50KN0-0.5

XGBoost Regression Overview

  1. Initialize Predictions: Start with initial predictions set to average for all training examples.
  • Calculate Residuals: Determine the differences between the actual target values and the current predictions. These differences represent the errors.
  • Build a New Tree: Create a new decision tree that attempts to predict these residuals (errors).
  • Update Predictions: Add the predictions from this new tree to the current predictions, scaled by a learning rate to control the contribution of the new tree.
  1. Return Final Predictions: After all boosting rounds, return the final predictions, which are the result of all the trees combined.

XGBoost Classification Overview

  1. Initialize Predictions: Start with initial predictions set to 0.5 for all training examples.
  • Calculate Pseudo-Residuals: Calculate the differences between the actual class labels and the predicted probabilities using a logistic function (sigmoid). This gives a measure of how well the current model is performing.
  • Build a New Tree: Create a new decision tree that aims to predict these pseudo-residuals.
  • Update Predictions: Add the predictions from this new tree to the current predictions, scaled by a learning rate.
  1. Convert to Class Labels: After completing all boosting rounds, convert the final predictions into class labels based on a threshold (e.g., if the predicted probability is greater than 0.5, classify it as one class; otherwise, classify it as another).
  2. Return Final Predictions: Return the final class predictions along with the ensemble model of all the trees.

Vector similarity and nearest neighbors

Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration

Cosine similarity

One of the issue with euclidean distance is that it is biased towards higher counts in one dimension

Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration

Similar vectors have higher score

Vector similarity and nearest neighbors — illustration

PCA

Vector similarity and nearest neighbors — illustration

Eigenvectors give direction of uncorrelated features

Eigenvalues are variance of new features

Dot product gives projection on uncorrelated features

Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration

Locality sensitive hashing

Locality sensitive hashing is a technique that allows you to hash similar inputs into the same buckets with high probability.

Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration

We divide our vector space into many multiple planes

And use a single hash value to denote each section

Vector similarity and nearest neighbors — illustration

Approximating nearest neighbors

Vector similarity and nearest neighbors — illustration
Vector similarity and nearest neighbors — illustration

Edit distance and spelling correction

Edit distance and spelling correction — illustration
Edit distance and spelling correction — illustration
Edit distance and spelling correction — illustration

Minimum edit distance

Edit distance and spelling correction — illustration
Edit distance and spelling correction — illustration

N-gram language models

Language modeling introduces context: instead of treating words independently, we ask how earlier words affect what comes next.

N-gram applications

N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration

Starting and Ending sentences

Start of sentence token: <s>

End of sentence token: </s>

Why introduce SOS token?

N-gram language models — illustration

You don’t have context of previous word for the case of 'the'

You cant calculate the bigram probability for that, after adding a

special term in the beginning of each sentence in your corpus.

Similar problem in trigrams, first two words don’t have enough context

Missed contexts can be fixed by adding two start of sentence symbols

To generalize, for N-grams you need N-1 SOS tokens

N-gram language models — illustration

Why introduce EOS tokens?

Not having a EOS token makes the model map a different probability distribution for each different sentence length. Having a EOS token allows the model to have a single probability distribution for sentences upto infinite length

N-gram language models — illustration
N-gram language models — illustration

The N-gram Language Model

Count matrix tells you how many times each word is followed by every other word in corpus

N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration

Evaluating Language Models

Perplexity is a evaluation metric used in Language models to measure how well probability model predicts a sample. It’s a way to quantify how 'surprised' or 'perplexed' a model is by new text

Lower perplexity indicates a better model performance

N-gram language models — illustration

Good language models have perplexity between 20-60

N-gram language models — illustration

Some papers use log perplexity

N-gram language models — illustration

Good language models have log perplexity between 4.3-5.9

N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration

How to handle missing Grams?

N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration
N-gram language models — illustration

<s> I am a human </s>

<s> I am not a stone</s>

<s> I I live in Mumbai</s>

N-gram language models — illustration
N-gram language models — illustration

Laplace Smoothing

\[P\left( X\,Y \right)=\,\frac{C\left( X\,Y \right)+1}{C\left( Y \right)+V}\]
N-gram language models — illustration
N-gram language models — illustration
import nltk from nltk import bigrams from nltk.probability import FreqDist, ConditionalFreqDist # Sample text text = "I love natural language processing. Natural language processing is fascinating." # Tokenize the text tokens = nltk.word_tokenize(text.lower()) # Create bigrams bi_grams = list(bigrams(tokens)) # Frequency distribution of bigrams bigram_freq = FreqDist(bi_grams) # Conditional frequency distribution cond_freq = ConditionalFreqDist(bi_grams) # Display the bigrams and their frequencies print("Bigram Frequencies:") for bigram, freq in bigram_freq.items(): print(f"{bigram}: {freq}") # Function to calculate P(X|Y) for a bigram def bigram_probability(x, y): return cond_freq[y][x] / bigram_freq[(y, x)] if (y, x) in bigram_freq else 0 # Example of calculating P('processing' | 'language') print(f"P('processing' | 'language') = {bigram_probability('processing', 'language'):.4f}")

N Gram model code:

import nltk from nltk import ngrams from nltk.probability import FreqDist, ConditionalFreqDist # Sample text text = "I love natural language processing. Natural language processing is fascinating." # Tokenize the text tokens = nltk.word_tokenize(text.lower()) # Function to create n-grams def ngram_model(tokens, n): n_grams = list(ngrams(tokens, n)) freq_dist = FreqDist(n_grams) cond_freq = ConditionalFreqDist(n_grams) return freq_dist, cond_freq # Create bigram model (n=2) bigram_freq, bigram_cond_freq = ngram_model(tokens, 2) # Display the bigrams and their frequencies print("Bigram Frequencies:") for bigram, freq in bigram_freq.items(): print(f"{bigram}: {freq}") # Example of calculating P(X|Y) for a bigram def bigram_probability(x, y): return bigram_cond_freq[y][x] / bigram_freq[(y, x)] if (y, x) in bigram_freq else 0 # Example of calculating P('processing' | 'language') print(f"P('processing' | 'language') = {bigram_probability('processing', 'language'):.4f}") # Create trigram model (n=3) trigram_freq, trigram_cond_freq = ngram_model(tokens, 3) # Display the trigrams and their frequencies print("\nTrigram Frequencies:") for trigram, freq in trigram_freq.items(): print(f"{trigram}: {freq}") # Example of calculating P(X|Y,Z) for a trigram def trigram_probability(x, y, z): return trigram_cond_freq[(y, z)][x] / bigram_freq[(y, z)] if (y, z) in bigram_freq else 0 # Example of calculating P('is' | 'processing', 'natural') print(f"P('is' | 'processing', 'natural') = {trigram_probability('is', 'processing', 'natural'):.4f}")
  • Tokenization: The text is tokenized into words.
  • N-grams Creation: We use nltk.ngrams to generate n-grams (bigrams, trigrams, etc.) from the tokens.
  • Frequency Distribution: We compute the frequency distribution of the n-grams and create a conditional frequency distribution.
  • Probability Calculation: Functions are provided to calculate the conditional probabilities for bigrams and trigrams.

Sequence tagging and hidden Markov models

Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration

Hidden Markov model

Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration

Viterbi algorithm

Used to find most likely sequence of hidden states (called viterbi path)

The algorithm identifies the hidden-state sequence most likely to have produced the observations.

Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration

Parts of speech

Parts of speech are categories that describe the function of words in a sentence.

e.g. Nouns, pronouns, verbs, adjectives, adverbs

Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration
NLP — 🥩HMM*
NLP — 🥩HMM*
Sequence tagging and hidden Markov models — illustration
Sequence tagging and hidden Markov models — illustration

Word embeddings

Word embeddings = Word Vectors = Word embedding Vectors

One hot vector is a word vector too

Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration

The yield keyword in Python is used to turn a function into a generator. A generator is a special type of iterator that generates values one at a time and only when requested, which makes it memory efficient for large datasets.

Word embeddings — illustration

Here's how it works:

  1. Generator Function: When a function contains the yield keyword, it becomes a generator function. Instead of using return to send a value back to the caller and terminate the function, yield sends a value back to the caller but saves the state of the function so it can be resumed right where it left off.
  2. State Retention: The state of the generator function is retained between each call. This means local variables and their values are preserved.
  3. Lazy Evaluation: Values are generated only when needed, which makes it memory efficient, especially when working with large sequences of data.

Here’s an example to illustrate the use of yield:

defcount_up_to(max):
    count = 1whilecount <= max:
        yieldcount
        count += 1counter = count_up_to(5)
print(next(counter)) # Output: 1print(next(counter)) # Output: 2print(next(counter)) # Output: 3print(next(counter)) # Output: 4print(next(counter)) # Output: 5print(next(counter)) # Raises StopIteration

Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration
Word embeddings — illustration

\[X_{ij}=frequency\,of\,i\,\left( target\,word \right)appearing\,in\,context\,of\,j\left( context\,word \right)\]

GloVe model minimizes the difference between context and target words

Window length = 1

NLP — 🥩Word Embeddings*

GloVe co-occurrence equation

\[w_{i}.w_{j}=logP(i|j)\]

Loss function:

\[J=\,\sum_{i=1}^{V} \sum_{j=1}^{V} {f\left( X_{ij} \right)\left( {\overset{⃑}{w_{i}^{T}}.\,\overset{⃑}{w_{j}}+b_{i}+b_{j}−logX_{ij}} \right)^{2}}\]

\[\overset{⃑}{w_{i}}\,and\,\overset{⃑}{w_{j}}\,are\,embeddings\,of\,words\,w_{i}\,w_{j}\]

\[f\left( X_{ij} \right)\,outputs\,influence\,of\,cooccurence\,counts\,X_{ij}\]

Neural language models

Neural language models — illustration

Traditional Language Models

Neural language models — illustration

Better Language Models

Neural language models — illustration
Neural language models — illustration
Neural language models — illustration
Neural language models — illustration
Neural language models — illustration
Neural language models — illustration

Recurrent sequence models

Recurrent sequence models — illustration

Gradient descent: further reading

Recurrent sequence models — illustration
Recurrent sequence models — illustration
Recurrent sequence models — illustration
Recurrent sequence models — illustration

Siamese networks and text similarity

Siamese networks and text similarity — illustration

Siamese networks can also be used for text similarity.

Siamese networks and text similarity — illustration
Siamese networks and text similarity — illustration
Siamese networks and text similarity — illustration

Purpose for Alpha term

  1. Margin for better separation
    The alpha term ensures that the positive example is not just closer to the anchor than the negative example but is closer by at least a certain margin.
  2. Margin helps model more robust to variations
    model is more sensitive to small perturbations
Siamese networks and text similarity — illustration
Siamese networks and text similarity — illustration
Siamese networks and text similarity — illustration

One-shot learning for NLP

Siamese networks and text similarity — illustration
Siamese networks and text similarity — illustration
Siamese networks and text similarity — illustration

Parsing sentences

Parsing sentences — illustration
Parsing sentences — illustration
NLP — 🥩Parsing*

CYK

Bottom up parsing

Complexity =

Uses dynamic programming

Is string 'baaba' in L(G)

Grammer for G

Parsing sentences — illustration

S → AB | BC
A → BA | a
B → CC | b

C → AB | a

Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration

Yes string is in L(G) because and i=5, there is S

Earley parsing

Parses CFG

Three fundamental operations:

  1. Predict:
    Generates possible expansions for non-terminal symbols
    Suggests potential expansions for non-terminals.
  2. Scan:
    It checks if the current token matches the expected terminal symbol in the parser’s state. parser moves the input pointer forward by one token if the next token matches the expected terminal symbol.
  3. Complete:
    Finalizes partial structures. Combines partial structures into complete ones when the necessary components are found.

Applications:

  1. Syntactic Parsing
  2. Semantic Analysis
  3. Machine Translation

Advantages:

  1. Flexible
  2. Parsing efficiency

Example question

Grammar:

S → NP VP

NP → Det N | N

VP → V NP

Det → 'the' | 'a'

N → 'cat' | 'dog'

V → 'chases' | 'sees'

String: 'dog chases the cat'

Operation TypeProduction rulesCompleted status
InitializationS → .NP VP
predictNP → .Det N NP → .N
scanNP → N .Dog scanned
completeS → NP . VP
predictVP → .V NP
scanVP → V . NPChases scanned
predictNP → .Det N NP → .N
scanNP → Det . NThe scanned
ScanNP → Det N .Cat scanned
CompleteS → NP VP .
Parsing sentences — illustration

Question #02

S → NP VP

PP → P NP

VP → V NP

VP → VP PP

P → 'with'

V → 'drink'

NP → NP PP

NP → N

N → 'papu'

N → 'milk'

N → 'chocolate'

N → 'coffee'

"papu drink milk with chocolate"

Parsing sentences — illustration
Parsing sentences — illustration
Parsing sentences — illustration

Machine translation and evaluation

Translation brings representation and generation together. Evaluating the result requires looking at both the output and the reference it is compared with.

Machine translation and evaluation — illustration
Machine translation and evaluation — illustration
Machine translation and evaluation — illustration
Machine translation and evaluation — illustration

Machine translation Evaluation

Key goals in evaluation:

  1. Correctness in conveying the translation
  2. Fluency of translation
  3. Determining whether translation is contextually appropriate

Evaluation methods:

  1. Automatic evaluation:
    Uses computational metrics to evaluate large scale translations quickly. May not capture nuances fully.
  2. Human evaluation:

Provides insights into fluency, adequacy, and overall quality.

Automatic Evaluation: BLEU

(Bilingual Evaluation Understudy)

Measures the quality of candidate translations by comparing them with several reference translations.

Focuses on n-gram precision, Counts n-grams in candidate translation and in reference translations

\[Precision_{n}=\frac{\sum_{c} \sum_{n\,gram} {MaxFreq_{ref}(n\,gram)}}{\sum_{c} \sum_{n\,gram} {Freq_{c}(n\,gram)}}\]

is maximum frequency of n-gram in any one reference translation

is count of n-gram in candidate translation

Brevity penalty (BP):

Applied to prevent shorter, partial translations from receiving high scores

c = length or candidate translation corpus

r = length of reference corpus

\[BP=\,\left\{ \begin{aligned} \operatorname{exp}\left( {1−\frac{r}{c}} \right)\,if\,c

This helps prevent the model from generating overly short translations that might align with certain reference phrases but lack completeness.

\[BLEUscore=BP\,×exp\left( {\frac{1}{N}\sum_{n=1}^{N} {\operatorname{log}(Precision_{n})}} \right)\]

Human evaluation

Provides insights that automated metrics like BLEU cannot fully capture, such as how natural and informative the translation is to a human reader.

Assess on:

  1. Fluency: if translation is grammatically correct and sounds natural
  2. Adequacy: if translation conveys meaning of source text without losing essential information.

Cloze task: A method to measure fluency by giving raters sentences with missing words, asking them to guess the word. This indicates if the context flows naturally.

______________________________________________________________________________________________________________

Seq-2-Seq RNN

Machine translation and evaluation — illustration
Machine translation and evaluation — illustration

Many to many RNN

Recurrence relation at any time step to process a sequence:

=

t = time step

= cell state

= function parameterized by W

= output of previous state t-1

= input at current time step t

NLP — 🥩Machine Translation*
Machine translation and evaluation — illustration
\[\operatorname{tanh}\left( x \right)=\frac{e^{x}−e^{−x}}{e^{x}+e^{−x}}\]

Hyperparameters for RNN architecture definition

h: hidden state size, determines number of neurons in hidden state vector at each time step

l: depth of RNN layers/blocks

t: the number of time steps in input sequence

NLP — 🥩Machine Translation*

Back Propagation Through Time

NLP — 🥩Machine Translation*
  1. Calculate individual losses
  2. Sum individual losses to get total loss
  3. Errors are back propagated from overall loss through each time step from most recent to beginning of the sequence
NLP — 🥩Machine Translation*
NLP — 🥩Machine Translation*
NLP — 🥩Machine Translation*

\[L_{1}\,=\frac{1}{2}\left( {y_{1}−\hat{y_{1}}} \right)^{2}\]

\[L_{2}\,=\frac{1}{2}\left( {y_{2}−\hat{y_{2}}} \right)^{2}\]

\[L_{3}\,=\frac{1}{2}\left( {y_{3}−\hat{y_{3}}} \right)^{2}\]

L₁ = 1/2 * [(1 - 0.4)² + (0 - 0.3)² + (0 - 0.3)²]

= 1/2 * [0.36 + 0.09 + 0.09]

= 1/2 * 0.54

= 0.27

L₂ = 1/2 * [(0 - 0.2)² + (1 - 0.5)² + (0 - 0.3)²]

= 1/2 * [0.04 + 0.25 + 0.09]

= 1/2 * 0.38

= 0.19

L₃ = 1/2 * [(0 - 0.3)² + (0 - 0.2)² + (1 - 0.5)²]

= 1/2 * [0.09 + 0.04 + 0.25]

= 1/2 * 0.38

= 0.19

L_total = L₁ + L₂ + L₃

= 0.27 + 0.19 + 0.19

= 0.65

BLEU Score (Bilingual Evaluation study)

BLEU Score is a metric used to evaluate quality of text translations by comparing it with one or more reference translations.

Machine generated translations (Candidate)

Human generated translations (Reference)

Steps

  1. Tokenize both reference and candidate sentence into words.

Tokenization is process of splitting sentence into individual n-grams

Reference sentence: 'AI transforms industries'

Candidate sentence: 'AI powers industries'

After tokenization:

Reference: ['AI', 'transforms', 'industries']

Candidate: ['AI', 'powers', 'industries']

  1. Calculate n-grams precision

BLEU score calculates precision for different n-grams

Reference 1-grams: {'AI', 'transforms', 'industries'}

Candidate 1-grams: {'AI', 'powers', 'industries'}

Matching n-grams: ['AI', 'industries'] (2 out of match)

Total candidate unigrams: 3

Total matching unigrams: 2

1-gram precision:

Reference 2-grams: {'AI transforms', 'transforms industries'}

Candidate 2-grams: {'AI powers', 'powers industries'}

Matching 2-grams: [None]

Total candidate 2-grams: 2

Total matching 2-grams: 0

2-gram precision:

  1. Calculate Geometric mean of precision Scores

Process done to combine n-gram precision scores into single value

\[Geometric\,mean=\,\sqrt{unigram\,precision\,×Bigram\,precision}\]

\[Geometric\,mean=\,\sqrt{0.66667×0\,}=0\]

  1. Calculate Brevity penalty

Adjusts for translations that are too short compared to reference

\[BP=\operatorname{min}\left( {1,\,\operatorname{e}^{\left( {1−\frac{c}{r}} \right)}} \right)\]

c: candidate length = 3

r: reference length = 3

\[BP=\operatorname{min}(1,\,e^{\left( {1−\frac{3}{3}} \right)})\]

BP = min(1, 2.71828)

BP = 1

A score above 0.6 is considered good

A score below 0.5 is seen as poor

  1. Calculate BLEU score

BLEU = Geometric Mean Brevity Penalty

BLEU = 0 x 1

BLEU = 0

Attention and sequence generation

Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration

In seq2seq as sequence size increases,

model performance decreases.

Can we use all encoder hidden states?

Attention and sequence generation — illustration

No, it would consume too much memory

Solution: use attention

Attention and sequence generation — illustration

Seq2seq vs Attention model(2014) BLEU score

Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration

Q K V, attention with transformers(2017)

Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration

ROUGE score

Recall Oriented Understudy for Gisting Evaluation

Compares candidates with reference human translations

Many variations

Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration

BLEU = precision

Attention and sequence generation — illustration

ROUGE = recall

Methods for construct a sentence

LSTM hidden state is concatenated with context vector

Which is passed to a dense layer followed by a softmax activation layer

What method to use to generate output token in the attention model?

The predicted token is sampled using decoding strategies like greedy decoding,

Random sampling or beam search

Attention and sequence generation — illustration
  1. Random sampling
    samples words according to their probability distribution

Can generate more diverse and interesting sequences
can be too random and produce less coherent sentences

Attention and sequence generation — illustration

Temperature in sampling

Parameter that controls randomness of predictions during sampling

Scale: 0-1, where 0 means low randomness (more conservative and predictable) and 1 means high randomness (more adventurous and varied).

Low Temperature: Suitable for making safe, predictable decisions (e.g., a confident but possibly boring output).

High Temperature: Allows for more creativity and variability, but with a higher risk of mistakes.

Attention and sequence generation — illustration

Greedy Decoding: Suitable for shorter sequences but can fail for longer sequences due to lack of context.

Random Sampling with Temperature: Allows balancing between coherence and creativity, depending on the application's needs.

method to explore multiple potential sequences simultaneously, aiming to find the most likely sequence of words given the input. Search operates with a fixed beam width BBB. At each decoding step, the algorithm maintains B candidate sequences.

Instead of maximizing the probability of individual words at each step, beam search evaluates the joint probability of entire sequences up to that point.

Minimum Bayes Risk (MBR)

Unlike traditional decoding methods like beam search or greedy decoding, which focus on maximizing the likelihood of individual words or sequences, MBR decoding aims to minimize the expected loss of an entire sequence based on a defined loss function.

Attention and sequence generation — illustration
Attention and sequence generation — illustration
Attention and sequence generation — illustration

Why Attention?

In Encoder decoder blocks using RNN, Encoder compresses the entire input sequence into a fixed-length context vector. Context vector is passed to decoder to generate the output sequence.

Context vector can lead to bottleneck, especially for long sequences as decoder might not capture all necessary information.

Attention mechanism addresses this issue by dynamically assigning weights to different parts of input sequence during decoding, allowing model to attend the most relevant input token

NLP — 🥩Simple Attention

Advantages:

  1. Improved Performance: model focuses on important parts of the source sentence, improving translation quality.
  2. Human-like Translation: Mimics human translation by allowing the decoder to refer back to the source.
  3. Solves Bottleneck Problem: Bypasses the restriction of a fixed-size context window, allowing more direct access to information.
  4. Mitigates Vanishing Gradient Problem: Facilitates gradient flow through deep networks, making training more stable.
  5. Interpretability: Provides insight into the model’s decision process by showing which parts of the source are focused on.
  6. Automated Alignment: Automatically learns alignment without additional training, simplifying the model.

Seq2Seq Model with Attention

• With attention, Seq2Seq model does not forget source input.

• With attention, the decoder knows where to focus.

• Downside: much more computation

Attention process:

  1. Compute alignment scores for all encoder hidden states
  2. Apply softmax to normalize scores into weights
  3. Calculate context vector as a weighted sum of encoder hidden states
  4. Use context vector + decoders previous state to generate next decoder state

\[\boldsymbol{a}_{\boldsymbol{i}}=\boldsymbol{Align}\left( {\,\boldsymbol{h}_{\boldsymbol{i}},\,\boldsymbol{s}_{\boldsymbol{o}}} \right)\]

Inputs:

  1. Inputs encoder hidden state at each time step
  2. Current state of decoder at time step t

Outputs:

Alignment Scores (): Scores that indicate how well each encoder hidden state aligns with the current decoder hidden state.

NLP — 🥩Simple Attention

Option 1 (used in original paper)

AKA Multi-layer perceptron ('Bahdanau Attention')

NLP — 🥩Simple Attention

weights

Are shared across all hidden states

\[T_{x}:length\,of\,input\,sequence\]

Step1: Compute alignment scores

\[\tilde{a_{i}}=v_{a}^{T}⋅tanh(W_{a}⋅h_{i}+U_{a}⋅s_{t})\]

​: A trainable matrix that projects the encoder hidden state ​ into a shared space.

​: A trainable matrix that projects the decoder hidden state ​ into the same shared space.

​: A trainable vector that computes a scalar score for each encoder-decoder pair.

: Adds non-linearity, allowing the model to capture complex dependencies between and .

Step2: Normalize scores

Alignment scores are converted into a probability distribution using softmax

\[a_{i}=\frac{\operatorname{exp}\left( \tilde{a_{i}} \right)}{\sum\nolimits_{j=1}^{T_{x}} {\operatorname{exp}(\tilde{a_{j}})}}\]

Each ​ represents the importance (or weight) of the i-th encoder hidden state for the current decoding step.

This step decides how much attention should be paid to each encoder hidden state when generating the current output.

Step3: Compute Context Vector

\[c_{t}=\sum\nolimits_{i=1}^{T_{x}} {a_{i}h_{i}}\]

The context vector is a weighted sum of the encoder hidden states

Step4: Update Decoder State

\[S_{t}=f(s_{t−1},\,y_{t−1},\,c_{t})\]

AKA Bilinear Function ('Luong Attention')

f: Usually a RNN cell like LSTM or GRU

Step1: Compute Key and Query Vectors

weights

\[k_{i}=W_{k}\,.\,h_{i}\]

Are shared across all hidden states

: Represents each encoder hidden state ​. These vectors are computed by applying a trainable linear transformation to the encoder states

: Trainable weight matrix

\[q_{t}=W_{q}\,.\,s_{t}\]

: Represents the decoder's current hidden state ​. It is computed similarly via another trainable linear transformation

: trainable weight matrix

These transformations project the encoder and decoder states into a shared space, making them comparable.

Attention and sequence generation — illustration

Step3: Normalize Scores Using Softmax

\[a_{i}=\frac{\operatorname{exp}\left( \tilde{a_{i}} \right)}{\sum\nolimits_{j=1}^{T_{x}} {\operatorname{exp}(\tilde{a_{j}})}}\]

Step4: Compute Context Vector (

\[c_{t}=\sum\nolimits_{i=1}^{T_{x}} {a_{i}h_{i}}\]

Step5: Update Decoder State

\[S_{t}=f(s_{t−1},\,y_{t−1},\,c_{t})\]

How RNN f( ) incorporates this new Context Vector

To incorporate the context ​ into the decoding process, it is concatenated with the previous output token's embedding

Fewer Parameters: Multiplicative attention eliminates the need for learned parameters like ​ in the additive approach. Only ​ are required.

The concatenation is represented as:

has dimension of d

has dimension of d

will have 2d dimension

However despite the concatenation. Hidden state remains d after processing

If hidden state dim d was changed, it would affect number of parameters in model making it more computationally expensive

(2 dim)

\[s_{t}=\operatorname{tanh}(W_{x^{′}}.x_{t}^{′}+W_{h}\,.\,s_{t−1}+b)\]

projects 2d into d

Time Complexity

𝑚: source sequence length

𝑡: target sequence length

Standard Seq2Seq: O(𝑚+𝑡) time complexity

Seq2Seq + attention: O(𝑚𝑡) time complexity

To compute one vector 𝐜, we compute 𝑚 weights: , ⋯,

The decode has 𝑡 states, so there are totally 𝑚𝑡 weights.

Option 3 Dot product

Attention and sequence generation — illustration

Step2: Normalize Scores Using Softmax

\[a_{i}=\frac{\operatorname{exp}\left( \tilde{a_{i}} \right)}{\sum\nolimits_{j=1}^{T_{x}} {\operatorname{exp}(\tilde{a_{j}})}}\]

Step3: Compute Context Vector (

\[c_{t}=\sum\nolimits_{i=1}^{T_{x}} {a_{i}h_{i}}\]

Step4: Update Decoder State

\[S_{t}=f(s_{t−1},\,y_{t−1},\,c_{t})\]

Softmax activation Function

NLP — 🥩Simple Attention

Transformer architecture

Attention is all you need(2017)

We didn’t needed convolutions but only just attention

Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration

Types of Attention

Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration

Multi head attention

Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration
Transformer architecture — illustration

Input Formatting: Articles are concatenated with an end-of-sequence (EOS) token, followed by the summary and another EOS token. This concatenated sequence is tokenized into integers for model input.

Training Setup: A weighted cross-entropy loss function is used during training. The loss focuses more on words within the summary part (weighted as 1) and less on words in the article (weighted as 0), allowing the model to prioritize learning important relationships for summarization.

Inference: During inference, the model predicts the next word in the summary by generating a probability distribution over possible words. Sampling from this distribution generates diverse summaries for the same input article.

Model Training and Use: The Transformer model is trained to predict the next word based on the concatenated input sequence. It learns to generate summaries by understanding relationships between words in the input article and generating coherent summaries.

Future Directions: The video hints at using more advanced Transformer models with pre-training for better summarization results, highlighting the ongoing advancements in natural language processing.

Transformer model (2017)

A Transformer is a neural network architecture that applies self-attention to process sequential data. Is a Seq2Seq model and not based on RNNs

Higher accuracy on large datasets compared to RNNs

Uses purely attention mechanisms and dense layers.

Handles long-range dependencies better than RNNs, and computation is parallelizable due to the self-attention mechanism.

Self-Attention:

Computes the importance of each input position with respect to every other position.

Attention for RNNs

This is option#2 revised

Process:

  1. Calculate Query (Q)
    Decoders current hidden state
    (to match others)
  2. Calculate Key (K)
    encoders hidden state
    (to be matched)
  3. Calculate Value (V)
    Same encoder states which are weighted and combined into context vector

(to be weighted averaged)

  1. Calculate alignment scores

\[\boldsymbol{a}_{:\boldsymbol{j}}=softmax\left( {\boldsymbol{K}^{\boldsymbol{T}}\boldsymbol{q}_{:\boldsymbol{j}}} \right)\]

  1. Calculate context vector

\[\boldsymbol{C}_{\boldsymbol{j}}=\boldsymbol{a}_{𝟏\boldsymbol{j}}\,.\,\boldsymbol{v}_{:𝟏}+…+\boldsymbol{a}_{\boldsymbol{mj}}\,.\,\boldsymbol{v}_{:\boldsymbol{m}}\]

  1. Concatenate context vector into RNN

Why we need to compute Attention without RNN?

\[S_{t}=f(s_{t−1},\,y_{t−1},\,c_{j})\]

  1. RNN is dependent on previous steps, time complexity grows linearly with input sequence length
  2. Sequential processing limits ability to parallelize computations, slowing down training and inference in GPUs
  3. As information still flows through many layers, diminishing gradients problem

Self-Attention without RNN

Attention layer: C = Attn(X, X')

Encoders input: X = []

Decoders input: X' = []

Self-attention layer: C = Attn(X, X)

Inputs: [

  1. Calculate Query (Q)
    Decoders current hidden state
  2. Calculate Key (K)
    encoders hidden state
  3. Calculate Value (V)
    Same encoder states which are weighted and combined into context vector

\[\boldsymbol{v}_{:\boldsymbol{i}}=W_{v}\,.\,x_{i}\]

  1. Calculate Self-attention Value

\[a_{:j}=softmax\left( {K^{T}.\,q_{:j}} \right)\]

  1. Calculate Context vector

\[c_{:j}=\boldsymbol{v}.softmax(\boldsymbol{K}^{\boldsymbol{T}}.\,\boldsymbol{q}_{:\boldsymbol{j}})\]

\[c_{:j}=a_{1j}.v_{:1}+…+a_{mj}.\,v_{:m}=va_{:j}\]

  1. Pass context values to FNN (additional content)

\[FNN\left( c_{j} \right)=ReLU\left( {W_{1}.c_{j}+b_{1}} \right).W_{2}+b_{2}\]

Skip connections

  1. Aagy poori wahi transformers wali calculation

…

Multi head attention

Self-attention using a single head tou kar hi liya.

Ye self-attention using multiple heads he.

Each head computes self-attention independently with its own parameters

Outputs from all heads are concatenated and linearly transformed with to produce multi-head output.

Weights are not shared between multi head attention layers

If each head produces matrix and there are l heads,

the concatenated output is .

After projecting concatenated output with the shape is returned to

Transformer architecture — illustration

Putting Everything together

NLP — 🥩Transformers-2

Inside a transformer

Seq-seq essentially consists of encoder and decoder

Encoder takes input and maps it into encoding scheme

Decoder takes the encoded scheme and decodes it to determine desired output

Issues with RNN, LSTM, GRU

→ Difficult to track large dependencies

→ Large inference + training time

Inside a transformer — illustration

Transformers

Seq-seq essentially consists of encoder and decoder

Non-recurrence model

Encoder takes input and maps it into encoding scheme

Consists of encoder unit and decoder unit

Decoder takes the encoded scheme and decodes it to determine desired output

For NNs the most commonly used methods to convert words into numbers is word embeddings

Issues with RNN, LSTM, GRU

Inside a transformer — illustration

→ Difficult to track large dependencies

Inside a transformer — illustration

→ Large inference + training time

Transformers

Non-recurrence model

Consists of encoder unit and decoder unit

Input to the embedding NN is one hot vector for the word for which we wanna create the embedding vector

Inside a transformer — illustration

Output is the x and y coordinates of the word's vector

There are many ways to do positional encoding

We only studied one method

Positional Encoding

Encoder

Inside a transformer — illustration
  1. Positional Encoding

Add context of positions in the sentence
inputs word embeddings
outputs positional embeddings

  1. Multi-head attention
    generates attention vectors

We will add a number to each word's

Embedding's dimension value to specify the word order

  1. Add and Norm
    adds matrices
    normalizes the layer

The numbers that represent word order comes

from Sine and Cosine waves

Inside a transformer — illustration
  1. Feed Forward

Purpose of this block is to make output vector more digestable to next decoder block of to linear layer

Inside a transformer — illustration

Decoder

  1. Masked Multi-head attention
    attention block on decoder side, generates attention vector for every word in output language.

This attention vector represents how much each word in output sentence is related to every word in the same sentence

Decoders multi-head attention is masked to ensure each position only attends to previous positions

Self-Attention

  1. Encoder decoder attention block
    takes input from encoder and input from decoder's Masked attention block

It Works by seeing how similar each word is to all of the words

in the sentence including itself

Determines attention vector from input to output

Inside a transformer — illustration

Outputs attention vectors

  1. Linear layer
    expands dimensions for output language
  2. Softmax layer
    transforms output into probablility distribution
    word with highest probability is selected
Inside a transformer — illustration

Encoder decoder model is executed several time steps until we reach the end of sentence

Why masking the inputs to decoder?

To ensure that the prediction for a given position only depends on the positions before it, not on the future positions.

Training

Why shift right?

Inside a transformer — illustration

We shift right the decoders input by one step to ensure that predictions are made autoregressively during training

At each step, the model has access to previous tokens and not the current or future one

Mimicking actual conditions during inference

Inside a transformer — illustration

If you looked at a lot of sentences about 'pizza'

Encoder input

and word 'it' was more commonly associated with pizza than oven

Input sequence of tokens from input language

Then similarity score for 'pizza' will cause 'it' to have larger impact on how

Word 'it' is encoded by transformer

Encoder output

Sequence of vectors, each vector represents a token in input sequence transformed through self attention layers and feed forward to capture contextual information

Calculating Self attention of 'lets' against 'go'

Decoder input

Inside a transformer — illustration

Shifted sequence

First word is filled with start of sentence token

Output from decoder

End of sentence is mark to end of sentence

Probabilities for next token at each position in target sequence

Process

  1. Sequence of words at input is converted into embeddings
    transformed into positional embeddings
    fed to encoder
  2. Stack of Encoders produce encoded representations
  3. Words which have been generated so far are inputted to decoder as a sequence
  4. Stack of decoders inputs encoded representations and positional embeddings
    produces encoded representations for output
  5. Decoder outputs probabilities of the next word in sequence.
    Total number of neurons at output layer is total number of unique words in corpus
  6. At output loss function is used to compare predicted words with actual output
Inside a transformer — illustration

Inference

We begin with start of sequence and begin keep adding the next

word with highest probability

process

  1. Input English sentence to encoder and start of sequence to decoder
  2. Add first output word in seq of decoder
  3. Iterate by appending decoder sequence and predicting next word in decoder seq until <EOS> input token reached

Positional encoding

\[P\left( k,\,2i \right)=sin\left( \frac{k}{n^{\frac{2i}{d}}} \right)\]
\[P\left( k,\,2i+1 \right)=cos\left( \frac{k}{n^{\frac{2i}{d}}} \right)\]

To calculate self-attention for 'go' you don’t need to calculate key and values again, they remain same

You just need to create the query that represents the word 'go'

L: length of sequence

Calculate similarity scores between new query and keys

k: position of object in input sequence

Run the similarity score through the softmax

d: dimension of output embedding space

Scale the values

P(k, j): outputs positional embedding. k, j are indexes in positional matrix

Then add them

n: user defined scalar

Then we get the self attention values for 'go'

i: used to map column indices

Inside a transformer — illustration
Inside a transformer — illustration

Compute in Radians

Scaled-dot Attention

Query (Q):
Search term you enter into the search engine. This is what you are looking for.

Keys (K):
The indexed terms or metadata associated with web pages, such as titles, descriptions, and keywords. These help the search engine understand what each page is about.

Values (V):
The actual web pages or the content that the search engine returns as results. These pages contain the information you want.

Blue stuff is same weights

Inside a transformer — illustration

Red stuff in different values

We reuse the same weights for self-attention queries, keys and values

Inside a transformer — illustration

We don’t have to calculate query key and value for first word first, before moving on to the second word

We can calculate queries, keys and values for each word at the same time

Transformers can take advantage of parallel computing and run fast

We can create a stack of self-attention cells each with its own weights that we apply to position encoded words to capture different relationships among words

Stacking 8 self-attention cells is called multi-head attention

\[Attention\left( Q,\,K,\,V \right)=softmax\,\left( \frac{QK^{T}}{\sqrt{d_{k}}} \right).\,V\]
Inside a transformer — illustration

We divide by to standardize the outputs

The outputs of scaled-dot Attention are attention vectors

Inside a transformer — illustration

We use multi-head Attention to run attention mechanism in parallel

Inside a transformer — illustration

Green part is the self-attention cell

Linearity in multi-head Attention purpose:

  1. Mapping Input to Output
  2. Reduce dimensions
Inside a transformer — illustration

ith head in Attention

\[head_{i}=Attention(QW_{i}^{Q},\,\,KW_{i}^{K},\,\,VW_{i}^{V})\]

Concatenation in Multi-head

\[MultiHead\left( Q,\,K,\,V \right)=Concat(head_{1},\,…\,,\,head_{h})W^{o}\]
Inside a transformer — illustration

These 4 features allows transformers to

  1. Encode the words into numbers
  2. Encode position of words
  3. Encode the relationships of words
  4. Train quickly in parallel

Residual Connection

Purpose:

Inside a transformer — illustration
  1. Knowledge preservation, forward propagation modifies input considerably by time it reaches last layer. Results in loss of information
  2. To solve Vanishing gradient problem

We can add as many of these for each input word

Types of transformers

  1. Encoder only
    BERT
    code Bert
    Med Bert
  2. Decoder only
    ChatGPT
  3. Encoder Decoder
    Text-to-Text transformer

Transformer can do computation for each word in the input at the same time

We can calculate word embeddings on different processors at the same time

Add positional encoding at the same time

Calculate queries, keys and values at the same time

And once that is done, we can calculate self-attention values at the same time

We can calculate residual connections at the same time

Inside a transformer — illustration

Encoder with its Decoder

Inside a transformer — illustration

Make query for word 'x' in decoder

Create keys for each word in encoder

Calculate similarities between word 'x' and keys by calculating Dot products

We run similarities through SoftMax function

Which tells which word to use 100

Inside a transformer — illustration
Inside a transformer — illustration

Ek Tareeqy se Encoder Decoder ki attention values ka bhi ek cell bnjata

Inside a transformer — illustration

We then pass the encoder decoder attention values to a fully connected layer, we get the output translation for let's go = vamos

Inside a transformer — illustration

Basic architecture of a Transformer

BERT and language-model pretraining

BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration

Oldest model:

BERT and language-model pretraining — illustration

Masked Language Modelling (MLM)

In BERT training process some words are

replaced with [MASK] token

BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration

The BERT loss function takes into consideration only the prediction

of the masked values and ignores the prediction of the non-masked words.

As a consequence, the model converges slower than directional models, a

characteristic which is offset by its increased context awareness

BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration

GLUE benchmark

(General Language Understanding Evaluation)

BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration
BERT and language-model pretraining — illustration

- Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer (Raffel et al, 2019)

- Reformer: The Efficient Transformer (Kitaev et al, 2020)

- Attention Is All You Need (Vaswani et al, 2017)

- Deep contextualized word representations (Peters et al, 2018)

- The Illustrated Transformer (Alammar, 2018)

- The Illustrated GPT-2 (Visualizing Transformer Language Models) (Alammar, 2019)

- BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding (Devlin et al, 2018)

- How GPT3 Works - Visualizations and Animations (Alammar, 2020)

Bidirectional Encoder Representations from transformers

Developed by Google in 2018

Based on transformer architecture

Bidirectional, looks at context of word from both directions

Takes tokenized text as input

Output is a sequence of vectors representing relationships between words

How language models evolved

NLP — 🥩Survey paper

01: Introduction

Language modeling began in the 1950s using n-gram models, with motivation to perform machine translation and a desire to enable machines understand and generate human language.

Evolution of Language Models through time

  1. Statistical Language Models (SLMs): Early models used n-grams to predict word sequences. They dealt with data sparsity through smoothing techniques.
  2. Neural Language Models (NLMs): Utilized continuous vector embeddings to predict words which dealt with data sparsity and introduced semantic similarity
  3. Pre-trained Language Models (PLMs): General-purpose models pre-trained on vast text corpora followed by fine-tuning on specific tasks.
  4. Large Language Models (LLMs): Transformer-based models with hundreds of billions of parameters, trained on massive text data. They exhibit stronger language understanding, emergent abilities like in-context learning, instruction following, and multi-step reasoning.

LLM Capabilities:

  1. In-Context Learning: Ability to learn new tasks from few examples
  2. Instruction Following: Ability to follow new types of tasks without proper examples
  3. Multi step reasoning: Ability to break down complex tasks into steps
  4. Augmentation techniques: LLMs can interact with external knowledge
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration
How language models evolved — illustration

Building with LangChain

The final sections connect these model ideas to applications: loading documents, splitting text, creating embeddings, and retrieving context.

Build simple app with langchain

Trace application with langsmith

Server application with langserve

Important components of LangChain

  1. Data ingestion from data sources
  2. Data Transformation into textual chunks
  3. Conversion of chunks into embeddings
  4. Storing vectors into vector store DB

LangChain data ingestion techniques

Means loading datasets from specific sources

Converts various file types into documents for further processing

Document loader types:

  1. Text loader

Converts text file content into a document with metadata

Code
from langchain_community.document_loaders import TextLoader
Code
loader = TextLoader("speech.txt")
Code
documents = loader.load()
Code
print(documents)
  1. PDF loader

Converts page of PDF into separate document

from langchain_community.document_loaders import PyPDFLoader

loader = PyPDFLoader("attention.pdf")

documents = loader.load()

print(documents)

  1. Web Base Loader

Extracts content from webpage, text and metadata

from langchain_community.document_loaders import WebBaseLoader

loader = WebBaseLoader("https://example.com")

documents = loader.load()

print(documents)

  1. ArXiv Loader

Loads the research paper content into documents

from langchain_community.document_loaders import ArXivLoader

loader = ArXivLoader(query="1706.03762", load_max_docs=2)

documents = loader.load()

print(documents)

  1. Wikipedia Loader

Retrieves wikipedia content related to query

from langchain_community.document_loaders import WikipediaLoader

loader = WikipediaLoader(query="Generative AI", load_max_docs=2)

documents = loader.load()

print(documents)

Text Splitting techniques

Convert documents into textual chunks for processing by LLM models with limited context size

Why split text into chunks?

  • LLMs have maximum token/chunk size
  • Divide documents into smaller chunks for processing

1. Recursive character text splitter

Recursively splits text by characters.

from langchain_text_splitters import RecursiveCharacterTextSplitter

text_splitter = RecursiveCharacterTextSplitter(

chunk_size=500,

chunk_overlap=50

)

final_documents = text_splitter.split_documents(docs)

Returns List of smaller documents with overlapping text.

2. Character text splitter

If the separator is not found, it creates larger chunks than specified.

from langchain_text_splitters import CharacterTextSplitter

text_splitter = CharacterTextSplitter(

separator="\n", # Split by newline

chunk_size=100,

chunk_overlap=20

)

3. HTML Header text splitter

Structure aware chunker that splits at HTML element levels

Preserves semantic grouping of related text

from langchain_text_splitters import HTMLHeaderTextSplitter

headers_to_split_on = [

("h1", "Header 1"),

("h2", "Header 2"),

("h3", "Header 3"),

]

html_splitter = HTMLHeaderTextSplitter(headers_to_split_on=headers_to_split_on)

html_string = """

<!DOCTYPE html>

<html>

<body>

<h1>Foo</h1>

<p>Some intro about foo.</p>

<div>

<h2>Bar</h2>

<p>Some intro about bar.</p>

<h3>Baz</h3>

<p>Some intro about baz.</p>

</div>

</body>

</html>

"""

html_header_splits = html_splitter.split_text(html_string)

  • Header: <h1>Foo</h1>
  • Content: "Some intro about foo."
  • Metadata: {"header": "Header 1", "content": "Foo"}
  • Header: <h2>Bar</h2>
  • Content: "Some intro about bar."
  • Metadata: {"header": "Header 2", "content": "Bar"}
  • Header: <h3>Baz</h3>
  • Content: "Some intro about baz."
  • Metadata: {"header": "Header 3", "content": "Baz"}

4. JSON Data Splitting

Used to split a large JSON data from an API into manageable chunks for further processing

Splits JSON data while controlling chunk sizes.

Embedding techniques

Types of recent embeddings

  1. OpenAI Embedding:

Paid service. High accuracy. Models like text-embedding-3-large and text-embedding-3-small are used. Output dimensions: 3072 (default) or customizable (e.g., 1024).

  1. Llama:

Open source. Can be run locally.

  1. Hugging Face:

Open source. Popular for embedding techniques.

Basic RAG project flow

  1. Load Documents
Code
from langchain_community.document_loaders import TextLoader
Code
loader = TextLoader("docs/sample.txt")  # Load text file
Code
documents = loader.load()  # Returns document objects
  1. Split text into chunks
Code
from langchain.text_splitter import RecursiveCharacterTextSplitter
Code
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
Code
texts = text_splitter.split_documents(documents)

chunk_size=500 → Each chunk has 500 characters.

chunk_overlap=50 → Overlapping 50 characters between chunks helps keep context.

  1. Convert text into vector embeddings and store in FAISS
Code
from langchain.vectorstores import FAISS
Code
from langchain.embeddings import OpenAIEmbeddings
Code
embeddings = OpenAIEmbeddings()  # Use OpenAI to generate embeddings
Code
vector_store = FAISS.from_documents(texts, embeddings)  # Store embeddings in FAISS
  1. Retrieve relevant chunks
Code
Retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 3})
  1. Generate AI powered response (RAG Chain)
Code
From langchain.chains import RetreivalQA
Code
From langchain.chat_models import ChatOpenAI
Code
Qa_chain = RetrievalQA.from_chain_type(llm=ChatOpenAI(model="gpt-4"), retriever=retriever)
  1. Query and Get AI Response
Code
Query = "what is the main topic of the document?"

Vector DB

Code
Response = qa_chain.run(query)

Some vector databases

Code
Print('Ai response:', response)

FAISS (Facebook AI Similarity Search): Library for efficient similarity search and clustering of dense vectors.

Chroma DB: Another vector store to be explored.

Astra DB: Cloud-based vector store using Cassandra DB, to be demonstrated in end-to-end projects

Querying vector store

Similarity Search: Querying the vector store to find relevant documents based on a query.

Retriever Interface: Converting the vector store into a retriever for easier integration with other LangChain methods.

Similarity Search with Score: Using similarity_search_with_score to get documents along with their L2 (Manhattan) distance scores.

Retrieval-augmented generation

RAG components

  1. Indexing:

Raw data is preprocessed and transformed into chunks(nodes)

Each chunk is embedded into a vector space using an embedding model
Index is like a dictionary that stores vector embeddings as keys and chunks as values

Similar data points are grouped together

  • Embed user query into same high dimensional vector space.
  1. Cosine similarity
  2. Euclidean distance
  3. Dot product
  • For large datasets, finding exact nearest neighbors can be slow,
    FAISS, HNSW, Annoy can be used to return approximate results
  • Query expansion involves processing users query before performing search, ensures query retrieves more relevant information
  • During querying metadata can be used to filter results to make search context-aware
  • Re-ranking involves re-ranking the documents after first retrieval after a re-evaluation to generate a better response
  • Concatenating retrieved documents with user query to provide additional context
  • We can use knowledge injection to inject domain specific knowledge into the system
  1. Generation:

Uses LLM to generate response based on augmented data

  1. Orchestration:

Manages flow between components

Implements caching

  1. Evaluation and monitoring:

Collects users feedback

Monitors response accuracy

Query translation

Converting query into a form so it can be understood correctly, types:

  1. Extract the semantic behind the query
  2. Extract keywords in query
  3. Extract intention of query

Chunking methods

Breaking down large dataset into smaller manageable chunks

  1. Fixed size chunking:
    Documents are divided into fixed size chunks, may lead to a loss of contextual understanding.
  2. Sentence based chunking:
    Each chunk corresponds to single sentence, leads to many small chunks.
  3. Paragraph based chunking:
    Documents are chunked by paragraphs, may result in chunks that are too large.
  4. Sliding window chunking:
    A sliding window chunks the text into overlapping windows, leads to redundancy
  5. Semantic chunking:
    Breaks chunks into conceptual units, requires sophisticated NLP techniques to detect boundaries
  6. Token Based chunking:
    Text is chunked into transformers based tokens, not suitable for every application
  7. Hierarchical chunking:
    Chunking based on paragraphs, sentences, words ek saath. Requires more computational resources and more sophisticated indexing methods
  8. Graph based chunking:
    Content is clustered and relationships are formed between chunks. Resource intensive

Retrieval methods

  1. Embedding based retrieval:
    use cosine similarity to find relevant documents
  2. Multi hop retrieval:
    using re-ranking to refine documents retrieval
  3. Query expansion:
  4. Dense retrieval:
    using embeddings and vectors to measure semantic similarity
  5. Sparse retrieval:
    using TF-IDF or BM25 to get sparse vectors then retrieving the documents

Types of RAGs

  1. Multi-Query RAG:
    Generates multiple variations of users query and combines results
  2. RAG Fusion:
    Does the same thing as multi query but combines the results
  3. Query decomposition
    Breaks long queries into atomic queries, then combines the results
  4. Step-Back Prompting
    Extracts the semantics behind the query and retrieves general and specific information
  5. Hypothetical Document Embeddings (HyDE)
    Creates a hypothetical perfect document answering the query, use this document to perform retrieval
  6. Self-RAG:
    System evaluates and improves on its own responses
  7. Corrective RAG:
    Implements feedback loops to improve accuracy