问题
使用 pytorch matplotlib 等包时,Jupyter 中 Kernel 莫名内核死掉,重启。
Jupyter 显示如下:

1
2
  | Kernel Restarting
The kernel for data_op.ipynb appears to have died. It will restart automatically.
  | 
Python 终端显示如下:
1
2
3
4
5
6
7
  | (base) PS C:\temp\code> python .\test.py
qt.qpa.window: SetProcessDpiAwarenessContext() failed: Access is denied.
Qt's default DPI awareness context is DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2. If you know what you are doing, you can overwrite this default using qt.conf (https://doc.qt.io/qt-6/highdpi.html#configuring-windows).
OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
OMP: Hint This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/.
QThreadStorage: entry 1 destroyed before end of thread 0x1c347137290
QThreadStorage: entry 0 destroyed before end of thread 0x1c347137290
  | 
原因
OpenMP 运行时冲突,你的程序里加载了两个不同版本的 OpenMP 动态库 (libiomp5md.dll),这常见于以下组合之一:
| 冲突来源 | 原因 | 
|---|
PyTorch + NumPy | 两者都自带 OpenMP | 
Matplotlib + PyTorch | Qt 后端间接载入 MKL/OpenMP | 
| 你用的是 Conda 环境 + 多个 MKL 包 | 不同包加载不同版本的 libiomp5md.dll | 
解决
在代码中设置环境变量
1
2
  | import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
  | 
- 这条官方建议的**“unsafe workaround”在科研/绘图环境中几乎总是安全的**。
 - 它的作用是让多个 OpenMP 实例共存,不再报错。