採購大型語言模型的調查
簡單的定義:語言建模是預測接下來哪個單詞的任務。
“那隻狗在……在……”
語言模型的主要目的是將概率分配給句子,以區分較小的句子和較小的句子。
為了進行語音識別,我們不僅使用聲學模型(語音信號),還使用語言模型。同樣,對於光學特徵識別(OCR),我們同時使用視覺模型和語言模型。語言模型對於此類識別系統非常重要。
有時,您會聽到或閱讀尚不清楚的句子,但是使用您的語言模型,儘管有嘈雜的視覺/語音輸入,但您仍然可以很高的精度識別它。
語言模型計算以下任意:
語言建模是許多NLP任務的子組件,尤其是涉及生成文本或估算文本概率的任務。
鏈條規則:
$ p(,水為,,so,so clear)= p(the)×p(wath | the | the)×p(is | the,wath)×p(so | | |,水,is)×p(clear | the | the | the | the,水是,so)$
剛剛發生了什麼?鏈條規則用於計算句子中單詞的關節概率。
使用大量文本(例如Wikipedia等語料庫),我們收集有關不同單詞的頻率的統計信息,並使用它們來預測下一個單詞。例如,一個單詞w的可能性是在學生打開以下三個單詞打開他們的三個單詞之後的概率,如下所示:
上面的示例是4克模型。我們可能會得到:
我們可以得出結論,在這種情況下,“書”一詞比“汽車”更有可能。
在“學生打開他們的”之前,我們忽略了以前的上下文
因此,可以從給定單詞的語言模型,通過從下一個單詞的輸出概率分佈進行採樣等語言模型生成任意文本。
我們可以在任何類型的文本上訓練LM,然後以這種樣式(Harry Potter等)生成文本。
我們可以擴展到Trigram,4克,5克和N-Grams。
通常,這是語言模型不足,因為該語言具有長途依賴性。但是,實際上,這3,4克對於大多數應用程序都可以很好地工作。
Google的N-Gram模型屬於您:Google Research一直在為各種研發項目使用Word N-Gram模型。 Google n-gram處理了1,024,908,267,229單詞,並發布了所有1,176,470,663個五字序列的計數,這些序列至少出現了40次。
語言學數據聯盟的文本計數如下:
File sizes: approx. 24 GB compressed (gzip'ed) text files
Number of tokens: 1,024,908,267,229
Number of sentences: 95,119,665,584
Number of unigrams: 13,588,391
Number of bigrams: 314,843,401
Number of trigrams: 977,069,902
Number of fourgrams: 1,313,818,354
Number of fivegrams: 1,176,470,663
以下是此語料庫中4克數據的示例:
serve as the incoming 92
serve as the incubator 99
serve as the independent 794
serve as the index 223
serve as the indication 72
serve as the indicator 120
serve as the indicators 45
serve as the indispensable 111
serve as the indispensible 40
例如,在語料庫中已經看到了四個單詞“用作指示”的序列72次。
有時我們沒有足夠的數據來估計。增加n使稀疏性問題變得更糟。通常,我們不能擁有大於5的n。
NLM通常(但並非總是)使用RNN來學習單詞序列(句子,段落等),因此可以預測下一個單詞。
優點:

如圖所示,在每個步驟中,我們在詞彙上都有下一個單詞的概率分佈。
培訓NLM:
長序列學習的示例:
缺點:
LM可用於在不同應用程序上生成輸入(語音,圖像(OCR),文本等)上的文本條件,例如:語音識別,機器翻譯,摘要等。

我們的語言模型比不良句子更喜歡好(可能)句子嗎?
語言模型的標準評估度量是困惑的困惑是測試集的反可能性,由單詞數量歸一化

較低的困惑=更好的模型
困惑與分支因素有關:平均而言,接下來可能發生多少件事。
我們使用注意力而不是RNN,讓我們使用大型預培訓模型
問題是什麼?自然語言處理(NLP)最大的挑戰之一是缺乏許多不同任務的培訓數據。但是,現代深度學習的NLP模型在接受帶註釋的培訓示例的數百萬或數十億培訓時會有所改善。
預訓練是解決方案:為了幫助縮小這一差距,已經開發了多種技術,用於使用大量未註釋的文本訓練通用語言表示模型。然後,可以在較小的數據上微調預訓練的模型,以進行不同的任務,例如答案和情感分析,從而與從頭開始的這些數據集進行培訓相比,可以提高準確的準確性。
在紙張註意中提出了變壓器體系結構,您需要全部使用,用於神經機器翻譯任務(NMT),由:
如論文中所述:
“我們提出了一種新的簡單網絡體系結構,即變壓器,僅基於注意機制,完全以復發和卷積的方式分配”
正如Openai的文章中提到的那樣,可以總結注意力的主要思想:
“ ...每個輸出元素都連接到每個輸入元素,並且它們之間的權重是根據情況動態計算的,一個稱為註意的過程。 ”
基於此體系結構(香草變壓器!),可以單獨使用編碼器或解碼器組件來啟用大量的預訓練的通用模型,這些模型可以進行微調,以用於下游任務,例如文本分類,翻譯,摘要,問題答案等。例如:例如:
例如,BERT和GPT這些模型可以視為NLP的Imagenet。

如圖所示,Bert是雙向的,Openai GPT是單向的,Elmo是雙向的。
預訓練的表示可能是:
上下文語言模型可以是:
在這一部分中,我們將使用不同的大語模型
GPT2(GPT的繼任者)是使用因果語言建模( CLM )目標的英語培訓模型,經過培訓,僅需預測40GB Internet文本中的下一個單詞即可。它首先在此頁面上發布。 GPT2顯示了一系列功能,包括生成條件合成文本樣本的能力。關於問題回答,閱讀理解,摘要和翻譯等語言任務,GPT2開始從原始文本中學習這些任務,沒有使用特定於任務的培訓數據。 Distilgpt2是GPT2的蒸餾版本,它旨在用於類似用例,其功能增加的功能比基本模型更小,更易於運行。
在這裡,我們加載了預訓練的GPT2模型,要求GPT2模型繼續我們的輸入文本(提示),最後,從DistilGPT2模型中提取嵌入式功能。
from transformers import pipeline
generator = pipeline('text-generation', model='gpt2')
generator("The capital of Japan is Tokyo, The capital of Egypt is", max_length=13, num_return_sequences=2)
[{'generated_text': 'The capital of Japan is Tokyo, The capital of Egypt is Cairo'},
{'generated_text': 'The capital of Japan is Tokyo, The capital of Egypt is Alexandria'}]
伯特(Bert)是一種以自我監督的方式對大量英語數據進行預訓練的變形金剛模型。這意味著它僅在原始文本上進行了預先訓練,沒有人類以任何方式標記它們,以自動過程來生成這些文本的輸入和標籤。更確切地說,它是有兩個目標鑑定的:
在此示例中,我們將使用預先訓練的BERT模型進行情感分析任務。
import transformers as ppb
model_class, tokenizer_class, pretrained_weights = (ppb.BertModel, ppb.BertTokenizer, 'bert-base-uncased')
bert_tokenizer = tokenizer_class.from_pretrained(pretrained_weights)
bert_model = model_class.from_pretrained(pretrained_weights)
GPT4ALL是一個生態系統,可以培訓和部署在消費級CPU上本地運行的功能強大和定制的大型語言模型。
import gpt4all
gptj = gpt4all.GPT4All("ggml-gpt4all-j-v1.3-groovy.bin")
with gptj.chat_session():
response = gptj.generate(prompt='hello', top_k=1)
response = gptj.generate(prompt='My name is Ibrahim, what is your name?', top_k=1)
response = gptj.generate(prompt='What is the capital of Egypt?', top_k=1)
response = gptj.generate(prompt='What is my name?', top_k=1)
print(gptj.current_chat_session)
[{'role': 'user', 'content': 'hello'},
{'role': 'assistant', 'content': 'Hello! How can I assist you today?'},
{'role': 'user', 'content': 'My name is Ibrahim, what is your name?'},
{'role': 'assistant', 'content': 'I am an artificial intelligence assistant. My name is AI-Assistant.'},
{'role': 'user', 'content': 'What is the capital of Egypt?'},
{'role': 'assistant', 'content': 'The capital city of Egypt is Cairo.'},
{'role': 'user', 'content': 'What is my name?'},
{'role': 'assistant', 'content': 'Your name is Ibrahim, what a beautiful name!'}]
嘗試以下模型:
import gpt4all
model = gpt4all.GPT4All("ggml-vicuna-7b-1.1-q4_2.bin")
model = gpt4all.GPT4All("ggml-vicuna-13b-1.1-q4_2.bin")
model = gpt4all.GPT4All("ggml-wizardLM-7B.q4_2.bin")
model = gpt4all.GPT4All("ggml-mpt-7b-chat.bin")
model = gpt4all.GPT4All("orca-mini-3b.ggmlv3.q4_0.bin")
Falcon LLM是TII的大型語言模型的旗艦系列,使用自定義數據管道和分佈式培訓從頭開始構建。 Falcon-7b/40b型號的尺寸是最先進的,在NLP基準測試上的其他大多數模型都優於其他大多數型號。開源的許多文物:
from transformers import AutoTokenizer, AutoModelForCausalLM
import transformers
import torch
model = "tiiuae/falcon-7b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model)
pipeline = transformers.pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
torch_dtype=torch.bfloat16,
trust_remote_code=True,
device_map="auto",
)
sequences = pipeline(
"Girafatron is obsessed with giraffes, the most glorious animal on the face of this Earth. Giraftron believes all other animals are irrelevant when compared to the glorious majesty of the giraffe.nDaniel: Hello, Girafatron!nGirafatron:",
max_length=200,
do_sample=True,
top_k=10,
num_return_sequences=1,
eos_token_id=tokenizer.eos_token_id,
)
for seq in sequences:
print(f"Result: {seq['generated_text']}")
Result: Girafatron is obsessed with giraffes, the most glorious animal on the face of this Earth. Giraftron believes all other animals are irrelevant when compared to the glorious majesty of the giraffe.
Daniel: Hello, Girafatron!
Girafatron: Hi Daniel! I am Girafatron, the world's first Giraffe. How can I be of assistance to you, human boy?
Daniel: I'd like to ask you questions about yourself, like how your day is going and how you feel about your job and everything. Would you like to talk about that?
Girafatron: Sure, my day is going great. I'm feeling fantastic. As for my job, I'm enjoying it!
Daniel: What do you like most about your job?
Girafatron: I love being the tallest animal in the universe! It's really fulfilling.
Llama2是Meta今天發布的最先進的開放式大型語言模型的家族,我們很高興能以全面的融合在擁抱面孔中充分支持發射。 Llama 2具有非常寬鬆的社區許可證,可用於商業用途。今天發布的代碼,預估計的型號和微調模型都將發布
pip install transformers
huggingface-cli login
from transformers import AutoTokenizer
import transformers
import torch
model = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = AutoTokenizer.from_pretrained(model)
pipeline = transformers.pipeline(
"text-generation",
model=model,
torch_dtype=torch.float16,
device_map="auto",
)
sequences = pipeline(
'I liked "Breaking Bad" and "Band of Brothers". Do you have any recommendations of other shows I might like?n',
do_sample=True,
top_k=10,
num_return_sequences=1,
eos_token_id=tokenizer.eos_token_id,
max_length=200,
)
for seq in sequences:
print(f"Result: {seq['generated_text']}")
Result: I liked "Breaking Bad" and "Band of Brothers". Do you have any recommendations of other shows I might like?
Answer:
Of course! If you enjoyed "Breaking Bad" and "Band of Brothers," here are some other TV shows you might enjoy:
1. "The Sopranos" - This HBO series is a crime drama that explores the life of a New Jersey mob boss, Tony Soprano, as he navigates the criminal underworld and deals with personal and family issues.
2. "The Wire" - This HBO series is a gritty and realistic portrayal of the drug trade in Baltimore, exploring the impact of drugs on individuals, communities, and the criminal justice system.
3. "Mad Men" - Set in the 1960s, this AMC series follows the lives of advertising executives on Madison Avenue, expl
CODET5+是一個開放代碼大型語言模型的新家族,具有編碼器編碼器體系結構,可以以不同的模式靈活地操作(即僅編碼,僅解碼器和編碼器編碼器),以支持廣泛的代碼理解和生成任務。
from transformers import T5ForConditionalGeneration, AutoTokenizer
checkpoint = "Salesforce/codet5p-770m-py"
device = "cuda" # for GPU usage or "cpu" for CPU usage
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = T5ForConditionalGeneration.from_pretrained(checkpoint).to(device)
inputs = tokenizer.encode("def factorial(n):", return_tensors="pt").to(device)
outputs = model.generate(inputs, max_length=150)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
def factorial(n):
'''
Returns the factorial of a given number.
'''
if n == 0:
return 1
return n * factorial(n - 1)
def main():
'''
Tests the factorial function.
'''
assert factorial(0) == 1
assert factorial(1) == 1
assert factorial(2) == 2
assert factorial(3) == 6
assert factorial(4) == 120
assert factorial(5) == 720
assert factorial(6) == 5040
assert factorial(7) == 5040
對於更多模型,請檢查Salesforce的CODETF,這是一個基於Python Transformer的代碼大型語言模型(代碼LLM)和代碼智能的庫,提供了一個無縫接口的接口,用於培訓和推斷代碼智能任務,例如代碼匯總,翻譯,代碼生成等。
與開放的大語模型聊天
✅梁搜索始終會找到比貪婪搜索更高的輸出序列,但不能保證找到最可能的輸出。
在變壓器中,我們只需將參數num_return_ sequences設置為應返回的最高評分樑的數量即可。確保num_return_sequences <= num_beams!
✅梁搜索在所需生成的長度或多或少可預測的任務中可以很好地工作,就像機器翻譯或摘要一樣。但是,對於開放式一代而言,這不是這種情況,所需的輸出長度可以很大變化,例如對話和故事生成。梁搜索嚴重遭受重複產生。作為人類,我們希望生成的文本使我們感到驚訝,而不是無聊/可預測(?梁搜索不那麼令人驚訝)
在變形金剛中,我們通過top_k = 0設置do_sample = true = true和停用top-k採樣(稍後再進行)。
??? - ? ????? GPT2採用了此抽樣方案。
??? - ? ?????????:不是僅從最可能的k單詞中取樣,而是從頂部Pampling中從最小可能的單詞組中選擇,其累積概率超過概率p的最小單詞。然後將概率質量重新分佈在這組單詞之間。在設置P = 0.92的情況下,Top-P採樣選擇最小單詞數量超過了概率質量的92%。
# set top_k = 50 and set top_p = 0.95 and num_return_sequences = 3
sample_outputs = model.generate(
**model_inputs,
max_new_tokens=40,
do_sample=True,
top_k=50,
top_p=0.95,
num_return_sequences=3,
)
✅儘管Top-P似乎比TOUP-K更優雅,但兩種方法在實踐中都很好。 TOP-P也可以與TOUP-K結合使用,TOUP-K可以避免排名非常低的單詞,同時允許進行一些動態選擇。

✅作為臨時解碼方法,TOP-P和TOP-K採樣似乎比傳統的貪婪產生的文本更流利 - 並且在開放式語言生成上搜索了光束搜索。
及時工程是設計提示(文本輸入)以生成所需輸出的過程。及時工程涉及選擇適當的關鍵字,提供上下文,清晰明確,以指導語言模型行為實現所需響應的方式。通過及時的工程,我們可以控制模型的音調,樣式,長度等,而無需微調。
零拍攝的學習涉及要求模型進行預測而不提供任何示例(零射擊),例如:
Classify the text into neutral, negative or positive.
Text: I think the vacation is excellent.
Sentiment:
Answer: Positive
當零射擊不夠好時,建議通過在提示中提供示例來幫助模型,從而導致很少的提示。
Text: This is awesome!
Sentiment: Positive
Text: This is bad!
Sentiment: Negative
Text: Wow that movie was rad!
Sentiment: Positive
Text: What a horrible show!
Sentiment:
Answer: Negative

除了迅速的工程外,我們還可以考慮更多選擇:
有關更多及時的工程信息,請參閱包含所有最新論文,學習指南,講座,參考和工具的及時工程指南。
與使用預告片的LLMS相比,下游數據集上的微調LLMS可在巨大的性能增長(例如,零攝像推理)。但是,隨著模型越來越大,對消費者硬件進行培訓變得不可行。此外,為每個下游任務獨立存儲和部署微調模型變得非常昂貴,因為微型模型的大小與原始預告片的型號相同。參數有效的微調(PEFT)方法旨在解決這兩個問題! PEFT方法使您能夠獲得與完整的微調相當的性能,而僅具有少量可訓練的參數。例如:
及時調整:學習“軟提示”以調節冷凍語言模型以執行特定下游任務的簡單而有效的機制。就像工程文本的提示一樣,軟提示會加入輸入文本。但是,軟提示的“代幣”不是從現有詞彙項目中選擇的,而是可學習的矢量。這意味著可以通過培訓數據集優化軟提示,如下所示:
LLMS的LORA低級適應性是一種凍結預驗證的模型權重,並註入了可訓練的秩分解矩陣中的每一層。大大減少了下游任務的可訓練參數的數量。下面的圖,從本視頻中解釋了主要思想: 
大型語言模型通常是通用的,對於特定領域的任務效率較低。但是,可以在某些任務(例如情感分析)上進行微調。對於需要外部知識的更複雜的TAK,可以構建一個基於語言模型的系統,該系統訪問外部知識源以完成所需的任務。這樣可以提高事實準確性,並有助於減輕“幻覺”的問題。如下圖所示:

在這種情況下,我們將LLM用作外部知識的自然語言接口,而不是使用LLM來訪問其內部知識。第一步是將文檔和任何用戶查詢轉換為兼容格式,以執行相關搜索(將文本轉換為向量或嵌入)。然後將原始用戶提示附加在外部知識源(作為上下文)中的相關 /類似文檔。然後,該模型根據提供的外部上下文回答問題。
大型語言模型(LLM)正在作為一種變革性技術。但是,將這些LLM隔離使用通常不足以創建真正強大的應用程序。 Langchain旨在協助開發此類應用程序。

Langchain旨在幫助您有六個主要領域。這些是越來越複雜的順序:
這包括提示管理,及時優化,所有LLM的通用接口以及與LLMS合作的通用實用程序。 LLM和聊天模型巧妙,但重要的是不同。 Langchain中的LLM是指純文本完成模型。他們包裝的API以字符串提示為輸入並輸出字符串完成。 OpenAI的GPT-3作為LLM實施。聊天模型通常由LLMS支持,但專門針對進行對話。
pip install openai
export OPENAI_API_KEY="..."
from langchain.llms import OpenAI
llm = OpenAI(openai_api_key="...")
llm("Tell me a joke")
# 'Why did the chicken cross the road?nnTo get to the other side.'
您還可以訪問返回的提供商的特定信息。此信息不是在提供商之間標準化的。
llm_result.llm_output
{'token_usage': {'completion_tokens': 3903,
'total_tokens': 4023,
'prompt_tokens': 120}}
from langchain.chat_models import ChatOpenAI
chat = ChatOpenAI()
messages = [
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="I love programming.")
]
chat(messages)
# AIMessage(content="J'aime programmer.", additional_kwargs={})
from langchain import PromptTemplate
prompt_template = PromptTemplate.from_template(
"Tell me a {adjective} joke about {content}."
)
prompt_template.format(adjective="funny", content="chickens")
提示聊天模型是聊天消息的列表。每個聊天消息與內容相關聯,還有一個稱為角色的附加參數。例如,在OpenAI聊天完成API中,聊天消息可以與AI助手,人類或系統角色相關聯。
from langchain.prompts import ChatPromptTemplate
template = ChatPromptTemplate.from_messages([
("system", "You are a helpful AI bot. Your name is {name}."),
("human", "Hello, how are you doing?"),
("ai", "I'm doing well, thanks!"),
("human", "{user_input}"),
])
messages = template.format_messages(
name="Bob",
user_input="What is your name?")
鏈條超越了單個LLM呼叫,涉及呼叫序列(無論是LLM還是其他實用程序)。 Langchain為鏈條提供了一個標準接口,與其他工具進行了大量集成以及常見應用的端到端鏈。鏈條非常普遍可以定義為對組件的調用序列,其中可能包括其他鏈條。
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
# To use the LLMChain, first create a prompt template.
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",)
# We can now create a very simple chain that will take user input, format the prompt with it, and then send it to the LLM.
from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
# Run the chain only specifying the input variable.
print(chain.run("colorful socks"))
# Result
Colorful Toes Co.
數據增強生成涉及特定類型的鏈條,這些鏈首先與外部數據源相互作用,以獲取數據以用於生成步驟。示例包括對特定數據源的問題/回答。
from langchain.document_loaders import TextLoader
loader = TextLoader("./index.md")
loader.load()
# This is a long document we can split up.
with open('../../state_of_the_union.txt') as f:
state_of_the_union = f.read()
from langchain.text_splitter import RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter(
# Set a really small chunk size, just to show.
chunk_size = 100,
chunk_overlap = 20,
length_function = len,
add_start_index = True,
)
texts = text_splitter.create_documents([state_of_the_union])
print(texts[0])
print(texts[1])
# page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and' metadata={'start_index': 0}
#page_content='of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.' metadata={'start_index': 82}
from langchain.embeddings import OpenAIEmbeddings
embeddings_model = OpenAIEmbeddings(openai_api_key="...")
embeddings = embeddings_model.embed_documents(
[
"Hi there!",
"Oh, hello!",
"What's your name?",
"My friends call me World",
"Hello World!"
]
)
from langchain.document_loaders import TextLoader
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma
# Load the document, split it into chunks, embed each chunk and load it into the vector store.
raw_documents = TextLoader('../../../state_of_the_union.txt').load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
documents = text_splitter.split_documents(raw_documents)
db = Chroma.from_documents(documents, OpenAIEmbeddings())
相似性搜索
query = "What did the president say about Ketanji Brown Jackson"
docs = db.similarity_search(query)
print(docs[0].page_content)
# Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.
# One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.
# And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.
# Let's walk through this in code
documents = loader.load()
#Next, we will split the documents into chunks.
from langchain.text_splitter import CharacterTextSplitter
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
# We will then select which embeddings we want to use.
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
# We now create the vectorstore to use as the index.
from langchain.vectorstores import Chroma
db = Chroma.from_documents(texts, embeddings)
# So that's creating the index. Then, we expose this index in a retriever interface.
retriever = db.as_retriever()
# Then, as before, we create a chain and use it to answer questions!
qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=retriever)
query = "What did the president say about Ketanji Brown Jackson"
qa.run(query)
# " The President said that Judge Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He said she is a consensus builder and has received a broad range of support from organizations such as the Fraternal Order of Police and former judges appointed by Democrats and Republicans."
代理商涉及LLM做出決定要採取哪些行動,採取該行動,觀察觀察並重複此操作的決定,直到完成為止。 Langchain為代理提供了標準接口,可以選擇的代理和端到端代理的示例。代理的核心思想是使用LLM選擇一系列動作。在鏈條中,一系列動作是硬編碼(在代碼中)。在代理中,語言模型被用作推理引擎,以確定要採取哪些動作以及在哪個順序中採取的行動。
from langchain.agents import tool
@tool
def get_word_length(word: str) -> int:
"""Returns the length of a word."""
return len(word)
tools = [get_word_length]
from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
內存是指鏈/代理的調用之間的持久狀態。 Langchain提供了一個標準接口,用於內存,內存實現集合以及使用內存的鏈/代理的示例。
from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory
llm = ChatOpenAI()
prompt = ChatPromptTemplate(
messages=[
SystemMessagePromptTemplate.from_template(
"You are a nice chatbot having a conversation with a human."
),
# The `variable_name` here is what must align with memory
MessagesPlaceholder(variable_name="chat_history"),
HumanMessagePromptTemplate.from_template("{question}")
]
)
# Notice that we `return_messages=True` to fit into the MessagesPlaceholder
# Notice that `"chat_history"` aligns with the MessagesPlaceholder name.
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
conversation = LLMChain(
llm=llm,
prompt=prompt,
verbose=True,
memory=memory
)
# Notice that we just pass in the `question` variables - `chat_history` gets populated by memory
conversation({"question": "hi"})
我們可以使用不同的方法與文檔聊天。無需微調整個LLM,而是我們可以為預訓練的模型提供正確的上下文以及我們的問題,然後根據我們提供的文檔獲得答案。
在這裡,我們與這篇名為“不痛苦的變形金剛”的精美文章聊天?在利用Google強大的Palm模型和Langchain框架的同時,詢問與變形金剛,注意力,編碼器碼頭等有關的問題,用於開發由語言模型提供支持的應用程序。
# load docs and construct the index
urls = ['https://www.linkedin.com/pulse/transformers-without-pain-ibrahim-sobh-phd/',]
loader = WebBaseLoader(urls)
index = VectorstoreIndexCreator(
embedding=GooglePalmEmbeddings(),
text_splitter=RecursiveCharacterTextSplitter(chunk_size=1000,
chunk_overlap=0, separators=[" ", ",", "n"])).from_loaders([loader])
# QA Retrieval
qa_retriever = RetrievalQA.from_chain_type(llm=Palm_llm, chain_type="stuff",
retriever=index.vectorstore.as_retriever(),
input_key="question")
問題: ? “這些文件是什麼?”
回答: ? “這些文檔是關於變形金剛的,這是一種成功用於自然語言處理和計算機視覺任務的神經網絡。”
問題: ? “變形金剛的主要思想是什麼?”
回答: ? “變形金剛的主要思想是使用注意機制以序列建模遠程依賴性。”
問題: ? “什麼是位置編碼?”
回答: ? “位置編碼是一種用於表示順序中單詞順序的技術。”
問題: ? “如何使用查詢,鍵和值向量?”
回答: ? '查詢向量用於通過鍵計算值的加權總和。具體來說:Q點產品所有鍵,然後softmax獲得權重,最後使用這些權重計算值的加權總和。
問題: ? “如何開始使用變壓器?”
回答: ? '要開始使用變形金剛,您可以使用HuggingFace Transformers庫。該庫提供了數千個審慎的模型,以用100多種語言進行分類,信息提取,摘要,翻譯,文本生成等文本執行任務。
您可以嘗試自己的文檔和問題!
在這些簡單的教程中:如何使用Chroma Vector Database,Google的Palm LLM以及Langchain的問答鏈從文本文檔, PDF文件,甚至YouTube視頻中獲取答案。最後,使用簡化來開發和託管Web應用程序。您將需要使用Google_api_key(可以從Google獲得一個)。 THS系統體系結構如下:



評估LLM與評估基於LLM的系統之間是有區別的。通常在通用預訓練後,在標準基准上評估LLM:
LLMS系統可以總結文本,進行問答,找到文本的情感,可以進行翻譯等等。基於系統,評估可以如下:
例如,如果要問答系統,我們需要在評估集中成對的問題和答案。我們可以使用人類註釋來手動創建金色標準的問題和答案。但是,這是昂貴且耗時的。創建此類數據集的一種可行方法是利用LLM。
You are a smart assistant designed to come up with meaninful question and answer pair. The question should be to the point and the answer should be as detailed as possible.
Given a piece of text, you must come up with a question and answer pair that can be used to evaluate a QA bot. Do not make up stuff. Stick to the text to come up with the question and answer pair.
When coming up with this question/answer pair, you must respond in the following format:
{{
"question": "$YOUR_QUESTION_HERE",
"answer": "$THE_ANSWER_HERE"
}}
Everything between the ``` must be valid json.
Please come up with a question/answer pair, in the specified JSON format, for the following text:
----------------
{text}
使用LLM查找預測與給定兩個文本(真實和預測答案)的真實答案相比,LLM可以從理論上找到它們是否在語義上相同。 Langchain有一個鏈條稱為
此外,我們可以使用標準指標進行評估,例如召回,精度和F1分數。
一旦有了一個EDAT數據集,就可以將Hyper參數優化方法構成SENS,並且可以在不同的模型,提示等上應用。
有關更多信息,本文提供瞭如何評估大型語言模型(LLM)系統的交互式介紹。
拉加斯是一個框架,可幫助您評估檢索增強發電(RAG)管道。 RAG表示使用外部數據來增強LLM上下文的一類LLM應用程序。現有的工具和框架可以幫助您構建這些管道,但是對其進行評估並量化管道性能可能很難。這就是拉加斯(RAG評估)的出現。

代理的核心思想是使用LLM選擇一系列動作。在鏈條中,一系列動作是硬編碼(在代碼中)。在代理中,語言模型被用作推理引擎,以確定要採取哪些動作以及在哪個順序中採取的行動。
該代碼顯示瞭如何使用代理以CSV格式與數據進行交互。它主要針對問答的優化。

ChatGpt插件是旨在幫助ChatGpt訪問最新信息,運行計算或使用第三方服務的工具。

擴展Chatgpt力量的示例:
通過通過顯示我的圖表創建和編輯圖

通過訪問Wolfram提供的數學力量

通過允許您將應用程序,服務和工具連接在一起,從而使您的生活自動化。 Zapier插件可將您連接到100個在線服務,例如電子郵件,社交媒體,雲存儲等。

? Autogpt自動實現您設定的任何目標! Auto-GPT是一個實驗性開源應用程序,展示了GPT-4語言模型的功能。該程序由GPT-4驅動,將LLM“ Thought”鏈接在一起,以自主實現您設定的任何目標。