{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RJSnI0Xy-kCm"
   },
   "source": [
    "![Meta---Logo@1x.jpg](data:image/jpeg;base64,[encoded data, 20312 characters])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LERqQn5v8-ak"
   },
   "source": [
    "# **Getting to know Llama 3.1: Everything you need to start building**\n",
    "Our goal in this session is to provide a guided tour of Llama 3.1 with comparison with Llama 2, including understanding different Llama 3.1 models, how and where to access them, Generative AI and Chatbot architectures, prompt engineering, RAG (Retrieval Augmented Generation), Fine-tuning and more. All this is implemented with a starter code for you to take it and use it in your Llama 3.1 projects."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ioVMNcTesSEk"
   },
   "source": [
    "### **0 - Prerequisites**\n",
    "* Basic understanding of Large Language Models\n",
    "* Basic understanding of Python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install matplotlib ipywidgets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "executionInfo": {
     "elapsed": 248,
     "status": "ok",
     "timestamp": 1695832228254,
     "user": {
      "displayName": "Amit Sangani",
      "userId": "11552178012079240149"
     },
     "user_tz": 420
    },
    "id": "ktEA7qXmwdUM"
   },
   "outputs": [],
   "source": [
    "# presentation layer code\n",
    "\n",
    "import base64\n",
    "from IPython.display import Image, display\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "def mm(graph):\n",
    "  graphbytes = graph.encode(\"ascii\")\n",
    "  base64_bytes = base64.b64encode(graphbytes)\n",
    "  base64_string = base64_bytes.decode(\"ascii\")\n",
    "  display(Image(url=\"https://mermaid.ink/img/\" + base64_string))\n",
    "\n",
    "def genai_app_arch():\n",
    "  mm(\"\"\"\n",
    "  flowchart TD\n",
    "    A[Users] --> B(Applications e.g. mobile, web)\n",
    "    B --> |Hosted API|C(Platforms e.g. Custom, HuggingFace, Replicate)\n",
    "    B -- optional --> E(Frameworks e.g. LangChain)\n",
    "    C-->|User Input|D[Llama 3]\n",
    "    D-->|Model Output|C\n",
    "    E --> C\n",
    "    classDef default fill:#CCE6FF,stroke:#84BCF5,textColor:#1C2B33,fontFamily:trebuchet ms;\n",
    "  \"\"\")\n",
    "\n",
    "def rag_arch():\n",
    "  mm(\"\"\"\n",
    "  flowchart TD\n",
    "    A[User Prompts] --> B(Frameworks e.g. LangChain)\n",
    "    B <--> |Database, Docs, XLS|C[fa:fa-database External Data]\n",
    "    B -->|API|D[Llama 3]\n",
    "    classDef default fill:#CCE6FF,stroke:#84BCF5,textColor:#1C2B33,fontFamily:trebuchet ms;\n",
    "  \"\"\")\n",
    "\n",
    "def llama2_family():\n",
    "  mm(\"\"\"\n",
    "  graph LR;\n",
    "      llama-2 --> llama-2-7b\n",
    "      llama-2 --> llama-2-13b\n",
    "      llama-2 --> llama-2-70b\n",
    "      llama-2-7b --> llama-2-7b-chat\n",
    "      llama-2-13b --> llama-2-13b-chat\n",
    "      llama-2-70b --> llama-2-70b-chat\n",
    "      classDef default fill:#CCE6FF,stroke:#84BCF5,textColor:#1C2B33,fontFamily:trebuchet ms;\n",
    "  \"\"\")\n",
    "\n",
    "def llama3_family():\n",
    "  mm(\"\"\"\n",
    "  graph LR;\n",
    "      llama-3 --> llama-3-8b\n",
    "      llama-3 --> llama-3-70b\n",
    "      llama-3-8b --> llama-3-8b\n",
    "      llama-3-8b --> llama-3-8b-instruct\n",
    "      llama-3-70b --> llama-3-70b\n",
    "      llama-3-70b --> llama-3-70b-instruct\n",
    "      classDef default fill:#CCE6FF,stroke:#84BCF5,textColor:#1C2B33,fontFamily:trebuchet ms;\n",
    "  \"\"\")\n",
    "  \n",
    "def llama3_1_family():\n",
    "  mm(\"\"\"\n",
    "  graph LR;\n",
    "      llama-3-1 --> llama-3-8b\n",
    "      llama-3-1 --> llama-3-70b\n",
    "      llama-3-1 --> llama-3-4050b\n",
    "      llama-3-1-8b --> llama-3-1-8b\n",
    "      llama-3-1-8b --> llama-3-1-8b-instruct\n",
    "      llama-3-1-70b --> llama-3-1-70b\n",
    "      llama-3-1-70b --> llama-3-1-70b-instruct\n",
    "      llama-3-1-405b --> llama-3-1-405b-instruct\n",
    "      classDef default fill:#CCE6FF,stroke:#84BCF5,textColor:#1C2B33,fontFamily:trebuchet ms;\n",
    "  \"\"\")\n",
    "\n",
    "import ipywidgets as widgets\n",
    "from IPython.display import display, Markdown\n",
    "\n",
    "# Create a text widget\n",
    "API_KEY = widgets.Password(\n",
    "    value='',\n",
    "    placeholder='',\n",
    "    description='API_KEY:',\n",
    "    disabled=False\n",
    ")\n",
    "\n",
    "def md(t):\n",
    "  display(Markdown(t))\n",
    "\n",
    "def bot_arch():\n",
    "  mm(\"\"\"\n",
    "  graph LR;\n",
    "  user --> prompt\n",
    "  prompt --> i_safety\n",
    "  i_safety --> context\n",
    "  context --> Llama_3\n",
    "  Llama_3 --> output\n",
    "  output --> o_safety\n",
    "  i_safety --> memory\n",
    "  o_safety --> memory\n",
    "  memory --> context\n",
    "  o_safety --> user\n",
    "  classDef default fill:#CCE6FF,stroke:#84BCF5,textColor:#1C2B33,fontFamily:trebuchet ms;\n",
    "  \"\"\")\n",
    "\n",
    "def fine_tuned_arch():\n",
    "  mm(\"\"\"\n",
    "  graph LR;\n",
    "      Custom_Dataset --> Pre-trained_Llama\n",
    "      Pre-trained_Llama --> Fine-tuned_Llama\n",
    "      Fine-tuned_Llama --> RLHF\n",
    "      RLHF --> |Loss:Cross-Entropy|Fine-tuned_Llama\n",
    "      classDef default fill:#CCE6FF,stroke:#84BCF5,textColor:#1C2B33,fontFamily:trebuchet ms;\n",
    "  \"\"\")\n",
    "\n",
    "def load_data_faiss_arch():\n",
    "  mm(\"\"\"\n",
    "  graph LR;\n",
    "      documents --> textsplitter\n",
    "      textsplitter --> embeddings\n",
    "      embeddings --> vectorstore\n",
    "      classDef default fill:#CCE6FF,stroke:#84BCF5,textColor:#1C2B33,fontFamily:trebuchet ms;\n",
    "  \"\"\")\n",
    "\n",
    "def mem_context():\n",
    "  mm(\"\"\"\n",
    "      graph LR\n",
    "      context(text)\n",
    "      user_prompt --> context\n",
    "      instruction --> context\n",
    "      examples --> context\n",
    "      memory --> context\n",
    "      context --> tokenizer\n",
    "      tokenizer --> embeddings\n",
    "      embeddings --> LLM\n",
    "      classDef default fill:#CCE6FF,stroke:#84BCF5,textColor:#1C2B33,fontFamily:trebuchet ms;\n",
    "  \"\"\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "i4Np_l_KtIno"
   },
   "source": [
    "### **1 - Understanding Llama 3.1**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "PGPSI3M5PGTi"
   },
   "source": [
    "### **1.1 - What is Llama 3.1?**\n",
    "\n",
    "* State of the art (SOTA), Open Source LLM\n",
    "* 8B, 70B, 405B - base and instruct models\n",
    "* Choosing model: Size, Quality, Cost, Speed\n",
    "* Pretrained + Chat\n",
    "* [Meta Llama 3.1 Blog](https://ai.meta.com/blog/meta-llama-3-1/)\n",
    "* [Getting Started with Meta Llama](https://llama.meta.com/docs/get-started)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 240
    },
    "executionInfo": {
     "elapsed": 248,
     "status": "ok",
     "timestamp": 1695832233087,
     "user": {
      "displayName": "Amit Sangani",
      "userId": "11552178012079240149"
     },
     "user_tz": 420
    },
    "id": "OXRCC7wexZXd",
    "outputId": "1feb1918-df4b-4cec-d09e-ffe55c12090b"
   },
   "outputs": [],
   "source": [
    "llama2_family()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "llama3_family()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "llama3_1_family()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "aYeHVVh45bdT"
   },
   "source": [
    "### **1.2 - Accessing Llama 3.1**\n",
    "* Download + Self Host (i.e. [download Llama](https://ai.meta.com/resources/models-and-libraries/llama-downloads))\n",
    "* Hosted API Platform (e.g. [Groq](https://console.groq.com/), [Replicate](https://replicate.com/meta/meta-llama-3-8b-instruct), [Together](https://api.together.xyz/playground/language/meta-llama/Llama-3-8b-hf), [Anyscale](https://app.endpoints.anyscale.com/playground))\n",
    "\n",
    "* Hosted Container Platform (e.g. [Azure](https://techcommunity.microsoft.com/t5/ai-machine-learning-blog/introducing-llama-2-on-azure/ba-p/3881233), [AWS](https://aws.amazon.com/blogs/machine-learning/llama-2-foundation-models-from-meta-are-now-available-in-amazon-sagemaker-jumpstart/), [GCP](https://console.cloud.google.com/vertex-ai/publishers/google/model-garden/139))\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "kBuSay8vtzL4"
   },
   "source": [
    "### **1.3 - Use Cases of Llama 3.1**\n",
    "* Content Generation\n",
    "* Summarization\n",
    "* General Chatbots\n",
    "* RAG (Retrieval Augmented Generation): Chat about Your Own Data\n",
    "* Fine-tuning\n",
    "* Agents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "sd54g0OHuqBY"
   },
   "source": [
    "## **2 - Using and Comparing Llama 3 and Llama 2**\n",
    "\n",
    "We will be using Llama 2 7b & 70b chat and Llama 3 8b & 70b instruct models hosted on [Replicate](https://replicate.com/search?query=llama) to run the examples here. You will need to first sign in with Replicate with your github account, then create a free API token [here](https://replicate.com/account/api-tokens) that you can use for a while. You can also use other Llama 3 cloud providers such as [Groq](https://console.groq.com/), [Together](https://api.together.xyz/playground/language/meta-llama/Llama-3-8b-hf), or [Anyscale](https://app.endpoints.anyscale.com/playground).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "h3YGMDJidHtH"
   },
   "source": [
    "### **2.1 - Install dependencies**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "VhN6hXwx7FCp"
   },
   "outputs": [],
   "source": [
    "!pip install replicate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **2.2 - Create helpers for Llama 2 and Llama 3**\n",
    "First, set your Replicate API token as environment variables.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8hkWpqWD28ho"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from getpass import getpass\n",
    "\n",
    "REPLICATE_API_TOKEN = getpass()\n",
    "\n",
    "os.environ[\"REPLICATE_API_TOKEN\"] = REPLICATE_API_TOKEN"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create Llama 2 and Llama 3 helper functions - for chatbot type of apps, we'll use Llama 3 instruct and Llama 2 chat models, not the base models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "bVCHZmETk36v"
   },
   "outputs": [],
   "source": [
    "import replicate\n",
    "\n",
    "def llama2_7b(prompt):\n",
    "    output = replicate.run(\n",
    "      \"meta/llama-2-7b-chat\",\n",
    "      input={\"prompt\": prompt}\n",
    "    )\n",
    "    return ''.join(output)\n",
    "\n",
    "def llama2_70b(prompt):\n",
    "    output = replicate.run(\n",
    "      \"meta/llama-2-70b-chat\",\n",
    "      input={\"prompt\": prompt}\n",
    "    )\n",
    "    return ''.join(output)\n",
    "\n",
    "def llama3_8b(prompt):\n",
    "    output = replicate.run(\n",
    "      \"meta/meta-llama-3-8b-instruct\",\n",
    "      input={\"prompt\": prompt}\n",
    "    )\n",
    "    return ''.join(output)\n",
    "\n",
    "def llama3_70b(prompt):\n",
    "    output = replicate.run(\n",
    "      \"meta/meta-llama-3-70b-instruct\",\n",
    "      input={\"prompt\": prompt}\n",
    "    )\n",
    "    return ''.join(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5Jxq0pmf6L73"
   },
   "source": [
    "### **2.3 - Basic QA with Llama 2 and 3**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "H93zZBIk6tNU"
   },
   "outputs": [],
   "source": [
    "prompt = \"The typical color of a llama is: \"\n",
    "output = llama2_7b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama3_8b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama2_7b(\"The typical color of a llama is what? Answer in one word.\")\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama3_8b(\"The typical color of a llama is what? Answer in one word.\")\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note: Llama 3 follows instructions better than Llama 2 in single-turn chat.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "cWs_s9y-avIT"
   },
   "source": [
    "## **3 - Chat conversation**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "r4DyTLD5ys6t"
   },
   "source": [
    "### **3.1 - Single-turn chat**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "EMM_egWMys6u"
   },
   "outputs": [],
   "source": [
    "prompt_chat = \"What is the average lifespan of a Llama? Answer the question in few words.\"\n",
    "output = llama2_7b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "sZ7uVKDYucgi"
   },
   "outputs": [],
   "source": [
    "output = llama3_8b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "WQl3wmfbyBQ1"
   },
   "outputs": [],
   "source": [
    "# example without previous context. LLM's are stateless and cannot understand \"they\" without previous context\n",
    "prompt_chat = \"What animal family are they? Answer the question in few words.\"\n",
    "output = llama2_7b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama3_8b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama2_70b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama3_70b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note: Llama 3 70b doesn't hallucinate.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **3.2 - Multi-turn chat**\n",
    "Chat app requires us to send in previous context to LLM to get in valid responses. Below is an example of Multi-turn chat."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "t7SZe5fT3HG3"
   },
   "outputs": [],
   "source": [
    "# example of multi-turn chat, with storing previous context\n",
    "prompt_chat = \"\"\"\n",
    "User: What is the average lifespan of a Llama?\n",
    "Assistant: 15-20 years.\n",
    "User: What animal family are they?\n",
    "\"\"\"\n",
    "output = llama2_7b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama3_8b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note: Llama 2 and 3 both behave well for using the chat history for follow up questions.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **3.3 - Multi-turn chat with more instruction**\n",
    "Adding the instructon \"Answer the question with one word\" to see the difference of Llama 2 and 3."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# example of multi-turn chat, with storing previous context\n",
    "prompt_chat = \"\"\"\n",
    "User: What is the average lifespan of a Llama?\n",
    "Assistant: Sure! The average lifespan of a llama is around 20-30 years.\n",
    "User: What animal family are they?\n",
    "\n",
    "Answer the question with one word.\n",
    "\"\"\"\n",
    "output = llama2_7b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama2_70b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama3_8b(prompt_chat)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Both Llama 3 8b and Llama 2 70b follows instructions (e.g. \"Answer the question with one word\") better than Llama 2 7b in multi-turn chat.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "moXnmJ_xyD10"
   },
   "source": [
    "### **4.2 - Prompt Engineering**\n",
    "* Prompt engineering refers to the science of designing effective prompts to get desired responses\n",
    "\n",
    "* Helps reduce hallucination\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "t-v-FeZ4ztTB"
   },
   "source": [
    "#### **4.2.1 - In-Context Learning (e.g. Zero-shot, Few-shot)**\n",
    " * In-context learning - specific method of prompt engineering where demonstration of task are provided as part of prompt.\n",
    "  1. Zero-shot learning - model is performing tasks without any\n",
    "input examples.\n",
    "  2. Few or “N-Shot” Learning - model is performing and behaving based on input examples in user's prompt."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "6W71MFNZyRkQ"
   },
   "outputs": [],
   "source": [
    "# Zero-shot example. To get positive/negative/neutral sentiment, we need to give examples in the prompt\n",
    "prompt = '''\n",
    "Classify: I saw a Gecko.\n",
    "Sentiment: ?\n",
    "\n",
    "Give one word response.\n",
    "'''\n",
    "output = llama2_7b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "MCQRjf1Y1RYJ"
   },
   "outputs": [],
   "source": [
    "output = llama3_8b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note: Llama 3 has different opinions than Llama 2.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8UmdlTmpDZxA"
   },
   "outputs": [],
   "source": [
    "# By giving examples to Llama, it understands the expected output format.\n",
    "\n",
    "prompt = '''\n",
    "Classify: I love Llamas!\n",
    "Sentiment: Positive\n",
    "Classify: I dont like Snakes.\n",
    "Sentiment: Negative\n",
    "Classify: I saw a Gecko.\n",
    "Sentiment:\n",
    "\n",
    "Give one word response.\n",
    "'''\n",
    "\n",
    "output = llama2_7b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "M_EcsUo1zqFD"
   },
   "outputs": [],
   "source": [
    "output = llama3_8b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note: Llama 2, with few shots, has the same output \"Neutral\" as Llama 3, but Llama 2 doesn't follow instructions (Give one word response) well.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "mbr124Y197xl"
   },
   "source": [
    "#### **4.2.2 - Chain of Thought**\n",
    "\"Chain of thought\" enables complex reasoning through logical step by step thinking and generates meaningful and contextually relevant responses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Xn8zmLBQzpgj"
   },
   "outputs": [],
   "source": [
    "# Standard prompting\n",
    "prompt = '''\n",
    "Llama started with 5 tennis balls. It buys 2 more cans of tennis balls. Each can has 3 tennis balls.\n",
    "How many tennis balls does Llama have?\n",
    "\n",
    "Answer in one word.\n",
    "'''\n",
    "\n",
    "output = llama3_8b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "lKNOj79o1Kwu"
   },
   "outputs": [],
   "source": [
    "output = llama3_70b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note: Llama 3-8b did not get the right answer because it was asked to answer in one word.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# By default, Llama 3 models follow \"Chain-Of-Thought\" prompting\n",
    "prompt = '''\n",
    "Llama started with 5 tennis balls. It buys 2 more cans of tennis balls. Each can has 3 tennis balls.\n",
    "How many tennis balls does Llama have?\n",
    "'''\n",
    "\n",
    "output = llama3_8b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama3_70b(prompt)\n",
    "md(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note: By default, Llama 3 models identify word problems and solves it step by step!**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt = \"\"\"\n",
    "15 of us want to go to a restaurant.\n",
    "Two of them have cars\n",
    "Each car can seat 5 people.\n",
    "Two of us have motorcycles.\n",
    "Each motorcycle can fit 2 people.\n",
    "Can we all get to the restaurant by car or motorcycle?\n",
    "Think step by step.\n",
    "Provide the answer as a single yes/no answer first.\n",
    "Then explain each intermediate step.\n",
    "\"\"\"\n",
    "output = llama3_8b(prompt)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llama3_70b(prompt)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note: Llama 3 70b model works correctly in this example.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Summary: Llama 2 often needs encouragement for step by step thinking to correctly reasoning. Llama 3 understands, reasons and explains better, making chain of thought unnecessary in the cases above.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "C7tDW-AH770Y"
   },
   "source": [
    "### **4.3 - Retrieval Augmented Generation (RAG)**\n",
    "* Prompt Eng Limitations - Knowledge cutoff & lack of specialized data\n",
    "\n",
    "* Retrieval Augmented Generation(RAG) allows us to retrieve snippets of information from external data sources and augment it to the user's prompt to get tailored responses from Llama 2.\n",
    "\n",
    "For our demo, we are going to download an external PDF file from a URL and query against the content in the pdf file to get contextually relevant information back with the help of Llama!\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 259
    },
    "executionInfo": {
     "elapsed": 329,
     "status": "ok",
     "timestamp": 1695832267093,
     "user": {
      "displayName": "Amit Sangani",
      "userId": "11552178012079240149"
     },
     "user_tz": 420
    },
    "id": "Fl1LPltpRQD9",
    "outputId": "4410c9bf-3559-4a05-cebb-a5731bb094c1"
   },
   "outputs": [],
   "source": [
    "rag_arch()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JJaGMLl_4vYm"
   },
   "source": [
    "#### **4.3.1 - LangChain**\n",
    "LangChain is a framework that helps make it easier to implement RAG."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install langchain\n",
    "!pip install langchain-community\n",
    "!pip install sentence-transformers\n",
    "!pip install faiss-cpu\n",
    "!pip install bs4\n",
    "!pip install langchain-groq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### **4.3.2 - LangChain Q&A Retriever**\n",
    "* ConversationalRetrievalChain\n",
    "\n",
    "* Query the Source documents\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "gAV2EkZqcruF"
   },
   "outputs": [],
   "source": [
    "from langchain_community.embeddings import HuggingFaceEmbeddings\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_community.document_loaders import WebBaseLoader\n",
    "import bs4\n",
    "\n",
    "# Step 1: Load the document from a web url\n",
    "loader = WebBaseLoader([\"https://huggingface.co/blog/llama31\"])\n",
    "documents = loader.load()\n",
    "\n",
    "# Step 2: Split the document into chunks with a specified chunk size\n",
    "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)\n",
    "all_splits = text_splitter.split_documents(documents)\n",
    "\n",
    "# Step 3: Store the document into a vector store with a specific embedding model\n",
    "vectorstore = FAISS.from_documents(all_splits, HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You'll need to first sign in at [Groq](https://console.groq.com/login) with your github or gmail account, then get an API token to try Groq out for free."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from getpass import getpass\n",
    "\n",
    "GROQ_API_TOKEN = getpass()\n",
    "\n",
    "os.environ[\"GROQ_API_KEY\"] = GROQ_API_TOKEN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_groq import ChatGroq\n",
    "llm = ChatGroq(temperature=0, model_name=\"llama3-8b-8192\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains import ConversationalRetrievalChain\n",
    "\n",
    "# Query against your own data\n",
    "chain = ConversationalRetrievalChain.from_llm(llm,\n",
    "                                              vectorstore.as_retriever(),\n",
    "                                              return_source_documents=True)\n",
    "\n",
    "# no chat history passed\n",
    "result = chain({\"question\": \"What’s new with Llama 3?\", \"chat_history\": []})\n",
    "md(result['answer'])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "CelLHIvoy2Ke"
   },
   "outputs": [],
   "source": [
    "# This time your previous question and answer will be included as a chat history which will enable the ability\n",
    "# to ask follow up questions.\n",
    "query = \"What two sizes?\"\n",
    "chat_history = [(query, result[\"answer\"])]\n",
    "result = chain({\"question\": query, \"chat_history\": chat_history})\n",
    "md(result['answer'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "TEvefAWIJONx"
   },
   "source": [
    "## **5 - Fine-Tuning Models**\n",
    "\n",
    "* Limitatons of Prompt Eng and RAG\n",
    "* Fine-Tuning Arch\n",
    "* Types (PEFT, LoRA, QLoRA)\n",
    "* Using PyTorch for Pre-Training & Fine-Tuning\n",
    "\n",
    "* Evals + Quality\n",
    "\n",
    "Examples of Fine-Tuning:\n",
    "* [Meta Llama Recipes](https://github.com/meta-llama/llama-recipes/tree/main/recipes/finetuning)\n",
    "* [Hugging Face fine-tuning with Llama 3](https://huggingface.co/blog/llama3#fine-tuning-with-%F0%9F%A4%97-trl)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "_8lcgdZa8onC"
   },
   "source": [
    "## **6 - Responsible AI**\n",
    "\n",
    "* Power + Responsibility\n",
    "* Hallucinations\n",
    "* Input & Output Safety\n",
    "* Red-teaming (simulating real-world cyber attackers)\n",
    "* [Responsible Use Guide](https://ai.meta.com/llama/responsible-use-guide/)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pbqb006R-T_k"
   },
   "source": [
    "## **7 - Conclusion**\n",
    "* Active research on LLMs and Llama\n",
    "* Leverage the power of Llama and its open community\n",
    "* Safety and responsible use is paramount!\n",
    "\n",
    "* Call-To-Action\n",
    "  * [Replicate Free Credits](https://replicate.fyi/connect2023) for Connect attendees!\n",
    "  * This notebook is available through Llama Github recipes\n",
    "  * Use Llama in your projects and give us feedback\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "gSz5dTMxp7xo"
   },
   "source": [
    "#### **Resources**\n",
    "- [Meta Llama 3.1 Blog](https://ai.meta.com/blog/meta-llama-3-1/)\n",
    "- [Getting Started with Meta Llama](https://llama.meta.com/docs/get-started)\n",
    "- [Llama 3 repo](https://github.com/meta-llama/llama3)\n",
    "- [Llama 3 model card](https://github.com/meta-llama/llama3/blob/main/MODEL_CARD.md)\n",
    "- [LLama 3 Recipes repo](https://github.com/meta-llama/llama-recipes)\n",
    "- [Responsible Use Guide](https://ai.meta.com/llama/responsible-use-guide/)\n",
    "- [Acceptable Use Policy](https://ai.meta.com/llama/use-policy/)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [
    "ioVMNcTesSEk"
   ],
   "machine_shape": "hm",
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
