Skip to content
Snippets Groups Projects
Commit b65edaf3 authored by sekyonda's avatar sekyonda
Browse files

Update HelloLlamaLocal.ipynb

parent e13ed634
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:b7cabb96-2715-492e-825a-8f4ff161dc3b tags:
## This demo app shows:
* how to run Llama2 locally on a Mac using llama-cpp-python and the llama-cpp's quantized Llama2 model;
* how to use LangChain to ask Llama general questions;
* how to use LangChain to load a recent PDF doc - the Llama2 paper pdf - and ask questions about it. This is the well known RAG (Retrieval Augmented Generation) method to let LLM such as Llama2 be able to answer questions about the data not publicly available when Llama2 was trained, or about your own data. RAG is one way to prevent LLM's hallucination.
%% Cell type:markdown id:22450267 tags:
We start by installing necessary requirements and import packages we will be using in this example.
- [llama-cpp-python](https://github.com/abetlen/llama-cpp-python) a simple Python bindings for [llama.cpp](https://github.com/ggerganov/llama.cpp) library
- pypdf gives us the ability to work with pdfs
- sentence-transformers for text embeddings
- chromadb gives us database capabilities
- langchain provides necessary RAG tools for this demo
%% Cell type:code id:2922732e-29e8-4ea7-8828-53364f5bf6fd tags:
``` python
# install all the required packages for the demo
!CMAKE_ARGS="-DLLAMA_METAL=on" FORCE_CMAKE=1 pip install llama-cpp-python
!pip install pypdf sentence-transformers chromadb langchain
```
%% Output
Requirement already satisfied: llama-cpp-python in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (0.2.11)
Requirement already satisfied: typing-extensions>=4.5.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from llama-cpp-python) (4.8.0)
Requirement already satisfied: numpy>=1.20.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from llama-cpp-python) (1.24.4)
Requirement already satisfied: diskcache>=5.6.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from llama-cpp-python) (5.6.3)
Requirement already satisfied: pypdf in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (3.16.2)
Requirement already satisfied: sentence-transformers in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (2.2.2)
Requirement already satisfied: chromadb in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (0.4.13)
Requirement already satisfied: langchain in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (0.0.308)
Requirement already satisfied: typing_extensions>=3.7.4.3 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from pypdf) (4.8.0)
Requirement already satisfied: transformers<5.0.0,>=4.6.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (4.34.0)
Requirement already satisfied: tqdm in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (4.66.1)
Requirement already satisfied: torch>=1.6.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (2.1.0)
Requirement already satisfied: torchvision in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (0.16.0)
Requirement already satisfied: numpy in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (1.24.4)
Requirement already satisfied: scikit-learn in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (1.3.1)
Requirement already satisfied: scipy in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (1.10.1)
Requirement already satisfied: nltk in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (3.8.1)
Requirement already satisfied: sentencepiece in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (0.1.99)
Requirement already satisfied: huggingface-hub>=0.4.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sentence-transformers) (0.16.4)
Requirement already satisfied: requests>=2.28 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (2.31.0)
Requirement already satisfied: pydantic>=1.9 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (2.4.2)
Requirement already satisfied: chroma-hnswlib==0.7.3 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (0.7.3)
Requirement already satisfied: fastapi>=0.95.2 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (0.103.2)
Requirement already satisfied: uvicorn[standard]>=0.18.3 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (0.23.2)
Requirement already satisfied: posthog>=2.4.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (3.0.2)
Requirement already satisfied: pulsar-client>=3.1.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (3.3.0)
Requirement already satisfied: onnxruntime>=1.14.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (1.16.0)
Requirement already satisfied: tokenizers>=0.13.2 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (0.14.0)
Requirement already satisfied: pypika>=0.48.9 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (0.48.9)
Requirement already satisfied: overrides>=7.3.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (7.4.0)
Requirement already satisfied: importlib-resources in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (6.1.0)
Requirement already satisfied: bcrypt>=4.0.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (4.0.1)
Requirement already satisfied: typer>=0.9.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (0.9.0)
Requirement already satisfied: graphlib-backport>=1.0.3 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from chromadb) (1.0.3)
Requirement already satisfied: PyYAML>=5.3 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from langchain) (6.0.1)
Requirement already satisfied: SQLAlchemy<3,>=1.4 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from langchain) (2.0.21)
Requirement already satisfied: aiohttp<4.0.0,>=3.8.3 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from langchain) (3.8.5)
Requirement already satisfied: anyio<4.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from langchain) (3.7.1)
Requirement already satisfied: async-timeout<5.0.0,>=4.0.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from langchain) (4.0.3)
Requirement already satisfied: dataclasses-json<0.7,>=0.5.7 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from langchain) (0.6.1)
Requirement already satisfied: jsonpatch<2.0,>=1.33 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from langchain) (1.33)
Requirement already satisfied: langsmith<0.1.0,>=0.0.40 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from langchain) (0.0.41)
Requirement already satisfied: tenacity<9.0.0,>=8.1.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from langchain) (8.2.3)
Requirement already satisfied: attrs>=17.3.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (23.1.0)
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (3.3.0)
Requirement already satisfied: multidict<7.0,>=4.5 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (6.0.4)
Requirement already satisfied: yarl<2.0,>=1.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.9.2)
Requirement already satisfied: frozenlist>=1.1.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.4.0)
Requirement already satisfied: aiosignal>=1.1.2 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.3.1)
Requirement already satisfied: idna>=2.8 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from anyio<4.0->langchain) (3.4)
Requirement already satisfied: sniffio>=1.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from anyio<4.0->langchain) (1.3.0)
Requirement already satisfied: exceptiongroup in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from anyio<4.0->langchain) (1.1.3)
Requirement already satisfied: marshmallow<4.0.0,>=3.18.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from dataclasses-json<0.7,>=0.5.7->langchain) (3.20.1)
Requirement already satisfied: typing-inspect<1,>=0.4.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from dataclasses-json<0.7,>=0.5.7->langchain) (0.9.0)
Requirement already satisfied: starlette<0.28.0,>=0.27.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from fastapi>=0.95.2->chromadb) (0.27.0)
Requirement already satisfied: filelock in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from huggingface-hub>=0.4.0->sentence-transformers) (3.12.4)
Requirement already satisfied: fsspec in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from huggingface-hub>=0.4.0->sentence-transformers) (2023.9.2)
Requirement already satisfied: packaging>=20.9 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from huggingface-hub>=0.4.0->sentence-transformers) (23.2)
Requirement already satisfied: jsonpointer>=1.9 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from jsonpatch<2.0,>=1.33->langchain) (2.4)
Requirement already satisfied: coloredlogs in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from onnxruntime>=1.14.1->chromadb) (15.0.1)
Requirement already satisfied: flatbuffers in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from onnxruntime>=1.14.1->chromadb) (23.5.26)
Requirement already satisfied: protobuf in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from onnxruntime>=1.14.1->chromadb) (4.24.4)
Requirement already satisfied: sympy in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from onnxruntime>=1.14.1->chromadb) (1.12)
Requirement already satisfied: six>=1.5 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from posthog>=2.4.0->chromadb) (1.16.0)
Requirement already satisfied: monotonic>=1.5 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from posthog>=2.4.0->chromadb) (1.6)
Requirement already satisfied: backoff>=1.10.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from posthog>=2.4.0->chromadb) (2.2.1)
Requirement already satisfied: python-dateutil>2.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from posthog>=2.4.0->chromadb) (2.8.2)
Requirement already satisfied: certifi in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from pulsar-client>=3.1.0->chromadb) (2023.7.22)
Requirement already satisfied: annotated-types>=0.4.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from pydantic>=1.9->chromadb) (0.5.0)
Requirement already satisfied: pydantic-core==2.10.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from pydantic>=1.9->chromadb) (2.10.1)
Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from requests>=2.28->chromadb) (2.0.6)
Requirement already satisfied: networkx in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from torch>=1.6.0->sentence-transformers) (3.1)
Requirement already satisfied: jinja2 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from torch>=1.6.0->sentence-transformers) (3.1.2)
Requirement already satisfied: regex!=2019.12.17 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from transformers<5.0.0,>=4.6.0->sentence-transformers) (2023.10.3)
Requirement already satisfied: safetensors>=0.3.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from transformers<5.0.0,>=4.6.0->sentence-transformers) (0.3.3)
Requirement already satisfied: click<9.0.0,>=7.1.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from typer>=0.9.0->chromadb) (8.1.7)
Requirement already satisfied: h11>=0.8 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from uvicorn[standard]>=0.18.3->chromadb) (0.14.0)
Requirement already satisfied: httptools>=0.5.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from uvicorn[standard]>=0.18.3->chromadb) (0.6.0)
Requirement already satisfied: python-dotenv>=0.13 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from uvicorn[standard]>=0.18.3->chromadb) (1.0.0)
Requirement already satisfied: uvloop!=0.15.0,!=0.15.1,>=0.14.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from uvicorn[standard]>=0.18.3->chromadb) (0.17.0)
Requirement already satisfied: watchfiles>=0.13 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from uvicorn[standard]>=0.18.3->chromadb) (0.20.0)
Requirement already satisfied: websockets>=10.4 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from uvicorn[standard]>=0.18.3->chromadb) (11.0.3)
Requirement already satisfied: zipp>=3.1.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from importlib-resources->chromadb) (3.17.0)
Requirement already satisfied: joblib in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from nltk->sentence-transformers) (1.3.2)
Requirement already satisfied: threadpoolctl>=2.0.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from scikit-learn->sentence-transformers) (3.2.0)
Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from torchvision->sentence-transformers) (10.0.1)
Requirement already satisfied: mypy-extensions>=0.3.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from typing-inspect<1,>=0.4.0->dataclasses-json<0.7,>=0.5.7->langchain) (1.0.0)
Requirement already satisfied: humanfriendly>=9.1 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from coloredlogs->onnxruntime>=1.14.1->chromadb) (10.0)
Requirement already satisfied: MarkupSafe>=2.0 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from jinja2->torch>=1.6.0->sentence-transformers) (2.1.3)
Requirement already satisfied: mpmath>=0.19 in /Users/jeffxtang/anaconda3/envs/llama-demo-apps/lib/python3.8/site-packages (from sympy->onnxruntime>=1.14.1->chromadb) (1.3.0)
%% Cell type:code id:26bc4912 tags:
``` python
from langchain.llms import LlamaCpp
from langchain.chains import LLMChain
from langchain.callbacks.manager import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.prompts import PromptTemplate
```
%% Cell type:markdown id:73df46d9 tags:
Next, initialize the langchain `CallBackManager`. This handles callbacks from Langchain and for this example we will use token-wise streaming so the answer gets generated token by token when Llama is answering your question.
%% Cell type:code id:01fe5b9c tags:
``` python
# for token-wise streaming so you'll see the answer gets generated token by token when Llama is answering your question
callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
```
%% Cell type:markdown id:8536c352 tags:
Set up the Llama 2 model.
Replace `<path-to-llama-gguf-file>` with the path either to your downloaded quantized model file [here](https://drive.google.com/file/d/1afPv3HOy73BE2MoYCgYJvBDeQNa9rZbj/view?usp=sharing),
or to the `ggml-model-q4_0.gguf` file built with the following commands:
```bash
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
python3 -m pip install -r requirements.txt
python convert.py <path_to_your_downloaded_llama-2-13b_model>
./quantize <path_to_your_downloaded_llama-2-13b_model>/ggml-model-f16.gguf <path_to_your_downloaded_llama-2-13b_model>/ggml-model-q4_0.gguf q4_0
```
For more info see https://python.langchain.com/docs/integrations/llms/llamacpp
%% Cell type:code id:dff6aa6b tags:
``` python
llm = LlamaCpp(
model_path="<path-to-llama-gguf-file>"
temperature=0.0,
top_p=1,
n_ctx=6000,
callback_manager=callback_manager,
verbose=True,
)
```
%% Cell type:markdown id:f2cae215 tags:
With the model set up, you are now ready to ask some questions.
Here is an example of the simplest way to ask the model some general questions.
%% Cell type:code id:0e78549c-9c93-4bc2-b525-38d578a94fae tags:
``` python
question = "who wrote the book Innovator's dilemma?"
answer = llm(question)
```
%% Output
The book "The Innovator's Dilemma" was written by Clayton Christensen, a professor at Harvard Business School. It was first published in 1997 and has since become a widely influential book on business strategy and innovation.
llama_print_timings: load time = 1202.24 ms
llama_print_timings: sample time = 46.44 ms / 58 runs ( 0.80 ms per token, 1249.03 tokens per second)
llama_print_timings: prompt eval time = 1815.15 ms / 15 tokens ( 121.01 ms per token, 8.26 tokens per second)
llama_print_timings: eval time = 5582.64 ms / 57 runs ( 97.94 ms per token, 10.21 tokens per second)
llama_print_timings: total time = 7545.78 ms
%% Cell type:markdown id:545cb6aa tags:
Alternatively, you can sue LangChain's `PromptTemplate` for some flexibility in your prompts and questions.
For more information on LangChain's prompt template visit this [link](https://python.langchain.com/docs/modules/model_io/prompts/prompt_templates/)
%% Cell type:code id:f7305c5b-6f55-4664-9206-2d7467653498 tags:
``` python
# a more flexible way to ask Llama general questions using LangChain's PromptTemplate and LLMChain
prompt = PromptTemplate.from_template(
"who wrote {book}?"
)
chain = LLMChain(llm=llm, prompt=prompt)
answer = chain.run("innovator's dilemma")
```
%% Output
Llama.generate: prefix-match hit
Clayton Christensen is the author of "The Innovator's Dilemma," which was first published in 1997. The book explores why successful companies often struggle to adapt to disruptive technologies and business models that ultimately lead to their downfall. Christensen argues that these companies are faced with a dilemma because they have invested so heavily in their existing products and processes that it is difficult for them to pivot and embrace new, disruptive technologies. He also introduces the concept of "disruptive innovation," which he defines as a process by which a small company with limited resources is able to successfully challenge established industry leaders.
llama_print_timings: load time = 1202.24 ms
llama_print_timings: sample time = 116.69 ms / 147 runs ( 0.79 ms per token, 1259.79 tokens per second)
llama_print_timings: prompt eval time = 1180.31 ms / 8 tokens ( 147.54 ms per token, 6.78 tokens per second)
llama_print_timings: eval time = 13192.98 ms / 147 runs ( 89.75 ms per token, 11.14 tokens per second)
llama_print_timings: total time = 14746.13 ms
%% Cell type:markdown id:189de613 tags:
Now, let's see how Llama2 hallucinates, because it did not have knowledge about Llama2 at the time it was trained.
By default it behaves like a know-it-all expert who will not say "I don't know".
%% Cell type:code id:8ba66a29-77e9-4149-9523-63a09545584e tags:
``` python
prompt = PromptTemplate.from_template(
"What is {what}?"
)
chain = LLMChain(llm=llm, prompt=prompt)
answer = chain.run("llama2")
```
%% Output
Llama.generate: prefix-match hit
Llama2 is a free, open-source tool for generating high-quality, randomized test data for software applications. It is designed to be easy to use and to produce realistic, diverse test data that can help you identify and fix bugs in your application before it is released.
Llama2 is the successor to the popular Llama tool, and it includes many new features and improvements over its predecessor. Some of the key features of Llama2 include:
* Support for a wide range of data types, including strings, numbers, dates, and more
* The ability to generate random data based on user-defined rules and constraints
* A powerful and flexible API that allows you to customize and extend the tool to meet your specific needs
* Integration with popular testing frameworks and tools, such as JUnit and TestNG
* Support for a variety of programming languages, including Java, Python, C#, and more.
Overall, Llama2 is a powerful and flexible tool that can help you improve the quality and reliability of your software applications by generating realistic and diverse test data.
llama_print_timings: load time = 1202.24 ms
llama_print_timings: sample time = 191.25 ms / 240 runs ( 0.80 ms per token, 1254.87 tokens per second)
llama_print_timings: prompt eval time = 480.79 ms / 6 tokens ( 80.13 ms per token, 12.48 tokens per second)
llama_print_timings: eval time = 22013.19 ms / 239 runs ( 92.11 ms per token, 10.86 tokens per second)
llama_print_timings: total time = 23111.55 ms
%% Cell type:markdown id:37f77909 tags:
One way we can fix the hallucinations is to use RAG, to augment it with more recent or custom data that holds the information for it to answer correctly.
First we load the Llama2 paper using LangChain's [PDF loader](https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf)
%% Cell type:code id:f3ebc261 tags:
``` python
from langchain.document_loaders import PyPDFLoader
loader = PyPDFLoader("llama2.pdf")
documents = loader.load()
```
%% Cell type:code id:302eaa54 tags:
``` python
# quick check on the loaded document for the correct pages etc
print(len(documents), documents[0].page_content[0:300])
```
%% Output
77 Llama 2 : Open Foundation and Fine-Tuned Chat Models
Hugo Touvron∗Louis Martin†Kevin Stone†
Peter Albert Amjad Almahairi Yasmine Babaei Nikolay Bashlykov Soumya Batra
Prajjwal Bhargava Shruti Bhosale Dan Bikel Lukas Blecher Cristian Canton Ferrer Moya Chen
Guillem Cucurull David Esiobu Jude Fernande
%% Cell type:markdown id:8c4ede5b tags:
Next we will store our documents.
There are more than 30 vector stores (DBs) supported by LangChain.
For this example we will use [Chroma](https://python.langchain.com/docs/integrations/vectorstores/chroma) which is light-weight and in memory so it's easy to get started with.
For other vector stores especially if you need to store a large amount of data - see https://python.langchain.com/docs/integrations/vectorstores
We will also import the `HuggingFaceEmbeddings` and `RecursiveCharacterTextSplitter` to assist in storing the documents.
%% Cell type:code id:4f94f6f8 tags:
``` python
from langchain.vectorstores import Chroma
# embeddings are numerical representations of the question and answer text
from langchain.embeddings import HuggingFaceEmbeddings
# use a common text splitter to split text into chunks
from langchain.text_splitter import RecursiveCharacterTextSplitter
```
%% Cell type:markdown id:0bfdacf7 tags:
To store the documents, we will need to split them into chunks using [`RecursiveCharacterTextSplitter`](https://python.langchain.com/docs/modules/data_connection/document_transformers/text_splitters/recursive_text_splitter) and create vector representations of these chunks using [`HuggingFaceEmbeddings`](https://www.google.com/search?q=langchain+hugging+face+embeddings&sca_esv=572890011&ei=ARUoZaH4LuumptQP48ah2Ac&oq=langchian+hugg&gs_lp=Egxnd3Mtd2l6LXNlcnAiDmxhbmdjaGlhbiBodWdnKgIIADIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCkjeHlC5Cli5D3ABeAGQAQCYAV6gAb4CqgEBNLgBAcgBAPgBAcICChAAGEcY1gQYsAPiAwQYACBBiAYBkAYI&sclient=gws-wiz-serp) on them before storing them into our vector database.
%% Cell type:code id:2b101485 tags:
``` python
# split the loaded documents into chunks
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=20)
all_splits = text_splitter.split_documents(documents)
# create the vector db to store all the split chunks as embeddings
embeddings = HuggingFaceEmbeddings()
vectordb = Chroma.from_documents(
documents=all_splits,
embedding=embeddings,
)
```
%% Cell type:markdown id:bddc38e8 tags:
We then use ` RetrievalQA` to retrieve the documents from the vector database and give the model more context on Llama 2, thereby increasing its knowledge.
%% Cell type:code id:1a2472c9 tags:
``` python
# use another LangChain's chain, RetrievalQA, to associate Llama with the loaded documents stored in the vector db
from langchain.chains import RetrievalQA
qa_chain = RetrievalQA.from_chain_type(
llm,
retriever=vectordb.as_retriever()
)
```
%% Output
Llama.generate: prefix-match hit
Llama 2 is a new language model developed by Meta AI that has been released openly to encourage responsible AI innovation. It is a fine-tuned version of the original Llama model and is optimized for dialogue use cases. The model has not covered all scenarios and may produce inaccurate or objectionable responses, so developers should perform safety testing and tuning before deploying any applications of Llama 2.
llama_print_timings: load time = 1202.24 ms
llama_print_timings: sample time = 76.83 ms / 97 runs ( 0.79 ms per token, 1262.48 tokens per second)
llama_print_timings: prompt eval time = 97067.98 ms / 1146 tokens ( 84.70 ms per token, 11.81 tokens per second)
llama_print_timings: eval time = 10431.81 ms / 96 runs ( 108.66 ms per token, 9.20 tokens per second)
llama_print_timings: total time = 107897.31 ms
%% Cell type:markdown id:db71e5d7 tags:
For each question, LangChain performs a semantic similarity search of it in the vector db, then passes the search results as the context to the model to answer the question.
It takes close to 2 minutes to return the result (but using other vector stores other than Chroma such as FAISS can take longer) because Llama2 is running on a local Mac.
To get much faster results, you can use a cloud service with GPU used for inference - see HelloLlamaCloud for a demo.
%% Cell type:code id:dd2e62a4-6ea2-4ea7-b7ae-800185177e6c tags:
``` python
question = "What is llama2?"
result = qa_chain({"query": question})
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment