CPSC 330 Lecture 18: Introduction to NLP, LLMs, and RAG

Varada Kolhatkar

Focus on the breath!

Announcements

  • HW7 was due yesterday
  • HW8 has been released (due next week Monday)
    • Almost there! Hang in there 😊
  • Midterm 2 grading is in progress.

iClicker

Select all of the following statements which are TRUE for you.

    1. I found the multiple-choice questions challenging.
    1. The coding questions took a lot of time.
    1. I didn’t like the format of the midterm.
    1. I appreciated the mix of coding, conceptual, and multiple-choice questions.
    1. I felt the midterm was a good reflection of what we cover in the lectures and homework assignments.

iClicker: Guess before we start

Select all statements you think are true. No prior knowledge of NLP is needed.

  • A. ChatGPT or Claude can give a confident answer that is factually wrong.
  • B. A search system can find a relevant document even if it shares no words with the query.
  • C. Giving ChatGPT or Claude relevant documents can help reduce factual errors in its answer.
  • D. If you Google “When is the CPSC 330 final exam?”, the top result must give the correct date for your section this term.

Today’s big questions

  1. How can we represent text numerically?
  2. How can we retrieve information relevant to a question?
  3. How can a language model answer using evidence?

Text representations \(\to\) retrieval \(\to\) language models \(\to\) RAG

What is natural language processing?

Natural Language Processing (NLP) develops computational methods for analyzing and generating human language.

But interpreting language is not always straightforward …

Language can be ambiguous

Ambiguity: What does it refer to?

Ambiguous news headlines

PROSTITUTES APPEAL TO POPE
KICKING BABY CONSIDERED TO BE HEALTHY
MILK DRINKERS ARE TURNING TO POWDER

Why are these funny?

Language is ambiguous. We use context, world knowledge, and common sense to interpret it.

What should a text representation capture?

Machine learning models need a numerical representation of that language.

The goal is not to capture every aspect of a sentence’s meaning. Ask:

Does the representation preserve the information needed for our task?

Text representations

A campus-survival catalog

14 documents: 12 products and 2 articles. Each full description is a document.

product_id title text
C001 Sony WH-1000XM6 headphones Over-ear wireless headphones with active noise cancellation and up to 30 hours of battery life. Useful for studying in noisy spaces.
C002 Pocket power bank Portable 20,000 mAh battery with two USB-C ports. Recharges mobile devices several times when wall power is unavailable.
C003 Waterproof laptop backpack Rain-resistant backpack with sealed zippers and a padded compartment for a 16-inch laptop. Keeps electronics and notes dry during wet commutes.
C004 Sunrise alarm clock Gradually brightens the room before the alarm sounds. Designed to make waking up on dark winter mornings easier.
C005 Ergonomic keyboard Split keyboard with a padded wrist rest. Designed to reduce wrist strain during long typing and programming sessions.
C006 Laptop stand Raises a laptop screen to eye level and folds flat for carrying. An external keyboard is recommended for prolonged use.
C007 USB-C hub The HUB-7X adds HDMI, Ethernet, an SD-card reader, and three USB ports to laptops with limited connections.
C008 Insulated travel mug Leak-resistant 500 mL mug that keeps coffee hot for eight hours. Fits standard campus cup holders.
C009 Pomodoro timer Distraction-free timer with 25- and 50-minute study modes. It does not connect to a phone.
C010 Bike-light set Rechargeable front and rear bicycle lights with weather-resistant housings. Improves visibility when commuting after dark.
C011 Mini rice cooker Compact rice cooker suitable for a dormitory kitchen. Makes two servings and switches automatically to warming mode.
C012 White-noise machine Produces fan, rain, and ambient sounds without playing music. Intended for sleep or concentration.
C013 Study-skills article An article describing ways to concentrate in a busy library.
C014 Vancouver weather guide An article about preparing for wet and dark winter commutes in Vancouver.

Download the full catalog

Bag-of-words: catalog descriptions to counts

bow = CountVectorizer()
product_bow = bow.fit_transform(products["text"])
print("Shape:", product_bow.shape)
print("Nonzero entries:", product_bow.nnz)
Shape: (14, 173)
Nonzero entries: 231

Selected rows and columns of the count matrix:

with battery laptop rain wrist
Product
Sony WH-1000XM6 headphones 1 1 0 0 0
Pocket power bank 1 1 0 0 0
Waterproof laptop backpack 1 0 1 1 0
Laptop stand 0 0 1 0 0
Ergonomic keyboard 1 0 0 0 2
White-noise machine 0 0 0 1 0

Does “with” help distinguish these products? Should it count as much as a more distinctive word?

TF–IDF: weighting distinguishing terms

Should every word count equally?

“With” appears in several different product descriptions. Matching it tells us little about which product meets a need.

Term frequency: How often does a term appear in this document?

Inverse document frequency: How uncommon is it across the collection?

TF-IDF gives higher scores to words that appear frequently in a particular document but are relatively rare across the collection of documents.

TF–IDF on the catalog

tfidf = TfidfVectorizer()
product_tfidf = tfidf.fit_transform(products["text"])

Same products and terms as before, now with TF–IDF weights (rounded):

with battery laptop rain wrist
Product
Sony WH-1000XM6 headphones 0.13 0.20 0.00 0.00 0.00
Pocket power bank 0.13 0.21 0.00 0.00 0.00
Waterproof laptop backpack 0.13 0.00 0.22 0.22 0.00
Laptop stand 0.00 0.00 0.22 0.00 0.00
Ergonomic keyboard 0.14 0.00 0.00 0.00 0.50
White-noise machine 0.00 0.00 0.00 0.25 0.00

For a rainy Vancouver commute, does the shared “rain” feature make the backpack and white-noise machine useful matches?

Your turn: vocabulary mismatch

Query: “How can I avoid hearing people talk while I study?”

Relevant description:

Sony WH-1000XM6 headphones: Over-ear wireless headphones with active noise cancellation and up to 30 hours of battery life. Useful for studying in noisy spaces.

Would bag-of-words or TF–IDF reliably rank these headphones highly for this query?

  1. Which words would match?
  2. Would changing counts to TF–IDF weights solve the problem?

Word embeddings: learning from context

What might glorp mean?

The movie was glorp and moving.
What a delightful, glorp story.
We loved the glorp ending.

Words used in similar contexts can receive similar vectors.

Word2vec learns dense word vectors from word-context prediction tasks.

Comparing vectors

We want related texts to have similar vectors. But how should we measure similarity?

Measure Formula What matters?
Euclidean distance \(\sqrt{\sum_{i=1}^d(u_i-v_i)^2}\) Distance between endpoints; smaller is closer
Dot product \(\mathbf{u}^{\top}\mathbf{v}=\sum_{i=1}^d u_i v_i\) Direction and magnitude; larger is more similar
Cosine similarity \(\frac{\mathbf{u}^{\top}\mathbf{v}}{\lVert\mathbf{u}\rVert_2\lVert\mathbf{v}\rVert_2}\) Direction; larger is more similar

Here, \(\mathbf{u},\mathbf{v}\in\mathbb{R}^d\) are vectors; \(u_i,v_i\) are their scalar \(i\)-th components.

Doubling every word count changes a vector’s length, but preserves its direction.

Which item ranks first?

Which item ranks first under each measure? Explain using the picture.

  • Euclidean distance
  • Dot product
  • Cosine similarity

Pretrained word and text embeddings

Choosing a pretrained embedding model

As in computer vision, we can choose from many pretrained models to represent language.

We’ll explore the historical Google News word2vec model:

  • About 3 million words and phrases.
  • A 300-dimensional vector for each item.
  • For our demonstration: a 410-item subset of the original vectors.

Interpreting learned word vectors

print("Words and phrases:", len(word_vectors))
print("Dimensions per word:", word_vectors.vector_size)
word_vectors["UBC"][:5]
Words and phrases: 410
Dimensions per word: 300
array([-0.3828125 , -0.18066406,  0.10644531,  0.4296875 ,  0.21582031],
      dtype=float32)

An individual coordinate need not have a name such as “university-ness.”

Nearest neighbours in word2vec

word_vectors.most_similar("UBC", topn=5)
[('UVic', 0.788647472858429),
 ('SFU', 0.7588528394699097),
 ('Simon_Fraser', 0.7356574535369873),
 ('UFV', 0.6880435943603516),
 ('VIU', 0.6778583526611328)]

Are these synonyms, or words used in related contexts?

Analogies as vector arithmetic

\[v(\text{king})-v(\text{man})+v(\text{woman})\approx v(\text{queen})\]

Schematic analogy directions for man, woman, king, and queen

Trying an analogy

“Man is to king as woman is to ___.”

word_vectors.most_similar(
    positive=["king", "woman"], negative=["man"], topn=4
)
[('queen', 0.7118191719055176),
 ('monarch', 0.6189674139022827),
 ('princess', 0.5902431011199951),
 ('crown_prince', 0.5499460697174072)]

Does the model’s result match your expectation?

Embeddings also encode bias

“Man is to Computer programmer as woman is to ___.”

The chapter’s historical word2vec model returns:

\[v(\text{computer\_programmer})-v(\text{man})+v(\text{woman})\]

word_vectors.most_similar(
    positive=["computer_programmer", "woman"],
    negative=["man"], topn=5
)
[('homemaker', 0.5627118945121765),
 ('housewife', 0.5105046629905701),
 ('graphic_designer', 0.505180299282074),
 ('schoolteacher', 0.49794942140579224),
 ('businesswoman', 0.493489146232605)]

This exposes a gender stereotype learned from the corpus.

Learned associations can be harmful; removing one analogy would not establish that a model is unbiased.

Sentence and text embeddings

Traditional word2vec gives bank one vector, regardless of the sentence.

A text-embedding model maps a complete input text to a dense vector.

Which two sentences should be most similar?

  1. I need a quiet place to study.
  2. I want to do my coursework somewhere without noise.
  3. I like studying with music playing in the background.
  4. My phone is running out of battery.

Encoding sentences with a pretrained model

embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
sentences = [
    "I need a quiet place to study.",
    "I want to do my coursework somewhere without noise.",
    "I like studying with music playing in the background.",
    "My phone is running out of battery.",
]
sentence_embeddings = embedding_model.encode(
    sentences, normalize_embeddings=True,
    show_progress_bar=False,
)
print("Embedding matrix shape:", sentence_embeddings.shape)
Embedding matrix shape: (4, 384)

Interpreting sentence similarity

Computed cosine similarities for four campus-themed sentences: two requests for quiet, studying with music, and a low phone battery.

Shared topic does not guarantee the same need.

iClicker: Pretrained features

Last lecture, a frozen pretrained CNN turned images into feature vectors. In your clustering homework, you used a pretrained text model to turn recipe titles into feature vectors.

In both cases, what does it mean for the pretrained model to be frozen?

  • A. Every input produces the same feature vector.
  • B. Its weights stay fixed, but different inputs can produce different feature vectors.
  • C. Its weights update each time it processes a new input.
  • D. Its output vectors cannot be used to train another model.

Information retrieval

Finding useful documents

How can I avoid hearing people talk while I study?

Document indexing, query processing, and search produce ranked documents

Represent \(\to\) compare \(\to\) return the top-\(k\) descriptions.

Which search method should we use?

Query What needs to match? Useful approach
“Avoid hearing people talk while I study” Related meanings despite different wording Dense retrieval: text embeddings
“HUB-7X” A specific identifier Sparse retrieval: e.g. TF–IDF, plus an exact identifier check

Neither method always wins.

Hybrid retrieval combines word matching and embedding-based search.

iClicker: an absent model number

A query asks for HUB-7Y. The catalog lists HUB-7X.

The retriever ranks HUB-7X first. What can we conclude?

  • A. HUB-7Y is available.
  • B. The two models are interchangeable.
  • C. A related item was found; availability of HUB-7Y is unconfirmed.
  • D. Dense retrieval would guarantee an exact match.

Did the search find what we needed?

For each realistic query, check the returned descriptions:

  • Is the needed information in the top-\(k\)?
  • Are the results useful, or merely related in topic?
  • What happens when the catalog has no answer?

A ranking is a starting point, not proof that an answer is available.

Language models and large language models (LLMs)

Become a language model

Suggest several next words and rough probabilities.

Context Possible next words and probabilities
Too much … ?
My model works perfectly on … ?
I sat on the bank of the … ?
The capital of Canada is … ?

For each context, the full distribution should sum to 1.

What did you do?

You used context to assign probabilities to possible continuations.

\[P(\text{next token}\mid\text{context})\]

A tokenizer splits text into tokens: words, parts of words, or punctuation.

One word does not always equal one token; the split depends on the tokenizer.

A language model assigns probabilities to token sequences through these conditional predictions.

Generating text one token at a time

  1. Predict a distribution over the next token.
  2. Choose a token from that distribution.
  3. Append it to the context.
  4. Repeat.

My model works perfectly on \(\to\) training \(\to\) data \(\to\) but \(\to\) …

A plausible continuation can still be factually wrong.

Large language models (LLMs)

A large language model is a language model built with a large neural network and trained on large amounts of data.

  • It learns patterns by predicting tokens from context.
  • Given a prompt, it can generate an answer, summary, translation, or other text.
  • ChatGPT and Claude are familiar applications powered by LLMs.

How does token prediction become a useful assistant?

Pretraining, post-training, and prompting

Stage What happens? Weights change?
Pretraining Learn token prediction from large amounts of text Yes
Post-training Further training, e.g. instruction-response examples or preference feedback Yes
Prompting Supply instructions and context to a trained model No

Embedding model: returns a numerical vector.
Generative language model: produces text.

Clear instructions versus supplied evidence

Compare these prompts in your favourite chatbot.

Prompt A: Recommend gear for my commute.

Prompt B: I cycle home after evening labs in Vancouver rain and carry a laptop. Recommend exactly two products and briefly explain why.

B gives clearer instructions: the shopper’s needs and the requested output.

A sensible suggestion is a start. Now imagine you are building an assistant for MEC:

Recommend only products in MEC’s current catalog, and explain your choices using their documented specifications.

Clearer instructions specify what to do. Catalog descriptions supply evidence to answer from.

How can we find the relevant descriptions and give them to the chatbot?

Retrieval-augmented generation

Retrieve relevant text \(\to\) add it to the prompt \(\to\) generate an answer.

RAG retrieves catalog evidence for a rainy bicycle commute and supplies it to a generator

Why retrieve instead of include everything?

A small document or catalog might fit in a prompt.

A large collection may exceed the model’s context window: the amount of text it can process at once.

A retriever selects relevant passages to supply with the question.

RAG adds evidence; it does not retrain the language model.

RAG in our campus catalog

Question: “I cycle home after evening labs in the rain and carry a laptop. Which two products would help?”

Retrieved evidence Example answer based on that evidence
Backpack: keeps electronics and notes dry during wet commutes Waterproof laptop backpack: protects your laptop and notes from rain.
Bike lights: improve visibility when commuting after dark Bike-light set: helps you stay visible after evening labs.

The prompt contains the question + retrieved descriptions + instructions.

Does RAG guarantee a correct answer?

Retrieved description: “Rechargeable bike lights. Improves visibility when commuting after dark.”

Generated answer: “These lights will run for 12 hours on a single charge.”

Does the description support the answer? What should the system say instead?

Today’s takeaways

  • Representations determine which similarities we can detect.
  • Sparse and dense retrieval have different strengths; rankings need evaluation.
  • Language models generate tokens conditioned on context; fluency does not establish truth.
  • RAG supplies retrieved evidence without changing generator weights.
  • Check the evidence: a fluent answer can still make unsupported claims.

Exit question

In your own words, what does the retriever do, and what does the generator do in a RAG system?

Does giving the model retrieved documents change its weights?