File size: 1,622 Bytes
fd45282
75ecc06
 
fd45282
c0ba1b5
75ecc06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
import torch

model_id = "deepseek-ai/deepseek-coder-1.3b-base"
lora_id = "Seunggg/lora-plant"

# 加载 tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)

# 加载基础模型,启用自动设备分配并脱载
base = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map="auto",
    offload_folder="offload/",
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    trust_remote_code=True
)

# 加载 LoRA adapter,同样启用脱载
model = PeftModel.from_pretrained(
    base,
    lora_id,
    offload_folder="offload/",
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
)

model.eval()

# 生成 pipeline
from transformers import pipeline
pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    device_map="auto",
    max_new_tokens=256
)

def respond(user_input):
    if not user_input.strip():
        return "请输入植物相关的问题 :)"
    prompt = f"用户提问:{user_input}\n请用更人性化的语言生成建议,并推荐相关植物文献或资料。\n回答:"
    result = pipe(prompt)
    return result[0]["generated_text"]

# Gradio 界面
gr.Interface(
    fn=respond,
    inputs=gr.Textbox(lines=4, placeholder="在这里输入你的植物问题..."),
    outputs="text",
    title="🌱 植物助手 LoRA 版",
    description="基于 DeepSeek 微调模型,提供植物养护建议和文献推荐。",
    allow_flagging="never"
).launch()