Token导航 LogoToken导航

Agent Skill · 开发

pytorch-model-recovery(PyTorch 模型恢复)

pytorch-model-recovery 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

pytorch-model-recovery 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证为 MIT,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 13,983。

总安装 776周安装 33GitHub Stars 93下载 272核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:pytorch-model-recovery(PyTorch 模型恢复)
来源仓库:https://github.com/letta-ai/skills
仓库路径:skills/pytorch-model-recovery
安装命令:
npx skills add https://github.com/letta-ai/skills --skill pytorch-model-recovery
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/letta-ai/skills --skill pytorch-model-recovery

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。适合围绕仓库状态、代码变更或协作事项进行整理和分析。可结合来源仓库和原始 README 核验具体用法,确保功能匹配需求。安装方式:通过 npx skills add 从指定 GitHub 仓库添加。

安装前建议确认权限范围和是否会触发联网或文件读写操作。

来源仓库内路径:skills/pytorch-model-recovery

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/letta-ai/skills --skill pytorch-model-recovery;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

pytorch-model-recovery 怎么安装?

在终端执行 npx skills add https://github.com/letta-ai/skills --skill pytorch-model-recovery。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

pytorch-model-recovery 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

pytorch-model-recovery 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

pytorch-model-recovery 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

pytorch-model-recovery 用的人多吗?

公开数据是累计安装 776 次,近一周安装 33 次,下载 272 次,GitHub 93 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

pytorch-model-recovery 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。
  • 需要许可证清楚、并且有第三方扫描结果的团队项目。

不太适合

  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
pytorch-model-recovery

PyTorch 模型恢复 · 本页

77693需要联网MIT通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

PyTorch Model Recovery

This skill provides guidance for tasks involving PyTorch model architecture recovery from state dictionaries, selective layer training, and TorchScript export.

When to Use This Skill

This skill applies when:

  • Reconstructing a model architecture from a state dictionary (.pt or .pth file containing weights)
  • Training or fine-tuning specific layers while keeping others frozen
  • Converting a recovered model to TorchScript format
  • Debugging model loading issues or architecture mismatches

Approach Overview

Model recovery tasks require a systematic, incremental approach with verification at each step. The key phases are:

  1. Architecture Analysis - Infer model structure from state dictionary keys
  2. Architecture Implementation - Build the model class to match the state dict
  3. Verification - Confirm weights load correctly before any training
  4. Training - Fine-tune specific layers with appropriate hyperparameters
  5. Export - Save to required format (often TorchScript)

Phase 1: Architecture Analysis

Examining the State Dictionary

To understand the model architecture, first load and inspect the state dictionary:

import torch

weights = torch.load('model_weights.pt', map_location='cpu')

# Print all keys with shapes
for key, value in weights.items():
    print(f"{key}: {value.shape}")

Key Patterns to Identify

Common patterns in state dictionary keys:

Key PatternIndicates
encoder.layers.N.*Transformer encoder with N+1 layers
decoder.layers.N.*Transformer decoder with N+1 layers
embedding.weightEmbedding layer
pos_encoder.pePositional encoding (often a buffer)
output_layer.weight/biasFinal linear projection
*.in_proj_weightCombined QKV projection in attention
*.self_attn.*Self-attention component
*.linear1/linear2.*Feed-forward network layers
*.norm1/norm2.*Layer normalization

Inferring Dimensions

Extract model dimensions from weight shapes:

# Example: Inferring transformer dimensions
d_model = weights['encoder.layers.0.self_attn.in_proj_weight'].shape[1]
nhead = weights['encoder.layers.0.self_attn.in_proj_weight'].shape[0] // (3 * d_model) * nhead_factor
# Note: in_proj_weight has shape [3*d_model, d_model] for combined QKV

vocab_size = weights['embedding.weight'].shape[0]
num_layers = max(int(k.split('.')[2]) for k in weights if 'encoder.layers' in k) + 1

Phase 2: Architecture Implementation

Building the Model Class

When implementing the model class:

  1. Match the exact layer names used in the state dictionary
  2. Use the same PyTorch module types (e.g., nn.TransformerEncoder vs custom)
  3. Register buffers for non-learnable tensors (e.g., positional encodings)
class RecoveredModel(nn.Module):
    def __init__(self, vocab_size, d_model, nhead, num_layers, dim_feedforward):
        super().__init__()
        # Ensure attribute names match state dict keys exactly
        self.embedding = nn.Embedding(vocab_size, d_model)

        # For positional encoding stored as buffer
        self.pos_encoder = PositionalEncoding(d_model)

        encoder_layer = nn.TransformerEncoderLayer(
            d_model=d_model,
            nhead=nhead,
            dim_feedforward=dim_feedforward,
            batch_first=True  # Check if original used batch_first
        )
        self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
        self.output_layer = nn.Linear(d_model, vocab_size)

Common Architecture Mistakes

  • Incorrect layer naming: self.fc vs self.output_layer - must match exactly
  • Missing buffers: Positional encodings often registered as buffers, not parameters
  • Wrong module types: Custom attention vs nn.MultiheadAttention
  • Batch dimension mismatch: batch_first=True vs batch_first=False

Phase 3: Verification (Critical)

Verify Architecture Before Training

Always verify the model loads weights correctly before any training:

model = RecoveredModel(...)

# This will raise an error if keys don't match
model.load_state_dict(weights, strict=True)
print("Weights loaded successfully!")

# Verify a forward pass works
with torch.no_grad():
    dummy_input = torch.randint(0, vocab_size, (1, 10))
    output = model(dummy_input)
    print(f"Output shape: {output.shape}")

Handling Key Mismatches

If load_state_dict fails, compare keys:

model_keys = set(model.state_dict().keys())
weight_keys = set(weights.keys())

missing = weight_keys - model_keys
unexpected = model_keys - weight_keys

print(f"Missing in model: {missing}")
print(f"Unexpected in model: {unexpected}")

Verify TorchScript Compatibility Early

If TorchScript export is required, test it early:

# Test scripting works before investing time in training
try:
    scripted = torch.jit.script(model)
    print("TorchScript scripting successful")
except Exception as e:
    print(f"Scripting failed: {e}")
    # Try tracing instead
    traced = torch.jit.trace(model, dummy_input)
    print("TorchScript tracing successful")

Phase 4: Training Specific Layers

Freezing Layers

To train only specific layers, freeze all others:

# Freeze all parameters first
for param in model.parameters():
    param.requires_grad = False

# Unfreeze only target layers
for param in model.output_layer.parameters():
    param.requires_grad = True

# Verify freeze status
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
print(f"Trainable: {trainable:,} / {total:,} parameters")

Computing Baseline Loss

Before training, establish a baseline:

model.eval()
with torch.no_grad():
    outputs = model(inputs)
    original_loss = criterion(outputs, targets)
    print(f"Original MSE loss: {original_loss.item()}")

Training Loop Considerations

# Create optimizer only for trainable parameters
optimizer = torch.optim.Adam(
    filter(lambda p: p.requires_grad, model.parameters()),
    lr=0.001
)

# Training with progress tracking
for epoch in range(num_epochs):
    model.train()
    optimizer.zero_grad()

    outputs = model(inputs)
    loss = criterion(outputs, targets)

    loss.backward()
    optimizer.step()

    if epoch % 10 == 0:
        print(f"Epoch {epoch}: Loss = {loss.item():.6f}")

Alternative: Closed-Form Solution for Linear Layers

When retraining only a linear output layer, consider a closed-form solution for efficiency:

# Pre-compute frozen layer outputs
model.eval()
with torch.no_grad():
    # Get features before output layer
    features = model.get_features(inputs)  # Shape: [N, d_model]

# Solve linear regression: W*features = targets
# Using pseudo-inverse: W = targets @ features.T @ (features @ features.T)^-1
solution = torch.linalg.lstsq(features, targets).solution
model.output_layer.weight.data = solution.T

Phase 5: TorchScript Export

Saving the Model

# Ensure model is in eval mode
model.eval()

# Script the model (preferred for control flow)
scripted_model = torch.jit.script(model)
scripted_model.save('/app/model.pt')

# Or trace the model (for simpler models)
traced_model = torch.jit.trace(model, example_input)
traced_model.save('/app/model.pt')

Verify Saved Model

# Reload and verify
loaded = torch.jit.load('/app/model.pt')
loaded.eval()

with torch.no_grad():
    original_out = model(test_input)
    loaded_out = loaded(test_input)

    diff = (original_out - loaded_out).abs().max()
    print(f"Max difference: {diff.item()}")
    assert diff < 1e-5, "Model outputs don't match!"

Environment Considerations

Handling Slow Environments

When operating in resource-constrained environments:

  1. Benchmark first: Test basic operations before committing to full solution import time start = time.time() _ = model(torch.randint(0, vocab_size, (1, 10))) print(f"Single forward pass: {time.time() - start:.2f}s")
  2. Reduce batch size: Process samples individually if needed
  3. Set realistic timeouts: Base on benchmarks, not arbitrary values
  4. Use incremental checkpoints: Save progress periodically

Memory Management

# Clear GPU cache between operations
torch.cuda.empty_cache()

# Use gradient checkpointing for large models
from torch.utils.checkpoint import checkpoint

# Process in smaller batches
for batch in torch.split(data, batch_size):
    process(batch)

Common Pitfalls

  1. Not verifying architecture match before training - Always test load_state_dict first
  2. Arbitrary hyperparameters - Justify choices based on task characteristics
  3. Ignoring TorchScript compatibility - Test export early, not after training
  4. Syntax errors in edits - Review code changes carefully, especially string formatting
  5. Incomplete state dict mapping - Verify all keys are accounted for
  6. Not establishing baseline metrics - Compute original loss before training
  7. Missing torch.no_grad() for inference - Use context manager for evaluation
  8. Forgetting to set model.eval() - Required for consistent behavior in eval/export

Verification Checklist

Before considering the task complete:

  • State dictionary keys fully analyzed and documented
  • Model architecture matches state dict exactly (verified with load_state_dict)
  • Forward pass produces valid output
  • Baseline loss/metric computed
  • Target layers correctly unfrozen, others frozen
  • Training improves loss over baseline
  • TorchScript export succeeds
  • Exported model produces same outputs as original
  • Model saved to required path

平台分布

Claude Code

25.87%
按下载量换算70

Gemini CLI

22.15%
按下载量换算60

Antigravity

18.78%
按下载量换算51

windsurf

12.16%
按下载量换算33

OpenCode

8.1%
按下载量换算22

Codex

3.48%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

继续浏览同类 Skills