woywan commited on
Commit
78078d8
·
verified ·
1 Parent(s): e281b23

Update pretrain_inference.py

Browse files
Files changed (1) hide show
  1. pretrain_inference.py +51 -4
pretrain_inference.py CHANGED
@@ -2,6 +2,7 @@ import torch
2
  import torch.nn.functional as F
3
  from tokenizers import Tokenizer
4
  from novel_model import NovelTransformer
 
5
 
6
  # 配置参数
7
  VOCAB_SIZE = 8000
@@ -11,7 +12,7 @@ NUM_LAYERS = 4
11
  DIM_FEEDFORWARD = 512
12
  DROPOUT = 0.1
13
  MAX_LEN = 4096
14
- MODEL_PATH = "./novel_model/best_model.pt"
15
  TOKENIZER_PATH = "./novel_tokenizer.json"
16
 
17
  def generate_text(model, tokenizer, prompt, max_length=100, temperature=0.8, top_k=50, top_p=0.9, device="cuda"):
@@ -65,6 +66,26 @@ def generate_text(model, tokenizer, prompt, max_length=100, temperature=0.8, top
65
  output = tokenizer.decode(input_ids[0].tolist())
66
  return output
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  def main():
69
  # 设置设备
70
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@@ -79,9 +100,25 @@ def main():
79
  # 加载分词器
80
  tokenizer = Tokenizer.from_file(TOKENIZER_PATH)
81
 
82
- # 加载模型
83
- checkpoint = torch.load(MODEL_PATH, map_location=device)
 
 
 
 
 
 
84
 
 
 
 
 
 
 
 
 
 
 
85
  model = NovelTransformer(
86
  vocab_size=VOCAB_SIZE,
87
  d_model=D_MODEL,
@@ -92,7 +129,17 @@ def main():
92
  max_len=MAX_LEN
93
  )
94
 
95
- model.load_state_dict(checkpoint['model_state_dict'])
 
 
 
 
 
 
 
 
 
 
96
  model = model.to(device)
97
 
98
  # 设置为评估模式
 
2
  import torch.nn.functional as F
3
  from tokenizers import Tokenizer
4
  from novel_model import NovelTransformer
5
+ import os
6
 
7
  # 配置参数
8
  VOCAB_SIZE = 8000
 
12
  DIM_FEEDFORWARD = 512
13
  DROPOUT = 0.1
14
  MAX_LEN = 4096
15
+ MODEL_PATH = "./novel_model_cuda/best_model.pt" # 修改为CUDA模型路径
16
  TOKENIZER_PATH = "./novel_tokenizer.json"
17
 
18
  def generate_text(model, tokenizer, prompt, max_length=100, temperature=0.8, top_k=50, top_p=0.9, device="cuda"):
 
66
  output = tokenizer.decode(input_ids[0].tolist())
67
  return output
68
 
69
+ def load_model_safely(model_path, device):
70
+ """安全加载模型,处理设备不兼容的情况"""
71
+ try:
72
+ print(f"尝试加载模型: {model_path}")
73
+ # 使用map_location参数确保模型加载到正确的设备
74
+ checkpoint = torch.load(model_path, map_location=device)
75
+ return checkpoint
76
+ except (AssertionError, RuntimeError) as e:
77
+ print(f"加载模型时出错: {e}")
78
+ print("这可能是因为模型是在不同的设备上保存的(如Intel HPU)")
79
+
80
+ # 尝试使用CPU作为中间设备
81
+ try:
82
+ print("尝试通过CPU加载模型...")
83
+ checkpoint = torch.load(model_path, map_location="cpu")
84
+ return checkpoint
85
+ except Exception as e2:
86
+ print(f"通过CPU加载失败: {e2}")
87
+ return None
88
+
89
  def main():
90
  # 设置设备
91
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
100
  # 加载分词器
101
  tokenizer = Tokenizer.from_file(TOKENIZER_PATH)
102
 
103
+ # 尝试加载模型
104
+ model_loaded = False
105
+
106
+ # 首先尝试加载CUDA模型
107
+ if os.path.exists(MODEL_PATH):
108
+ checkpoint = load_model_safely(MODEL_PATH, device)
109
+ if checkpoint is not None:
110
+ model_loaded = True
111
 
112
+ # 如果CUDA模型加载失败,尝试加载原始模型
113
+ if not model_loaded:
114
+ original_model_path = "d:/图像/novel_model/best_model.pt"
115
+ if os.path.exists(original_model_path):
116
+ print(f"尝试加载原始模型: {original_model_path}")
117
+ checkpoint = load_model_safely(original_model_path, device)
118
+ if checkpoint is not None:
119
+ model_loaded = True
120
+
121
+ # 创建模型
122
  model = NovelTransformer(
123
  vocab_size=VOCAB_SIZE,
124
  d_model=D_MODEL,
 
129
  max_len=MAX_LEN
130
  )
131
 
132
+ # 如果成功加载了模型,加载状态
133
+ if model_loaded and checkpoint is not None:
134
+ try:
135
+ model.load_state_dict(checkpoint['model_state_dict'])
136
+ print("模型状态加载成功")
137
+ except Exception as e:
138
+ print(f"加载模型状态时出错: {e}")
139
+ print("将使用未训练的模型")
140
+ else:
141
+ print("无法加载任何模型,将使用未训练的模型")
142
+
143
  model = model.to(device)
144
 
145
  # 设置为评估模式