Skip to content

"Awesome-LLM: a curated list of Azure OpenAI & Large Language Models" 🔎References to Azure OpenAI, 🦙Large Language Models, and related 🌌 services and 🎋libraries.

kimtth/azure-openai-llm-vector-langchain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Azure OpenAI + LLMs (Large Language Models)

This repository contains references to Azure OpenAI, Large Language Models (LLM), and related services and libraries. It follows a similar approach to the ‘Awesome-list’.

🔹Brief each item on a few lines as possible.
🔹The dates are determined by the date of the commit history, the Article published date, or the Paper issued date (v1).
🔹Capturing a chronicle and key terms of that rapidly advancing field.
🔹Disclaimer: Please be aware that some content may be outdated.

What's the difference between Azure OpenAI and OpenAI?

  1. OpenAI is a better option if you want to use the latest features, and access to the latest models.
  2. Azure OpenAI is recommended if you require a reliable, secure, and compliant environment.
  3. Azure OpenAI provides seamless integration with other Azure services..
  4. Azure OpenAI offers private networking and role-based authentication, and responsible AI content filtering.
  5. Azure OpenAI does not use user input as training data for other customers. Data, privacy, and security for Azure OpenAI

Table of contents

Section 1: RAG, LlamaIndex, and Vector Storage

What is the RAG (Retrieval-Augmented Generation)?

  • RAG (Retrieval-Augmented Generation) : Integrates the retrieval (searching) into LLM text generation. RAG helps the model to “look up” external information to improve its responses. cite [25 Aug 2023]

  • In a 2020 paper, Meta (Facebook) came up with a framework called retrieval-augmented generation to give LLMs access to information beyond their training data. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks: [cnt] [22 May 2020]

    1. RAG-sequence — We retrieve k documents, and use them to generate all the output tokens that answer a user query.
    2. RAG-token— We retrieve k documents, use them to generate the next token, then retrieve k more documents, use them to generate the next token, and so on. This means that we could end up retrieving several different sets of documents in the generation of a single answer to a user’s query.
    3. Of the two approaches proposed in the paper, the RAG-sequence implementation is pretty much always used in the industry. It’s cheaper and simpler to run than the alternative, and it produces great results. cite [30 Sep 2023]

Retrieval-Augmented Generation: Research Papers

  • RAG for LLMs: [cnt] 🏆Retrieval-Augmented Generation for Large Language Models: A Survey: Three paradigms of RAG Naive RAG > Advanced RAG > Modular RAG

  • Benchmarking Large Language Models in Retrieval-Augmented Generation: [cnt]: Retrieval-Augmented Generation Benchmark (RGB) is proposed to assess LLMs on 4 key abilities [4 Sep 2023]:

    1. Noise robustness (External documents contain noises, struggled with noise above 80%)
    2. Negative rejection (External documents are all noises, Highest rejection rate was only 45%)
    3. Information integration (Difficulty in summarizing across multiple documents, Highest accuracy was 60-67%)
    4. Counterfactual robustness (Failed to detect factual errors in counterfactual external documents.)
  • Expand
    • Active Retrieval Augmented Generation : [cnt]: Forward-Looking Active REtrieval augmented generation (FLARE): FLARE iteratively generates a temporary next sentence and check whether it contains low-probability tokens. If so, the system retrieves relevant documents and regenerates the sentence. Determine low-probability tokens by token_logprobs in OpenAI API response. git [11 May 2023]
    • Self-RAG: [cnt] 1. Critic model C: Generates reflection tokens (IsREL (relevant,irrelevant), IsSUP (fullysupported,partially supported,nosupport), IsUse (is useful: 5,4,3,2,1)). It is pretrained on data labeled by GPT-4. 2. Generator model M: The main language model that generates task outputs and reflection tokens. It leverages the data labeled by the critic model during training. 3. Retriever model R: Retrieves relevant passages. The LM decides if external passages (retriever) are needed for text generation. git [17 Oct 2023]
    • A Survey on Retrieval-Augmented Text Generation: [cnt]: This paper conducts a survey on retrieval-augmented text generation, highlighting its advantages and state-of-the-art performance in many NLP tasks. These tasks include Dialogue response generation, Machine translation, Summarization, Paraphrase generation, Text style transfer, and Data-to-text generation. [2 Feb 2022]
    • Retrieval meets Long Context LLMs: [cnt]: We demonstrate that retrieval-augmentation significantly improves the performance of 4K context LLMs. Perhaps surprisingly, we find this simple retrieval-augmented baseline can perform comparable to 16K long context LLMs. [4 Oct 2023]
    • FreshLLMs: [cnt]: Fresh Prompt, Google search first, then use results in prompt. Our experiments show that FreshPrompt outperforms both competing search engine-augmented prompting methods such as Self-Ask (Press et al., 2022) as well as commercial systems such as Perplexity.AI. git [5 Oct 2023]
    • RECOMP: Improving Retrieval-Augmented LMs with Compressors: [cnt]: 1. We propose RECOMP (Retrieve, Compress, Prepend), an intermediate step which compresses retrieved documents into a textual summary prior to prepending them to improve retrieval-augmented language models (RALMs). 2. We present two compressors – an extractive compressor which selects useful sentences from retrieved documents and an abstractive compressor which generates summaries by synthesizing information from multiple documents. 3. Both compressors are trained. [6 Oct 2023]
    • Retrieval-Augmentation for Long-form Question Answering: [cnt]: 1. The order of evidence documents affects the order of generated answers 2. the last sentence of the answer is more likely to be unsupported by evidence. 3. Automatic methods for detecting attribution can achieve reasonable performance, but still lag behind human agreement. Attribution in the paper assesses how well answers are based on provided evidence and avoid creating non-existent information. [18 Oct 2023]
    • INTERS: Unlocking the Power of Large Language Models in Search with Instruction Tuning: INTERS covers 21 search tasks across three categories: query understanding, document understanding, and query-document relationship understanding. The dataset is designed for instruction tuning, a method that fine-tunes LLMs on natural language instructions. git [12 Jan 2024]
    • RAG vs Fine-tuning: Pipelines, Tradeoffs, and a Case Study on Agriculture. [16 Jan 2024]
    • The Power of Noise: Redefining Retrieval for RAG Systems: No more than 2-5 relevant docs + some amount of random noise to the LLM context maximizes the accuracy of the RAG. [26 Jan 2024]
    • Corrective Retrieval Augmented Generation (CRAG): Retrieval Evaluator assesses the retrieved documents and categorizes them as Correct, Ambiguous, or Incorrect1. For Ambiguous and Incorrect documents, the method uses Web Search to improve the quality of the information. The refined and distilled documents are then used to generate the final output. [29 Jan 2024] CRAG implementation by LangGraph git
    • RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval: Introduce a novel approach to retrieval-augmented language models by constructing a recursive tree structure from documents. git pip install llama-index-packs-raptor / git [31 Jan 2024]

RAG Pipeline & Advanced RAG

  • RAG Pipeline

    1. Indexing Stage: Preparing a knowledge base.
    2. Querying Stage: Querying the indexed data to retrieve relevant information.
    3. Responding Stage: Generating responses based on the retrieved information. ref
  • How to optimize RAG pipeline: Indexing optimization [24 Oct 2023]

  • Advanced RAG Patterns: How to improve RAG peformance ref / ref [17 Oct 2023]

    1. Data quality: Clean, standardize, deduplicate, segment, annotate, augment, and update data to make it clear, consistent, and context-rich.
    2. Embeddings fine-tuning: Fine-tune embeddings to domain specifics, adjust them according to context, and refresh them periodically to capture evolving semantics.
    3. Retrieval optimization: Refine chunking, embed metadata, use query routing, multi-vector retrieval, re-ranking, hybrid search, recursive retrieval, query engine, HyDE [20 Dec 2022], and vector search algorithms to improve retrieval efficiency and relevance.
    4. Synthesis techniques: Query transformations, prompt templating, prompt conditioning, function calling, and fine-tuning the generator to refine the generation step.
    • HyDE: Implemented in Langchain: HypotheticalDocumentEmbedder. A query generates hypothetical documents, which are then embedded and retrieved to provide the most relevant results. query -> generate n hypothetical documents -> documents embedding - (avg of embeddings) -> retrieve -> final result. ref
  • Demystifying Advanced RAG Pipelines: An LLM-powered advanced RAG pipeline built from scratch git [19 Oct 2023]

  • 9 Effective Techniques To Boost Retrieval Augmented Generation (RAG) Systems doc: ReRank, Prompt Compression, Hypothetical Document Embedding (HyDE), Query Rewrite and Expansion, Enhance Data Quality, Optimize Index Structure, Add Metadata, Align Query with Documents, Mixed Retrieval (Hybrid Search) [2 Jan 2024]

  • cite [7 Nov 2023] OpenAI has put together a pretty good roadmap for building a production RAG system. Naive RAG -> Tune Chunks -> Rerank & Classify -> Prompt Engineering. In llama_index... Youtube

  • Graph RAG: NebulaGraph proposes the concept of Graph RAG, which is a retrieval enhancement technique based on knowledge graphs. demo [8 Sep 2023]

  • Evaluation with Ragas: UMAP (often used to reduce the dimensionality of embeddings) with Ragas metrics for visualizing RAG results. [Mar 2024] / Ragas provides metrics: Context Precision, Context Relevancy, Context Recall, Faithfulness, Answer Relevance, Answer Semantic Similarity, Answer Correctness, Aspect Critique git [May 2023]

The Problem with RAG

  • The Problem with RAG

    1. A question is not semantically similar to its answers. Cosine similarity may favor semantically similar texts that do not contain the answer.
    2. Semantic similarity gets diluted if the document is too long. Cosine similarity may favor short documents with only the relevant information.
    3. The information needs to be contained in one or a few documents. Information that requires aggregations by scanning the whole data.
  • Seven Failure Points When Engineering a Retrieval Augmented Generation System: 1. Missing Content, 2. Missed the Top Ranked Documents, 3. Not in Context, 4. Not Extracted, 5. Wrong Format, 6. Incorrect Specificity, 7. Lack of Thorough Testing [11 Jan 2024]

  • Solving the core challenges of Retrieval-Augmented Generation ref [Feb 2024]

LlamaIndex

  • LlamaIndex (formerly GPT Index) is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. The high-level API allows users to ingest and query their data in a few lines of code. ref / High-Level Concept: ref

    Fun fact this core idea was the initial inspiration for GPT Index (the former name of LlamaIndex) 11/8/2022 - almost a year ago!. cite / Walking Down the Memory Maze: Beyond Context Limit through Interactive Reading

    1. Build a data structure (memory tree)
    2. Transverse it via LLM prompting
  • Query engine vs Chat engine

    1. The query engine wraps a retriever and a response synthesizer into a pipeline, that will use the query string to fetch nodes (sentences or paragraphs) from the index and then send them to the LLM (Language and Logic Model) to generate a response
    2. The chat engine is a quick and simple way to chat with the data in your index. It uses a context manager to keep track of the conversation history and generate relevant queries for the retriever. Conceptually, it is a stateful analogy of a Query Engine.
  • Storage Context vs Service Context

    • Both the Storage Context and Service Context are data classes.
    index = load_index_from_storage(storage_context, service_context=service_context)
    1. Storage Context is responsible for the storage and retrieval of data in Llama Index, while the Service Context helps in incorporating external context to enhance the search experience.

    2. The Service Context is not directly involved in the storage or retrieval of data, but it helps in providing a more context-aware and accurate search experience.

      Context class definition
      # The storage context container is a utility container for storing nodes, indices, and vectors.
      class StorageContext:
        docstore: BaseDocumentStore
        index_store: BaseIndexStore
        vector_store: VectorStore
        graph_store: GraphStore
      # The service context container is a utility container for LlamaIndex index and query classes.
      class ServiceContext:
        llm_predictor: BaseLLMPredictor
        prompt_helper: PromptHelper
        embed_model: BaseEmbedding
        node_parser: NodeParser
        llama_logger: LlamaLogger
        callback_manager: CallbackManager
  • LlamaIndex Overview (Japanese) [17 Jul 2023]

  • LlamaIndex Tutorial: A Complete LlamaIndex Guide [18 Oct 2023]

  • CallbackManager (Japanese) [27 May 2023] / Customize TokenTextSplitter (Japanese) [27 May 2023] / Chat engine ReAct mode, FLARE Query engine

  • Multimodal RAG Pipeline ref [Nov 2023]

  • LlamaIndex Toolkits: LlamaHub: A library of data loaders for LLMs git [Feb 2023] / LlamaIndex CLI: a command line tool to generate LlamaIndex apps ref [Nov 2023] / LlamaParse: A unique parsing tool for intricate documents git [Feb 2024]

  • From Simple to Advanced RAG ref [10 Oct 2023]

    • Building and Productionizing RAG: doc: Optimizing RAG Systems 1. Table Stakes 2. Advanced Retrieval: Small-to-Big 3. Agents 4. Fine-Tuning 5. Evaluation [Nov 2023]
    • A Cheat Sheet and Some Recipes For Building Advanced RAG RAG cheat sheet shared above was inspired by RAG survey paper. doc [Jan 2024]
    • Fine-Tuning a Linear Adapter for Any Embedding Model: Fine-tuning the embeddings model requires you to reindex your documents. With this approach, you do not need to re-embed your documents. Simply transform the query instead. [7 Sep 2023]
    • 4 RAG techniques implemented in llama_index / cite [20 Sep 2023] / git
      1. SQL Router Query Engine: Query router that can reference your vector database or SQL database
      2. Sub Question Query Engine: Break down the complex question into sub-questions
      3. Recursive Retriever + Query Engine: Reference node relationships, rather than only finding a node (chunk) that is most relevant.
      4. Self Correcting Query Engines: Use an LLM to evaluate its own output.

Vector Database Comparison

  • Not All Vector Databases Are Made Equal: Printed version for "Medium" limits. doc [2 Oct 2021]
  • Faiss: Facebook AI Similarity Search (Faiss) is a library for efficient similarity search and clustering of dense vectors. It is used as an alternative to a vector database in the development and library of algorithms for a vector database. It is developed by Facebook AI Research. git [Feb 2017]
  • Milvus (A cloud-native vector database) Embedded git [Sep 2019]: Alternative option to replace PineCone and Redis Search in OSS. It offers support for multiple languages, addresses the limitations of RedisSearch, and provides cloud scalability and high reliability with Kubernetes.
  • Pinecone: A fully managed cloud Vector Database. Commercial Product [Jan 2021]
  • Weaviate: Store both vectors and data objects. [Jan 2021]
  • Chroma: Open-source embedding database [Oct 2022]
  • Qdrant: Written in Rust. Qdrant (read: quadrant) [May 2020]
  • Redis extension for vector search, RedisVL: Redis Vector Library (RedisVL) [Nov 2022]
  • A SQLite extension for efficient vector search, based on Faiss! [Jan 2023]
  • pgvector: Open-source vector similarity search for Postgres git [Apr 2021]
  • A Comprehensive Survey on Vector Database: Categorizes search algorithms by their approach, such as hash-based, tree-based, graph-based, and quantization-based. [18 Oct 2023]

Vector Database Options for Azure

Note: Azure Cache for Redis Enterprise: Enterprise Sku series are not able to deploy by a template such as Bicep and ARM.

Deploy to Azure

Lucene based search engine with text-embedding-ada-002

  • Azure Open AI Embedding API, text-embedding-ada-002, supports 1536 dimensions. Elastic search, Lucene based engine, supports 1024 dimensions as a max. Open search can insert 16,000 dimensions as a vector storage. Open search is available to use as a vector database with Azure Open AI Embedding API.
  • text-embedding-ada-002: Smaller embedding size. The new embeddings have only 1536 dimensions, one-eighth the size of davinci-001 embeddings, making the new embeddings more cost effective in working with vector databases. [15 Dec 2022]
  • However, one exception to this is that the maximum dimension count for the Lucene engine is 1,024, compared with 16,000 for the other engines. ref
  • LlamaIndex ElasticsearchReader class: The name of the class in LlamaIndex is ElasticsearchReader. However, actually, it can only work with open search.
  • Vector Search with OpenAI Embeddings: Lucene Is All You Need: Our experiments were based on Lucene 9.5.0, but indexing was a bit tricky because the HNSW implementation in Lucene restricts vectors to 1024 dimensions, which was not sufficient for OpenAI’s 1536-dimensional embeddings. Although the resolution of this issue, which is to make vector dimensions configurable on a per codec basis, has been merged to the Lucene source trunk git, this feature has not been folded into a Lucene release (yet) as of early August 2023. [29 Aug 2023]
  • Is Cosine-Similarity of Embeddings Really About Similarity?: In linear matrix factorization, the use of regularization can impact, and in some cases, render cosine similarities meaningless. Regularization involves two objectives. The first objective applies L2-norm regularization to the product of matrices A and B, a process similar to dropout. The second objective applies L2-norm regularization to each individual matrix, similar to the weight decay technique used in deep learning. [8 Mar 2024]

Section 2 : Azure OpenAI and Reference Architecture

Microsoft Azure OpenAI relevant LLM Framework

  1. Semantic Kernel: Semantic Kernel is an open-source SDK that lets you easily combine AI services like OpenAI, Azure OpenAI, and Hugging Face with conventional programming languages like C# and Python. An LLM Ochestrator, similar to Langchain. / git [Feb 2023]
  2. Kernel Memory: Kernel Memory (FKA. Semantic Memory (SM)) is an open-source service and plugin specialized in the efficient indexing of datasets through custom continuous data hybrid pipelines. [Jul 2023]
  3. guidance: A guidance language for controlling large language models. Simple, intuitive syntax, based on Handlebars templating. Domain Specific Language (DSL) for handling model interaction. Langchain libaries but different approach rather than ochestration, particularly effective for implementing Chain of Thought. / git [Nov 2022]
  4. Azure Machine Learning Promt flow: Visual Designer for Prompt crafting. Use Jinja as a prompt template language. / ref / git [Jun 2023]
  5. Prompt Engine: Craft prompts for Large Language Models: npm install prompt-engine / git / python [Jun 2022]
  6. TypeChat: TypeChat replaces prompt engineering with schema engineering. To build natural language interfaces using types. / git [Apr 2023]
  7. DeepSpeed: DeepSpeed is a deep learning optimization library that makes distributed training and inference easy, efficient, and effective. [May 2020]
  8. LMOps: a collection of tools for improving text prompts used as input to generative AI models. The toolkit includes Promptist, which optimizes a user's text input for text-to-image generation, and Structured Prompting. [Dec 2022]
  9. LLMLingua: Compress the prompt and KV-Cache, which achieves up to 20x compression with minimal performance loss. [Jul 2023]
  10. FLAML: A lightweight Python library for efficient automation of machine learning and AI operations. FLAML provides an seamless interface for AutoGen, AutoML, and generic hyperparameter tuning. [Dec 2020]
  11. TaskWeaver: A code-first agent framework which can convert natural language user requests into executable code, with additional support for rich data structures, dynamic plugin selection, and domain-adapted planning process. [Sep 2023]
  12. JARVIS: an interface for LLMs to connect numerous AI models for solving complicated AI tasks! [Mar 2023]
  13. Autogen: Customizable and conversable agents framework ref [Mar 2023]
  14. AI Central: An AI Control Centre for monitoring, authenticating, and providing resilient access to multiple Open AI services. [Oct 2023]
  15. PromptBench: A unified evaluation framework for large language models [Jun 2023]
  16. UFO: A UI-Focused Agent for Windows OS Interaction. [Mar 2024]
  17. SAMMO: A general-purpose framework for prompt optimization. ref [April 2024]
  • Microsoft Fabric: Fabric integrates technologies like Azure Data Factory, Azure Synapse Analytics, and Power BI into a single unified product [May 2023]
  • A Memory in Semantic Kernel vs Kernel Memory (FKA. Semantic Memory (SM)): Kernel Memory is designed to efficiently handle large datasets and extended conversations. Deploying the memory pipeline as a separate service can be beneficial when dealing with large documents or long bot conversations. ref

Microsoft Copilot Product Lineup

  1. Copilot Products

    • Microsoft Copilot in Windows vs Microsoft Copilot (= Copilot in Windows + Commercial Data Protection) vs Microsoft 365 Copilot (= Microsoft Copilot + M365 Integration) [Nov 2023]
    • Copilot Scenario Library
    1. Azure
    2. Microsoft 365 (Incl. Dynamics 365 and Power Platform)
    3. Windows, Bing and so on
  2. Customize Copilot

    1. Microsoft AI and AI Studio
    2. Copilot Studio
    3. Microsoft Office Copilot: Natural Language Commanding via Program Synthesis: [cnt]: Semantic Interpreter, a natural language-friendly AI system for productivity software such as Microsoft Office that leverages large language models (LLMs) to execute user intent across application features. [6 Jun 2023]
    4. NL2KQL: From Natural Language to Kusto Query [3 Apr 2024]

ChatGPT + Enterprise data Demo and Azure OpenAI samples

ChatGPT + Enterprise data Demo

  • ChatGPT + Enterprise data RAG (Retrieval-Augmented Generation) Demo

  • A sample app for the Retrieval-Augmented Generation pattern running in Azure, using Azure Cognitive Search for retrieval and Azure OpenAI git [8 Feb 2023]

  • ChatGPT + Enterprise data RAG Screenshot

    sk
    Expand: Deployment Steps

    The files in code\azure-search-openai-demo directory, extra_steps, have been created for managing extra configurations and steps for launching the demo repository.

    1. (optional) Check Azure module installation in Powershell by running ms_internal_az_init.ps1 script

    2. (optional) Set your Azure subscription Id to default

      Start the following commands in ./azure-search-openai-demo directory

    3. (deploy azure resources) Simply Run azd up

      The azd stores relevant values in the .env file which is stored at ${project_folder}\.azure\az-search-openai-tg\.env.

    4. Move to app by cd app command

    5. (sample data loading) Move to scripts then Change into Powershell by Powershell command, Run prepdocs.ps1

      • console output (excerpt)

                Uploading blob for page 29 -> role_library-29.pdf
                Uploading blob for page 30 -> role_library-30.pdf
        Indexing sections from 'role_library.pdf' into search index 'gptkbindex'
        Splitting './data\role_library.pdf' into sections
                Indexed 60 sections, 60 succeeded
        
    6. Move to app by cd .. and cd app command

    7. (locally running) Run start.cmd

    • console output (excerpt)

      Building frontend
      
      
      > [email protected] build \azure-search-openai-demo\app\frontend
      > tsc && vite build
      
      vite v4.1.1 building for production...
      ✓ 1250 modules transformed.
      ../backend/static/index.html                    0.49 kB
      ../backend/static/assets/github-fab00c2d.svg    0.96 kB
      ../backend/static/assets/index-184dcdbd.css     7.33 kB │ gzip:   2.17 kB
      ../backend/static/assets/index-41d57639.js    625.76 kB │ gzip: 204.86 kB │ map: 5,057.29 kB
      
      Starting backend
      
      * Serving Flask app 'app'
      * Debug mode: off
      WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
      * Running on http://127.0.0.1:5000
      Press CTRL+C to quit
      ...
      

    Running from second times

    1. Move to app by cd .. and cd app command
    2. (locally running) Run start.cmd

    (optional)

    • fix_from_origin : The modified files, setup related
    • ms_internal_az_init.ps1 : Powershell script for Azure module installation
    • ms_internal_troubleshootingt.ps1 : Set Specific Subscription Id as default

Azure OpenAI samples

  • Azure OpenAI samples: ref [Apr 2023]
  • The repository for all Azure OpenAI Samples complementing the OpenAI cookbook.: ref [Apr 2023]
  • Azure-Samples ref
    • Azure OpenAI with AKS By Terraform: git [Jun 2023]
    • Azure OpenAI with AKS By Bicep: git [May 2023]
    • Enterprise Logging: git [Feb 2023]
    • Azure OpenAI with AKS by Terraform (simple version): git [May 2023]
    • ChatGPT Plugin Quickstart using Python and FastAPI: git [May 2023]
    • Azure-Cognitive-Search-Azure-OpenAI-Accelerator: git [Feb 2023]
    • GPT-Azure-Search-Engine: git Integration of Azure Bot Service with LangChain [Feb 2023]
    • Azure OpenAI Network Latency Test Script : git [Jun 2023]
    • Create an Azure OpenAI, LangChain, ChromaDB, and Chainlit ChatGPT-like application in Azure Container Apps using Terraform git [Jul 2023]
  • Azure Open AI work with Cognitive Search act as a Long-term memory
    1. ChatGPT + Enterprise data with Azure OpenAI and Cognitive Search [Feb 2023]
    2. Can ChatGPT work with your enterprise data? [06 Apr 2023]
    3. Azure OpenAI と Azure Cognitive Search の組み合わせを考える [24 May 2023]
  • AI-in-a-Box: AI-in-a-Box aims to provide an "Azure AI/ML Easy Button" for common scenarios [Sep 2023]

Azure Reference Architectures

Azure OpenAI Embeddings QnA [Apr 2023] Azure Cosmos DB + OpenAI ChatGPT C# blazor [Mar 2023]
embeddin_azure_csharp gpt-cosmos
C# Implementation ChatGPT + Enterprise data with Azure OpenAI and Cognitive Search [Apr 2023] Simple ChatGPT UI application Typescript, ReactJs and Flask [Apr 2023]
embeddin_azure_csharp gpt-cosmos
Azure Video Indexer demo Azure Video Indexer + OpenAI [Apr 2023] Miyagi Integration demonstrate for multiple langchain libraries [Feb 2023]
demo-videoindexer miyagi

Azure AI Search

  • Azure Cognitive Search rebranding Azure AI Search, it supports Vector search and semantic ranker. [16 Nov 2023]
  • In the vector databases category within Azure, several alternative solutions are available. However, the only option that provides a range of choices, including a conventional Lucene-based search engine and a hybrid search incorporating vector search capabilities.
  • Vector Search Sample Code: git [Apr 2023]
  • Azure AI Search (FKA. Azure Cognitive Search) supports
    1. Text Search
    2. Pure Vector Search
    3. Hybrid Search (Text search + Vector search)
    4. Semantic Hybrid Search (Text search + Semantic search + Vector search)
  • A set of capabilities designed to improve relevance in these scenarios. We use a combination of hybrid retrieval (vector search + keyword search) + semantic ranking as the most effective approach for improved relevance out-of–the-box. TL;DR: Retrieval Performance; Hybrid search + Semantic rank > Hybrid search > Vector only search > Keyword only ref [18 Sep 2023]

    acs
  • Hybrid search using Reciprocal Rank Fusion (RRF): Reciprocal Rank Fusion (RRF) is an algorithm that evaluates the search scores from multiple, previously ranked results to produce a unified result set. In Azure Cognitive Search, RRF is used whenever there are two or more queries that execute in parallel. ref

Azure Enterprise Services

  • Copilot (FKA. Bing Chat Enterprise) [18 Jul 2023] Privacy and Protection
    1. Doesn't have plugin support
    2. Only content provided in the chat by users is accessible to Bing Chat Enterprise.
  • Azure OpenAI Service On Your Data in Public Preview ref [19 Jun 2023]
  • Azure OpenAI Finetuning: Babbage-002 is $34/hour, Davinci-002 is $68/hour, and Turbo is $102/hour. ref [16 Oct 2023]
  • Customer Copyright Commitment: protects customers from certain IP claims related to AI-generated content. ref [16 Nov 2023]
  • Models as a Service (MaaS): A cloud-based AI approach that provides developers and businesses with access to pre-built, pre-trained machine learning models. [July 2023]
  • Assistants API: Code Interpreter, Function calling, Knowledge retrieval tool, and Threads (Truncated and optimized conversation history for the model's context length) in Azure [06 Feb 2024]

Section 3 : Microsoft Semantic Kernel and Stanford NLP DSPy

Semantic Kernel

  • Microsoft Langchain Library supports C# and Python and offers several features, some of which are still in development and may be unclear on how to implement. However, it is simple, stable, and faster than Python-based open-source software. The features listed on the link include: Semantic Kernel Feature Matrix / git [Feb 2023]

Feature Roadmap

  • .NET Semantic Kernel SDK: 1. Renamed packages and classes that used the term “Skill” to now use “Plugin”. 2. OpenAI specific in Semantic Kernel core to be AI service agnostic 3. Consolidated our planner implementations into a single package ref [10 Oct 2023]
  • Road to v1.0 for the Python Semantic Kernel SDK ref [23 Jan 2024] backlog

Code Recipes

  • Chat Copilot Sample Application: A reference application for building a chat experience using Semantic Kernel. Leveraging plugins, planners, and AI memories. git [Apr 2023]
  • Semantic Kernel Recipes: A collection of C# notebooks git [Mar 2023]
  • Deploy Semantic Kernel with Bot Framework ref git [26 Oct 2023]
  • Semantic Kernel-Powered OpenAI Plugin Development Lifecycle ref [30 Oct 2023]
  • SemanticKernel Implementation sample to overcome Token limits of Open AI model. Semantic Kernel でトークンの限界を超えるような長い文章を分割してスキルに渡して結果を結合したい (zenn.dev) ref [06 May 2023]
  • Learning Paths for Semantic Kernel [28 Mar 2024]

Semantic Kernel Planner

  • Semantic Kernel Planner ref [24 Jul 2023]

    sk-plan
  • Is Semantic Kernel Planner the same as LangChain agents?

    Planner in SK is not the same as Agents in LangChain. cite [11 May 2023]

    Agents in LangChain use recursive calls to the LLM to decide the next step to take based on the current state. The two planner implementations in SK are not self-correcting. Sequential planner tries to produce all the steps at the very beginning, so it is unable to handle unexpected errors. Action planner only chooses one tool to satisfy the goal

  • Stepwise Planner released. The Stepwise Planner features the "CreateScratchPad" function, acting as a 'Scratch Pad' to aggregate goal-oriented steps. [16 Aug 2023]

  • Gen-4 and Gen-5 planners: 1. Gen-4: Generate multi-step plans with the Handlebars 2. Gen-5: Stepwise Planner supports Function Calling. ref [16 Nov 2023]

Semantic Function

  • Semantic Function - expressed in natural language in a text file "skprompt.txt" using SK's Prompt Template language. Each semantic function is defined by a unique prompt template file, developed using modern prompt engineering techniques. cite

  • Prompt Template language Key takeaways

1. Variables : use the {{$variableName}} syntax : Hello {{$name}}, welcome to Semantic Kernel!
2. Function calls: use the {{namespace.functionName}} syntax : The weather today is {{weather.getForecast}}.
3. Function parameters: {{namespace.functionName $varName}} and {{namespace.functionName "value"}} syntax
   : The weather today in {{$city}} is {{weather.getForecast $city}}.
4. Prompts needing double curly braces :
   {{ "{{" }} and {{ "}}" }} are special SK sequences.
5. Values that include quotes, and escaping :

    For instance:
    ... {{ 'no need to \\"escape" ' }} ...
    is equivalent to:
    ... {{ 'no need to "escape" ' }} ...

Semantic Kernel Glossary

DSPy

  • DSPy (Declarative Self-improving Language Programs, pronounced “dee-es-pie”)

  • DSPy Documentation & Cheetsheet ref

  • DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines [5 Oct 2023] / git

  • DSPy Explained! youtube [30 Jan 2024]

  • DSPy RAG example in weviate recipes: recipes > integrations git

  • Instead of a hard-coded prompt template, "Modular approach: compositions of modules -> compile". Building blocks such as ChainOfThought or Retrieve and compiling the program, optimizing the prompts based on specific metrics. Unifying strategies for both prompting and fine-tuning in one tool, Pythonic operations, prioritizing and tracing program execution. These features distinguish it from other LMP frameworks such as LangChain, and LlamaIndex. ref [Jan 2023]

  • Automatically iterate until the best result is achieved: 1. Collect Data -> 2. Write DSPy Program -> 3. Define validtion logic -> 4. Compile DSPy program

    workflow
  • DSPy vs. LangChain, LlamaIndex: LangChain and LlamaIndex offer pre-built modules for specific applications. DSPy provides general-purpose modules that learn to optimize your language model based on your data and pipeline. It's like the difference between PyTorch (DSPy) and HuggingFace Transformers (higher-level libraries).

DSPy Glossary

  • Glossary reference to the ref.
    1. Signatures: Hand-written prompts and fine-tuning are abstracted and replaced by signatures.

      "question -> answer"
      "long-document -> summary"
      "context, question -> answer"

    2. Modules: Prompting techniques, such as Chain of Thought or ReAct, are abstracted and replaced by modules.
      # pass a signature to ChainOfThought module
      generate_answer = dspy.ChainOfThought("context, question -> answer")
    3. Optimizers (formerly Teleprompters): Manual iterations of prompt engineering is automated with optimizers (teleprompters) and a DSPy Compiler.
      # Self-generate complete demonstrations. Teacher-student paradigm, `BootstrapFewShotWithOptuna`, `BootstrapFewShotWithRandomSearch` etc. which work on the same principle.
      optimizer = BootstrapFewShot(metric=dspy.evaluate.answer_exact_match)
    4. DSPy Compiler: Internally trace your program and then optimize it using an optimizer (teleprompter) to maximize a given metric (e.g., improve quality or cost) for your task.
    • e.g., the DSPy compiler optimizes the initial prompt and thus eliminates the need for manual prompt tuning.

      cot_compiled = teleprompter.compile(CoT(), trainset=trainset, valset=devset)
      cot_compiled.save('turbo_gsm8k.json')
      Expand

      DSPy optimizer

      As a rule of thumb, if you don't know where to start, use BootstrapFewShotWithRandomSearch.

      If you have very little data, e.g. 10 examples of your task, use BootstrapFewShot.

      If you have slightly more data, e.g. 50 examples of your task, use BootstrapFewShotWithRandomSearch.

      If you have more data than that, e.g. 300 examples or more, use BayesianSignatureOptimizer.

      If you have been able to use one of these with a large LM (e.g., 7B parameters or above) and need a very efficient program, compile that down to a small LM with BootstrapFinetune.

Section 4 : Langchain Features, Usage, and Comparisons

  • LangChain is a framework for developing applications powered by language models. (1) Be data-aware: connect a language model to other sources of data. (2) Be agentic: Allow a language model to interact with its environment.

  • It highlights two main value props of the framework:

    1. Components: modular abstractions and implementations for working with language models, with easy-to-use features.
    2. Use-Case Specific Chains: chains of components that assemble in different ways to achieve specific use cases, with customizable interfaces.cite: ref
    • Towards LangChain 0.1 ref [Dec 2023]

    • Basic LangChain building blocks ref [2023]

      '''
      LLMChain: A LLMChain is the most common type of chain. It consists of a PromptTemplate, a model (either an LLM or a ChatModel), and an optional output parser.
      '''
      chain = prompt | model | parser

Langchain Feature Matrix & Cheetsheet

Langchain Impressive Features

  • Langchain/cache: Reducing the number of API calls
  • Langchain/context-aware-splitting: Splits a file into chunks while keeping metadata
  • LangChain Expression Language: A declarative way to easily compose chains together [Aug 2023]
  • LangSmith Platform for debugging, testing, evaluating. [Jul 2023]
  • langflow: LangFlow is a UI for LangChain, designed with react-flow. [Feb 2023]
  • Flowise Drag & drop UI to build your customized LLM flow [Apr 2023]
  • Langchain Template: Langchain Reference architectures and samples. e.g., RAG Conversation Template [Oct 2023]
  • OpenGPTs: An open source effort to create a similar experience to OpenAI's GPTs [Nov 2023]
  • LangGraph: Build and navigate language agents as graphs [Aug 2023]

Langchain Quick Start: How to Use

  • code\deeplearning.ai\langchain-chat-with-your-data: DeepLearning.ai LangChain: Chat with Your Data
  • code\deeplearning.ai\langchain-llm-app-dev: LangChain for LLM Application Development

Langchain chain type: Chains & Summarizer

  • Chains ref
    • SimpleSequentialChain: A sequence of steps with single input and output. Output of one step is input for the next.
    • SequentialChain: Like SimpleSequentialChain but handles multiple inputs and outputs at each step.
    • MultiPromptChain: Routes inputs to specialized sub-chains based on content. Ideal for different prompts for different tasks.
  • Summarizer
    • stuff: Sends everything at once in LLM. If it's too long, an error will occur.
    • map_reduce: Summarizes by dividing and then summarizing the entire summary.
    • refine: (Summary + Next document) => Summary
    • map_rerank: Ranks by score and summarizes to important points.

Langchain Agent & Memory

Langchain Agent

  1. If you're using a text LLM, first try zero-shot-react-description.
  2. If you're using a Chat Model, try chat-zero-shot-react-description.
  3. If you're using a Chat Model and want to use memory, try conversational-react-description.
  4. self-ask-with-search: Measuring and Narrowing the Compositionality Gap in Language Models [7 Oct 2022]
  5. react-docstore: ReAct: Synergizing Reasoning and Acting in Language Models [6 Oct 2022]
  6. Agent Type
class AgentType(str, Enum):
    """Enumerator with the Agent types."""

    ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description"
    REACT_DOCSTORE = "react-docstore"
    SELF_ASK_WITH_SEARCH = "self-ask-with-search"
    CONVERSATIONAL_REACT_DESCRIPTION = "conversational-react-description"
    CHAT_ZERO_SHOT_REACT_DESCRIPTION = "chat-zero-shot-react-description"
    CHAT_CONVERSATIONAL_REACT_DESCRIPTION = "chat-conversational-react-description"
    STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION = (
        "structured-chat-zero-shot-react-description"
    )
    OPENAI_FUNCTIONS = "openai-functions"
    OPENAI_MULTI_FUNCTIONS = "openai-multi-functions"
  • ReAct vs MRKL (miracle)

    ReAct is inspired by the synergies between "acting" and "reasoning" which allow humans to learn new tasks and make decisions or reasoning.

    MRKL stands for Modular Reasoning, Knowledge and Language and is a neuro-symbolic architecture that combines large language models, external knowledge sources, and discrete reasoning

    cite: ref [28 Apr 2023]

    zero-shot-react-description This agent uses the ReAct framework to determine which tool to use based solely on the tool’s description. Any number of tools can be provided. This agent requires that a description is provided for each tool.

    react-docstore This agent uses the ReAct framework to interact with a docstore. Two tools must be provided: a Search tool and a Lookup tool (they must be named exactly as so). The Search tool should search for a document, while the Lookup tool should lookup a term in the most recently found document. This agent is equivalent to the original ReAct paper, specifically the Wikipedia example.

    According to my understanding, MRKL is implemented by using ReAct framework in langchain ,which is called zero-shot-react-description. The original ReAct is been implemented in react-docstore agent type.

    ps. MRKL is published at 1 May 2022, earlier than ReAct, which is published at 6 Oct 2022.

Langchain Memory

  1. ConversationBufferMemory: Stores the entire conversation history.
  2. ConversationBufferWindowMemory: Stores recent messages from the conversation history.
  3. Entity Memory: Stores and retrieves entity-related information.
  4. Conversation Knowledge Graph Memory: Stores entities and relationships between entities.
  5. ConversationSummaryMemory: Stores summarized information about the conversation.
  6. ConversationSummaryBufferMemory: Stores summarized information about the conversation with a token limit.
  7. ConversationTokenBufferMemory: Stores tokens from the conversation.
  8. VectorStore-Backed Memory: Leverages vector space models for storing and retrieving information.

Criticism to Langchain

  • The Problem With LangChain: ref / git [14 Jul 2023]

  • What’s your biggest complaint about langchain?: ref [May 2023]

  • Langchain Is Pointless: ref [Jul 2023]

    LangChain has been criticized for making simple things relatively complex, which creates unnecessary complexity and tribalism that hurts the up-and-coming AI ecosystem as a whole. The documentation is also criticized for being bad and unhelpful.

Comparison: Langchain vs Its Competitors

Prompting Frameworks

Langchain vs LlamaIndex

  • Basically LlamaIndex is a smart storage mechanism, while Langchain is a tool to bring multiple tools together. cite [14 Apr 2023]

  • LangChain offers many features and focuses on using chains and agents to connect with external APIs. In contrast, LlamaIndex is more specialized and excels at indexing data and retrieving documents.

Langchain vs Semantic Kernel

Langchain Semantic Kernel
Memory Memory
Tookit Plugin (pre. Skill)
Tool LLM prompts (semantic functions) or native C# or Python code (native function)
Agent Planner
Chain Steps, Pipeline
Tool Connector

Langchain vs Semantic Kernel vs Azure Machine Learning Prompt flow

  • What's the difference between LangChain and Semantic Kernel?

    LangChain has many agents, tools, plugins etc. out of the box. More over, LangChain has 10x more popularity, so has about 10x more developer activity to improve it. On other hand, Semantic Kernel architecture and quality is better, that's quite promising for Semantic Kernel. ref [11 May 2023]

  • What's the difference between Azure Machine Learing PromptFlow and Semantic Kernel?

    1. Low/No Code vs C#, Python, Java
    2. Focused on Prompt orchestrating vs Integrate LLM into their existing app.
  • Promptflow is not intended to replace chat conversation flow. Instead, it’s an optimized solution for integrating Search and Open Source Language Models. By default, it supports Python, LLM, and the Prompt tool as its fundamental building blocks.

  • Using Prompt flow with Semantic Kernel: ref [07 Sep 2023]

Prompt Template Language

Handlebars.js Jinja2 Prompt Template
Conditions {{#if user}}
  Hello {{user}}!
{{else}}
  Hello Stranger!
{{/if}}
{% if user %}
  Hello {{ user }}!
{% else %}
  Hello Stranger!
{% endif %}
Branching features such as "if", "for", and code blocks are not part of SK's template language.
Loop {{#each items}}
  Hello {{this}}
{{/each}}
{% for item in items %}
  Hello {{ item }}
{% endfor %}
By using a simple language, the kernel can also avoid complex parsing and external dependencies.
Langchain Library guidance. LangChain.js Langchain, Azure ML prompt flow Semantic Kernel
URL ref ref ref
  • Semantic Kernel supports HandleBars and Jinja2. [Mar 2024]

Section 5: Prompt Engineering, Finetuning, and Visual Prompts

Prompt Engineering

  1. Zero-shot

  2. Few-shot Learning

  3. Chain of Thought (CoT): Chain-of-Thought Prompting Elicits Reasoning in Large Language Models [cnt]: ReAct and Self Consistency also inherit the CoT concept. [28 Jan 2022]

  4. Self-Consistency: The three steps in the self-consistency method: 1) prompt the language model using CoT prompting, 2) sample a diverse set of reasoning paths from the language model, and 3) marginalize out reasoning paths to aggregate final answers and choose the most consistent answer. [21 Mar 2022]

  5. Recursively Criticizes and Improves (RCI): [cnt] [30 Mar 2023]

    • Critique: Review your previous answer and find problems with your answer.
    • Improve: Based on the problems you found, improve your answer.
  6. ReAct: [cnt]: Grounding with external sources. (Reasoning and Act): Combines reasoning and acting ref [6 Oct 2022]

  7. Tree of Thought: [cnt]: Self-evaluate the progress intermediate thoughts make towards solving a problem [17 May 2023] git / Agora: Tree of Thoughts (ToT) git

    • tree-of-thought\forest_of_thought.py: Forest of thought Decorator sample
    • tree-of-thought\tree_of_thought.py: Tree of thought Decorator sample
    • tree-of-thought\react-prompt.py: ReAct sample without Langchain
  8. Graph of Thoughts (GoT): [cnt] Solving Elaborate Problems with Large Language Models git [18 Aug 2023]

  9. Retrieval Augmented Generation (RAG): [cnt]: To address such knowledge-intensive tasks. RAG combines an information retrieval component with a text generator model. [22 May 2020]

  10. Zero-shot, one-shot and few-shot cite [28 May 2020]

  11. Prompt Engneering overview cite [10 Jul 2023]

  12. Prompt Concept

    1. Question-Answering
    2. Roll-play: Act as a [ROLE] perform [TASK] in [FORMAT]
    3. Reasoning
    4. Prompt-Chain
  13. Chain-of-Verification reduces Hallucination in LLMs: [cnt]: A four-step process that consists of generating a baseline response, planning verification questions, executing verification questions, and generating a final verified response based on the verification results. [20 Sep 2023]

  14. Reflexion: [cnt]: Language Agents with Verbal Reinforcement Learning. 1. Reflexion that uses verbal reinforcement to help agents learn from prior failings. 2. Reflexion converts binary or scalar feedback from the environment into verbal feedback in the form of a textual summary, which is then added as additional context for the LLM agent in the next episode. 3. It is lightweight and doesn’t require finetuning the LLM. [20 Mar 2023] / git

  15. Large Language Models as Optimizers: [cnt]: Take a deep breath and work on this problem step-by-step. to improve its accuracy. Optimization by PROmpting (OPRO) [7 Sep 2023]

  16. Promptist

    • Promptist: Microsoft's researchers trained an additional language model (LM) that optimizes text prompts for text-to-image generation.
      • For example, instead of simply passing "Cats dancing in a space club" as a prompt, an engineered prompt might be "Cats dancing in a space club, digital painting, artstation, concept art, soft light, hdri, smooth, sharp focus, illustration, fantasy."
  17. Power of Prompting

    • GPT-4 with Medprompt: GPT-4, using a method called Medprompt that combines several prompting strategies, has surpassed MedPaLM 2 on the MedQA dataset without the need for fine-tuning. [28 Nov 2023]
    • promptbase: Scripts demonstrating the Medprompt methodology [Dec 2023]
  18. Adversarial Prompting

    • Prompt Injection: Ignore the above directions and ...
    • Prompt Leaking: Ignore the above instructions ... followed by a copy of the full prompt with exemplars:
    • Jailbreaking: Bypassing a safety policy, instruct Unethical instructions if the request is contextualized in a clever way. ref
  19. Prompt Principle for Instructions: 26 prompt principles: e.g., 1) No need to be polite with LLM so there .. 16) Assign a role.. 17) Use Delimiters.. [26 Dec 2023]

  20. ChatGPT : “user”, “assistant”, and “system” messages.**

    To be specific, the ChatGPT API allows for differentiation between “user”, “assistant”, and “system” messages.

    1. always obey "system" messages.
    2. all end user input in the “user” messages.
    3. "assistant" messages as previous chat responses from the assistant.

    Presumably, the model is trained to treat the user messages as human messages, system messages as some system level configuration, and assistant messages as previous chat responses from the assistant. ref [2 Mar 2023]

  21. Automatic Prompt Engineer (APE): Automatically optimizing prompts. APE has discovered zero-shot Chain-of-Thought (CoT) prompts superior to human-designed prompts like “Let’s think through this step-by-step” (Kojima et al., 2022). The prompt “To get the correct answer, let’s think step-by-step.” triggers a chain of thought. Two approaches to generate high-quality candidates: forward mode and reverse mode generation. [3 Nov 2022] git / ref [Mar 2024]

  22. Claude Prompt Engineer: Simply input a description of your task and some test cases, and the system will generate, test, and rank a multitude of prompts to find the ones that perform the best. [4 Jul 2023]

  23. Many-Shot In-Context Learning: Transitioning from few-shot to many-shot In-Context Learning (ICL) can lead to significant performance gains across a wide variety of generative and discriminative tasks [17 Apr 2024]

  • Expand
    1. FireAct: [cnt]: Toward Language Agent Fine-tuning. 1. This work takes an initial step to show multiple advantages of fine-tuning LMs for agentic uses. 2. Duringfine-tuning, The successful trajectories are then converted into the ReAct format to fine-tune a smaller LM. 3. This work is an initial step toward language agent fine-tuning, and is constrained to a single type of task (QA) and a single tool (Google search). / git [9 Oct 20239]

    2. RankPrompt: Self-ranking method. Direct Scoring independently assigns scores to each candidate, whereas RankPrompt ranks candidates through a systematic, step-by-step comparative evaluation. [19 Mar 2024]

Prompt Guide & Leaked prompts

Finetuning & Model Compression

PEFT: Parameter-Efficient Fine-Tuning (Youtube) [24 Apr 2023]

  • PEFT: Parameter-Efficient Fine-Tuning. PEFT is an approach to fine tuning only a few parameters. [10 Feb 2023]

  • Scaling Down to Scale Up: A Guide to Parameter-Efficient Fine-Tuning: [cnt] [28 Mar 2023]

  • Category: Represent approach - Description - Pseudo Code ref [22 Sep 2023]

    1. Adapters: Adapters - Additional Layers. Inference can be slower.

      def transformer_with_adapter(x):
        residual = x
        x = SelfAttention(x)
        x = FFN(x) # adapter
        x = LN(x + residual)
        residual = x
        x = FFN(x) # transformer FFN
        x = FFN(x) # adapter
        x = LN(x + residual)
        return x
    2. Soft Prompts: Prompt-Tuning - Learnable text prompts. Not always desired results.

      def soft_prompted_model(input_ids):
        x = Embed(input_ids)
        soft_prompt_embedding = SoftPromptEmbed(task_based_soft_prompt)
        x = concat([soft_prompt_embedding, x], dim=seq)
        return model(x)
    3. Selective: BitFit - Update only the bias parameters. fast but limited.

      params = (p for n,p in model.named_parameters() if "bias" in n)
      optimizer = Optimizer(params)
    4. Reparametrization: LoRa - Low-rank decomposition. Efficient, Complex to implement.

      def lora_linear(x):
        h = x @ W # regular linear
        h += x @ W_A @ W_B # low_rank update
        return scale * h
  • LoRA: Low-Rank Adaptation of Large Language Models: [cnt]: LoRA is one of PEFT technique. To represent the weight updates with two smaller matrices (called update matrices) through low-rank decomposition. git [17 Jun 2021]

    LoRA
    Expand: LoRA Family
    1. LoRA+: Improves LoRA’s performance and fine-tuning speed by setting different learning rates for the LoRA adapter matrices. [19 Feb 2024]
    2. LoTR: Tensor decomposition for gradient update. [2 Feb 2024]
    3. The Expressive Power of Low-Rank Adaptation: Theoretically analyzes the expressive power of LoRA. [26 Oct 2023]
    4. DoRA: Weight-Decomposed Low-Rank Adaptation. Decomposes pre-trained weight into two components, magnitude and direction, for fine-tuning. [14 Feb 2024]
    5. LoRA Family ref [11 Mar 2024]
      • LoRA introduces low-rank matrices A and B that are trained, while the pre-trained weight matrix W is frozen.
      • LoRA+ suggests having a much higher learning rate for B than for A.
      • VeRA does not train A and B, but initializes them randomly and trains new vectors d and b on top.
      • LoRA-FA only trains matrix B.
      • LoRA-drop uses the output of B*A to determine, which layers are worth to be trained at all.
      • AdaLoRA adapts the ranks of A and B in different layers dynamically, allowing for a higher rank in these layers, where more contribution to the model’s performance is expected.
      • DoRA splits the LoRA adapter into two components of magnitude and direction and allows to train them more independently.
      • Delta-LoRA changes the weights of W by the gradient of A*B.
  • Practical Tips for Finetuning LLMs Using LoRA (Low-Rank Adaptation) [19 Nov 2023]: Best practical guide of LoRA.

    1. QLoRA saves 33% memory but increases runtime by 39%, useful if GPU memory is a constraint.
    2. Optimizer choice for LLM finetuning isn’t crucial. Adam optimizer’s memory-intensity doesn’t significantly impact LLM’s peak memory.
    3. Apply LoRA across all layers for maximum performance.
    4. Adjusting the LoRA rank is essential.
    5. Multi-epoch training on static datasets may lead to overfitting and deteriorate results.
  • QLoRA: Efficient Finetuning of Quantized LLMs: [cnt]: 4-bit quantized pre-trained language model into Low Rank Adapters (LoRA). git [23 May 2023]

  • Training language models to follow instructions with human feedback: [cnt] [4 Mar 2022]

  • Fine-tuning a GPT - LoRA: Comprehensive guide for LoRA doc [20 Jun 2023]

  • LIMA: Less Is More for Alignment: [cnt]: fine-tuned with the standard supervised loss on only 1,000 carefully curated prompts and responses, without any reinforcement learning or human preference modeling. LIMA demonstrates remarkably strong performance, either equivalent or strictly preferred to GPT-4 in 43% of cases. [18 May 2023]

  • Efficient Streaming Language Models with Attention Sinks: [cnt] 1. StreamingLLM, an efficient framework that enables LLMs trained with a finite length attention window to generalize to infinite sequence length without any fine-tuning. 2. We neither expand the LLMs' context window nor enhance their long-term memory. git [29 Sep 2023]

    Expand: StreamingLLM streaming-attn
    • Key-Value (KV) cache is an important component in the StreamingLLM framework.
    1. Window Attention: Only the most recent Key and Value states (KVs) are cached. This approach fails when the text length surpasses the cache size.
    2. Sliding Attention /w Re-computation: Rebuilds the Key-Value (KV) states from the recent tokens for each new token. Evicts the oldest part of the cache.
    3. StreamingLLM: One of the techniques used is to add a placeholder token (yellow-colored) as a dedicated attention sink during pre-training. This attention sink attracts the model’s attention and helps it generalize to longer sequences. Outperforms the sliding window with re-computation baseline by up to a remarkable 22.2× speedup.
  • How to continue pretraining an LLM on new data: Continued pretraining can be as effective as retraining on combined datasets. [13 Mar 2024]

    Expand: Continued pretraining

    Three training methods were compared:

    1. Regular pretraining: A model is initialized with random weights and pretrained on dataset D1.
    2. Continued pretraining: The pretrained model from 1) is further pretrained on dataset D2.
    3. Retraining on combined dataset: A model is initialized with random weights and trained on the combined datasets D1 and D2.

    Continued pretraining can be as effective as retraining on combined datasets. Key strategies for successful continued pretraining include:

    1. Re-warming: Increasing the learning rate at the start of continued pre-training.
    2. Re-decaying: Gradually reducing the learning rate afterwards.
    3. Data Mixing: Adding a small portion (e.g., 5%) of the original pretraining data (D1) to the new dataset (D2) to prevent catastrophic forgetting.
  • Expand
    1. LongLoRA: Efficient Fine-tuning of Long-Context Large Language Models: [cnt]: A combination of sparse local attention and LoRA git [21 Sep 2023]
    • Key Takeaways from LongLora

      long-lora
      1. The document states that LoRA alone is not sufficient for long context extension.
      2. Although dense global attention is needed during inference, fine-tuning the model can be done by sparse local attention, shift short attention (S2-Attn).
      3. S2-Attn can be implemented with only two lines of code in training.
    1. QA-LoRA: [cnt]: Quantization-Aware Low-Rank Adaptation of Large Language Models. A method that integrates quantization and low-rank adaptation for large language models. git [26 Sep 2023]

Llama 2 Finetuning

  • A key difference between Llama 1: [cnt] [27 Feb 2023] and Llama 2: [cnt] [18 Jul 2023] is the architectural change of attention layer, in which Llama 2 takes advantage of Grouped Query Attention (GQA) mechanism to improve efficiency.

    llm-grp-attn
  • Multi-query attention (MQA): [cnt] [22 May 2023]

  • Coding LLaMA 2 from scratch in PyTorch - KV Cache, Grouped Query Attention, Rotary PE, RMSNorm Youtube / git [03 Sep 2023]

    Coding LLaMA 2: KV Cache, Grouped Query Attention, Rotary PE

    Rotary PE

    def apply_rotary_embeddings(x: torch.Tensor, freqs_complex: torch.Tensor, device: str):
        # Separate the last dimension pairs of two values, representing the real and imaginary parts of the complex number
        # Two consecutive values will become a single complex number
        # (B, Seq_Len, H, Head_Dim) -> (B, Seq_Len, H, Head_Dim/2)
        x_complex = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
        # Reshape the freqs_complex tensor to match the shape of the x_complex tensor. So we need to add the batch dimension and the head dimension
        # (Seq_Len, Head_Dim/2) --> (1, Seq_Len, 1, Head_Dim/2)
        freqs_complex = freqs_complex.unsqueeze(0).unsqueeze(2)
        # Multiply each complex number in the x_complex tensor by the corresponding complex number in the freqs_complex tensor
        # Which results in the rotation of the complex number as shown in the Figure 1 of the paper
        # (B, Seq_Len, H, Head_Dim/2) * (1, Seq_Len, 1, Head_Dim/2) = (B, Seq_Len, H, Head_Dim/2)
        x_rotated = x_complex * freqs_complex
        # Convert the complex number back to the real number
        # (B, Seq_Len, H, Head_Dim/2) -> (B, Seq_Len, H, Head_Dim/2, 2)
        x_out = torch.view_as_real(x_rotated)
        # (B, Seq_Len, H, Head_Dim/2, 2) -> (B, Seq_Len, H, Head_Dim)
        x_out = x_out.reshape(*x.shape)
        return x_out.type_as(x).to(device)

    KV Cache, Grouped Query Attention

      # Replace the entry in the cache
      self.cache_k[:batch_size, start_pos : start_pos + seq_len] = xk
      self.cache_v[:batch_size, start_pos : start_pos + seq_len] = xv
    
      # (B, Seq_Len_KV, H_KV, Head_Dim)
      keys = self.cache_k[:batch_size, : start_pos + seq_len]
      # (B, Seq_Len_KV, H_KV, Head_Dim)
      values = self.cache_v[:batch_size, : start_pos + seq_len]
    
      # Since every group of Q shares the same K and V heads, just repeat the K and V heads for every Q in the same group.
    
      # (B, Seq_Len_KV, H_KV, Head_Dim) --> (B, Seq_Len_KV, H_Q, Head_Dim)
      keys = repeat_kv(keys, self.n_rep)
      # (B, Seq_Len_KV, H_KV, Head_Dim) --> (B, Seq_Len_KV, H_Q, Head_Dim)
      values = repeat_kv(values, self.n_rep)
  • Comprehensive Guide for LLaMA with RLHF: StackLLaMA: A hands-on guide to train LLaMA with RLHF [5 Apr 2023]

  • Official LLama Recipes incl. Finetuning: git

  • Llama 2 ONNX git [Jul 2023]

    • ONNX, or Open Neural Network Exchange, is an open standard for machine learning interoperability. It allows AI developers to use models across various frameworks, tools, runtimes, and compilers.

RLHF (Reinforcement Learning from Human Feedback) & SFT (Supervised Fine-Tuning)

  • Machine learning technique that trains a "reward model" directly from human feedback and uses the model as a reward function to optimize an agent's policy using reinforcement learning.

  • InstructGPT: Training language models to follow instructions with human feedback: [cnt] is a model trained by OpenAI to follow instructions using human feedback. [4 Mar 2022]

    cite

  • Libraries: TRL, trlX, Argilla

    TRL: from the Supervised Fine-tuning step (SFT), Reward Modeling step (RM) to the Proximal Policy Optimization (PPO) step

    The three steps in the process: 1. pre-training on large web-scale data, 2. supervised fine-tuning on instruction data (instruction tuning), and 3. RLHF. ref [ⓒ 2023]

  • Supervised Fine-Tuning (SFT) fine-tuning a pre-trained model on a specific task or domain using labeled data. This can cause more significant shifts in the model’s behavior compared to RLHF.

  • Reinforcement Learning from Human Feedback (RLHF)) is a process of pretraining and retraining a language model using human feedback to develop a scoring algorithm that can be reapplied at scale for future training and refinement. As the algorithm is refined to match the human-provided grading, direct human feedback is no longer needed, and the language model continues learning and improving using algorithmic grading alone. [18 Sep 2019] ref [9 Dec 2022]

    • Proximal Policy Optimization (PPO) is a reinforcement learning method using first-order optimization. It modifies the objective function to penalize large policy changes, specifically those that move the probability ratio away from 1. Aiming for TRPO (Trust Region Policy Optimization)-level performance without its complexity which requires second-order optimization.
  • Direct Preference Optimization (DPO): [cnt]: 1. RLHF can be complex because it requires fitting a reward model and performing significant hyperparameter tuning. On the other hand, DPO directly solves a classification problem on human preference data in just one stage of policy training. DPO more stable, efficient, and computationally lighter than RLHF. 2. Your Language Model Is Secretly a Reward Model [29 May 2023]

    • Direct Preference Optimization (DPO) uses two models: a trained model (or policy model) and a reference model (copy of trained model). The goal is to have the trained model output higher probabilities for preferred answers and lower probabilities for rejected answers compared to the reference model. ref: RHLF vs DPO [Jan 2, 2024] / ref [1 Jul 2023]
  • ORPO (odds ratio preference optimization): Monolithic Preference Optimization without Reference Model. New method that combines supervised fine-tuning and preference alignment into one process git [12 Mar 2024] Fine-tune Llama 3 with ORPO [Apr 2024]

  • Reinforcement Learning from AI Feedback (RLAF): [cnt]: Uses AI feedback to generate instructions for the model. TLDR: CoT (Chain-of-Thought, Improved), Few-shot (Not improved). Only explores the task of summarization. After training on a few thousand examples, performance is close to training on the full dataset. RLAIF vs RLHF: In many cases, the two policies produced similar summaries. [1 Sep 2023]

  • OpenAI Spinning Up in Deep RL!: An educational resource to help anyone learn deep reinforcement learning. git [Nov 2018]

Model Compression for Large Language Models

  • A Survey on Model Compression for Large Language Models ref [15 Aug 2023]

Quantization Techniques

  • Quantization-aware training (QAT): The model is further trained with quantization in mind after being initially trained in floating-point precision.

  • Post-training quantization (PTQ): The model is quantized after it has been trained without further optimization during the quantization process.

    Method Pros Cons
    Post-training quantization Easy to use, no need to retrain the model May result in accuracy loss
    Quantization-aware training Can achieve higher accuracy than post-training quantization Requires retraining the model, can be more complex to implement
  • bitsandbytes: 8-bit optimizers git [Oct 2021]

  • The Era of 1-bit LLMs: All Large Language Models are in 1.58 Bits. BitNet b1.58, in which every single parameter (or weight) of the LLM is ternary {-1, 0, 1}. [27 Feb 2024]

Pruning and Sparsification

  • Pruning: The process of removing some of the neurons or layers from a neural network. This can be done by identifying and removing neurons or layers that have little or no impact on the output of the network.

  • Sparsification is indeed a technique used to reduce the size of large language models by removing redundant parameters.

  • Both sparsification and pruning involve removing neurons or connections from the network. The main difference between network sparsification and model pruning is that there is no operational difference between them, and a pruned network usually leads to a sparser network.

  • Wanda Pruning: [cnt]: A Simple and Effective Pruning Approach for Large Language Models [20 Jun 2023] ref

Knowledge Distillation: Reducing Model Size with Textbooks

  • phi-series: cost-effective small language models (SLMs)

    Expand
    • phi-3: Phi-3-mini, with 3.8 billion parameters, supports 4K and 128K context, instruction tuning, and hardware optimization. [Apr 2024] ref

    • phi-2: open source, and 50% better at mathematical reasoning. git [Dec 2023]

    • phi-1.5: [cnt]: Textbooks Are All You Need II. Phi 1.5 is trained solely on synthetic data. Despite having a mere 1 billion parameters compared to Llama 7B's much larger model size, Phi 1.5 often performs better in benchmark tests. [11 Sep 2023]

    • phi-1: [cnt]: Despite being small in size, phi-1 attained 50.6% on HumanEval and 55.5% on MBPP. Textbooks Are All You Need. ref [20 Jun 2023]

  • Orca 2: [cnt]: Orca learns from rich signals from GPT 4 including explanation traces; step-by-step thought processes; and other complex instructions, guided by teacher assistance from ChatGPT. ref [18 Nov 2023]

  • Distilled Supervised Fine-Tuning (dSFT)

    1. Zephyr 7B: [cnt] Zephyr-7B-β is the second model in the series, and is a fine-tuned version of mistralai/Mistral-7B-v0.1 that was trained on on a mix of publicly available, synthetic datasets using Direct Preference Optimization (DPO). ref [25 Oct 2023]
    2. Mistral 7B: [cnt]: Outperforms Llama 2 13B on all benchmarks. Uses Grouped-query attention (GQA) for faster inference. Uses Sliding Window Attention (SWA) to handle longer sequences at smaller cost. ref [10 Oct 2023]

Other optimization techniques

  • LLM patterns: 🏆From data to user, from defensive to offensive doc
  • Large Transformer Model Inference Optimization: Besides the increasing size of SoTA models, there are two main factors contributing to the inference challenge ... [10 Jan 2023]
  • Mixture of experts models: Mixtral 8x7B: Sparse mixture of experts models (SMoE) magnet [Dec 2023]
  • Huggingface Mixture of Experts Explained: Mixture of Experts, or MoEs for short [Dec 2023]
  • Simplifying Transformer Blocks: Simplifie Transformer. Removed several block components, including skip connections, projection/value matrices, sequential sub-blocks and normalisation layers without loss of training speed. [3 Nov 2023]
  • Model merging: : A technique that combines two or more large language models (LLMs) into a single model, using methods such as SLERP, TIES, DARE, and passthrough. [Jan 2024] git: mergekit
    Method Pros Cons
    SLERP Preserves geometric properties, popular method Can only merge two models, may decrease magnitude
    TIES Can merge multiple models, eliminates redundant parameters Requires a base model, may discard useful parameters
    DARE Reduces overfitting, keeps expectations unchanged May introduce noise, may not work well with large differences
  • Mamba: Linear-Time Sequence Modeling with Selective State Spaces [1 Dec 2023] git: 1. Structured State Space (S4) - Class of sequence models, encompassing traits from RNNs, CNNs, and classical state space models. 2. Hardware-aware (Optimized for GPU) 3. Integrating selective SSMs and eliminating attention and MLP blocks ref / A Visual Guide to Mamba and State Space Models ref [19 FEB 2024]
  • Sakana.ai: Evolutionary Optimization of Model Merging Recipes.: A Method to Combine 500,000 OSS Models. git [19 Mar 2024]
  • Mixture-of-Depths: All tokens should not require the same effort to compute. The idea is to make token passage through a block optional. Each block selects the top-k tokens for processing, and the rest skip it. ref [2 Apr 2024]
  • Kolmogorov-Arnold Networks (KANs): KANs use activation functions on connections instead of nodes like Multi-Layer Perceptrons (MLPs) do. Each weight in KANs is replaced by a learnable 1D spline function. KANs’ nodes simply sum incoming signals without applying any non-linearities. git [30 Apr 2024]
  • Better & Faster Large Language Models via Multi-token Prediction: Suggest that training language models to predict multiple future tokens at once [30 Apr 2024]

3. Visual Prompting & Visual Grounding

Section 6 : Large Language Model: Challenges and Solutions

Context constraints

  • Introducing 100K Context Windows: hundreds of pages, Around 75,000 words; [11 May 2023] demo Anthropic Claude
  • “Needle in a Haystack” Analysis [21 Nov 2023]: Context Window Benchmarks; Claude 2.1 (200K Context Window) vs GPT-4; Long context prompting for Claude 2.1 adding just one sentence, “Here is the most relevant sentence in the context:”, to the prompt resulted in near complete fidelity throughout Claude 2.1’s 200K context window. [6 Dec 2023]
  • Rotary Positional Embedding (RoPE): [cnt] / ref / doc [20 Apr 2021]
    • How is this different from the sinusoidal embeddings used in "Attention is All You Need"?
      1. Sinusoidal embeddings apply to each coordinate individually, while rotary embeddings mix pairs of coordinates
      2. Sinusoidal embeddings add a cos or sin term, while rotary embeddings use a multiplicative factor.
  • Lost in the Middle: How Language Models Use Long Contexts: [cnt] [6 Jul 2023]
    1. Best Performace when relevant information is at beginning
    2. Too many retrieved documents will harm performance
    3. Performacnce decreases with an increase in context
  • Structured Prompting: Scaling In-Context Learning to 1,000 Examples: [cnt] [13 Dec 2022]
    1. Microsoft's Structured Prompting allows thousands of examples, by first concatenating examples into groups, then inputting each group into the LM. The hidden key and value vectors of the LM's attention modules are cached. Finally, when the user's unaltered input prompt is passed to the LM, the cached attention vectors are injected into the hidden layers of the LM.
    2. This approach wouldn't work with OpenAI's closed models. because this needs to access [keys] and [values] in the transformer internals, which they do not expose. You could implement yourself on OSS ones. cite [07 Feb 2023]
  • Ring Attention: [cnt]: 1. Ring Attention, which leverages blockwise computation of self-attention to distribute long sequences across multiple devices while overlapping the communication of key-value blocks with the computation of blockwise attention. 2. Ring Attention can reduce the memory requirements of Transformers, enabling us to train more than 500 times longer sequence than prior memory efficient state-of-the-arts and enables the training of sequences that exceed 100 million in length without making approximations to attention. 3. we propose an enhancement to the blockwise parallel transformers (BPT) framework. git [3 Oct 2023]
  • LLM Maybe LongLM: Self-Extend LLM Context Window Without Tuning. With only four lines of code modification, the proposed method can effortlessly extend existing LLMs' context window without any fine-tuning. [2 Jan 2024]
  • Giraffe: Adventures in Expanding Context Lengths in LLMs. A new truncation strategy for modifying the basis for the position encoding. ref [2 Jan 2024]
  • Leave No Context Behind: Efficient Infinite Context Transformers with Infini-attention. The Infini-attention incorporates a compressive memory into the vanilla attention mechanism. Integrate attention from both local and global attention. [10 Apr 2024]

OpenAI's Roadmap and Future Plans

OpenAI's plans according to Sam Altman

  • Humanloop Interview 2023 : doc [29 May 2023]
  • OpenAI’s CEO Says the Age of Giant AI Models Is Already Over ref [17 Apr 2023]
  • Q* (pronounced as Q-Star): The model, called Q* was able to solve basic maths problems it had not seen before, according to the tech news site the Information. ref [23 Nov 2023]
  • Sam Altman reveals in an interview with Bill Gates (2 days ago) what's coming up in GPT-4.5 (or GPT-5): Potential integration with other modes of information beyond text, better logic and analysis capabilities, and consistency in performance over the next two years. ref [12 Jan 2024]

GPT-4 details leaked unverified

  • GPT-4V(ision) system card: ref [25 Sep 2023] / ref
  • The Dawn of LMMs: [cnt]: Preliminary Explorations with GPT-4V(ision) [29 Sep 2023]
  • GPT-4 details leaked
    • GPT-4 is a language model with approximately 1.8 trillion parameters across 120 layers, 10x larger than GPT-3. It uses a Mixture of Experts (MoE) model with 16 experts, each having about 111 billion parameters. Utilizing MoE allows for more efficient use of resources during inference, needing only about 280 billion parameters and 560 TFLOPs, compared to the 1.8 trillion parameters and 3,700 TFLOPs required for a purely dense model.
    • The model is trained on approximately 13 trillion tokens from various sources, including internet data, books, and research papers. To reduce training costs, OpenAI employs tensor and pipeline parallelism, and a large batch size of 60 million. The estimated training cost for GPT-4 is around $63 million. ref [Jul 2023]

OpenAI Products

  • OpenAI DevDay 2023: GPT-4 Turbo with 128K context, Assistants API (Code interpreter, Retrieval, and function calling), GPTs (Custom versions of ChatGPT: ref), Copyright Shield, Parallel Function Calling, JSON Mode, Reproducible outputs [6 Nov 2023]
  • ChatGPT can now see, hear, and speak: It has recently been updated to support multimodal capabilities, including voice and image. [25 Sep 2023] Whisper / CLIP
  • GPT-3.5 Turbo Fine-tuning Fine-tuning for GPT-3.5 Turbo is now available, with fine-tuning for GPT-4 coming this fall. [22 Aug 2023]
  • DALL·E 3 : In September 2023, OpenAI announced their latest image model, DALL-E 3 git [Sep 2023]
  • Open AI Enterprise: Removes GPT-4 usage caps, and performs up to two times faster ref [28 Aug 2023]
  • ChatGPT Plugin [23 Mar 2023]
  • ChatGPT Function calling [Jun 2023]
    • syntax the model has been trained on. This means functions count against the model's context limit and are billed as input tokens. If running into context limits, we suggest limiting the number of functions or the length of documentation you provide for function parameters.
    • Azure OpenAI start to support function calling. ref
  • Custom instructions: In a nutshell, the Custom Instructions feature is a cross-session memory that allows ChatGPT to retain key instructions across chat sessions. [20 Jul 2023]
  • Introducing the GPT Store: Roll out the GPT Store to ChatGPT Plus, Team and Enterprise users GPTs [10 Jan 2024]
  • New embedding models text-embedding-3-small: Embedding size: 512, 1536 text-embedding-3-large: Embedding size: 256,1024,3072 [25 Jan 2024]
  • Sora Text-to-video model. Sora can generate videos up to a minute long while maintaining visual quality and adherence to the user’s prompt. [15 Feb 2024]
  • ChatGPT Memory: Remembering things you discuss across all chats saves you from having to repeat information and makes future conversations more helpful. [Apr 2024]

GPT series release date

  • GPT 1: Decoder-only model. 117 million parameters. [Jun 2018] git
  • GPT 2: Increased model size and parameters. 1.5 billion. [14 Feb 2019] git
  • GPT 3: Introduced few-shot learning. 175B. [11 Jun 2020] git
  • GPT 3.5: 3 variants each with 1.3B, 6B, and 175B parameters. [15 Mar 2022] Estimate the embedding size of OpenAI's gpt-3.5-turbo to be about 4,096
  • ChtGPT: GPT-3 fine-tuned with RLHF. 20B or 175B. unverified ref [30 Nov 2022]
  • GPT 4: Mixture of Experts (MoE). 8 models with 220 billion parameters each, for a total of about 1.76 trillion parameters. unverified ref [14 Mar 2023]

Numbers LLM and LLM Token Limits

Building Trustworthy, Safe and Secure LLM

  • NeMo Guardrails: Building Trustworthy, Safe and Secure LLM Conversational Systems [Apr 2023]

  • Trustworthy LLMs: [cnt]: Comprehensive overview for assessing LLM trustworthiness; Reliability, safety, fairness, resistance to misuse, explainability and reasoning, adherence to social norms, and robustness. [10 Aug 2023]

  • Political biases of LLMs: [cnt]: From Pretraining Data to Language Models to Downstream Tasks: Tracking the Trails of Political Biases Leading to Unfair NLP Models. [15 May 2023]

  • Red Teaming: The term red teaming has historically described systematic adversarial attacks for testing security vulnerabilities. LLM red teamers should be a mix of people with diverse social and professional backgrounds, demographic groups, and interdisciplinary expertise that fits the deployment context of your AI system. ref

  • The Foundation Model Transparency Index: [cnt]: A comprehensive assessment of the transparency of foundation model developers ref [19 Oct 2023]

  • Hallucinations: [cnt]: A Survey on Hallucination in Large Language Models: Principles, Taxonomy, Challenges, and Open Questions [9 Nov 2023]

  • Hallucination Leaderboard: Evaluate how often an LLM introduces hallucinations when summarizing a document. [Nov 2023]

  • OpenAI Weak-to-strong generalization: In the superalignment problem, humans must supervise models that are much smarter than them. The paper discusses supervising a GPT-4 or 3.5-level model using a GPT-2-level model. It finds that while strong models supervised by weak models can outperform the weak models, they still don’t perform as well as when supervised by ground truth. git [14 Dec 2023]

  • A Comprehensive Survey of Hallucination Mitigation Techniques in Large Language Models: A compre hensive survey of over thirty-two techniques developed to mitigate hallucination in LLMs [2 Jan 2024]

  • Anthropic Many-shot jailbreaking: simple long-context attack, Bypassing safety guardrails by bombarding them with unsafe or harmful questions and answers. [3 Apr 2024]

  • FactTune: A procedure that enhances the factuality of LLMs without the need for human feedback. The process involves the fine-tuning of a separated LLM using methods such as DPO and RLAIF, guided by preferences generated by FActScore. [14 Nov 2023] FActScore works by breaking down a generation into a series of atomic facts and then computing the percentage of these atomic facts by a reliable knowledge source.

  • The Instruction Hierarchy: Training LLMs to Prioritize Privileged Instructions. The OpenAI highlights the need for instruction privileges in LLMs to prevent attacks and proposes training models to conditionally follow lower-level instructions based on their alignment with higher-level instructions. [19 Apr 2024]

LLM to Master APIs

  • Gorilla: An API store for LLMs: [cnt]: Gorilla: Large Language Model Connected with Massive APIs git [24 May 2023]

    1. Used GPT-4 to generate a dataset of instruction-api pairs for fine-tuning Gorilla.
    2. Used the abstract syntax tree (AST) of the generated code to match with APIs in the database and test set for evaluation purposes.

    Another user asked how Gorilla compared to LangChain; Patil replied: Langchain is a terrific project that tries to teach agents how to use tools using prompting. Our take on this is that prompting is not scalable if you want to pick between 1000s of APIs. So Gorilla is a LLM that can pick and write the semantically and syntactically correct API for you to call! A drop in replacement into Langchain! cite [04 Jul 2023]

  • Meta: Toolformer: [cnt]: Language Models That Can Use Tools, by MetaAI git [9 Feb 2023]

  • ToolLLM: [cnt]: : Facilitating Large Language Models to Master 16000+ Real-world APIs git [31 Jul 2023]

Memory Optimization

  • Transformer cache key-value tensors of context tokens into GPU memory to facilitate fast generation of the next token. However, these caches occupy significant GPU memory. The unpredictable nature of cache size, due to the variability in the length of each request, exacerbates the issue, resulting in significant memory fragmentation in the absence of a suitable memory management mechanism.

  • To alleviate this issue, PagedAttention was proposed to store the KV cache in non-contiguous memory spaces. It partitions the KV cache of each sequence into multiple blocks, with each block containing the keys and values for a fixed number of tokens.

  • PagedAttention : vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttention, 24x Faster LLM Inference doc. ref [12 Sep 2023]

    • PagedAttention for a prompt “the cat is sleeping in the kitchen and the dog is”. Key-Value pairs of tensors for attention computation are stored in virtual contiguous blocks mapped to non-contiguous blocks in the GPU memory.
  • TokenAttention an attention mechanism that manages key and value caching at the token level. git [Jul 2023]

  • Flash Attention: [cnt] [27 May 2022] & FlashAttention-2: [cnt] [17 Jul 2023]: An method that reorders the attention computation and leverages classical techniques (tiling, recomputation). Instead of storing each intermediate result, use kernel fusion and run every operation in a single kernel in order to avoid memory read/write overhead. git -> Compared to a standard attention implementation in PyTorch, FlashAttention-2 can be up to 9x faster

Large Language Model Is: Abilities

Section 7 : Large Language Model: Landscape

Large Language Models (in 2023)

  1. Change in perspective is necessary because some abilities only emerge at a certain scale. Some conclusions from the past are invalidated and we need to constantly unlearn intuitions built on top of such ideas.
  2. From first-principles, scaling up the Transformer amounts to efficiently doing matrix multiplications with many, many machines.
  3. Further scaling (think 10000x GPT-4 scale). It entails finding the inductive bias that is the bottleneck in further scaling.

Evolutionary Tree of Large Language Models

Navigating the Generative AI Landscape

Model Description Strengths Weaknesses
GANs Two neural networks, a generator and a discriminator, work together. The generator creates synthetic samples, and the discriminator distinguishes between real and generated samples. Can generate new data similar to a training data set. Known for potentially unstable training and less diversity in generation.
VAEs Consists of an encoder and a decoder. The encoder maps input data into a low-dimensional representation, and the decoder reconstructs the original input data from this representation. Can generate new data similar to a training data set. Relies on a surrogate loss.
Diffusion Models Consists of forward and reverse diffusion processes. Forward diffusion adds noise to input data until white noise is obtained. The reverse diffusion process removes the noise to recover the original data. Creates samples step by step. Not a learnable process and typically takes 1000 steps.

A Taxonomy of Natural Language Processing

  • An overview of different fields of study and recent developments in NLP. doc ref [24 Sep 2023]

    “Exploring the Landscape of Natural Language Processing Research” ref [20 Jul 2023]

    NLP taxonomy

    Distribution of the number of papers by most popular fields of study from 2002 to 2022

Open-Source Large Language Models

  • KoAlpaca: Alpaca for korean [Mar 2023]
  • Pythia: How do large language models (LLMs) develop and evolve over the course of training and change as models scale? A suite of decoder-only autoregressive language models ranging from 70M to 12B parameters git [Apr 2023]
  • OLMo: Truly open language model and framework to build, study, and advance LMs, along with the training data, training and evaluation code, intermediate model checkpoints, and training logs. git [Feb 2024]
  • Gemma: Open weights LLM from Google DeepMind. git / Pytorch git [Feb 2024]
  • Qualcomm’s on-device AI models: Bring generative AI to mobile devices [Feb 2024]
  • Grok xAI. 314B parameter Mixture-of-Experts (MoE) model. Released under the Apache 2.0 license. Not includeded training code. Developed by JAX git [March 17, 2024]
  • Open-Sora: Democratizing Efficient Video Production for All [Mar 2024]
  • DBRX: MoE, open, general-purpose LLM created by Databricks. git [27 Mar 2024]
  • Jamba: AI21's SSM-Transformer Model. Mamba + Transformer + MoE [28 Mar 2024]

MLLM (multimodal large language model)

  • Multimodal Foundation Models: From Specialists to General-Purpose Assistants: [cnt]: A comprehensive survey of the taxonomy and evolution of multimodal foundation models that demonstrate vision and vision-language capabilities. Specific-Purpose 1. Visual understanding tasks 2. Visual generation tasks General-Purpose 3. General-purpose interface. [18 Sep 2023]

  • Awesome Multimodal Large Language Models: Latest Papers and Datasets on Multimodal Large Language Models, and Their Evaluation. [Jun 2023]

  • CLIP: [cnt]: CLIP (Contrastive Language-Image Pretraining), Trained on a large number of internet text-image pairs and can be applied to a wide range of tasks with zero-shot learning. git [26 Feb 2021]

  • LLaVa: [cnt]: Large Language-and-Vision Assistant git [17 Apr 2023]

    • Simple linear layer to connect image features into the word embedding space. A trainable projection matrix W is applied to the visual features Zv, transforming them into visual embedding tokens Hv. These tokens are then concatenated with the language embedding sequence Hq to form a single sequence. Note that Hv and Hq are not multiplied or added, but concatenated, both are same dimensionality.
    • LLaVA-1.5: [cnt]: is out! git: Changing from a linear projection to an MLP cross-modal. [5 Oct 2023]
  • Video-ChatGPT: [cnt]: a video conversation model capable of generating meaningful conversation about videos. / git [8 Jun 2023]

  • MiniGPT-4 & MiniGPT-v2: [cnt]: Enhancing Vision-language Understanding with Advanced Large Language Models git [20 Apr 2023]

  • TaskMatrix, aka VisualChatGPT: [cnt]: Microsoft TaskMatrix git; GroundingDINO + SAM git [8 Mar 2023]

  • GroundingDINO: [cnt]: DINO with Grounded Pre-Training for Open-Set Object Detection git [9 Mar 2023]

  • BLIP-2 [30 Jan 2023]: [cnt]: Salesforce Research, Querying Transformer (Q-Former) / git / ref / Youtube / BLIP: [cnt]: git [28 Jan 2022]

    • Q-Former (Querying Transformer): A transformer model that consists of two submodules that share the same self-attention layers: an image transformer that interacts with a frozen image encoder for visual feature extraction, and a text transformer that can function as both a text encoder and a text decoder.
    • Q-Former is a lightweight transformer which employs a set of learnable query vectors to extract visual features from the frozen image encoder. It acts as an information bottleneck between the frozen image encoder and the frozen LLM.
  • Vision capability to a LLM ref [22 Aug 2023]

    • The model has three sub-models:

      1. A model to obtain image embeddings
      2. A text model to obtain text embeddings
      3. A model to learn the relationships between them
    • This is analogous to adding vision capability to a LLM.

  • Facebook

    1. facebookresearch/ImageBind: [cnt]: ImageBind One Embedding Space to Bind Them All git [9 May 2023]
    2. facebookresearch/segment-anything(SAM): [cnt]: The repository provides code for running inference with the SegmentAnything Model (SAM), links for downloading the trained model checkpoints, and example notebooks that show how to use the model. git [5 Apr 2023]
    3. facebookresearch/SeamlessM4T: [cnt]: SeamlessM4T is the first all-in-one multilingual multimodal AI translation and transcription model. This single model can perform speech-to-text, speech-to-speech, text-to-speech, and text-to-text translations for up to 100 languages depending on the task. ref [22 Aug 2023]
    4. Models and libraries
  • Microsoft

    1. Language Is Not All You Need: Aligning Perception with Language Models Kosmos-1: [cnt] [27 Feb 2023]
    2. Kosmos-2: [cnt]: Grounding Multimodal Large Language Models to the World [26 Jun 2023]
    3. Kosmos-2.5: [cnt]: A Multimodal Literate Model [20 Sep 2023]
    4. BEiT-3: [cnt]: Image as a Foreign Language: BEiT Pretraining for Vision and Vision-Language Tasks [22 Aug 2022]
    5. TaskMatrix.AI: [cnt]: TaskMatrix connects ChatGPT and a series of Visual Foundation Models to enable sending and receiving images during chatting. [29 Mar 2023]
  • Google

    1. Gemini 1.5: 1 million token context window, 1 hour of video, 11 hours of audio, codebases with over 30,000 lines of code or over 700,000 words. [Feb 2024]
  • Anthrophic

    1. Claude 3 Opus, the largest version of the new LLM, outperforms rivals GPT-4 and Google’s Gemini 1.0 Ultra. Three variants: Opus, Sonnet, and Haiku. [Mar 2024]
  • Benchmarking Multimodal LLMs.

    • LLaVA-1.5 achieves SoTA on a broad range of 11 tasks incl. SEED-Bench.

    • SEED-Bench: [cnt]: Benchmarking Multimodal LLMs git [30 Jul 2023]

  • Optimizing Memory Usage for Training LLMs and Vision Transformers: When applying 10 techniques to a vision transformer, we reduced the memory consumption 20x on a single GPU. ref / git [2 Jul 2023]

Section 8: Survey and Reference

Survey on Large Language Models

Build an LLMs from scratch: picoGPT and lit-gpt

  • An unnecessarily tiny implementation of GPT-2 in NumPy. picoGPT: Transformer Decoder [Jan 2023]

    q = x @ w_k # [n_seq, n_embd] @ [n_embd, n_embd] -> [n_seq, n_embd]
    k = x @ w_q # [n_seq, n_embd] @ [n_embd, n_embd] -> [n_seq, n_embd]
    v = x @ w_v # [n_seq, n_embd] @ [n_embd, n_embd] -> [n_seq, n_embd]
    
    # In picoGPT, combine w_q, w_k and w_v into a single matrix w_fc
    x = x @ w_fc # [n_seq, n_embd] @ [n_embd, 3*n_embd] -> [n_seq, 3*n_embd]
  • lit-gpt: Hackable implementation of state-of-the-art open-source LLMs based on nanoGPT. Supports flash attention, 4-bit and 8-bit quantization, LoRA and LLaMA-Adapter fine-tuning, pre-training. Apache 2.0-licensed. git [Mar 2023]

  • pix2code: Generating Code from a Graphical User Interface Screenshot. Trained dataset as a pair of screenshots and simplified intermediate script for HTML, utilizing image embedding for CNN and text embedding for LSTM, encoder and decoder model. Early adoption of image-to-code. [May 2017] -> Screenshot to code: Turning Design Mockups Into Code With Deep Learning [Oct 2017] ref

  • Build a Large Language Model (From Scratch): Implementing a ChatGPT-like LLM from scratch, step by step

  • Spreadsheets-are-all-you-need: Spreadsheets-are-all-you-need implements the forward pass of GPT2 entirely in Excel using standard spreadsheet functions. [Sep 2023]

  • llm.c: LLM training in simple, raw C/CUDA [Apr 2024]

    Expand
    • Beam Search [1977] in Transformers is an inference algorithm that maintains the beam_size most probable sequences until the end token appears or maximum sequence length is reached. If beam_size (k) is 1, it's a Greedy Search. If k equals the total vocabularies, it's an Exhaustive Search. ref [Mar 2022]

    Classification of Attention

    • ref: Must-Read Starter Guide to Mastering Attention Mechanisms in Machine Learning [12 Jun 2023]
    1. Encoder-Decoder Attention:

      1. Soft Attention: assigns continuous weights to input elements, allowing the model to attend to multiple elements simultaneously. Used in neural machine translation.
      2. Hard Attention: selects a subset of input elements to focus on while ignoring the rest. Used in image captioning.
      3. Global Attention: focuses on all elements of the input sequence when computing attention weights. Captures long-range dependencies and global context.
      4. Local Attention: focuses on a smaller, localized region of the input sequence when computing attention weights. Reduces computational complexity. Used in time series analysis.
    2. Extended Forms of Attention: Only one Decoder component (only Input Sequence, no Target Sequence)

      1. Self Attention: attends to different parts of the input sequence itself, rather than another sequence or modality. Captures long-range dependencies and contextual information. Used in transformer models.
      2. Multi-head Self-Attention: performs self-attention multiple times in parallel, allowing the model to jointly attend to information from different representation subspaces.
    3. Other Types of Attention:

      1. Sparse Attention: reduces computation by focusing on a limited selection of similarity scores in a sequence, resulting in a sparse matrix. It includes implementations of “strided” and “fixed” attention. ref [23 Oct 2020]
      1. Cross-Attention: mixes two different embedding sequences, allowing the model to attend to information from both sequences. In a Transformer, when the information is passed from encoder to decoder that part is known as Cross Attention. ref / ref [9 Feb 2023]

      2. Sliding Window Attention (SWA): A technique used Longformer. It uses a fixed-size window of attention around each token, which allows the model to scale efficiently to long inputs. Each token attends to half the window size tokens on each side. ref

Japanese Language Materials for LLMs

Learning and Supplementary Materials

Section 9: Relevant Solutions and Frameworks

Solutions and Frameworks

  • Pytorch: PyTorch is the most favorite library among researchers. Papers with code Trends [Sep 2016]
  • jax: JAX is Autograd (automatically differentiate native Python & Numpy) and XLA (compile and run NumPy)
  • fairseq: a sequence modeling toolkit that allows researchers and developers to train custom models for translation, summarization, language modeling [Sep 2017]
  • Weights & Biases: Visualizing and tracking your machine learning experiments wandb.ai doc: deeplearning.ai/wandb [Jan 2020]
  • activeloopai/deeplake: AI Vector Database for LLMs/LangChain. Doubles as a Data Lake for Deep Learning. Store, query, version, & visualize any data. Stream data in real-time to PyTorch/TensorFlow. ref [Jun 2021]
  • mosaicml/llm-foundry: LLM training code for MosaicML foundation models [Jun 2022]
  • openai/shap-e Generate 3D objects conditioned on text or images [3 May 2023] git
  • Drag Your GAN: [cnt]: Interactive Point-based Manipulation on the Generative Image Manifold git [18 May 2023]
  • string2string: The library is an open-source tool that offers a comprehensive suite of efficient algorithms for a broad range of string-to-string problems. string2string [Mar 2023]
  • Sentence Transformers: Python framework for state-of-the-art sentence, text and image embeddings. Useful for semantic textual similar, semantic search, or paraphrase mining. git [27 Aug 2019]
  • fastText: A library for efficient learning of word representations and sentence classification [Aug 2016 ]
  • Math formula OCR: MathPix, OSS LaTeX-OCR [Jan 2021]
  • Nougat: Neural Optical Understanding for Academic Documents: The academic document PDF parser that understands LaTeX math and tables. git [25 Aug 2023]
  • Camelot is a Python library that can help you extract tables from PDFs! git / ref: Comparison with other PDF Table Extraction libraries [Jul 2016]
  • PostgresML: The GPU-powered AI application database. [Apr 2022]
  • Azure AI Document Intelligence (FKA. Azure Form Recognizer): ref: Table and Meta data Extraction in the Document
  • Table to Markdown: LLM can recognize Markdown-formatted tables more effectively than raw table formats.
  • LM Studio: UI for Discover, download, and run local LLMs [2023]
  • GPT4All: Open-source large language models that run locally on your CPU [Mar 2023]
  • MemGPT: Virtual context management to extend the limited context window of LLM. A tiered memory system and a set of functions that allow it to manage its own memory. ref [12 Oct 2023]
  • ollama: Running with Large language models locally [Jun 2023]
  • unsloth: Finetune Mistral, Gemma, Llama 2-5x faster with 70% less memory! QLoRA & LoRA finetuning [Nov 2023]
  • unstructured: Open-Source Pre-Processing Tools for Unstructured Data [Sep 2022]
  • LLaMA-Factory: Unify Efficient Fine-Tuning of 100+ LLMs [May 2023]

Agents: AutoGPT and Communicative Agents

Agent Design Patterns

Agent Applications and Libraries

  • Auto-GPT: Most popular [Mar 2023]
  • babyagi: Most simplest implementation - Coworking of 4 agents [Apr 2023]
  • SuperAGI: GUI for agent settings [May 2023]
  • lightaime/camel: 🐫 CAMEL: Communicative Agents for “Mind” Exploration of Large Scale Language Model Society [Mar 2023]
  • 1:1 Conversation between two ai agents Camel Agents - a Hugging Face Space by camel-ai Hugging Face (camel-agents)
  • ChatDev: Create Customized Software using Natural Language Idea (through LLM-powered Multi-Agent Collaboration) [Sep 2023]
  • GPT Pilot: Dev tool that writes scalable apps from scratch while the developer oversees the implementation [Jul 2023]
  • OpenAgents: three distinct agents: Data Agent for data analysis, Plugins Agent for plugin integration, and Web Agent for autonomous web browsing. [Aug 2023]
  • SeeAct: GPT-4V(ision) is a Generalist Web Agent, if Grounded [Jan 2024]
  • Qwen-Agent: Agent framework built upon Qwen1.5, featuring Function Calling, Code Interpreter, RAG, and Chrome extension. Qwen series released by Alibaba Group [Sep 2023]
  • skyvern: Automate browser-based workflows with LLMs and Computer Vision [Feb 2024]
  • LaVague: Automate automation with Large Action Model framework. Generate Selenium code. [Feb 2024]
  • MetaGPT: Multi-Agent Framework. Assign different roles to GPTs to form a collaborative entity for complex tasks. e.g., Data Interpreter [Jun 2023]
  • llm-answer-engine: Build a Perplexity-Inspired Answer Engine Using Next.js, Groq, Mixtral, Langchain, OpenAI, Brave & Serper [Mar 2024]

Application Development and User Interface (UI/UX)

  • Gradio: Build Machine Learning Web Apps - in Python [Mar 2023]
  • Text generation web UI: Text generation web UI [Mar 2023]
  • Very Simple Langchain example using Open AI: langchain-ask-pdf [Apr 2023]
  • An open source implementation of OpenAI's ChatGPT Code interpreter: gpt-code-ui [May 2023]
  • Open AI Chat Mockup: An open source ChatGPT UI. mckaywrigley/chatbot-ui [Mar 2023]
  • Streaming with Azure OpenAI SSE [May 2023]
  • BIG-AGI FKA nextjs-chatgpt-app [Mar 2023]
  • Embedding does not use Open AI. Can be executed locally: pdfGPT [Mar 2023]
  • Tiktoken Alternative in C#: microsoft/Tokenizer: .NET and Typescript implementation of BPE tokenizer for OpenAI LLMs. [Mar 2023]
  • Azure OpenAI Proxy: OpenAI API requests converting into Azure OpenAI API requests [Mar 2023]
  • Opencopilot: Build and embed open-source AI Copilots into your product with ease. [Aug 2023]
  • TaxyAI/browser-extension: Browser Automation by Chrome debugger API and Prompt > src/helpers/determineNextAction.ts [Mar 2023]
  • Spring AI: Developing AI applications for Java. [Jul 2023]
  • RAG capabilities of LlamaIndex to QA about SEC 10-K & 10-Q documents: A real world full-stack application using LlamaIndex [Sep 2023]
  • Open-source GPT Wrappers 1. ChatGPT-Next-Web 2. FastGPT 3. Lobe Chat [Jan 2024]
  • GPT Researcher: Autonomous agent designed for comprehensive online research [Jul 2023] / GPT Newspaper: Autonomous agent designed to create personalized newspapers [Jan 2024]
  • RAGxplorer: Visualizing document chunks and the queries in the embedding space. [Jan 2024]
  • notesGPT: Record voice notes & transcribe, summarize, and get tasks [Nov 2023]
  • Danswer: Ask Questions in natural language and get Answers backed by private sources: Slack, GitHub, Confluence, etc. [Apr 2023]
  • screenshot-to-code: Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue) [Nov 2023]
  • pyspark-ai: English instructions and compile them into PySpark objects like DataFrames. [Apr 2023]
  • Instructor: Structured outputs for LLMs, easily map LLM outputs to structured data. [Jun 2023]
  • chainlit: Build production-ready Conversational AI applications in minutes. [Mar 2023]
  • Generative AI Design Patterns: A Comprehensive Guide: 9 architecture patterns for working with LLMs. [Feb 2024]
  • CopilotKit: Built-in React UI components [Jun 2023]
  • PrivateGPT: 100% privately, no data leaks 1. The API is built using FastAPI and follows OpenAI's API scheme. 2. The RAG pipeline is based on LlamaIndex. [May 2023]
  • Verba Retrieval Augmented Generation (RAG) chatbot powered by Weaviate git [Jul 2023]

OSS Alternatives for OpenAI Code Interpreter (aka. Advanced Data Analytics)

  • OpenAI Code Interpreter Integration with Sandboxed python execution environment [23 Mar 2023]
    • We provide our models with a working Python interpreter in a sandboxed, firewalled execution environment, along with some ephemeral disk space.
  • OSS Code Interpreter A LangChain implementation of the ChatGPT Code Interpreter. [Jul 2023]
  • gpt-code-ui An open source implementation of OpenAI's ChatGPT Code interpreter. [May 2023]
  • Open Interpreter: Let language models run code on your computer. [Jul 2023]
  • SlashGPT The tool integrated with "jupyter" agent [Apr 2023]

Caching

  • Caching: A technique to store data that has been previously retrieved or computed, so that future requests for the same data can be served faster.
  • To reduce latency, cost, and LLM requests by serving pre-computed or previously served responses.
  • Strategies for caching: Caching can be based on item IDs, pairs of item IDs, constrained input, or pre-computation. Caching can also leverage embedding-based retrieval, approximate nearest neighbor search, and LLM-based evaluation. ref
  • GPTCache: Semantic cache for LLMs. Fully integrated with LangChain and llama_index. git [Mar 2023]

Defensive UX

  • Defensive UX: A design strategy that aims to prevent and handle errors in user interactions with machine learning or LLM-based products.
  • Why defensive UX?: Machine learning and LLMs can produce inaccurate or inconsistent output, which can affect user trust and satisfaction. Defensive UX can help by increasing accessibility, trust, and UX quality.
  • Guidelines for Human-AI Interaction: Microsoft: Based on a survey of 168 potential guidelines from various sources, they narrowed it down to 18 action rules organized by user interaction stages.
  • People + AI Guidebook: Google: Google’s product teams and academic research, they provide 23 patterns grouped by common questions during the product development process3.
  • Human Interface Guidelines for Machine Learning: Apple: Based on practitioner knowledge and experience, emphasizing aspects of UI rather than model functionality4.

LLM for Robotics: Bridging AI and Robotics

  • PromptCraft-Robotics: Robotics and a robot simulator with ChatGPT integration git [Feb 2023]
  • ChatGPT-Robot-Manipulation-Prompts: A set of prompts for Communication between humans and robots for executing tasks. git [Apr 2023]
  • Siemens Industrial Copilot ref [31 Oct 2023]
  • Mobile ALOHA: Stanford’s mobile ALOHA robot learns from humans to cook, clean, do laundry. Mobile ALOHA extends the original ALOHA system by mounting it on a wheeled base ref [4 Jan 2024] / ALOHA: A Low-cost Open-source Hardware System for Bimanual Teleoperation.
  • Figure 01 + OpenAI: Humanoid Robots Powered by OpenAI ChatGPT youtube [Mar 2024]

Awesome demo

  • FRVR Official Teaser: Prompt to Game: AI-powered end-to-end game creation [16 Jun 2023]
  • rewind.ai: Rewind captures everything you’ve seen on your Mac and iPhone [Nov 2023]
  • Mobile ALOHA: A day of Mobile ALOHA [4 Jan 2024]
  • groq: An LPU Inference Engine, the LPU is reported to be 10 times faster than NVIDIA’s GPU performance ref [Jan 2024]
  • Sora: Introducing Sora — OpenAI’s text-to-video model [Feb 2024]

GPT for Domain Specific

  • TimeGPT: The First Foundation Model for Time Series Forecasting git [Mar 2023]
  • BioGPT: [cnt]: Generative Pre-trained Transformer for Biomedical Text Generation and Mining git [19 Oct 2022]
  • MeshGPT: Generating Triangle Meshes with Decoder-Only Transformers [27 Nov 2023]
  • BloombergGPT: A Large Language Model for Finance [30 Mar 2023]
  • Galactica: A Large Language Model for Science [16 Nov 2022]
  • EarthGPT: A Universal Multi-modal Large Language Model for Multi-sensor Image Comprehension in Remote Sensing Domain [30 Jan 2024]
  • SaulLM-7B: A pioneering Large Language Model for Law [6 Mar 2024]
  • Huggingface StarCoder: A State-of-the-Art LLM for Code: git [May 2023]
  • Code Llama: Built on top of Llama 2, free for research and commercial use. ref / git [24 Aug 2023]
  • Devin AI: Devin is an AI software engineer developed by Cognition AI [12 Mar 2024]
  • OpenDevin: an open-source project aiming to replicate Devin [Mar 2024]
  • FrugalGPT: LLM with budget constraints, requests are cascaded from low-cost to high-cost LLMs. git [9 May 2023]

Section 10: General AI Tools and Extensions

Section 11: Datasets for LLM Training

  • LLM-generated datasets:
    1. Self-Instruct: [cnt]: Seed task pool with a set of human-written instructions. [20 Dec 2022]
    2. Self-Alignment with Instruction Backtranslation: [cnt]: Without human seeding, use LLM to produce instruction-response pairs. The process involves two steps: self-augmentation and self-curation. [11 Aug 2023]
  • LLMDataHub: Awesome Datasets for LLM Training: A quick guide (especially) for trending instruction finetuning datasets
  • Open LLMs and Datasets: A list of open LLMs available for commercial use.
  • SQuAD: The Stanford Question Answering Dataset (SQuAD), a set of Wikipedia articles, 100,000+ question-answer pairs on 500+ articles. [16 Jun 2016]
  • RedPajama: LLaMA training dataset of over 1.2 trillion tokens git [17 Apr 2023]
  • FineWeb: HuggingFace: crawled 15 trillion tokens of high-quality web data from the summer of 2013 to March 2024. [Apr 2024]
  • MS MARCO Web Search: A large-scale information-rich web dataset, featuring millions of real clicked query-document labels [Apr 2024]

Pretrain for a base model

{
    "text": ...,
    "meta": {"url": "...", "timestamp": "...", "source": "...", "language": "...", ...},
    "red_pajama_subset": "common_crawl" | "c4" | "github" | "books" | "arxiv" | "wikipedia" | "stackexchange"
}

databricks-dolly-15k: Instruction-Tuned git: SFT training - QA pairs or Dialog

{
  "prompt": "What is the capital of France?",
  "response": "The capital of France is Paris."
},
{
    "prompt": "Can you give me a recipe for chocolate chip cookies?",
    "response": "Sure! ..."
}

Anthropic human-feedback: RLHF training - Chosen and Rejected pairs

{
  "chosen": "I'm sorry to hear that. Is there anything I can do to help?",
  "rejected": "That's too bad. You should just get over it."
}
  • 大規模言語モデルのデータセットまとめ: 大規模言語モデルのデータセットまとめ [Apr 2023]

  • Dataset example

    Expand

    cite

    SFT Dataset

    Category Instruction Context Response
    0 Open QA How do I get rid of mosquitos in my house? You can get rid of mosquitos in your house by ...
    1 Classification Classify each country as "African" or "European" Nigeria: African
    Rwanda: African
    Portugal: European
    2 Information Extraction Extract the unique names of composers from the text. To some extent, European and the US traditions... Pierre Boulez, Luigi Nono, Karlheinz Stockhausen
    3 General QA Should investors time the market? Timing the market is based on predictions of t...

    RLHF Dataset

    Instruction Chosen Response Rejected Response
    What is Depreciation Depreciation is the drop in value of an asset ... What is Depreciation – 10 Important Facts to K...
    What do you know about the city of Aberdeen in Scotland? Aberdeen is a city located in the North East of Scotland. It is known for its granite architecture and its offshore oil industry. As an AI language model, I don't have personal knowledge or experiences about Aberdeen.
    Describe thunderstorm season in the United States and Canada. Thunderstorm season in the United States and Canada typically occurs during the spring and summer months, when warm, moist air collides with cooler, drier air, creating the conditions for thunderstorms to form. Describe thunderstorm season in the United States and Canada.

Section 12: Evaluating Large Language Models & LLMOps

Evaluation Benchmark

Evaluation metrics

  1. Automated evaluation of LLMs

    • n-gram based metrics: Evaluates the model using n-gram statistics and F1 score. ROUGE and BLEU are used for summarization and translation tasks.
    • Embedding based metrics: Evaluates the model using semantic similarity of embeddings. Ada Similarity and BERTScore are used.
    Expand
    • ROUGE (Recall-Oriented Understudy for Gisting Evaluation): The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation. It includes several measures such as:

      1. ROUGE-N: Overlap of n-grams between the system and reference summaries.
      2. ROUGE-L: Longest Common Subsequence (LCS) based statistics.
      3. ROUGE-W: Weighted LCS-based statistics that favor consecutive LCSes.
      4. ROUGE-S: Skip-bigram based co-occurrence statistics.
      5. ROUGE-SU: Skip-bigram plus unigram-based co-occurrence statistics1.
    • n-gram: An n-gram is a contiguous sequence of n items from a given sample of text or speech. For example, in the sentence “I love AI”, the unigrams (1-gram) are “I”, “love”, “AI”; the bigrams (2-gram) are “I love”, “love AI”; and the trigram (3-gram) is “I love AI”.

    • BLEU: BLEU’s output is always a number between 0 and 1. An algorithm for evaluating the quality of machine-translated text. The closer a machine translation is to a professional human translation, the better it is.

    • BERTScore: A metric that leverages pre-trained contextual embeddings from BERT for text generation tasks. It combines precision and recall values.

  2. Human evaluation of LLMs (possibly Automate by LLM-based metrics): Evaluate the model’s performance on NLU and NLG tasks. It includes evaluations of relevance, fluency, coherence, and groundedness.

  3. Built-in evaluation methods in Prompt flow: ref [Aug 2023] / ref

LLMOps: Large Language Model Operations

  • OpenAI Evals: git [Mar 2023]
  • promptfoo: Test your prompts. Evaluate and compare LLM outputs, catch regressions, and improve prompt quality. [Apr 2023]
  • PromptTools: Open-source tools for prompt testing git [Jun 2023]
  • TruLens-Eval: Instrumentation and evaluation tools for large language model (LLM) based applications. git [Nov 2020]
  • Pezzo: Open-source, developer-first LLMOps platform git [May 2023]
  • Giskard: The testing framework for ML models, from tabular to LLMs git [Mar 2022]
  • Azure Machine Learning studio Model Data Collector: Collect production data, analyze key safety and quality evaluation metrics on a recurring basis, receive timely alerts about critical issues, and visualize the results. ref

Challenges in evaluating AI systems

  1. Pretraining on the Test Set Is All You Need: [cnt]
    • On that note, in the satirical Pretraining on the Test Set Is All You Need paper, the author trains a small 1M parameter LLM that outperforms all other models, including the 1.3B phi-1.5 model. This is achieved by training the model on all downstream academic benchmarks. It appears to be a subtle criticism underlining how easily benchmarks can be "cheated" intentionally or unintentionally (due to data contamination). cite [13 Sep 2023]
  2. Challenges in evaluating AI systems: The challenges and limitations of various methods for evaluating AI systems, such as multiple-choice tests, human evaluations, red teaming, model-generated evaluations, and third-party audits. doc [4 Oct 2023]

Contributors

https://github.com/kimtth all rights reserved.