Semantic Chunking - 3 Methods for Better RAG

James Briggs · Beginner ·🧠 Large Language Models ·2y ago

Key Takeaways

The video demonstrates semantic chunking using three methods - StatisticalChunker, ConsecutiveChunker, and another method, with tools such as semantic chunkers library, OpenAI's Embedding 3 small model, and OpenAI API key, for better RAG and text modality applications.

Full Transcript

today we are going to be taking a look at the different types of semantic chunkers that we can use in order to chunk our data for applications like rag in a more intelligent and effective way for now we're going to be focusing on the text modality which is generally going to be used for rag but we can apply this to video and also audio but for now let's stick with text so I'm going to take you through three different types of semantic chunkers everything we're working through today is going to be in the semantic chunkers library and we're going to go to the chunker's intro notebook here and I'm just going to go ahead and open this in collab Okay cool so first thing I'm going to do is just install the prerequisites so you have semantic chunkers of course and hooking face data sets so we're going to be pulling in uh some data to just test these different methods for chunking and and see what difference it makes especially in terms of latency and and also just quality of what we get out of it okay cool so we can come down to here and let's take a look at our data set so our data set contains a set of AI archive papers we can see one of them here so this is the m paper and you can see there's a few different sections in here already we have the title we have author where the authors are are studying or or performing research from and then we have the abstract so what we're going to do is I mean you can do this or you can just use the full content if you want for this paper it's up to you uh but especially one of these chunkers can be pretty slow and and quite intensive so I I've limited the amount of text that we're using here the other two are pretty fast so it's mainly for that one so we will need a embedding model to perform our semantic chunking semantic chunking at least the versions of it that we show here uses or or relies on embedding models and finding the semantic similarity between embeddings in some way or another so in this example we're going to be using open AI is embedding three small model so you will need an open AI API key or if you prefer not to you can use a open source model as well so if you do want to use a open source model instead so you don't need to get an API key you can just do this here but I'm going to be sticking with open AI okay so initialized my encoder and now I'm going to come down to the statistical chunking method and this is probably the chunky that I would recommend people to use just out of the box the reason for that is that it will handle a lot of the sort of figuring out of different parameters for you it is pretty cost effective and it is it's pretty fast as well so this is generally the one I recommend but we'll have a look at the others as well so we'll start with the statistical chunker and the way that this is going to work is that it's going to identify a good similarity threshold value for you based on the varying similarity throughout a document so the similarity that it will use for different documents and different parts of documents may actually change but it's all calculated for you so it it tends to work very well actually so if we have a look here we have a few of our chunks so we can see that it ran very quickly we have the first one here includes our title the authors and the abstract okay so it's kind of like the introduction to the paper then after that we have this I assume it's probably one of the first paragraphs in the paper can see that then we go on to this the second Point here or the second title here and so on and so on but generally speaking these trunks look relatively good of course you will probably need to look through them in a little more more detail just looking at the start of these it looks pretty reasonable so that is statistical chunking it's pretty easy the next one is consecutive chunking and consecutive chunking is probably the second one I would recommend it is again it's cost effective relatively quick uh but it does require a little more tweaking or inputs from outside so that primarily is due to the score threshold so the score threshold most of the encoders here require different score thresholds so for example text embedding order 002 similar for that model is anything sort of within the range of 0.73 to 0.8 that's usually the sort similarity threshold that you would need to use with the newer text embedding models and then text embedding three small you need to use something much smaller which is why I've gone with 0.3 down here so there's a little bit more of you need to actually input something here and to be honest it depends in some cases the performance can be better I I think but a lot of the time it's actually harder to to get like very good performance with this one so for example here I can see that it's probably splitting too frequently from what I can see so I may even want to modify my threshold okay and so I've decreased it to 0.2 and it's seems a little more reasonable cool may even want to go a little bit lower but that looks a bit better so that is the consective trunker again using a completely different process here this is essentially creating your embeddings one after the other so so it first splits your text into sentences actually the same for the for well for all of the trunet here they split your text into sentences and then they start merging your textes into larger chunks and they're looking especially this one is looking at where there is all of a sudden a drop in similarity between those sentences and that is how it defines okay this is a logical point to split our chunk so that's what we're doing there and then the final one I want to show you is the cumulative trunka now the cumulative trunka what this one will do is takes our sentences and okay we start with sentence one and then we add sentence two when creating embedding and then we create add sentence three create another embedding and then we compare those two embeddings so we're comparing the embedding of sentences one and two and 1 2 and three and then seeing if there is a big change in the similarity if not then we continue and then we compare uh basically the group of three sentences followed by the group of four sentences we look at those two see if there's a sudden similarity change if there is then that is where we make our split so what you're doing here is you're cumulatively adding text creating your embeddings and then continuing cumulatively adding more text continuing and the result of that is that this takes a lot longer to run it's also a lot more expensive you're creating far more embeddings but you'll find compared to at least the consecutive trunker it is a little more noise resistant so it requires a bit more of a change over time time to actually trigger a split for this chunker so the results tend to be a bit better but I would say either on par or maybe even a little worse than the statistical chunker in a lot of cases but it's worth trying just to see what gets the best performance for you for your particular use case okay so we can see that yes this trunker definitely took a bit longer than the others and let's have a look at what trunks we got so we come up again and I probably should have changed the threshold here but let's start with these so yeah we see generally I think probably worse performance than we got with the statistical chunker but especially if I modify the threshold here and tweak that a little bit generally you can get better performance than the consecutive trunker so yeah those are the three trunking methods that we currently have in the semantic chunkers Library I will also add that there are differences between these chunkers in which modalities they can handle so the statistical junker for now is only able to handle a Tex modality so great for rag not so great if you're wanting to pass video for example whereas the consecutive chunker is really good at passing video and we do we we have an example on that and I will walk through the in the near future but it's something to consider so consective trunker can basically handle any modalities things like the statistical trunker I cannnot and then the cumulative trunker is is more text focused as well so for now that is it on semantic chunkers I hope this has been useful and and interesting so thank you very much for watching and I will see you again in the next one bye

Original Description

Semantic chunking allows us to build more context-aware chunks of information. We can use this for RAG, splitting video and audio, and much more. In this video, we will use a simple RAG-focused example. We will learn about three different types of chunkers: StatisticalChunker, ConsecutiveChunker, and CumulativeChunker. At the end, we also discuss semantic chunking for video, such as for the new gpt-4o and other multi-modal use cases. 📌 Code: https://github.com/aurelio-labs/semantic-chunkers/blob/main/docs/00-chunkers-intro.ipynb ⭐️ Article: https://www.aurelio.ai/learn/semantic-chunkers-intro 🌟 Build Better Agents + RAG: https://platform.aurelio.ai (use "JBMARCH2025" coupon code for $20 free credits) 👾 Discord: https://discord.gg/c5QtDB9RAP Twitter: https://twitter.com/jamescalam LinkedIn: https://www.linkedin.com/in/jamescalam/ #ai #artificialintelligence #chatbot #nlp 00:00 3 Types of Semantic Chunking 00:42 Python Prerequisites 02:44 Statistical Semantic Chunking 04:38 Consecutive Semantic Chunking 06:45 Cumulative Semantic Chunking 08:58 Multi-modal Chunking
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from James Briggs · James Briggs · 0 of 60

← Previous Next →
1 Stoic Philosophy Text Generation with TensorFlow
Stoic Philosophy Text Generation with TensorFlow
James Briggs
2 How to Build TensorFlow Pipelines with tf.data.Dataset
How to Build TensorFlow Pipelines with tf.data.Dataset
James Briggs
3 Every New Feature in Python 3.10.0a2
Every New Feature in Python 3.10.0a2
James Briggs
4 How-to Build a Transformer for Language Classification in TensorFlow
How-to Build a Transformer for Language Classification in TensorFlow
James Briggs
5 How-to use the Kaggle API in Python
How-to use the Kaggle API in Python
James Briggs
6 Language Generation with OpenAI's GPT-2 in Python
Language Generation with OpenAI's GPT-2 in Python
James Briggs
7 Text Summarization with Google AI's T5 in Python
Text Summarization with Google AI's T5 in Python
James Briggs
8 How-to do Sentiment Analysis with Flair in Python
How-to do Sentiment Analysis with Flair in Python
James Briggs
9 Python Environment Setup for Machine Learning
Python Environment Setup for Machine Learning
James Briggs
10 Sequential Model - TensorFlow Essentials #1
Sequential Model - TensorFlow Essentials #1
James Briggs
11 Functional API - TensorFlow Essentials #2
Functional API - TensorFlow Essentials #2
James Briggs
12 Training Parameters - TensorFlow Essentials #3
Training Parameters - TensorFlow Essentials #3
James Briggs
13 Input Data Pipelines - TensorFlow Essentials #4
Input Data Pipelines - TensorFlow Essentials #4
James Briggs
14 6 of Python's Newest and Best Features (3.7-3.9)
6 of Python's Newest and Best Features (3.7-3.9)
James Briggs
15 Novice to Advanced RegEx in Less-than 30 Minutes + Python
Novice to Advanced RegEx in Less-than 30 Minutes + Python
James Briggs
16 Building a PlotLy $GME Chart in Python
Building a PlotLy $GME Chart in Python
James Briggs
17 How-to Use The Reddit API in Python
How-to Use The Reddit API in Python
James Briggs
18 How to Build Custom Q&A Transformer Models in Python
How to Build Custom Q&A Transformer Models in Python
James Briggs
19 How to Build Q&A Models in Python (Transformers)
How to Build Q&A Models in Python (Transformers)
James Briggs
20 How-to Decode Outputs From NLP Models (Python)
How-to Decode Outputs From NLP Models (Python)
James Briggs
21 Identify Stocks on Reddit with SpaCy (NER in Python)
Identify Stocks on Reddit with SpaCy (NER in Python)
James Briggs
22 Sentiment Analysis on ANY Length of Text With Transformers (Python)
Sentiment Analysis on ANY Length of Text With Transformers (Python)
James Briggs
23 Unicode Normalization for NLP in Python
Unicode Normalization for NLP in Python
James Briggs
24 The NEW Match-Case Statement in Python 3.10
The NEW Match-Case Statement in Python 3.10
James Briggs
25 Multi-Class Language Classification With BERT in TensorFlow
Multi-Class Language Classification With BERT in TensorFlow
James Briggs
26 How to Build Python Packages for Pip
How to Build Python Packages for Pip
James Briggs
27 How-to Structure a Q&A ML App
How-to Structure a Q&A ML App
James Briggs
28 How to Index Q&A Data With Haystack and Elasticsearch
How to Index Q&A Data With Haystack and Elasticsearch
James Briggs
29 Q&A Document Retrieval With DPR
Q&A Document Retrieval With DPR
James Briggs
30 How to Use Type Annotations in Python
How to Use Type Annotations in Python
James Briggs
31 Extractive Q&A With Haystack and FastAPI in Python
Extractive Q&A With Haystack and FastAPI in Python
James Briggs
32 Sentence Similarity With Sentence-Transformers in Python
Sentence Similarity With Sentence-Transformers in Python
James Briggs
33 Sentence Similarity With Transformers and PyTorch (Python)
Sentence Similarity With Transformers and PyTorch (Python)
James Briggs
34 NER With Transformers and spaCy (Python)
NER With Transformers and spaCy (Python)
James Briggs
35 Training BERT #1 - Masked-Language Modeling (MLM)
Training BERT #1 - Masked-Language Modeling (MLM)
James Briggs
36 Training BERT #2 - Train With Masked-Language Modeling (MLM)
Training BERT #2 - Train With Masked-Language Modeling (MLM)
James Briggs
37 Training BERT #3 - Next Sentence Prediction (NSP)
Training BERT #3 - Next Sentence Prediction (NSP)
James Briggs
38 Training BERT #4 - Train With Next Sentence Prediction (NSP)
Training BERT #4 - Train With Next Sentence Prediction (NSP)
James Briggs
39 FREE 11 Hour NLP Transformers Course (Next 3 Days Only)
FREE 11 Hour NLP Transformers Course (Next 3 Days Only)
James Briggs
40 New Features in Python 3.10
New Features in Python 3.10
James Briggs
41 Training BERT #5 - Training With BertForPretraining
Training BERT #5 - Training With BertForPretraining
James Briggs
42 How-to Use HuggingFace's Datasets - Transformers From Scratch #1
How-to Use HuggingFace's Datasets - Transformers From Scratch #1
James Briggs
43 Build a Custom Transformer Tokenizer - Transformers From Scratch #2
Build a Custom Transformer Tokenizer - Transformers From Scratch #2
James Briggs
44 3 Traditional Methods for Similarity Search (Jaccard, w-shingling, Levenshtein)
3 Traditional Methods for Similarity Search (Jaccard, w-shingling, Levenshtein)
James Briggs
45 3 Vector-based Methods for Similarity Search (TF-IDF, BM25, SBERT)
3 Vector-based Methods for Similarity Search (TF-IDF, BM25, SBERT)
James Briggs
46 Building MLM Training Input Pipeline - Transformers From Scratch #3
Building MLM Training Input Pipeline - Transformers From Scratch #3
James Briggs
47 Training and Testing an Italian BERT - Transformers From Scratch #4
Training and Testing an Italian BERT - Transformers From Scratch #4
James Briggs
48 Faiss - Introduction to Similarity Search
Faiss - Introduction to Similarity Search
James Briggs
49 Angular App Setup With Material - Stoic Q&A #5
Angular App Setup With Material - Stoic Q&A #5
James Briggs
50 Why are there so many Tokenization methods in HF Transformers?
Why are there so many Tokenization methods in HF Transformers?
James Briggs
51 Choosing Indexes for Similarity Search (Faiss in Python)
Choosing Indexes for Similarity Search (Faiss in Python)
James Briggs
52 Locality Sensitive Hashing (LSH) for Search with Shingling + MinHashing (Python)
Locality Sensitive Hashing (LSH) for Search with Shingling + MinHashing (Python)
James Briggs
53 How LSH Random Projection works in search (+Python)
How LSH Random Projection works in search (+Python)
James Briggs
54 IndexLSH for Fast Similarity Search in Faiss
IndexLSH for Fast Similarity Search in Faiss
James Briggs
55 Faiss - Vector Compression with PQ and IVFPQ (in Python)
Faiss - Vector Compression with PQ and IVFPQ (in Python)
James Briggs
56 Product Quantization for Vector Similarity Search (+ Python)
Product Quantization for Vector Similarity Search (+ Python)
James Briggs
57 How to Build a Bert WordPiece Tokenizer in Python and HuggingFace
How to Build a Bert WordPiece Tokenizer in Python and HuggingFace
James Briggs
58 Metadata Filtering for Vector Search + Latest Filter Tech
Metadata Filtering for Vector Search + Latest Filter Tech
James Briggs
59 Build NLP Pipelines with HuggingFace Datasets
Build NLP Pipelines with HuggingFace Datasets
James Briggs
60 Composite Indexes and the Faiss Index Factory
Composite Indexes and the Faiss Index Factory
James Briggs

This video teaches semantic chunking using three methods - StatisticalChunker, ConsecutiveChunker, and another method, with applications in RAG and text modality, and demonstrates how to use tools such as semantic chunkers library and OpenAI's Embedding 3 small model. The practical applications of semantic chunking are shown, including improving RAG and text modality applications.

Key Takeaways
  1. Install prerequisites such as semantic chunkers library and hooking face data sets
  2. Initialize encoder
  3. Use statistical chunker
  4. Use consecutive chunker
  5. Experiment with different score thresholds for text embedding
💡 The choice of chunking method depends on the specific application and requirements, with statistical chunking being cost-effective and fast, consecutive chunking being cost-effective and relatively quick, and cumulative chunking being noise-resistant but more expensive.

Related Reads

📰
Open-Weight LLM API Integration: A Developer Guide to Building with Transparent AI
Learn to integrate open-weight LLM APIs for transparent AI, enabling fine-grained control and inspecting the architecture behind the intelligence
Dev.to AI
📰
Stop Writing Boilerplate: How I Automated My Entire Workflow with LLM APIs
Automate your LLM workflow using APIs to reduce repetitive code, increasing productivity and efficiency
Dev.to AI
📰
The real AI race may no longer be at the frontier
The AI race may shift from frontier models to open models due to cost, accessibility, and ownership, impacting production AI and enterprise adoption
TechCrunch AI
📰
Building a Document-RAG Agent on GCP's Agent Development Kit (ADK)
Learn to build a Document-RAG agent on GCP's Agent Development Kit (ADK) for efficient document-based conversational AI
Dev.to · Dale Nguyen

Chapters (6)

3 Types of Semantic Chunking
0:42 Python Prerequisites
2:44 Statistical Semantic Chunking
4:38 Consecutive Semantic Chunking
6:45 Cumulative Semantic Chunking
8:58 Multi-modal Chunking
Up next
5 Levels of AI Agents - From Simple LLM Calls to Multi-Agent Systems
Dave Ebbelaar (LLM Eng)
Watch →