当前位置:   article > 正文

微调Llama3实现在线搜索引擎和RAG检索增强生成功能_llama3 在线搜索

llama3 在线搜索

视频中所出现的代码 Tavily Search+RAG

微调Llama3实现在线搜索引擎和RAG检索增强生成功能!打造自己的perplexity和GPTs!用PDF实现本地知识库_哔哩哔哩_bilibili

Llama3高级定制:在线搜索与RAG检索增强,打造你的专属perplexity和GPTs知识库! - 大模型知识库|大模型训练|开箱即用的企业大模型应用平台|智能体开发|53AI

一.准备工作

1.安装环境

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

 2.微调代码(要先登录一下)

huggingface-cli login

点击提示的网页获取token(注意要选择可写的)

  1. #dataset https://huggingface.co/datasets/shibing624/alpaca-zh/viewer
  2. from unsloth import FastLanguageModel
  3. import torch
  4. from trl import SFTTrainer
  5. from transformers import TrainingArguments
  6. max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
  7. dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
  8. load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
  9. # 4bit pre quantized models we support for 4x faster downloading + no OOMs.
  10. fourbit_models = [
  11. "unsloth/mistral-7b-bnb-4bit",
  12. "unsloth/mistral-7b-instruct-v0.2-bnb-4bit",
  13. "unsloth/llama-2-7b-bnb-4bit",
  14. "unsloth/gemma-7b-bnb-4bit",
  15. "unsloth/gemma-7b-it-bnb-4bit", # Instruct version of Gemma 7b
  16. "unsloth/gemma-2b-bnb-4bit",
  17. "unsloth/gemma-2b-it-bnb-4bit", # Instruct version of Gemma 2b
  18. "unsloth/llama-3-8b-bnb-4bit", # [NEW] 15 Trillion token Llama-3
  19. ] # More models at https://huggingface.co/unsloth
  20. model, tokenizer = FastLanguageModel.from_pretrained(
  21. model_name = "unsloth/llama-3-8b-bnb-4bit",
  22. max_seq_length = max_seq_length,
  23. dtype = dtype,
  24. load_in_4bit = load_in_4bit,
  25. # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
  26. )
  27. model = FastLanguageModel.get_peft_model(
  28. model,
  29. r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
  30. target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
  31. "gate_proj", "up_proj", "down_proj",],
  32. lora_alpha = 16,
  33. lora_dropout = 0, # Supports any, but = 0 is optimized
  34. bias = "none", # Supports any, but = "none" is optimized
  35. # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
  36. use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
  37. random_state = 3407,
  38. use_rslora = False, # We support rank stabilized LoRA
  39. loftq_config = None, # And LoftQ
  40. )
  41. 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.
  42. ### Instruction:
  43. {}
  44. ### Input:
  45. {}
  46. ### Response:
  47. {}"""
  48. EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
  49. def formatting_prompts_func(examples):
  50. instructions = examples["instruction"]
  51. inputs = examples["input"]
  52. outputs = examples["output"]
  53. texts = []
  54. for instruction, input, output in zip(instructions, inputs, outputs):
  55. # Must add EOS_TOKEN, otherwise your generation will go on forever!
  56. text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
  57. texts.append(text)
  58. return { "text" : texts, }
  59. pass
  60. from datasets import load_dataset
  61. #file_path = "/home/Ubuntu/alpaca_gpt4_data_zh.json"
  62. #dataset = load_dataset("json", data_files={"train": file_path}, split="train")
  63. dataset = load_dataset("yahma/alpaca-cleaned", split = "train")
  64. dataset = dataset.map(formatting_prompts_func, batched = True,)
  65. trainer = SFTTrainer(
  66. model = model,
  67. tokenizer = tokenizer,
  68. train_dataset = dataset,
  69. dataset_text_field = "text",
  70. max_seq_length = max_seq_length,
  71. dataset_num_proc = 2,
  72. packing = False, # Can make training 5x faster for short sequences.
  73. args = TrainingArguments(
  74. per_device_train_batch_size = 2,
  75. gradient_accumulation_steps = 4,
  76. warmup_steps = 5,
  77. max_steps = 60,
  78. learning_rate = 2e-4,
  79. fp16 = not torch.cuda.is_bf16_supported(),
  80. bf16 = torch.cuda.is_bf16_supported(),
  81. logging_steps = 1,
  82. optim = "adamw_8bit",
  83. weight_decay = 0.01,
  84. lr_scheduler_type = "linear",
  85. seed = 3407,
  86. output_dir = "outputs",
  87. ),
  88. )
  89. trainer_stats = trainer.train()
  90. model.save_pretrained_gguf("llama3", tokenizer, quantization_method = "q4_k_m")
  91. model.save_pretrained_gguf("llama3", tokenizer, quantization_method = "q8_0")
  92. model.save_pretrained_gguf("llama3", tokenizer, quantization_method = "f16")
  93. #to hugging face
  94. model.push_to_hub_gguf("leo009/llama3", tokenizer, quantization_method = "q4_k_m")
  95. model.push_to_hub_gguf("leo009/llama3", tokenizer, quantization_method = "q8_0")
  96. 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

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

二.实现在线搜索

1.获取Tavily AI API 

Tavily AI

export TAVILY_API_KEY=tvly-xxxxxxxxxxx

 2.安装对应的python库

install tavily-python

pip install phidata

pip install ollam

3.运行app.py

  1. #app.py
  2. import warnings
  3. # Suppress only the specific NotOpenSSLWarning
  4. warnings.filterwarnings("ignore", message="urllib3 v2 only supports OpenSSL 1.1.1+")
  5. from phi.assistant import Assistant
  6. from phi.llm.ollama import OllamaTools
  7. from phi.tools.tavily import TavilyTools
  8. # 创建一个Assistant实例,配置其使用OllamaTools中的llama3模型,并整合Tavily工具
  9. assistant = Assistant(
  10. llm=OllamaTools(model="mymodel3"), # 使用OllamaTools的llama3模型
  11. tools=[TavilyTools()],
  12. show_tool_calls=True, # 设置为True以展示工具调用信息
  13. )
  14. # 使用助手实例输出请求的响应,并以Markdown格式展示结果
  15. 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里面的数组里

streamlit  run  /home/cxh/phidata/cookbook/llms/ollama/rag/assistant.py

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/945391
推荐阅读
相关标签
  

闽ICP备14008679号