1/86
Looks like no tags are added yet.
Prompting techniques
Specificity
Hallucination
Order
Specificity
Accurately describe what you want to achieve. Instead of asking the IIM to «Write a description for a product ask it to "Write a description for a productin less than two sentences and use a formal toneẠại
Order
Either begin or end your prompt with the instruction. Especially with long prompts, information in the middle is often forgotten.' LLMs tend to focus on information either at the beginning of a prompt (primacy effect) or the end of a prompt (recency effect).
Hallucination
Tell the LLM that if it doesnt know the answer then to say IDK
Prompt engineering
Iteratively improving your prompt/instruction in order to get your preferred output
In Context Learning
Instead of describing what we want why not Show the LLM? When we provide the LLM with correct examples to show exactly the thing we want to achieve. Zero shot prompting, one shot,and few shot.
Zero Shot Prompt
Prompting with out examples
Few Shot Prompt
Prompting with more than one example
One Shot Prompt
Prompting with one/single example
Chain Prompting
Taking the output of one prompt and use it as the input for the next prompt, there by creating a continuous chain. This allows the LLM to spend more time on each individual question instead of tackling the whole problem.
Chain Prompting Use Cases
Response Validation
Parallel Prompts
Writing Stories
Response Validation
Ask the LLM to double check previously generated outputs
Parallel Prompts
Create multiple Prompts in parallel and do a final pass to merge them
Writing Stories
Leverage the LLM to write books or stories by breaking down the problem into components.
Self Consistency
Asks the gen model the same prompt multiple times and taking the majority result as the final answer, Can improve performance however it become n times slower where n is the number of out put samples
Tree of Thought
At each step the LLM is prompted to explore different solutions to the problem then it votes for the best solution and continues to the next step. Disadvantage is it needs many calls to the generative models, the work around for this method to not make a lot of calls is to ask the model to mimc that behavior by emulating a conversation between multiple experts.
Output Verification
It is important that we verify and control the output of the model to prevent breaking the application and to create a robust generative AI Application.
Reason for validating the output might include.
Structured Output - Some outputs need to be structured even though gen models are free text
Valid Output - Even though we allow the model to gen structured output it still has the capability to free gen its content.
Ethics - Consider safety and ethical concerns. Some use cases might require the output to be free of profanity.
Accuracy - Some use cases might requie the output to adhere to certain standards or performance.
3 ways of controlling the output of a generative model:
Examples - providing examples of the expected output
Grammar - Control the token selection process
Fine Tuning - Tune the model on data that contains the expected output.
To empty VRAM use…
torch.cuda.empty_cache()
to say we want all layers of the model to be run from the GPU use…
n_gpu_layers = -1
n_ctx
Refers to the context size of the model.
Embedding Models
Convert textual data to usable numeric vectors so that they are easily processed. The process of embedding the input is typically performed by an LLM (embedding model). The main purpose of a embedding models is to be as accurate as possible in representing the textual data as an embedding.
Semantic Similarity
The idea that we expect textual data with similar meanings to be closer to each other in n dim space.
What are we more interested in when building a sentiment classifier? Sentiment of texts or Semantic similarity
Sentiment of texts.
Sentiment versus Semantics
Sentiment is how does the speaker feel? and semantic is What is being actually said?
Contrastive Learning
Contrastive learning is a technique that aims to train an embedding model such that similar documents are closer in vector space while dissimilar documents are further apart. Techniques is for both training and fine tuning.
Cross-Encoder
A Cross-Encoder takes sentences as input simultaneously.
Unlike sentence transformers, it processes the sentences together and directly predicts a similarity or relevance score.
Sentence Transformer
A Sentence Transformer encodes each sentence independently into a numerical vector (embedding).
fp16
By enabling this parameter we allow for mixed precision training where computations are performed using 16 bit floating point numbers instead of 32 bit . Reduces memory usage and potentially increases the training speed.
MTEB Massive Text Embedding Benchmark
Developed to unify the eval procedures. Spans 8 embedding tasks that cover 58 datasets and 112 languages. The great thing about this eval benchmark is not only the diversity of the tasks and languages but that even the evaluation time is saved which is helpful because we typically want embedding models that accurate and have low latency. They often benefit from that and require fast inference.
To train sentence transformer models we typically use which two loss functions?
Cosine similarity and MNR - Multiple negatives ranking loss.
Multiple Negatives Ranking Loss
This is a loss that uses either positive pairs of sentences or triplets that contain a pair of positive sentences and an additional unrelated (negative) sentence. The unrelated shows the dissimilarity between the positive sentences
Easy Negative
These are sentences that are obviously unrelated to the anchor. Gathered through random sampling documents as we did before.
Semi Hard Negative
These are sentences that share some similarities with the anchor but are not actually relevant. Gathered through a pretrained embedding model where we apply cosine similarity on all sentence embeddings to find those that are highly related but generally this doesnt lead to hard negatives.
Hard Negative
These are sentences that are very similar to the anchor but have a different meaning or are incorrect answers. Gathered by manually entering labels, or generative model to judge or gen sentence pairs.
Why do we need Easy Medium and Hard Negatives?
Think of it as progressively challenging the model.
Easy negatives Learn to distinguish completely unrelated sentences.
Medium negatives Learn to distinguish similar topics with different meanings.
Hard negatives Learn subtle semantic differences between highly similar sentences.
What is a disadvantage to training or fine tuning embedding models?
They often require substantial training data.
Augmented SBERT
The procedure of augmenting your data such that an embedding model can be fine tuned when there is only a little labeled data available. We aim to augment the small amount of labeled data such that they can be used for regular training. Supervised Learning Fine tuning Embedding model
TSDAE -Transformer Based Sequential Denoising Auto Encoder
Unsupervised learning method for fine tuning an embedding model. A model takes a corrupted/noisy sentence as input and learns to reconstruct the original sentence. By learning to recover the original meaning despite missing or altered words, the model develops embeddings that capture the sentence's semantic meaning. Very similar to Masked language modeling however instead of trying to reconstruct the masked words we try to reconstruct the entire sentence.
Domain Adaptation
adapting a model's existing knowledge to a new domain without having to train it from scratch.
Adaptive Pretraining
the process of continuing to train an already pre-trained language model on text from a specific domain so it becomes more familiar with that domain's vocabulary, terminology, and language patterns.
DataCollector Class
a class that helps us build batches of data but also allows us to apply data augmentation. To create equally sized representations we use Padding to the input text.
Benefit of Freezing certain layers during training.
Can gain almost the same performance as if you trained fully throughout instead. Good if you do not have enough computing power.
Few Shot Classification.
Technique within supervised classification where you have a classifier learn target labels based on only a few labeled examples. Is great when you have a classification task but do not have many labeled data points available.
Set Fit
Efficient Fine tuning with Few training examples. Built on top of sentence transformers to generate high quality textual representations that are updated during training. Is competitive with a fine tuned BERT like model on a large dataset.
3 Step Process of Set Fit
1. Sample training data: Select a small number of labeled examples from each class (e.g., positive and negative reviews).
2. Fine-tune embeddings: Generate sentence pairs from the labeled examples and use contrastive learning to fine-tune the Sentence Transformer so that similar examples are closer together in embedding space.
3. Train a classifier: Use the fine-tuned sentence embeddings to train a classification model (e.g., logistic regression) that predicts the class of new sentences.
Main idea: SetFit achieves text classification with very little labeled training data by first improving sentence embeddings and then training a classifier on those embeddings.
NER Named Entity Recognition
is an NLP task that identifies and classifies important information (entities) in text into predefined categories.
Common categories include:
PER: Names of people
ORG: organization
LOC: Cities, countries, places
MISC: misc entity
O: no entity
Prefix B means begining and I means Inside, B followed by an I shows that the tokens belong to eachother and are not independent.
Parameter Efficient Fine Tuning (PEFT)
This is the opposite of full fine tuning where you don’t update all parameters of a model. Full fine tuning has disadvantages such as being costly to train, slow training times, requires more significant storage. To resolve these issues we have PEFT which focuses on training models with higher comp efficiency.
Adapters
Modular component inside the transformer that can be fine tuned without having to fine tune all of the model weights. Shown to deliver just as good of results as if we did full fine tuned training.
LoRA Low Rank Adaptation
alternative to adapters, widely used and effective technique for PEFT. Only requires updating a small set of parameters.
QLoRA
A quantized version of LoRA. Goes from higher number of bits to lower value without differentiating too much from the original weights. They used blockwise quantization.
Perplexity
How well a language model predicts a text.
What is a downside to Public benchmarks?
Models can be overfitted to them, Broadness so it might not cover specfic use cases, some require strong GPUs with long running time to compute.
Text Classification Examples
Sentiment Analysis
Intent Detection
Extracting Entities
Detecting language
Encoder Only Architecture
Excel in task specific use cases and significantly smaller in size
Precision
accuracy of the relevant results
Recall
How many relevant cases were found which indicates its ability to find all relevant results
Accuracy
How many correct predictions the model makes out of all predictions which indicates the overall correctness of the model.
F1 Score
Balances both precision and recall to create a models overall performance.
Zero Shot Classification
classifying text into labels the model was never trained on, with no labeled examples. You describe each label in plain language, for example “a negative movie review.” Then the model matches the input to the label description that fits best, either by embedding similarity or by prompting a generative model.
Cosine Similarity
a measure of how similar two vectors are, based on the angle between them rather than their length. You take the dot product of the embeddings and divide by the product of their length. It ranges from −1 (opposite) through 0 (unrelated) to 1 (same direction).
T5 Model
Text to Text Transfer Transformer Model, similar transformer architecture, first pre-trained on masked language modeling. second step involves not just finetuning for one task it involves converting to a sequence to sequence task and training simultaneously. Flan T5 family of models (1000 tasks)
Preference tuning
First manually create the desired output to an input prompt and use that data to create a first variant of its model. then use that to generate multiple other outputs and manually rank them from best to worst, model learns preference from this.
Topic Modeling
Discover abstract topics that appear in large collections of textual data.
HDBSCAN
Density based algorithm, Calcs the number of clusters, does not force all of the data points to be part of a cluster. theres also DBSCAN which is an algo that allows for Dense micro clusters to be found.
MMR-Maximal Marginal Relevancy
Used to remove redundant keywords and only keep words that contribute something new to the topic representation
KeyBERT
uses c TF IDF to extract the most representative documents per topic by calc the similarity between the documents c TF IDF value and those of the topic they correspond to.
what does do_sample = false do when loading a text generation model?
No sampling will be done and only the most probable next token is selected.
Temperature
Controls the randomness or creativity of the text generated. Defines how likely it is to choose tokens that are less probable,
A temperate of 1 generates …
The same response everytime.
Top P
controls which subset of tokens it can consider until it reaches their cumulative probability. if it equals 1 then it considers all tokens.
Instruction based Prompting
Have the LLM answer a specific question or resolve a certain task.
Top K
Similar to Top P except it controls exactly how many tokens the LLM can consider.
A Non exhaustive list of prompting techniques to improve the quality of the output is…
Specificity, Hallucination, Order.
Advanced Prompting Techniques
Persona, Instruction, Context, Format, Audience, Tone, Data.
Chain of Thought
Enhances the output but needs multiple examples which the user might not have access to. A workaround is to ask the LLM to think step by step ( Zero shot chain of thought)
to empty VRAM
use torch.cuda.empty_Cache()
ngpu layers = -1
this means we want all the layers of a model to be run from GPU
n_ctx
refers to the context size of the model.
DataCollector with Padding
Dynamically pads the input it receives
The three LLM Training steps are…
Pretraining, supervised finetuning, preference tuning
LoRA Configuration
Lora alpha = amount of change added to the original weights (LoRA scaling)
r = rank of the computational matrices, bigger r = more representation and less compression
lr_schedular_type
adjusts the learning rate dynamically.