使用Papermill运行Sagemaker Studio Notebook遇NoSuchKernel错误求解决
问题解决与替代方案
一、Papermill NoSuchKernel 错误解决办法
- 先确认目标Notebook指定的内核名称和当前Studio环境里的内核完全一致。Sagemaker Studio的内核名一般是
conda_<环境名>格式,比如conda_python3,运行jupyter kernelspec list就能看到所有可用内核,Papermill调用时的--kernel参数必须和输出的名称完全匹配。 - 如果目标Notebook是自定义环境创建的,得先在当前运行Papermill的Notebook实例里激活对应环境,或者把该环境的内核注册到Jupyter。先执行
conda activate <环境名>激活环境,再跑python -m ipykernel install --user --name <内核名>完成注册。 - 别用Studio界面显示的友好名称(比如“Data Science”),必须用
jupyter kernelspec list输出的实际标识符。
二、sagemaker-run-notebook 安装连接错误解决办法
- 换国内PyPI镜像源安装,比如执行
pip install sagemaker-run-notebook -i https://pypi.tuna.tsinghua.edu.cn/simple,绕开网络连接问题。 - 检查当前Notebook实例的网络权限,如果是VPC内的实例,确保安全组和NACL配置允许出站访问PyPI的443端口。
- 要是镜像源还是不行,直接从GitHub下载sagemaker-run-notebook的源码包,然后用
pip install <本地包路径>做离线安装。
三、替代方案
1. Sagemaker Processing Jobs
把Notebook转成Python脚本,再用Processing Job运行:
- 执行
jupyter nbconvert --to script target_notebook.ipynb把Notebook转成脚本。 - 编写Processing Job代码,示例如下:
import sagemaker from sagemaker.processing import ScriptProcessor, ProcessingInput, ProcessingOutput processor = ScriptProcessor( command=['python3'], image_uri='763104351884.dkr.ecr.us-east-1.amazonaws.com/pytorch-training:2.0.0-gpu-py310', role=sagemaker.get_execution_role(), instance_count=1, instance_type='ml.t3.medium' ) processor.run( code='target_script.py', inputs=[ProcessingInput(source='s3://your-bucket/data/', destination='/opt/ml/processing/input')], outputs=[ProcessingOutput(source='/opt/ml/processing/output', destination='s3://your-bucket/output/')] )
2. Sagemaker Studio Pipelines
把Notebook作为Pipeline的一个步骤,用SageMakerNotebookStep运行,还能编排工作流:
from sagemaker.workflow.steps import NotebookStep from sagemaker.workflow.pipeline import Pipeline notebook_step = NotebookStep( name='RunTargetNotebook', notebook_path='target_notebook.ipynb', instance_type='ml.t3.medium', role=sagemaker.get_execution_role(), kernel_name='conda_python3' ) pipeline = Pipeline( name='NotebookExecutionPipeline', steps=[notebook_step] ) pipeline.upsert(role_arn=sagemaker.get_execution_role()) execution = pipeline.start()
3. Jupyter nbclient 直接执行
用nbclient库直接跑Notebook代码,不用依赖Papermill的内核指定:
from nbclient import NotebookClient from nbformat import read, write with open('target_notebook.ipynb', 'r') as f: nb = read(f, as_version=4) client = NotebookClient(nb, timeout=600, kernel_name='conda_python3') client.execute() # 保存执行后的Notebook with open('executed_notebook.ipynb', 'w') as f: write(nb, f)
内容的提问来源于stack exchange,提问作者Tim Connor
相关产品推荐
相关产品推荐

