forked from 27182812/ChatGLM-LLaMA-chinese-insturct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfer.py
executable file
·62 lines (51 loc) · 1.95 KB
/
infer.py
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
59
60
61
62
import torch
from transformers import AutoTokenizer
from peft import get_peft_model, LoraConfig, TaskType
import json
from modeling_chatglm import ChatGLMForConditionalGeneration
from dataprocess import format_example
torch.set_default_tensor_type(torch.cuda.HalfTensor)
model = ChatGLMForConditionalGeneration.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True, device_map='auto')
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
peft_path = "output_zh-data01/chatglm-lora.pt"
peft_config = LoraConfig(
task_type=TaskType.CAUSAL_LM, inference_mode=True,
r=8,
lora_alpha=32, lora_dropout=0.1,
)
model = get_peft_model(model, peft_config)
model.load_state_dict(torch.load(peft_path), strict=False)
torch.set_default_tensor_type(torch.cuda.FloatTensor)
instructions = json.load(open("data/zh-data01.json"))
answers = []
with torch.no_grad():
for idx, item in enumerate(instructions[12:18]):
feature = format_example(item)
input_text = feature['context']
print(input_text)
ids = tokenizer.encode(input_text)
input_ids = torch.LongTensor([ids]).to('cuda')
out = model.generate(
input_ids=input_ids,
max_length=150,
do_sample=False,
temperature=0
)
out_text = tokenizer.decode(out[0])
answer = out_text.replace(input_text, "").replace("\nEND", "").strip()
item['infer_answer'] = answer
print(answer)
# print(f"### {idx+1}.Answer:\n", item.get('output'), '\n\n')
answers.append({'index': idx, **item})
# while True:
# input_text = input()
# ids = tokenizer.encode(input_text)
# input_ids = torch.LongTensor([ids])
# out = model.generate(
# input_ids=input_ids,
# max_length=150,
# do_sample=False,
# temperature=0
# )
# out_text = tokenizer.decode(out[0])
# print(out_text)