Streamlit for ML #3 - Make Apps Fast with Caching

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

Key Takeaways

This video demonstrates how to use Streamlit's caching mechanism to improve the performance of a machine learning web app by reducing the time it takes to load and process data, specifically by using the st.cache and st.experimental_singleton functions to cache the retriever model and pinecone index.

Full Transcript

in this video we are going to continue with the app that we've been building um so so far we it's a quick summary we have what you can see over here uh we have this ai q a it's just a you know the very basics of streamlit and we have this uh search bar that we or text input that we've built with streamer over here okay and then we put together sort of the back end of our app so that is initializing a connection to our vector database and we also created all of our context vectors and put those in there and also initializing our retriever model which takes care of encoding the query here and then pinecone over here takes care of finding the most relevant context vectors based on that query vector and then we had a look at how we can [Music] iterate through all the contexts that we return from pinecone and then display them now at the moment it's very ugly and at the same time another thing another really bad thing that we need to solve in this video is this takes forever to do anything right if i if i just um maybe even if i just remove that and press enter i'm not even searching for anything and this is going to take i don't know like a minute i'm going to cut forwards so you don't have to wait as long as i do okay so it's just finished that took way too long so what we want to do or the reason for that is mainly the retriever model uh download over here so every time we rerun or change anything in our app stream the way streaming it works is it re-executes everything in your script and that's really good because it makes developing an app super simple but when you you have something like that you're downloading an ml model you don't want to do redo that every time a tiniest little thing changes in your app you only want to do it once like when the user opens your app the first time then you download it and then you don't download it again that's what you want to happen and we also want the same to happen with our pinecone uh connection okay we just want to initialize that connection once and not every time something changes in the app so we're going to do that uh we're going to figure that out so we can go over to the streamlight dots and we can scroll up to the top or go to this menu and we go to advanced features now and it says advanced but it's not hard to do this okay so we can optimize performance with st catch okay let's have a look at that so we can scroll down it's a caching mechanism that allows you out to stay performant when loading data from the web a lot of data sets or do all performing experience for computations now that sounds pretty much like what we want okay so let's go down and we see basic usage so we have oh this is a good example right so we have this this function here it takes a long time to run every time um and therefore it makes it out pretty slow every time anything changes the whole thing is reloaded so this expensive computation is rerun every time we don't want that to happen what we want to do is okay you can just add this and that means that the output from that expensive computation is just stored okay it's not it's not reloaded every single time okay so let's let's try i'm not saying it's going to work but let's try and do that so we're going to put define init retriever okay and that is just going to return the retrieval model so return that and we do the same for our pinecone stuff here as well so define emit pinecone okay and then obviously we need to actually call those so let's let's do that let's do that here okay so we're going to call those um we want the model is equal to init retriever and we want the index is equal to init pine cone okay let's save that let's have a look at our app okay so it's it's running again let's wait a moment actually stop that because we here we're returning nothing so we do we actually want to return the index that would be that'll be useful um and now we do we have to press this rerun okay now the first time we do this it's going to take a while and first okay we want to make sure is actually is it working like it was before let's see we getting any errors okay now also it always seems to be working fine okay so let's do let's add that st cache that we saw in the documentation let's add that to both of these okay save rerun we get this nice little um spinner running in it retriever it's not very descriptive for our users so later on we'll have a look at making that a little more interesting or descriptive but for now we'll stick with that and this is quite useful because we can see okay you know what are the slow parts of our model to load uh okay so we get this get this error okay why is that so when we are um caching with streamlit what it is doing is well it basically checks if the whatever's being cash changes okay with every rerun uh so it's putting the function or putting some values into your function or rerunning it and having a look at what the the hash code is that comes out of it now in in this case we're calling a an api uh we don't or we cannot actually hash the connection to our pinecone index okay and we shouldn't really do that for our retrieval model either so what we can do is something um which is kind of new from streamer okay so where is st cache is always going to check the hashcode see if anything is changing and there are these new experimental um caches and one of those in particular is this we have experimental memo uh it's fine so we use that to sort expensive computations uh that's fine no no no try that with some things but that's not what we want we want this experimental singleton so basically what that means experiment experimental singleton is whatever you're running should just be run at once and it should not change right we're assuming it's assuming that this will not change right so it's not going to check if it's changed and therefore it is not going to create that um that hash representation of whatever it is you're running so we can write st experimental singleton put it here as well oops let's copy it put it here and okay we've just saved it let's have a look see what happens okay again it's going to take a little while to to rerun everything um hopefully not too long okay there we go so now we have our search um let's say who are the normans okay i'm not going to skip ahead straight away okay so when there's no waiting anymore which is it's really good because before it just took so long so yeah that's that's how we've sort of improved the performance of our streaming app using uh caching and these new experimental caching primitives that uh streamlet have developed so that's incredibly useful and what i want to look at in the in the next video is okay in over into our app yes the performance is there now but it doesn't look so good uh so maybe we can have a look at actually improving uh this look here and to do that we're actually going to not use well we are going to use streamlit but we're going to pull in uh what are called bootstrap card components which are another sort of html css library and using the style from them to display our information it will look a lot nicer than it does now so that's it for this video i hope so useful thank you very much for watching and i'll see you in the next one bye

Original Description

▶️ Streamlit for ML Part 4: https://www.youtube.com/watch?v=XdxeKiY2UXg&list=PLIUOU7oqGTLg5ssYxPGWaci6695wtosGw&index=4 Streamlit has proven itself as an incredibly popular tool for quickly putting together high-quality ML-oriented web apps. More recently, it has seen wider adoption in production environments by ever-larger organizations. All of this means that there is no better time to pick up some experience with Streamlit. Fortunately, the basics of Streamlit are incredibly easy to learn, and for most tools, this will be more than you need! In this series, we will introduce Streamlit by building a general knowledge Q&A interface. We will learn about key Streamlit components like write, text_input, container. How to use external libraries like Bootstrap to quickly create new app components. And use caching to speed up our app. ▶️ Streamlit for ML Playlist: https://www.youtube.com/watch?v=JLKUV-LiXjk&list=PLIUOU7oqGTLg5ssYxPGWaci6695wtosGw&index=1 📕 Article: https://towardsdatascience.com/getting-started-with-streamlit-for-nlp-75fe463821ec 🤖 70% Discount on the NLP With Transformers in Python course: https://bit.ly/3DFvvY5 🎉 Subscribe for Article and Video Updates! https://jamescalam.medium.com/subscribe https://medium.com/@jamescalam/membership 📖 Friend link to article: https://towardsdatascience.com/getting-started-with-streamlit-for-nlp-75fe463821ec?sk=ac5e0b7c39938f52162862411a66a58b 👾 Discord: https://discord.gg/c5QtDB9RAP 00:00 Intro 02:35 Streamlit Caching 06:56 Experimental Caching Primitives
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 how to use Streamlit's caching mechanism to improve the performance of a machine learning web app by reducing the time it takes to load and process data. The instructor demonstrates how to use the st.cache and st.experimental_singleton functions to cache the retriever model and pinecone index, resulting in a significant improvement in app performance.

Key Takeaways
  1. Import necessary libraries and initialize the Streamlit app
  2. Define a function to initialize the retriever model and use st.cache to cache it
  3. Define a function to initialize the pinecone index and use st.experimental_singleton to cache it
  4. Call the functions to initialize the retriever model and pinecone index
  5. Test the app and verify that the caching is working correctly
💡 Using caching can significantly improve the performance of a machine learning web app by reducing the time it takes to load and process data.

Related Reads

📰
Building Production-Grade LLM Evaluation Pipelines: From Vibes to Metrics
Learn to build production-grade LLM evaluation pipelines to catch hallucinations before deployment and improve model reliability
Dev.to AI
📰
Why Every AI Engineer Should Learn Hugging Face
Learn how Hugging Face simplifies AI development and why it's a crucial tool for AI engineers to master
Medium · Machine Learning
📰
A bug in Qwen3-TTS taught me voice is biometric
A developer's experience with a bug in a voice cloning model highlights the biometric nature of voice, emphasizing security and privacy concerns
Dev.to · Daniel Nwaneri
📰
What is LoRA and how it lets anyone fine-tune a massive AI model on a single GPU
Learn about LoRA, a technique that enables fine-tuning of massive AI models on a single GPU, making it accessible to individuals and small teams
Medium · LLM

Chapters (3)

Intro
2:35 Streamlit Caching
6:56 Experimental Caching Primitives
Up next
5 Levels of AI Agents - From Simple LLM Calls to Multi-Agent Systems
Dave Ebbelaar (LLM Eng)
Watch →