Wednesday, December 27, 2023

Terms in LLM architecture Part 3 - Multi-Query Attention, Rotary Embeddings

 Multi-Query Attention 


Multi-Query Attention (MQA) is a type of attention mechanism that can accelerate the speed of generating tokens in the decoder while ensuring model performance.

It is widely used in the era of large language models, many LLMs adopt MQA, such as Falcon, PaLM, StarCoder, and others.


Rotary Embeddings : 

Since Vaswani et al., 2017 [16] there have been many schemes introduced for encoding positional information in transformers. When applying self-attention to a given domain, the choice of position encoding typically involves tradeoffs between simplicity, flexibility, and efficiency. For example, learned absolute positional encoding is very simple, but may not generalize and are not always particularly meaningful due to the common practices [1, 3, 9, 15] of packing short sentences and phrases together in a single context and breaking up sentences across contexts.


Another major limitation of existing methods is that they do not work with efficient transformers. Methods like T5's relative positional bias [10] require constructing the full 

 attention matrix between positions, which is not possible when using many of the efficient alternatives to softmax attention, including kernelized variants like FAVOR+ [2].


In plain English, the dot product between two vectors is a function of the magnitude of individual vectors and the angle between them. With this in mind, the intuition behind RoPE is that we can represent the token embeddings as complex numbers and their positions as pure rotations that we apply to them. If we shift both the query and key by the same amount, changing absolute position but not relative position, this will lead both representations to be additionally rotated in the same manner---as we will see in the derivation---thus the angle between them will remain unchanged and thus the dot product will also remain unchanged. By exploiting the nature of rotations, the dot product used in self-attention will have the property we are looking for, preserving relative positional information while discarding absolute position.


references:

OpenAI 

Terms in LLM architecture Part 2 - Multi Head attention and masked multi head attention mechanism

Multi Head Attention 

It is the key to Transformer based architecture. Transformer model is a deep learning model introduced in the paper "Attention is all you need". Multi head attention enables the model to focus on different parts of the input sequence simultaneously, capturing diverse types of information. It is used in NLP tasks such as machine translation and language modelling. 

The formula of Multi Head attention involves linear projection, scaling , dot-products and softmax operations. 

The key concepts associated with Multi head attention are: 

Attention Mechanism: 

This allows model to selectively focus on different parts of the input sequence when making predictions. Instead of treating words equally, attention mechanism assign varying level of importance to different words. 

Single Head Attention 

In this, the model learns single set of attention weights  for each position in the input sequence. This means the model attends to different positions one at a time. 

Multi Head Attention: 

This extends the idea of attention by using multiple heads (sets of attention weights) in parallel. Each head operates independently on the input sequence and produces own output. The output from different heads are then combined into 

Parameter sharing: 

In multi head attention, the model learns separate set of parameters (weights) for each attention head. However the computational cost can be controlled by using parameter sharing where the same set of weights is applied to input sequence across all attention head. 

Masked Multi Head Attention 

It is a variant of Multi Head Attention used in the transformer architecture. The masking is introduced to prevent attending to the future positions during training, particularly in the context of autoregressive language modelling or sequence to sequence tasks. This is done to ensure that the model attends to only positions that have already been generated. 

In the context of language modelling or sequence generation, where the model generates one token at a time in an autoregressive manner, it is crucial to prevent information leakage from future positions. Without masking, the model could inadvertently attend to tokens that it has not yet generated during training, leading to sub optimal results.  


references:

OpenAI 


Tuesday, December 26, 2023

Terms in LLM architecture Part 1 - Embeddings Input and Output & positional encoding

Input Embedding - 

Input embedding is a technique used in natural language processing (NLP) and machine learning to represent words, phrases, or sentences as vectors of real numbers in a continuous vector space. It is a fundamental step in many NLP tasks, such as text classification, sentiment analysis, and machine translation.


Word Embeddings:


At the core of input embedding is the idea of word embeddings. Words are initially represented as discrete symbols (e.g., "dog," "cat," "house"), but these symbols lack the semantic relationships between words. Word embeddings aim to capture the meaning of words by representing them as dense vectors in a continuous vector space.


Continuous Vector Space:


In a continuous vector space, semantically similar words are closer to each other, and relationships between words (e.g., king - man + woman = queen) can be expressed as vector operations. This allows machine learning models to learn relationships and similarities between words based on the context in which they appear.


Training Word Embeddings:


Word embeddings are often trained using unsupervised learning on large text corpora. Popular algorithms for training word embeddings include Word2Vec, GloVe (Global Vectors for Word Representation), and FastText.


Input Embedding Layer:


In NLP models, an input embedding layer is added at the beginning of the network architecture. This layer transforms the input sequences (words or tokens) into their corresponding word embeddings. Each word in the input sequence is replaced by its embedding vector.


Learnable Parameters:


The embedding layer has learnable parameters that are adjusted during the training process. These parameters determine the mapping from discrete word indices to continuous vector representations.


Contextual Embeddings:


For more advanced NLP tasks, contextual embeddings are used. Contextual embeddings consider the context of each word in a sentence, capturing variations in meaning based on surrounding words. Models like BERT and GPT have been successful in capturing contextual embeddings 


In general embeddings provide a richer representation of input data enabling model to better understand the semantic relationship within the text. It enables the model to capture the semantic relationships, generalise to unseen words, and improve performance on downstream NLP tasks. 



Output Embedding 


Output embeddings, similar to input embeddings, are representations of data in a continuous vector space. In the context of natural language processing (NLP) or machine learning, output embeddings are often associated with the representations of the model's output, which can include words, phrases, or entire sentences.



Word Output Embeddings:


In tasks like language modeling or text generation, where the model is trained to predict the next word in a sequence, output embeddings represent the predicted words. These embeddings are used to generate the probability distribution over the vocabulary, and the word with the highest probability is chosen as the predicted next word.


Sequence Output Embeddings:


In sequence-to-sequence tasks, such as machine translation or text summarization, the model produces an output sequence. The output embeddings represent each element (word or token) in the generated sequence.


Sentence Output Embeddings:


In tasks like sentiment analysis or document classification, the model predicts a label or sentiment for an entire sentence or document. The output embeddings represent the features used for making the final prediction.


Contextual Embeddings:


Similar to contextual embeddings in input embeddings, models may generate contextual embeddings for the output sequence. These embeddings take into account the context of the entire sequence, capturing dependencies and relationships between different elements.


Learnable Parameters:


Output embeddings, like input embeddings, have learnable parameters. These parameters are adjusted during the training process to improve the model's ability to generate meaningful and coherent output sequences.


Applications:


Output embeddings play a crucial role in various NLP applications, including machine translation, text summarization, image captioning, and conversational AI. They are used to represent the model's generated output in a way that preserves semantic relationships and captures the nuances of the task.


Embedding Layers:


In neural network architectures, embedding layers are often used for both input and output embeddings. These layers map discrete indices (such as word indices) to continuous vector representations.



Positional Encoding :


Positional encoding is a technique used in natural language processing (NLP) and machine learning, specifically in the context of sequence-to-sequence models and attention mechanisms. It is employed to provide information about the positions of elements in a sequence, such as the order of words in a sentence, which is not inherently captured by standard embedding techniques.



In models like the Transformer architecture, which is widely used in NLP tasks, positional encoding is added to the input embeddings to give the model information about the positions of tokens in a sequence. The reason for using positional encoding is that traditional embedding methods, such as Word2Vec or GloVe, do not inherently encode information about the order or position of words in a sentence.


Python dataframes efficient coding tips

Youssef HosniYoussef Hosni's Notebooks 


1️⃣ Write Efficient Python Code


✅ Writing Python Efficient Code: Measuring Python Code Efficiency

https://lnkd.in/dQSUpQsQ


✅ Python Code Optimization for Data Scientists

https://lnkd.in/dGS7DWbX


✅ How To Eliminate Loops From Your Python Code

https://lnkd.in/dV5xDhyV


✅ Stop Looping Through Pandas DataFrames

https://lnkd.in/dsf7zWFs


✅ How To Use .groupby() Effectively As A Data Scient

https://lnkd.in/d8UX2zr6


✅ Selecting & Replacing Values In Pandas Effectively

https://lnkd.in/dcw6c36z


✅ Make Your Pandas Code 1000 Times Faster

https://lnkd.in/dvawCSGv


✅ 20 Pandas Functions for 80% of Data Science Tasks

https://lnkd.in/dvC4pJ9E


✅ Top 10 Pandas Mistakes to Avoid

https://lnkd.in/dvPZdis6


2️⃣ Practical Introduction to Time Series Analysis


✅ Manipulating Time Series Data In Python

https://lnkd.in/des9h7Fx


✅ Time Series Data Visualization In Python

https://lnkd.in/dnSAdKa6


✅ Time Series Exploratory Data Analysis In Python

https://lnkd.in/dX7bCfqJ


✅ Time Series Forecasting with ARIMA Models Part 1

https://lnkd.in/dS_MuYuH


✅ Time Series Forecasting with ARIMA Models Part 2

https://lnkd.in/db3k_gze


3️⃣ Practical Machine Learning

✅ Practical Guide to Dimesnioality Reduction in Python

https://lnkd.in/dFkBvZRi


✅ Building Complex Network with Keras Functional API

https://lnkd.in/dnGrJrGT


✅ Finding the Optimal Number of Clusters Effectively

https://lnkd.in/dwcPdhk3


✅ Chat with PDF Using OpenAI Assistant API

https://lnkd.in/dBk_yrQm


✅ Building & Training GAN Model From Scratch

https://lnkd.in/d2Wm6SAA

 

Monday, December 25, 2023

Various GenAI frameworks & Tools

Langchain 

Hugging Face 

LlamaIndex 

Haystack 

Llama2 

SingleStore notebook 



Langchain 

Developed by Harrison Chase and debuted in October 2022, LangChain serves as an open-source platform designed for constructing sturdy applications powered by LLMs, such as chatbots like ChatGPT and various tailor-made applications.


Initially, the system starts with a large document containing a vast array of data. This document is then broken down into smaller, more manageable chunks.


These chunks are subsequently embedded into vectors — a process that transforms the data into a format that can be quickly and efficiently retrieved by the system. These vectors are stored in a vector store, essentially a database optimized for handling vectorized data.


When a user inputs a prompt into the system, LangChain queries this vector store to find information that closely matches or is relevant to the user’s request. The system employs large LLMs to understand the context and intent of the user’s prompt, which guides the retrieval of pertinent information from the vector store.


Once the relevant information is identified, the LLM uses it to generate or complete an answer that accurately addresses the query. This final step culminates in the user receiving a tailored response, which is the output of the system’s data processing and language generation capabilities.



Hugging Face 


Hugging Face is a multifaceted platform that plays a crucial role in the landscape of artificial intelligence, particularly in the field of natural language processing (NLP) and generative AI.

The main parts of it are:


Model Hub : 

Hugging Face houses a massive repository of pre-trained models for diverse NLP tasks, including text classification, question answering, translation, and text generation.

These models are trained on large datasets and can be fine-tuned for specific requirements, making them readily usable for various purposes.

This eliminates the need for users to train models from scratch, saving time and resources.


Datasets:

Alongside the model library, Hugging Face provides access to a vast collection of datasets for NLP tasks.

These datasets cover various domains and languages, offering valuable resources for training and fine-tuning models.

Users can also contribute their own datasets, enriching the platform’s data resources and fostering community collaboration.


 Model Training & Fine-tuning Tools:


Hugging Face offers tools and functionalities for training and fine-tuning existing models on specific datasets and tasks.

This allows users to tailor models to their specific needs, improving their performance and accuracy in targeted applications.

The platform provides flexible options for training, including local training on personal machines or cloud-based solutions for larger models.


Application Building:


Hugging Face facilitates the development of AI applications by integrating seamlessly with popular programming libraries like TensorFlow and PyTorch.

This allows developers to build chatbots, content generation tools, and other AI-powered applications utilizing pre-trained models.

Numerous application templates and tutorials are available to guide users and accelerate the development process.



Community & Collaboration:


Hugging Face boasts a vibrant community of developers, researchers, and AI enthusiasts.

The platform fosters collaboration through features like model sharing, code repositories, and discussion forums.

This collaborative environment facilitates knowledge sharing, accelerates innovation, and drives the advancement of NLP and generative AI technologies.




References:

https://levelup.gitconnected.com/gen-ai-frameworks-and-tools-every-ai-ml-engineer-should-know-1f0ce36f1452

Things to note when Selecting GenAI and LLM Models

Availability of Proprietary LLM Models : If the platform provider provides state of the art models that is high on accuracy then half the battle is won.

Availability of Larger and Smaller models from Same vendor : arger models are awesome, but just that they are expensive and take more time for response. So, any platform that we choose needs to have a portfolio of models which are both smaller ( for quick and simple use cases) and large ( state of art as mentioned above )

availability of embedding model : Be it a document generation or RAG based soliton — all needs embeddings. So, any platform that provides highly accurate and high performant embeddings models become key contenders for the choice of platform.

availability of playground : Choice of algorithms, search strategies, prompting techniques etc. all need trial and error. Hence, the choice of platform should provide a playground area where users can quickly test and analyze the results of various trials.

RAI and content moderation services: esponsible AI and content moderations are not afterthought any more. With large language models — this have become ever so important. So any platform that offers out of box services and capabilities for RAI are winning the battle of the platform for sure .

General Availability of Other Cognitive Services-:  the biggest huddle in Gen AI application design and implementation is still the data engineering bit. The ability to extract and process unstructured content through variety of services like OCR, text-speech , audio-video etc. is critical to the choice of platform


Access to open source models : whether to use pre trained models or fine tuned. The answer is “both”. So a platform that makes it easy to access and consume open source models as well as pre-trained ones will have better traction


OOB Application implementation services :  this is more towards 3rd party services ( like co-pilots etc.). Any platform that provides out of box services and softwares to application build out will win the day

A/B testing framework —  We all need to made decisions. Which model is better in quality of response VS which one has better SLA VS which one is cost effective and so forth. Platforms that provide a framework/ service to help make that decision for enterprise applications have a huge advantage over others.

Model Catalog — Which models are available to me? how to access the models? what are the model metadata that I can learn from and so forth. Having a model catalog is a must and any platform that provides that as a service has a huge advantage over other.

Services/ IDEs to help fine tunes models — Notebooks are the lifeline for data scientists. Anyone who wants to build and train a LLM model (fine tune/ pre-train etc.) need to have all the tools in his/hers repository. So when we evaluate a platform based on maturity, we need to ensure that they provide developer friendly eco-system.

Fine Tune Frameworks — Now we are talking about some cool advanced stuff ! Model fine tuning can happen through many ways — it can happen in a model parallel way, data parallel way and so forth. So platforms who also provide these frameworks (like deep-speed etc.) that can help distribute and fine tune models in parallel wins the battle on this one

Fine Tune Model Registry and Inference — Does the platform provide capabilities for inference (GPU / CPU etc.) and does it allow for model endpoint management in terms of sharing / collaboration etc ? Any platform that provides these capabilities sore high naturally !

General Availability of Multi-Modal Models : Multi Modal Models (tongue twister for sure!) are the next big thing and any platform that has roadmap to include one has one leg up for the race.

1st party partnership with vendors : We cannot ignore the new open source models (like Llama2 etc.). We can surely access these models from a common open repository (like hugging face), but the best platforms are the ones that has 1st party relations with the model providers. For example, if Meta has partnerships with Azure and offers these models out of box in the model catalog then it is a huge boost.

On demand access to GPUs — GPUs are worth gold now. So any platform that can provide managed GPU clusters will surely have a lots of projects lining up.


References:

https://medium.com/@nayan.j.paul/how-i-selected-my-genai-and-large-language-model-llm-platform-cfe6da358b25


How usually the data security is handled with LLMs and its hosting providers

Will Azure OpenAI Models Store my Data and Train on those? 


No, In OpenAI that is secure within the Azure service boundary. Now, having said that, the Azure OpenAI model is hosted on shared Azure tenant, when any application wants to use the Azure OpenAI models, they will call the models via a dedicated and secure API. When we configure the API, we can use a checkbox to “opt out” of Azure saving any data for audit purpose (not training but simply audit). This will ensure that Azure will not save any usage data for logging or auditing. From a training perspective, Azure confirms and states in their service contract that no data used to interact with the model is ever used in training. This is similar to service contract to like usage of Azure Blob Storage or Snowflake database or Amazon S3 etc. where we store our data in Azure (or AWS etc.) cloud with the confidence that the data is not used for anything else.


Does one's model only serve them? 

Yes at least in Azure, only one person's LLM is serving only one. There is service boundary. So, how it works is — Azure will host a dedicated OpenAI model in Azure’s own environment. That environment is managed and controlled by Azure and within Azure network and service boundary. Within that setup, Azure will create a dedicated instance for you which can only be connected and integrated with your Azure Open AI service (which is running in your Azure account) thsough keys. This means that only the applications running in your Azure account can connect to the dedicated LLM model.


What are things need to be worried when moving LLMs to production? 


1) how to scale out; 

2) how to guarantee SLAs; 

3) how to handle hundreds of concurrent calls in parallel; 

4) how to handle the token limits in LLM’s; 

5) implement content moderations and safety breaks in the solution; 

6) responsible AI; six- audibility and logging; 

7) handle hallucinations and provide confidence in response; 

8) client data protection and role/ attribute based access control; 

9) handle security and vulnerability; 

10) high availability and disaster recovery; 

11) data aging 


 

references:

https://ai.plainenglish.io/faqs-and-frequent-questions-on-large-language-models-and-genai-dc004217f161