SimpleTransformers模型本地IDE运行报错,Colab正常问题求助
问题排查与解决
问题现象
- 使用SimpleTransformers构建的BERT分类模型在Google Colab可正常运行,但在本地Spyder/Visual Studio中执行时触发多进程相关的RuntimeError,错误提示为:
An attempt has been made to start a new process before the current process has finished its bootstrapping phase.
错误原因
Windows系统下Python多进程采用spawn启动方式,要求所有会触发子进程的代码必须放在if __name__ == '__main__':代码块内。原代码中模型初始化、预测逻辑直接写在全局作用域,当子进程启动时会重新执行全局代码,导致重复初始化模型并再次创建子进程,引发冲突。
修正方案
将模型初始化、预测等核心逻辑全部移至if __name__ == '__main__':对应的代码块内,确保子进程启动时不会重复执行这些逻辑。同时保留torch.multiprocessing.freeze_support()(Windows环境下推荐添加,避免打包成可执行文件时出问题)。
修正后的代码
from simpletransformers.classification import ClassificationModel import torch def run(): torch.multiprocessing.freeze_support() # 模型初始化与预测逻辑移至此处 Bert_model = ClassificationModel("bert", "bert_model") a = Bert_model.predict(["kötü"]) print(a) print('loop') if __name__ == '__main__': run()
额外说明
- 关于
cudart64_110.dll not found的警告:如果本地没有GPU,可忽略该提示,不影响CPU运行模型。 - 若仍有问题,可在初始化模型时显式指定
process_count=1关闭多进程:Bert_model = ClassificationModel("bert", "bert_model", args={"process_count": 1})
内容的提问来源于stack exchange,提问作者Gokhan Basaran
相关产品推荐
相关产品推荐

