Create App.py
Browse files
App.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 导入必要的库
|
2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
+
|
4 |
+
# 加载预训练模型的分词器
|
5 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
|
6 |
+
|
7 |
+
# 加载预训练的模型
|
8 |
+
# 使用 device_map 参数将模型自动加载到可用的硬件设备上,例如GPU
|
9 |
+
model = AutoModelForCausalLM.from_pretrained(
|
10 |
+
"meta-llama/Llama-2-7b-chat-hf",
|
11 |
+
device_map = 'auto')
|
12 |
+
|
13 |
+
# 定义一个提示,希望模型基于此提示生成故事
|
14 |
+
prompt = "请给我讲个玫瑰的爱情故事?"
|
15 |
+
|
16 |
+
# 使用分词器将提示转化为模型可以理解的格式,并将其移动到GPU上
|
17 |
+
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
|
18 |
+
|
19 |
+
# 使用模型生成文本,设置最大生成令牌数为2000
|
20 |
+
outputs = model.generate(inputs["input_ids"], max_new_tokens=2000)
|
21 |
+
|
22 |
+
# 将生成的令牌解码成文本,并跳过任何特殊的令牌,例如[CLS], [SEP]等
|
23 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
24 |
+
|
25 |
+
# 打印生成的响应
|
26 |
+
print(response)
|