Pytorch Style 标志

Pytorch Style

社区
happydog-intj
pytorch-style

PyTorch 编码风格 Skill。蒸馏自 pytorch/pytorch 源码、核心贡献者 PR review、 PyTorch 官方 Contributing Guide、Soumith Chintala 和 Adam Paszke 的设计决策记录。 触发词:「PyTorch 风格」「像 PyTorch 一样写 Python」「pytorch style」「深度学习库风格」。 适用:深度学习框架开发、科学计算库、Python + C++ 混合开发、autograd 系统。

概览

发布者happydog-intj
代码仓库luban-skill
技能名称pytorch-style
星标数
32
复刻数
3
附带文件
仅含指令
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 happydog-intj 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Pytorch Style AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/happydog-intj/luban-skill/tree/master/skills/pytorch.skill
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/happydog-intj/luban-skill.git /tmp/luban-skill
mkdir -p .claude/skills
cp -r /tmp/luban-skill/skills/pytorch.skill .claude/skills/pytorch-style
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Pytorch Style,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Pytorch Style。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Pytorch Style 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

PyTorch · 编码 DNA

"PyTorch is designed to be Pythonic first. If it feels awkward in Python, it's wrong." — Soumith Chintala

角色定义

此 Skill 激活后,你写出的代码应该让 PyTorch 核心 contributor 在 PR review 时感觉 「这代码是从 PyTorch 里长出来的」,而不是「这是 TensorFlow 代码转译过来的」。

这意味着:Pythonic 优先、API 直觉、数学意图显式。


命名 DNA

5 条直觉规则:

  1. snake_case 统治一切,类名用 PascalCase

    python
    # ✅
    class LinearLayer(nn.Module):
        def forward(self, input: Tensor) -> Tensor: ...
    
    def batch_norm(input, weight, bias, ...): ...
    
    # ❌
    class linearLayer(nn.Module): ...
    def batchNorm(input, weight, bias, ...): ...
  2. Tensor 参数统一叫 input,输出叫 output(或语义名)

    python
    # ✅ — 和数学符号对齐
    def relu(input: Tensor, inplace: bool = False) -> Tensor: ...
    def conv2d(input, weight, bias=None, stride=1, ...): ...
    
    # ❌ — 自造名字破坏一致性
    def relu(x: Tensor) -> Tensor: ...
    def conv2d(tensor, kernel, ...): ...
  3. 布尔参数名用 is_ 或语义形容词,不用动词

    python
    # ✅
    inplace: bool = False
    requires_grad: bool = True
    pin_memory: bool = False
    
    # ❌
    do_inplace: bool = False
    enable_grad: bool = True
  4. 私有方法 _ 前缀,C++ 绑定方法 _C. 前缀

    python
    class Tensor:
        def _make_subclass(cls, ...): ...        # 内部 Python
        def sum(self): return torch._C._sum(self)  # C++ 绑定
  5. 数学符号在 docstring 里用 LaTeX,变量名尽量贴近论文符号

    python
    def scaled_dot_product_attention(
        query: Tensor,   # Q 矩阵
        key: Tensor,     # K 矩阵
        value: Tensor,   # V 矩阵
    ) -> Tensor:
        r"""
        Computes scaled dot product attention:
        :math:`\text{Attention}(Q, K, V) = \text{softmax}(\frac{QK^T}{\sqrt{d_k}})V`
        """

结构偏好

nn.Module 设计哲学:

python
# ✅ 标准 Module 结构
class MultiHeadAttention(nn.Module):
    def __init__(
        self,
        embed_dim: int,
        num_heads: int,
        dropout: float = 0.0,
        bias: bool = True,
        *,              # keyword-only 参数分隔
        batch_first: bool = False,
    ) -> None:
        super().__init__()
        # 1. 保存超参数
        self.embed_dim = embed_dim
        self.num_heads = num_heads
        # 2. 定义子模块
        self.out_proj = NonDynamicallyQuantizableLinear(embed_dim, embed_dim, bias=bias)
        # 3. 初始化权重
        self._reset_parameters()

    def _reset_parameters(self) -> None:
        """初始化逻辑单独抽出,方便子类覆盖"""
        nn.init.xavier_uniform_(self.out_proj.weight)

    def forward(
        self,
        query: Tensor,
        key: Tensor,
        value: Tensor,
    ) -> tuple[Tensor, Tensor | None]:
        ...

functional vs Module 的选择:

  • nn.functional.xxx — 无状态操作,没有学习参数
  • nn.Module — 有学习参数、有状态、需要 train()/eval() 切换
  • 两者都提供:Module 内部调用 functional(PyTorch 的标准模式)
python
class Dropout(nn.Module):
    def forward(self, input: Tensor) -> Tensor:
        return F.dropout(input, self.p, self.training, self.inplace)  # Module 调 functional

类型注解:

  • 所有公开 API 必须有完整类型注解
  • 用 Tensor(不是 torch.Tensor),已导入
  • 可选参数用 X | None(Python 3.10+ 风格)或 Optional[X]
  • 返回类型永远标注,即使是 None

注释哲学

docstring 是 API 的一部分,和代码同等重要:

python
def embedding(
    input: Tensor,
    weight: Tensor,
    padding_idx: int | None = None,
    ...
) -> Tensor:
    r"""A simple lookup table that stores embeddings of a fixed dictionary and size.

    This module is often used to store word embeddings and retrieve them using indices.
    The input to the module is a list of indices, and the output is the corresponding
    word embeddings.

    Args:
        input (Tensor): LongTensor of arbitrary shape containing the indices to extract
        weight (Tensor): Float tensor of shape `(num_embeddings, embedding_dim)`
        padding_idx (int, optional): If specified, entries at :attr:`padding_idx` do
            not contribute to the gradient

    Returns:
        Tensor: of shape `(*input.shape, embedding_dim)`

    Example::

        >>> # Example of embedding usage
        >>> embedding_matrix = torch.randn(10, 3)
        >>> input = torch.LongTensor([[1, 2, 4, 5], [4, 3, 2, 9]])
        >>> F.embedding(input, embedding_matrix)
    """

注释规范:

  • r""" 前缀(raw string)保留 LaTeX 反斜杠
  • Args/Returns/Raises/Example 四段固定结构
  • 数学公式用 :math:...`` 内联,或 .. math:: 块
  • # type: ignore 注释要说明原因

反模式(绝不这样写)

  1. 用 *args/**kwargs 吞掉所有参数 — 公开 API 必须显式签名

    python
    # ❌
    def conv2d(*args, **kwargs): ...
    # ✅
    def conv2d(input, weight, bias=None, stride=1, padding=0, ...): ...
  2. eager 模式里写 graph-style 代码 — 不要假设用户在 torch.jit.script 里

  3. 直接 .data 访问绕过 autograd — 除非明确知道在做什么,不然是 bug

    python
    # ❌ 危险,切断梯度追踪
    x.data = new_value
    # ✅
    with torch.no_grad():
        x.copy_(new_value)
  4. inplace 操作不加 _ 后缀 — PyTorch 约定:inplace 版本用 _ 结尾

    python
    x.add_(1)    # ✅ inplace,有下划线
    y = x.add(1) # ✅ 非 inplace,无下划线
    x.add(1)     # ❌ 不 inplace 却叫 add,令人困惑
  5. 不检查 device 一致性 — 多 GPU 环境是常态

    python
    # ✅
    if query.device != key.device:
        raise ValueError(f"query and key must be on the same device, "
                         f"got {query.device} and {key.device}")
  6. 魔法维度假设 — 不注释 Tensor shape

    python
    # ❌
    attn = torch.bmm(q, k.transpose(-2, -1))
    # ✅
    # q: (batch, seq, head_dim), k: (batch, seq, head_dim)
    # attn: (batch, seq, seq)
    attn = torch.bmm(q, k.transpose(-2, -1))

校验测试

  1. Pythonic 测试:把这个 API 给一个熟悉 NumPy 的研究员看,他 10 秒内能猜出怎么用吗?
  2. Shape 注释:每个关键 Tensor 操作有没有注释输入/输出 shape?
  3. inplace 一致性:所有 inplace 操作都以 _ 结尾了吗?

来源

  • pytorch/pytorch 源码(torch/nn/、torch/functional.py)
  • PyTorch Contributing Guide
  • Soumith Chintala 的 PyTorch 设计哲学演讲(NeurIPS 2019)
  • Adam Paszke 博士论文:Automatic Differentiation in PyTorch

常见问题

Pytorch Style AI 技能有什么作用?

PyTorch 编码风格 Skill。蒸馏自 pytorch/pytorch 源码、核心贡献者 PR review、 PyTorch 官方 Contributing Guide、Soumith Chintala 和 Adam Paszke 的设计决策记录。 触发词:「PyTorch 风格」「像 PyTorch 一样写 Python」「pytorch style」「深度学习库风格」。 适用:深度学习框架开发、科学计算库、Python + C++ 混合开发、autograd 系统。

为什么在 TypingMind 中使用 Pytorch Style?

因为您只需安装一次,就能搭配任何模型使用。Pytorch Style 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Pytorch Style?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/happydog-intj/luban-skill/tree/master/skills/pytorch.skill。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Pytorch Style?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Pytorch Style 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Pytorch Style 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Pytorch Style AI 技能免费吗?

happydog-intj 已在 GitHub 上发布了该技能。请查看代码仓库了解许可条款。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇