运行YOLOv8训练代码时遭遇多进程RuntimeError问题求助
解决YOLOv8训练时多进程启动错误
问题场景
编写了training.py用于本地运行YOLOv8训练,代码如下:
from ultralytics import YOLO import torch # Create a new YOLO model from scratch model = YOLO('yolov8s.yaml') # Load a pretrained YOLO model (recommended for training) #model = YOLO('yolov8n.pt') # Train the model using the 'coco128.yaml' dataset for 3 epochs results = model.train(data='D:/master_yolo/ultralytics/datasets/data.yaml', epochs=3)
错误信息
运行后触发RuntimeError:
File "c:\python\py39\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main raise RuntimeError(''' RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable.
已尝试的无效方法
曾添加如下代码,但问题未解决:
def run(): torch.multiprocessing.freeze_support() print('loop') if __name__ == '__main__': run()
正确解决方案
问题根源是Windows系统多进程采用spawn模式,会重新导入主脚本,全局执行的训练代码会重复初始化进程,触发错误。需把所有训练逻辑放到if __name__ == '__main__':保护的区域内,确保只有主进程执行核心逻辑。
修改后的完整代码:
from ultralytics import YOLO import torch def train_model(): # 从配置文件创建新模型 model = YOLO('yolov8s.yaml') # 可选:加载预训练模型(训练推荐用这个) # model = YOLO('yolov8n.pt') # 启动训练 results = model.train(data='D:/master_yolo/ultralytics/datasets/data.yaml', epochs=3) if __name__ == '__main__': # Windows环境下需添加该行,非Windows可省略 torch.multiprocessing.freeze_support() train_model()
关键说明
- 所有涉及模型初始化、训练的代码必须放在
if __name__ == '__main__':块内或其调用的函数中,避免子进程重复执行全局代码 freeze_support()仅在Windows环境下需要,非Windows系统可以直接移除该行
内容的提问来源于stack exchange,提问作者Lim Chin Hong
相关产品推荐
相关产品推荐

