微調Llama3實現在線搜索引擎和RAG檢索增強生成功能

視頻中所出現的代碼 Tavily Search+RAG

微調Llama3實現在線搜索引擎和RAG檢索增強生成功能!打造自己的perplexity和GPTs!用PDF實現本地知識庫_嗶哩嗶哩_bilibili

一.準備工作

1.安裝環境

conda create --name unsloth_env python=3.10
conda activate unsloth_envconda install pytorch-cuda=12.1 pytorch cudatoolkit xformers -c pytorch -c nvidia -c xformerspip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"pip install --no-deps trl peft accelerate bitsandbytes

?2.微調代碼(要先登錄一下)

huggingface-cli login

點擊提示的網頁獲取token(注意要選擇可寫的)


#dataset https://huggingface.co/datasets/shibing624/alpaca-zh/viewerfrom unsloth import FastLanguageModel
import torchfrom trl import SFTTrainer
from transformers import TrainingArgumentsmax_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.# 4bit pre quantized models we support for 4x faster downloading + no OOMs.
fourbit_models = ["unsloth/mistral-7b-bnb-4bit","unsloth/mistral-7b-instruct-v0.2-bnb-4bit","unsloth/llama-2-7b-bnb-4bit","unsloth/gemma-7b-bnb-4bit","unsloth/gemma-7b-it-bnb-4bit", # Instruct version of Gemma 7b"unsloth/gemma-2b-bnb-4bit","unsloth/gemma-2b-it-bnb-4bit", # Instruct version of Gemma 2b"unsloth/llama-3-8b-bnb-4bit", # [NEW] 15 Trillion token Llama-3
] # More models at https://huggingface.co/unslothmodel, tokenizer = FastLanguageModel.from_pretrained(model_name = "unsloth/llama-3-8b-bnb-4bit",max_seq_length = max_seq_length,dtype = dtype,load_in_4bit = load_in_4bit,# token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
)model = FastLanguageModel.get_peft_model(model,r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128target_modules = ["q_proj", "k_proj", "v_proj", "o_proj","gate_proj", "up_proj", "down_proj",],lora_alpha = 16,lora_dropout = 0, # Supports any, but = 0 is optimizedbias = "none",    # Supports any, but = "none" is optimized# [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long contextrandom_state = 3407,use_rslora = False,  # We support rank stabilized LoRAloftq_config = None, # And LoftQ
)alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.### Instruction:
{}### Input:
{}### Response:
{}"""EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
def formatting_prompts_func(examples):instructions = examples["instruction"]inputs       = examples["input"]outputs      = examples["output"]texts = []for instruction, input, output in zip(instructions, inputs, outputs):# Must add EOS_TOKEN, otherwise your generation will go on forever!text = alpaca_prompt.format(instruction, input, output) + EOS_TOKENtexts.append(text)return { "text" : texts, }
passfrom datasets import load_dataset#file_path = "/home/Ubuntu/alpaca_gpt4_data_zh.json"#dataset = load_dataset("json", data_files={"train": file_path}, split="train")dataset = load_dataset("yahma/alpaca-cleaned", split = "train")dataset = dataset.map(formatting_prompts_func, batched = True,)trainer = SFTTrainer(model = model,tokenizer = tokenizer,train_dataset = dataset,dataset_text_field = "text",max_seq_length = max_seq_length,dataset_num_proc = 2,packing = False, # Can make training 5x faster for short sequences.args = TrainingArguments(per_device_train_batch_size = 2,gradient_accumulation_steps = 4,warmup_steps = 5,max_steps = 60,learning_rate = 2e-4,fp16 = not torch.cuda.is_bf16_supported(),bf16 = torch.cuda.is_bf16_supported(),logging_steps = 1,optim = "adamw_8bit",weight_decay = 0.01,lr_scheduler_type = "linear",seed = 3407,output_dir = "outputs",),
)trainer_stats = trainer.train()model.save_pretrained_gguf("llama3", tokenizer, quantization_method = "q4_k_m")
model.save_pretrained_gguf("llama3", tokenizer, quantization_method = "q8_0")
model.save_pretrained_gguf("llama3", tokenizer, quantization_method = "f16")#to hugging face
model.push_to_hub_gguf("leo009/llama3", tokenizer, quantization_method = "q4_k_m")
model.push_to_hub_gguf("leo009/llama3", tokenizer, quantization_method = "q8_0")
model.push_to_hub_gguf("leo009/llama3", tokenizer, quantization_method = "f16")

3.我們選擇將hugging face上微調好的模型下載下來(https://huggingface.co/leo009/llama3/tree/main)

4.模型導入ollama

下載ollama

?導入ollama

FROM ./downloads/mistrallite.Q4_K_M.gguf
ollama create example -f Modelfile

二.實現在線搜索

1.獲取Tavily AI API?

Tavily AI

export TAVILY_API_KEY=tvly-xxxxxxxxxxx

?2.install tavily-python

pip install tavily-python

3.運行app.py

#app.py
import warnings# Suppress only the specific NotOpenSSLWarning
warnings.filterwarnings("ignore", message="urllib3 v2 only supports OpenSSL 1.1.1+")from phi.assistant import Assistant
from phi.llm.ollama import OllamaTools
from phi.tools.tavily import TavilyTools# 創建一個Assistant實例,配置其使用OllamaTools中的llama3模型,并整合Tavily工具
assistant = Assistant(llm=OllamaTools(model="mymodel3"),  # 使用OllamaTools的llama3模型tools=[TavilyTools()],show_tool_calls=True,  # 設置為True以展示工具調用信息
)# 使用助手實例輸出請求的響應,并以Markdown格式展示結果
assistant.print_response("Search tavily for 'GPT-5'", markdown=True)

?三.實現RAG

1.git clone?https://github.com/phidatahq/phidata.git

2.phidata---->cookbook---->llms--->ollama--->rag里面?有示例和教程

修改assigant.py中的14行代碼,將llama3改為自己微調好的模型

另外需要注意的是!!!

要將自己的模型名稱加入到app.py里面的數組里

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/15340.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/15340.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/15340.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

周末總結(2024/05/25)

工作 人際關系核心實踐: 要學會隨時回應別人的善意。執行時間控制在5分鐘以內 堅持每天早會打招呼 工作上的要點 現狀(接受破爛現狀,改變狀態) - 這周使用和執行了生產環境發布流程(2天),2天時間在寫Java…

大膽預測:計算機將要回暖

中概財報集體亮眼 雖然最近幾天恒指(港股)稍有回落,但年線仍有 9% 的上漲。 過去三年,恒指分別下跌 14.08%、15.46% 和 13.82%。 而在近期,國內各大互聯網都公布了財報,別看各個大廠的作妖不斷,…

[前端|vue] v-if 和v-show的區別,為什么功能會類似

v-if 和 v-show 都是 Vue 中用于條件渲染的指令,但它們之間存在幾個關鍵區別,這些區別導致了它們在不同場景下的適用性也有所不同: v-if 的特點: 條件渲染:v-if 是一個動態的條件渲染指令,它會根據表達式的…

dubbo復習:(8)使用sentinel對服務進行降級

一、下載sentinel-dashboard控制臺應用并在8080端口啟動 二、項目添加springboot 和dubbo相關依賴(降級規則并未持久化,如果需要持久化,如果需要持久化降級規則,只需增加nacos相關依賴并在nacos中進行配置,然后配置app…

會話機制:Session

1、什么是會話: 會話對應的英語單詞:session 用戶打開瀏覽器,進行一系列操作,然后最終將瀏覽器關閉,這個整個過程叫做:一次會話。會話在服務器端也有一個對應的java對象,這個java對象叫做&…

使用Python Tkinter創建GUI應用程序

大家好,當我們談及使用Python Tkinter創建GUI應用程序時,我們涉及的不僅是技術和代碼,更是關于創造力和用戶體驗的故事。Tkinter作為Python標準庫中最常用的GUI工具包,提供了豐富的功能和靈活的接口,讓開發者能夠輕松地…

每日一題(4)——String連接,替換,比較,查找等

主要是一些字符串的連接, 替換,比較,去首尾空格,查找等操作; class ZiFu{public static void main(String []args){String s1"hello world";String s2new String("hello,world");s2" "…

Vue3判斷變量和對象不為null和undefined

Vue3判斷變量和對象不為null和undefined 一、判斷變量二、判斷對象 一、判斷變量 在 Vue 3 中,你可以使用 JavaScript 提供的常規方式來檢查變量是否不為 null 和不為 undefined。你可以分別使用嚴格不等運算符 ! 來比較變量是否不為 null 和不為 undefined。以下是…

【基于springboot+vue的房屋租賃系統】

介紹 本系統是基于springbootvue的房屋租賃系統,數據庫為mysql,可用于日常學習和畢設,系統分為管理員、房東、用戶,部分截圖如下所示: 部分界面截圖 用戶 管理員 聯系我 微信:Zzllh_

打開服務器遠程桌面連接不上,可能的原因及相應的解決策略

在解決遠程桌面連接不上服務器的問題時,我們首先需要從專業的角度對可能的原因進行深入分析,并據此提出針對性的解決方案。以下是一些可能的原因及相應的解決策略: 一、網絡連接問題 遠程桌面連接需要穩定的網絡支持,如果網絡連接…

金融業務及其他學習資料相關

目錄 金融業務相關學習資料 道路交通安全考試科一學習資料(2023年版) 英語學習資料

ArcGIS提取含有計曲線的等高線

喜歡就關注我們吧! 今天我么來看看,如何利用DEM提取含有計曲線的等高線! 常規的話我們利用DEM提取的等高線都是不帶計曲線的,無法把計曲線標注出來,今天我們就來看下,如何處理一下哦!提取帶有計…

springboot打包目錄解析

一、引言 Java開發中我們使用最多的便是spring框架,比如springboot應用。微服務模式下,每個服務都是一個springboot應用,都會被打包成一個可執行jar包。那么我們有多少人嘗試去了解過這個可執行jar到底是什么?它的結構是什么樣的…

2730. 找到最長的半重復子字符串(c++,滑動窗口)

給你一個下標從 0 開始的字符串 s ,這個字符串只包含 0 到 9 的數字字符。 如果一個字符串 t 中至多有一對相鄰字符是相等的,那么稱這個字符串 t 是 半重復的 。例如,0010 、002020 、0123 、2002 和 54944 是半重復字符串,而 00…

Homebrew安裝、 Mac上pyenv的安裝與使用,復制黏貼搞定,網上教程看得眼花繚亂的來看看,簡單明了一步到胃!!

安裝 Homebrew /bin/bash -c "$(curl -fsSL https://gitee.com/ineo6/homebrew-install/raw/master/install.sh)"安裝pyenv brew install pyenv添加到終端使用的配置文件.zshrc、.bashrc 避免不必要的麻煩兩個終端的配置文件都進行添加,文件在當前用戶目…

第四十天 | 509.斐波那契數 70.爬樓梯 746.用最小花費爬樓梯

題目:509.斐波那契數 思路: 1.確定dp[i]含義:第i個斐波拉契數值為dp[i] 2.確定遞推公式:dp[i] dp[i - 1] dp[i - 2] 3.dp數組如何初始化:d[0] 1, dp[1] 1 4.遍歷順序:從前向后 5.打印dp class Soluti…

C語言代碼文件開頭需要的代碼

#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h>

淚目!網絡連接中斷的原因,終于找到了!

朋友們&#xff0c;出大事了&#xff01; 不知道多少朋友玩過 DNF 這個游戲&#xff0c;這個我從小學玩到大學的 “破” 游戲&#xff0c;昨天竟然出手游了&#xff01; 我都忘了自己曾幾何時預約過這個手游通知&#xff0c;昨天給我發了條通知信息說游戲已開服。 老玩家直接…

Gitee好用的瀏覽器插件【GiteeTree】

使用gitee的時候&#xff0c;可能拉到別人的項目后&#xff0c;只是想看下某些文件的代碼&#xff0c;但是不得不全部都拉下來&#xff0c;每次點又很麻煩。這個插件【GiteeTree】就很好用了&#xff0c;只需要搜索GiteeTree&#xff0c;然后把插件下載下來

git revert 和 git reset

文章目錄 工作區 暫存區 本地倉庫 遠程倉庫需求&#xff1a;已推送到遠程倉庫&#xff0c;想要撤銷操作git revert &#xff08;添加新的提交來“反做”之前的更改&#xff0c;云端會殘留上次的提交記錄&#xff09;git reset&#xff08;相當于覆蓋上次的提交&#xff09;1.--…