Community编程与开发github.com

pytorch/metal-kernel

为PyTorch算子编写Metal/MPS内核。用于为算子添加MPS设备支持、实现Metal着色器或移植CUDA内核到Apple Silicon。涵盖native_functions.yaml分发、宿主端算子和Metal内核实现。

metal-kernel 是什么?

此技能专门用于在PyTorch中为Apple Silicon(MPS后端)编写Metal/MPS内核。对于需要将现有CUDA内核移植到Apple Silicon、为PyTorch算子添加MPS设备支持,或从头实现自定义Metal着色器的开发者来说,它非常有用。该技能指导你完成三个主要步骤:在`native_functions.yaml`中配置分发(以将算子映射到MPS设备)、实现宿主端C++算子(利用MPS流和调度),以及编写Metal着色器本身。它适用于Claude Code、Cursor和Codex等工具,提供Metal着色器语言(MSL)模板和最佳实践,确保高效利用MPS图、张量存储和张量形状。该技能包含处理对象类型(如`MTLBuffer`、`MTLComputeCommandEncoder`)和将PyTorch张量映射到Metal缓冲区的详细说明,同时强调性能注意事项,如避免不必要的内存拷贝和优化线程组大小。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/pytorch/pytorch/tree/main/skills/metal-kernel

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

metal-kernel 是做什么的?

为PyTorch算子编写Metal/MPS内核。用于为算子添加MPS设备支持、实现Metal着色器或移植CUDA内核到Apple Silicon。涵盖native_functions.yaml分发、宿主端算子和Metal内核实现。

概述

此技能提供在PyTorch中为Apple Silicon的Metal Performance Shaders(MPS)后端编写Metal内核的指导。它涵盖了将CUDA内核移植到MPS、为PyTorch算子添加MPS设备支持以及实现自定义Metal着色器的完整工作流程。

适用平台

  • Claude Code
  • Cursor
  • Codex

核心步骤

1. 在native_functions.yaml中配置分发

将算子映射到MPS后端,在aten/src/ATen/native/native_functions.yaml中添加或修改分发条目:

- func: my_operator(Tensor input, ...) -> Tensor
  dispatch:
    CPU: my_operator_cpu
    CUDA: my_operator_cuda
    MPS: my_operator_mps

2. 实现宿主端算子

在aten/src/ATen/native/mps/目录下创建C++文件,实现MPS算子。使用MPS流和调度:

#include <ATen/native/mps/OperationUtils.h>

Tensor my_operator_mps(const Tensor& input, ...) {
  // 获取MPS流
  auto stream = at::mps::getCurrentMPSStream();
  
  // 创建Metal着色器
  id<MTLComputePipelineState> pso = ...;
  
  // 创建命令缓冲区并编码
  id<MTLCommandBuffer> commandBuffer = stream->commandBuffer();
  id<MTLComputeCommandEncoder> encoder = [commandBuffer computeCommandEncoder];
  
  // 设置管道状态和缓冲区
  [encoder setComputePipelineState:pso];
  [encoder setBuffer:input_buffer offset:0 atIndex:0];
  [encoder setBuffer:output_buffer offset:0 atIndex:1];
  
  // 分发线程
  [encoder dispatchThreads:MTLSizeMake(N, 1, 1)
     threadsPerThreadgroup:MTLSizeMake(threadgroup_size, 1, 1)];
  [encoder endEncoding];
  
  // 提交并等待
  [commandBuffer commit];
  [commandBuffer waitUntilCompleted];
  
  return output;
}

3. 编写Metal着色器

在aten/src/ATen/native/mps/目录下的Metal着色器文件(.metal)中实现内核:

#include <metal_stdlib>
using namespace metal;

kernel void my_operator_kernel(
    device const float* input [[buffer(0)]],
    device float* output [[buffer(1)]],
    uint index [[thread_position_in_grid]])
{
    output[index] = input[index] * 2.0;
}

最佳实践

  • 利用MPS图:尽可能使用MPS图(MPSGraph)来优化性能。
  • 高效管理张量存储:使用mps::getMTLBufferStorage从PyTorch张量获取底层MTLBuffer。
  • 处理张量形状:通过mps::MPSShape传递正确的形状信息。
  • 优化线程组大小:让threadsPerThreadgroup是线程组执行宽度的倍数(通常为32或64的倍数)。
  • 避免不必要的内存拷贝:使用[commandBuffer addCompletedHandler:...]进行异步处理。

常见问题

  • 着色器编译失败:确保Metal着色器文件在Xcode项目中正确编译。
  • 张量类型不匹配:检查输入张量的数据类型是否与着色器期望的类型匹配。
  • 性能问题:使用Xcode的性能分析工具(Instruments)分析Metal着色器性能。

参考资源


使用此技能需对PyTorch内部原理、Metal着色器语言(MSL)和Apple Silicon架构有基本了解。

Individual skills in this repo

This repo contains 8 individual skills — each has its own dedicated page.

pytorch/add-uint-support

Add unsigned integer (uint) type support to PyTorch operators by updating AT_DISPATCH macros. Use when adding support for uint16, uint32, uint64 types to operators, kernels, or when user mentions enabling unsigned types, barebones unsigned types, or uint support.

pytorch/aoti-debug

Debug AOTInductor (AOTI) errors and crashes. Use when encountering AOTI segfaults, device mismatch errors, constant loading failures, or runtime errors from aot_compile, aot_load, aoti_compile_and_package, or aoti_load_package.

pytorch/at-dispatch-v2

Convert PyTorch AT_DISPATCH macros to AT_DISPATCH_V2 format in ATen C++ code. Use when porting AT_DISPATCH_ALL_TYPES_AND*, AT_DISPATCH_FLOATING_TYPES*, or other dispatch macros to the new v2 API. For ATen kernel files, CUDA kernels, and native operator implementations.

pytorch/docstring

Write docstrings for PyTorch functions and methods following PyTorch conventions. Use when writing or updating docstrings in PyTorch code.

pytorch/pr-review

Review PyTorch pull requests for code quality, test coverage, security, and backward compatibility. Use when reviewing PRs, when asked to review code changes, or when the user mentions "review PR", "code review", or "check this PR".

pytorch/pyrefly-type-coverage

Migrate a file to use stricter Pyrefly type checking with annotations required for all functions, classes, and attributes.

pytorch/skill-writer

Guide users through creating Agent Skills for Claude Code. Use when the user wants to create, write, author, or design a new Skill, or needs help with SKILL.md files, frontmatter, or skill structure.

pytorch/triaging-issues

Triages GitHub issues by routing to oncall teams, applying labels, and closing questions. Use when processing new PyTorch issues or when asked to triage an issue.

相关技能