NLP Notes
NLP Notes
Arun Sharma K
How ML What are the What are
Basics of Text Utilizing LLMs
processing
models SOTA DL LLMs and
and RAGs Foundation
process test models RAGs
Day Plan
Participate
Sessions
1 2
• Unstructured Vs structured • Feature engineering
• Need for NLP • Frequency based
• Typical applications • Sematic based
• Aspects of NLP • Hands-on
• Workflow
• Clean-up
• EDA
• Hands-on
NLP:Session-1
Structured Vs Unstructured
Need for NLP
• Managing
• Storing
• Analyzing
Generation (NLG)
NLU Vs NLG
• NLG is the inverse of NLU
• NLG maps from meaning to text, while
NLU maps from text to meaning
• NLG is easier than NLU because a NLU
system cannot control the complexity
of the language structure it receives as
input while NLG links the complexity of
the structure of its output.
[Link]
Typical Applications of NLP
• Spell Checking
• Text Classification
• Sentiment Analysis/opinion mining
• Question Answering
• Automatic Summarization
• Text suggestion
• Machine Translation(statistical machine translation)
• Speech Recognition
Workflow
• In house documents
• Encoding/
Application Embedding method • Mode
• Web-based Expertise sensitive • POS tagging (??)
• Augmentation • MLOPS strategies
• Digitized
[Link]
Lemmatization
• Lemmatization: unlike Stemming, reduces the inflected words
properly ensuring that the root word belongs to the language. In
Lemmatization root word is called Lemma.
• runs, running, ran are all forms of the word run, therefore run is the
lemma of all these words
Hands-on link
^[a-zA-Z0-9._]+@[a-zA-Z0-9]+.[a-zA-Z]{2,}$ ^\d{10}$
• ^ asserts the start of the string. • ^ asserts the start.
• [a-zA-Z0-9._]+ matches the username (1+ alphanumeric, • \d{10} matches exactly 10 digits.
dots, underscores).
• $ asserts the end.
• @ matches the literal "@" character.
• word2Vec
• Count vectorization
• Glove
• TF-IDF vectorization
• ELMO
• N-gram
• BERT, SBERT
• GPT
• Custom embedding
Bag of words
documents
• I like to eat apples
corpus • I hate bananas
• I like apples and bananas
# And Apples bananas eat hate I like to I like like to to eat eat I hate like apples and TARG
apples hate bananas apples and bananas ET
1 0 1 0 1 0 1 1 1 1 1 1 1 0 0 0 0 0 1
2 0 0 1 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0
3 1 1 1 0 0 1 1 0 1 0 0 0 0 0 1 1 1 1
Color embeddings
[1,0.5,0]
Orange [R,G,B]:[1,0.5,0] the feature vector way
• LD representation
• Captures similarity
• compare orange and Blue [1,0.5,0]-[0,0,1] large difference
• compare orange and red [1,0.5,0]-[1,0,0] less difference
• Essentially a FA type DR method
Context matters
• We watched a monkey swing effortlessly between the trees.
• My son tends to monkey around with the settings on the phone,
causing unintended changes.
• he is a rich man
• he is rich manuel
Adjacent words add to/ modify the meaning of the word
Word embedding
• Word embeddings are word representation as vectors in a multi-dimensional
space, that allows words with similar meaning to have a similar representation
• leads to a low dimensional dense matrix
• Each word is represented by a real-valued vector, often tens or hundreds of dimensions.
• This is contrasted to the thousands or millions of dimensions required for sparse word
representations
• Convert input OHE matrix (HDS) to real-valued vector(LDD)
• semantic-Based Vector Space Model
Distributional semantics
Distributional hypothesis: linguistic items with similar distributions have similar meanings.
Word embedding: the idea
16 colors
Color embeddings
[1,0.5,0]
Orange [R,G,B]:[1,0.5,0] the feature vector way
• LD representation
• Captures similarity Word embedding A DR technique applied to text data
• compare orange and Blue [1,0.5,0]-[0,0,1] large difference
• compare orange and red [1,0.5,0]-[1,0,0] less difference
• Essentially a FA type DR method
Word embedding: the idea
• The relationships between words in the embedding space lend themselves to unusual
word algebra, allowing words to be added and subtracted, and the results actually
making sense. For instance, in a well-defined word embedding model, calculations such
as (where [[x]] denotes the vector for the word ‘x’)
Word embedding
• Word embeddings are dense vector representations of words that
capture meaning based on word usage patterns in large corpora
• The central idea of word embedding is that similar words are typically
surrounded by the same “context” words
• So similar words have similar embeddings
• Word embeddings don’t “understand” definitions of words (like in a
dictionary). Instead, they understand patterns of usage (statistical).
Word embedding
V1
Word embedding
V2
V1 V3
V4
V5
After the soft drizzle, the petrichor rising from the parched soil was intoxicating
For the farmers, petrichor was more than a scent—it was a signal that life was beginning again.
When she opened the window, the petrichor wafted in, evoking memories of childhood monsoons
Word embedding
After the soft drizzle, the petrichor rising from the parched soil was intoxicating
For the farmers, petrichor was more than a scent—it was a signal that life was beginning again.
When she opened the window, the petrichor wafted in, evoking memories of childhood monsoons
Large data association with relevant words such as smell, monsoon, rain, drizzle
Different Embedding approaches
Embedding
[I am learning NLP] ML/MLP
extraction
0.1 0 0.2 0
1. Word2Vec 0.3 0.4 0.3 0.1 n × m Tensor for ‘m’ words/tokens
0.8 0.6 0.4 0
2. Glove 0.9 0.2 0.7 0.7
, , ,
| | | | How to use this Tensor as input?
3. FastText | | | |
| | | | 1) Aggregation Not a smart idea
4. ELMO (Sequential model-based) 0 0.5 0.1 0.2
2) Sequential models
5. BERT ( Transformer-based)
‘n’ dimensional
3) Transformers
matrix for each word
Google News is a news aggregator app developed by Google. It presents a continuous, customizable flow of
articles organized from thousands of publishers and magazines. Google News is available as an app on Android,
iOS, and the Web. Google released a beta version in September 2002 and the official app in January 2006.’
Sequential models Hidden states
Context vector
BERT, GPT, T5
Embedding
[I am learning NLP]
extraction
Transformer (ENCODER)
[Link]
CBOW
• Uses a neural network to predict a target word,
given a context of words
• Create embeddings for the target word
• Has a projection/ averaging layer
• No activation function for the hidden layer
• SoftMax AF for the output layer.
• Weights are learnt for vocabulary classification
(given context words, predict the probability of
target words)
• Once trained on a corpus, the OL can be
discarded since we are interested only in the
EL/HL output
Skip-gram
• Uses a neural network to predict context
words, given a target word
• Create embeddings for the target word
• No activation function for the hidden layer
• SoftMax AF for the output layer.
• Once trained on a corpus, the OL can be
discarded since we are interested only in
the EL/HL output
CBOW Vs. Skip-gram
• Skip-gram: works well with small amount of the training data,
represents well even rare words or phrases.
• CBOW: several times faster to train than the skip-gram, slightly better
accuracy for the frequent words.
Applications of W2V
• Analyzing Survey Responses
• Recommendation systems
GloVe
• Global Vectors for Word Representation
• Developed by Stanford University
• Glove is an unsupervised learning algorithm for obtaining vector
representations for words. Training is performed on aggregated global
word-word co-occurrence statistics from a corpus, and the resulting
representations showcase interesting linear substructures of the word
vector space ([Link]
• The word vector representation is in terms of a ratio of probability
GloVe
• I love programing.
• I love Math.
• I tolerate Biology
• to sanction is to permit
• put sanction on means not permit (same word different meaning)
• W2V and Glove lead to same vector for the words read/sanction in these
the sentences
● Input/output size
○ Fixed in NS
○ Varies in S
Activation Functions in RNNs
Sigmoid
Sigmoid and tanh
Sigmoid, tanh, ReLu
Sequential model ANNs
+
0.543609
0.53384
Ux2 +Wh1+b
T
0.56074 W
U
0.49956 0.77321
0.579995
+ Ux3 +Wh2+b
T
U
0.833438 0.493182
U
x1 x3 0.551826
x2
0.92 0.609265
0.56 0.19
0.38 0.03 0.23
0.19 0.45 0.24
I LOVE NLP
0.239 0.314
U= 0.423 w= 0.329 b=0.4
0.524 0.428
LSTM
● The intuition:
Intuition: Forgetting unnecessary information helps Intuition: Capture relevant new information without
the model avoid "clutter." overwriting important long-term knowledge.
Intuition: Controls what parts of the cell state are Intuition: The cell state acts as a "memory bank," retaining key
immediately relevant for the task. information across time steps.
Forget Gate
Decides which parts of the previous cell state (𝑐𝑡−1 ) are no
longer relevant.
Intuition: Forgetting unnecessary information helps the
model avoid "clutter."
xt
The update gate acts similar to the forget and input gate of an
h
LSTM.
It decides what new information to add
Bidirectional LSTM Vs Transformer
As opposed to directional models, which read the text input sequentially (left-to-right or right-to-
left), the Transformer encoder reads the entire sequence of words at once. Therefore it is considered
bidirectional, though it would be more accurate to say that it’s non-directional. This characteristic
allows the model to learn the context of a word based on all of its surroundings (left and right of the
word).
Greedy Vs Beam
Greedy
First word “The”
● [Link]
● [Link]
step-by-step-explanation-44e9eb85bf21
● [Link]
lessons-learned-c62fb1d3485b
Transformers
Elements of Transformers
Encoder
• Word embedding
• Position encoding
• Multi-headed self-Attention
• Skip Connections and Layer Normalization
Transformers • Feed forward
Decoder
• Position encoding
• Multi-headed self-Attention
• Masked Multi-headed attention
• Encoder-Decoder attention
• Skip Connections and Layer Normalization
• Linear and SoftMax
Generates the output sequence (such as the translated sentence)
by attending to both the encoded input and the previously
generated output
Encode-Decoder
Encoder
[ T1, T2, T3,---------Tm]
[ output sequence]
राहुल एक अ छा लड़का है
[ T1, T2, T3,---------Tn]
[ input sequence]
Rahul is a good boy
Transformer types
Encoder-Decoder machine translation, summarization,
and text generation
• BART, M2M, mBART
Bidirectional and Auto-Regressive Transformers
0.32
0.21
Lamborghini [0.65,0.74]
Grapes [0.32,0.21]
Contextualized Embeddings using self-
attention
0.32
0.21
• Where should the word ‘apple’ fit?
0.32
0.21
Apples are generally grown in regions with temperate climates where winters are cold
enough to allow the trees to go dormant and summers are warm enough to promote
fruit growth.
Words that establish what apple refers to fruit, trees, grown, climate region
Contextualized Embeddings using self-
attention
0.32
0.21
Apple launched its new iPhone*** in September. iPhone*** is Apple’s premium model, popular for its build quality and
software integration. A model class apart from its competitors.
Words that establish what apple refers to:
0.32
0.21
Apple Inc. is a leading technology company known for its innovative products. It has revolutionized consumer electronics
with focus on sleek design, user-friendly interfaces, and seamless ecosystem integration.
Words that establish what Apple refers to: innovative, technology, consumer,
electronics, sleek, user-friendly, seamless, ecosystem
Multi-headed self-attention
The meaning of the word depends on words that may or may not be in the immediate neighbourhood
Steps in SA:
64
Steps in SA:
STEP-1
• Create three vectors from each of the
encoder’s input vectors. For each word, we
create a Query vector, a Key vector, and a
Value vector
• These vectors are created by multiplying
the embedding by three matrices that we
trained during the training process
Self Attention
Steps in SA:
STEP-2
• Calculate scores for each word input
against the other words. The score
determines how much focus to place on
other parts of the input sentence as we
encode a word at a certain position
Steps in SA:
STEP-3 and 4
• Divide by 8
This SoftMax score determines how much each word will be expressed at this position. Clearly the word at its position will
have the highest SoftMax score, but it’s useful to attend to another word that is relevant to the current word
Self Attention Steps in SA:
STEP-5 and 6
• multiply each value vector by the SoftMax
score. The intuition here is to keep intact
the values of the word(s) we want to focus
on, and drown-out irrelevant words
This SoftMax score determines how much each word will be expressed at a position. Clearly the word at its own position
will have the highest SoftMax score, but it’s useful to attend to another word that is relevant to the current word
Multiheaded attention
Multi-head attention
Transformer: more details
Transformer: positional encoding
● [Link]
[Link]#subsec-positional-encoding
Training
• The causal mask is applied to ensure that each token can only "see" the previous
tokens since the entire sequence is available during training, This keeps the model
from cheating
Inferencing
• Masking is turned off in the last layer. The other layers still see masking to maintain
consistency between training and inferencing
Masked Multi headed self-attention
Applying mask:
[[Link], [Link], -108, -108, -108, -108, -108] Masked matrix for predicting the next word (“going”) Q.K output
[SOS]
Encoder Decoder
[SOS] यह
Encoder Decoder
[SOS] यह एक
Encoder Decoder
[SOS] यह एक अ छ
Encoder Decoder
• BERT architecture is a multi-layer bidirectional Transformer encoder. We have two versions of BERT: BERT base and BERT large.
• BERT base has 12 Encoders with 12 self-attention heads and 110 million parameters
• BERT large has 24 Encoders with 24 self-attention heads and 340 million parameters
• When training the BERT model, Masked LM and Next Sentence Prediction are trained together, with the goal of minimizing the
combined loss function of the two strategies
• Masked LM (MLM): Before feeding word sequences into BERT, 15% of the words in each sequence are replaced with a [MASK]
token. The model then attempts to predict the original value of the masked words, based on the context provided by the other,
non-masked, words in the sequence
• Next Sentence Prediction(NSP): During training, 50% of the inputs are a pair in which the second sentence is the subsequent
sentence in the original document, while in the other 50% a random sentence from the corpus is chosen as the second sentence.
The assumption is that the random sentence will be disconnected from the first sentence.
BERT models
Key Differences /
Model Size / Params Architecture Pretraining Objective Use Case Highlights
Improvements
MLM (Masked
General NLP tasks
Base: 110M Encoder-only Bidirectional; trained Language Modeling)
BERT (classification, QA,
Large: 340M Transformer with MLM + NSP NSP (Next Sentence
NER)
Prediction)
Removes NSP, uses
Improved
Base: 125M more data, longer
RoBERTa Encoder-only MLM only performance across
Large: 355M training, dynamic
tasks
masking
Lightweight version of
Encoder-only (6 Faster inference, low-
DistilBERT 66M (40% smaller) BERT, distilled from Distillation + MLM
layers) resource deployment
BERT
Parameter sharing +
MLM + SOP
Base: 12M factorized embedding Efficient training,
ALBERT Encoder-only (Sentence Order
XXL: 235M + sentence-order memory savings
Prediction)
prediction
Distilled BERT with
Encoder-only (4 task-specific Mobile-friendly
TinyBERT ~15M task-specific
layers) distillation deployment
distillation
BERT models
Key Differences / Pretraining
Model Size / Params Architecture Use Case Highlights
Improvements Objective
Trained to predict
Span Boundary
SpanBERT Similar to BERT Encoder-only entire spans, not NER, QA
Objectives
just tokens
BERT pretrained on
BioBERT BERT-Base (110M) Encoder-only MLM + NSP Biomedical NLP
biomedical corpora
Pretrained on
ClinicalBERT BERT-Base (110M) Encoder-only clinical notes MLM + NSP Healthcare NLP
(MIMIC-III)
Disentangled MLM + R1 Loss SOTA on many
Base: 139M Encoder-only
DeBERTa attention + relative (replaced token GLUE/SuperGLUE
Large: 385M (disentangled)
position encoding loss) tasks
Replaces MLM with
RTD (Discriminator
Encoder-only Replaced Token
ELECTRA Base: 110M trains on corrupted Efficient pretraining
(Discriminator) Detection (RTD);
input)
more efficient