Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问clear审计通过

ml-inference-optimization机器学习推理优化

Agent Skill

ml-inference-optimization 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

519

周安装

21

GitHub Stars

61

下载量

163
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

请帮我安装这个 Agent Skill:ml-inference-optimization(机器学习推理优化)
来源仓库:https://github.com/melodic-software/claude-code-plugins
仓库路径:skills/ml-inference-optimization
安装命令:
npx skills add https://github.com/melodic-software/claude-code-plugins --skill ml-inference-optimization
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/melodic-software/claude-code-plugins --skill ml-inference-optimization

简介

ml-inference-optimization 用于查找、检索和筛选相关信息,适合模型部署优化场景。

  • 适用于 Codex、Claude、Cursor、Gemini CLI 中的推理性能研究任务。
  • 使用 npx skills add 命令从 claude-code-plugins 仓库安装。
  • 安装前应确认项目活跃度及是否要求特定运行环境。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

ML Inference Optimization

When to Use This Skill

Use this skill when:

  • Optimizing ML inference latency
  • Reducing model size for deployment
  • Implementing model compression techniques
  • Designing inference caching strategies
  • Deploying models at the edge
  • Balancing accuracy vs. latency trade-offs

Keywords: inference optimization, latency, model compression, distillation, pruning, quantization, caching, edge ML, TensorRT, ONNX, model serving, batching, hardware acceleration

Inference Optimization Overview

┌─────────────────────────────────────────────────────────────────────┐
│                 Inference Optimization Stack                        │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌──────────────────────────────────────────────────────────────┐  │
│  │                    Model Level                                │  │
│  │  Distillation │ Pruning │ Quantization │ Architecture Search │  │
│  └──────────────────────────────────────────────────────────────┘  │
│                              │                                      │
│                              ▼                                      │
│  ┌──────────────────────────────────────────────────────────────┐  │
│  │                   Compiler Level                              │  │
│  │  Graph optimization │ Operator fusion │ Memory planning       │  │
│  └──────────────────────────────────────────────────────────────┘  │
│                              │                                      │
│                              ▼                                      │
│  ┌──────────────────────────────────────────────────────────────┐  │
│  │                  Runtime Level                                │  │
│  │  Batching │ Caching │ Async execution │ Multi-threading      │  │
│  └──────────────────────────────────────────────────────────────┘  │
│                              │                                      │
│                              ▼                                      │
│  ┌──────────────────────────────────────────────────────────────┐  │
│  │                  Hardware Level                               │  │
│  │  GPU │ TPU │ NPU │ CPU SIMD │ Custom accelerators            │  │
│  └──────────────────────────────────────────────────────────────┘  │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Model Compression Techniques

Technique Overview

TechniqueSize ReductionSpeed ImprovementAccuracy Impact
Quantization2-4x2-4xLow (1-2%)
Pruning2-10x1-3xLow-Medium
Distillation3-10x3-10xMedium
Low-rank factorization2-5x1.5-3xLow-Medium
Weight sharing10-100xVariableMedium-High

Knowledge Distillation

┌─────────────────────────────────────────────────────────────────────┐
│                    Knowledge Distillation                           │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌──────────────┐                                                   │
│  │ Teacher Model│ (Large, accurate, slow)                          │
│  │   GPT-4      │                                                   │
│  └──────────────┘                                                   │
│         │                                                           │
│         ▼ Soft labels (probability distributions)                   │
│  ┌──────────────────────────────────────────────────────────────┐  │
│  │                    Training Process                           │  │
│  │  Loss = α × CrossEntropy(student, hard_labels)               │  │
│  │       + (1-α) × KL_Div(student, teacher_soft_labels)         │  │
│  └──────────────────────────────────────────────────────────────┘  │
│         │                                                           │
│         ▼                                                           │
│  ┌──────────────┐                                                   │
│  │Student Model │ (Small, nearly as accurate, fast)                │
│  │  DistilBERT  │                                                   │
│  └──────────────┘                                                   │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Distillation Types:

TypeDescriptionUse Case
Response distillationMatch teacher outputsGeneral compression
Feature distillationMatch intermediate layersBetter transfer
Relation distillationMatch sample relationshipsStructured data
Self-distillationModel teaches itselfRegularization

Pruning Strategies

Unstructured Pruning (Weight-level):
Before: [0.1, 0.8, 0.2, 0.9, 0.05, 0.7]
After:  [0.0, 0.8, 0.0, 0.9, 0.0, 0.7]  (50% sparse)
• Flexible, high sparsity possible
• Needs sparse hardware/libraries

Structured Pruning (Channel/Layer-level):
Before: ┌───┬───┬───┬───┐
        │ C1│ C2│ C3│ C4│
        └───┴───┴───┴───┘
After:  ┌───┬───┬───┐
        │ C1│ C3│ C4│  (Removed C2 entirely)
        └───┴───┴───┘
• Works with standard hardware
• Lower compression ratio

Pruning Decision Criteria:

MethodDescriptionEffectiveness
Magnitude-basedRemove smallest weightsSimple, effective
Gradient-basedRemove low-gradient weightsBetter accuracy
Second-orderUse Hessian informationBest but expensive
Lottery ticketFind winning subnetworkTheoretical insight

Quantization (Detailed)

Precision Hierarchy:

FP32 (32 bits): ████████████████████████████████
FP16 (16 bits): ████████████████
BF16 (16 bits): ████████████████  (different mantissa/exponent)
INT8 (8 bits):  ████████
INT4 (4 bits):  ████
Binary (1 bit): █

Memory and Compute Scale Proportionally

Quantization Approaches:

ApproachWhen AppliedQualityEffort
Dynamic quantizationRuntimeGoodLow
Static quantizationPost-training with calibrationBetterMedium
QATDuring trainingBestHigh

Compiler-Level Optimization

Graph Optimization

Original Graph:
Input → Conv → BatchNorm → ReLU → Conv → BatchNorm → ReLU → Output

Optimized Graph (Operator Fusion):
Input → FusedConvBNReLU → FusedConvBNReLU → Output

Benefits:
• Fewer kernel launches
• Better memory locality
• Reduced memory bandwidth

Common Optimizations

OptimizationDescriptionSpeedup
Operator fusionCombine sequential ops1.2-2x
Constant foldingPre-compute constants1.1-1.5x
Dead code eliminationRemove unused opsVariable
Layout optimizationOptimize tensor memory layout1.1-1.3x
Memory planningOptimize buffer allocation1.1-1.2x

Optimization Frameworks

FrameworkVendorBest For
TensorRTNVIDIANVIDIA GPUs, lowest latency
ONNX RuntimeMicrosoftCross-platform, broad support
OpenVINOIntelIntel CPUs/GPUs
Core MLAppleApple devices
TFLiteGoogleMobile, embedded
Apache TVMOpen sourceCustom hardware, research

Runtime Optimization

Batching Strategies

No Batching:
Request 1: [Process] → Response 1      10ms
Request 2: [Process] → Response 2      10ms
Request 3: [Process] → Response 3      10ms
Total: 30ms, GPU underutilized

Dynamic Batching:
Requests 1-3: [Wait 5ms] → [Process batch] → Responses
Total: 15ms, 2x throughput

Trade-off: Latency vs. Throughput
• Larger batch: Higher throughput, higher latency
• Smaller batch: Lower latency, lower throughput

Batching Parameters:

ParameterDescriptionTrade-off
batch_sizeMaximum batch sizeThroughput vs. latency
max_wait_timeWait time for batch fillLatency vs. efficiency
min_batch_sizeMinimum before processingLatency predictability

Caching Strategies

┌─────────────────────────────────────────────────────────────────────┐
│                    Inference Caching Layers                         │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Layer 1: Input Cache                                               │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ Cache exact inputs → Return cached outputs                   │   │
│  │ Hit rate: Low (inputs rarely repeat exactly)                 │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                     │
│  Layer 2: Embedding Cache                                           │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ Cache computed embeddings for repeated tokens/entities       │   │
│  │ Hit rate: Medium (common tokens repeat)                      │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                     │
│  Layer 3: KV Cache (for transformers)                               │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ Cache key-value pairs for attention                          │   │
│  │ Hit rate: High (reuse across tokens in sequence)             │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                     │
│  Layer 4: Result Cache                                              │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ Cache semantic equivalents (fuzzy matching)                  │   │
│  │ Hit rate: Variable (depends on query distribution)           │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Semantic Caching for LLMs:

Query: "What's the capital of France?"
       ↓
Hash + Embed query
       ↓
Search cache (similarity > threshold)
       ↓
├── Hit: Return cached response
└── Miss: Generate → Cache → Return

Async and Parallel Execution

Sequential:
┌─────┐ ┌─────┐ ┌─────┐
│Prep │→│Model│→│Post │  Total: 30ms
│10ms │ │15ms │ │5ms  │
└─────┘ └─────┘ └─────┘

Pipelined:
Request 1: │Prep│Model│Post│
Request 2:      │Prep│Model│Post│
Request 3:           │Prep│Model│Post│

Throughput: 3x higher
Latency per request: Same

Hardware Acceleration

Hardware Comparison

HardwareStrengthsLimitationsBest For
GPU (NVIDIA)High parallelism, mature ecosystemPower, costTraining, large batch inference
TPU (Google)Matrix ops, cloud integrationVendor lock-inGoogle Cloud workloads
NPU (Apple/Qualcomm)Power efficient, on-deviceLimited modelsMobile, edge
CPUFlexible, availableSlower for MLLow-batch, CPU-bound
FPGACustomizable, low latencyDevelopment complexitySpecialized workloads

GPU Optimization

OptimizationDescriptionImpact
Tensor CoresUse FP16/INT8 tensor operations2-8x speedup
CUDA graphsReduce kernel launch overhead1.5-2x for small models
Multi-streamParallel executionHigher throughput
Memory poolingReduce allocation overheadLower latency variance

Edge Deployment

Edge Constraints

┌─────────────────────────────────────────────────────────────────────┐
│                      Edge Deployment Constraints                    │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Resource Constraints:                                              │
│  ├── Memory: 1-4 GB (vs. 64+ GB cloud)                             │
│  ├── Compute: 1-10 TOPS (vs. 100+ TFLOPS cloud)                    │
│  ├── Power: 5-15W (vs. 300W+ cloud)                                │
│  └── Storage: 16-128 GB (vs. TB cloud)                             │
│                                                                     │
│  Operational Constraints:                                           │
│  ├── No network (offline operation)                                 │
│  ├── Variable ambient conditions                                    │
│  ├── Infrequent updates                                            │
│  └── Long deployment lifetime                                       │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Edge Optimization Strategies

StrategyDescriptionUse When
Model selectionUse edge-native models (MobileNet, EfficientNet)Accuracy acceptable
Aggressive quantizationINT8 or lowerMemory/power constrained
On-device distillationDistill to tiny modelExtreme constraints
Split inferenceEdge preprocessing, cloud inferenceNetwork available
Model cachingCache results locallyRepeated queries

Edge ML Frameworks

FrameworkPlatformFeatures
TensorFlow LiteAndroid, iOS, embeddedQuantization, delegates
Core MLiOS, macOSNeural Engine optimization
ONNX Runtime MobileCross-platformBroad model support
PyTorch MobileAndroid, iOSFamiliar API
TensorRTNVIDIA JetsonMaximum performance

Latency Profiling

Profiling Methodology

┌─────────────────────────────────────────────────────────────────────┐
│                    Latency Breakdown Analysis                       │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  1. Data Loading:          ████████░░░░░░░░░░  15%                 │
│  2. Preprocessing:         ██████░░░░░░░░░░░░  10%                 │
│  3. Model Inference:       ████████████████░░  60%                 │
│  4. Postprocessing:        ████░░░░░░░░░░░░░░   8%                 │
│  5. Response Serialization:███░░░░░░░░░░░░░░░   7%                 │
│                                                                     │
│  Target: Model inference (60% = biggest optimization opportunity)  │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Profiling Tools

ToolUse For
PyTorch ProfilerPyTorch model profiling
TensorBoardTensorFlow visualization
NVIDIA NsightGPU profiling
Chrome TracingGeneral timeline visualization
perfCPU profiling

Key Metrics

MetricDescriptionTarget
P50 latencyMedian latency< SLA
P99 latencyTail latency< 2x P50
ThroughputRequests/secondMeet demand
GPU utilizationCompute usage> 80%
Memory bandwidthMemory usage< limit

Optimization Workflow

Systematic Approach

┌─────────────────────────────────────────────────────────────────────┐
│                  Optimization Workflow                              │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  1. Baseline                                                        │
│     └── Measure current performance (latency, throughput, accuracy) │
│                                                                     │
│  2. Profile                                                         │
│     └── Identify bottlenecks (model, data, system)                  │
│                                                                     │
│  3. Optimize (in order of effort/impact):                           │
│     ├── Hardware: Use right accelerator                             │
│     ├── Compiler: Enable optimizations (TensorRT, ONNX)            │
│     ├── Runtime: Batching, caching, async                          │
│     ├── Model: Quantization, pruning                                │
│     └── Architecture: Distillation, model change                    │
│                                                                     │
│  4. Validate                                                        │
│     └── Verify accuracy maintained, latency improved                │
│                                                                     │
│  5. Deploy and Monitor                                              │
│     └── Track real-world performance                                │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Optimization Priority Matrix

                    High Impact
                         │
    Compiler Opts    ────┼──── Quantization
    (easy win)           │     (best ROI)
                         │
Low Effort ──────────────┼──────────────── High Effort
                         │
    Batching         ────┼──── Distillation
    (quick win)          │     (major effort)
                         │
                    Low Impact

Common Patterns

Multi-Model Serving

┌─────────────────────────────────────────────────────────────────────┐
│                                                                     │
│  Request → ┌─────────┐                                              │
│            │ Router  │                                              │
│            └─────────┘                                              │
│               │   │   │                                             │
│      ┌────────┘   │   └────────┐                                    │
│      ▼            ▼            ▼                                    │
│  ┌───────┐   ┌───────┐   ┌───────┐                                 │
│  │ Tiny  │   │ Small │   │ Large │                                 │
│  │ <10ms │   │ <50ms │   │<500ms │                                 │
│  └───────┘   └───────┘   └───────┘                                 │
│                                                                     │
│  Routing strategies:                                                │
│  • Complexity-based: Simple→Tiny, Complex→Large                    │
│  • Confidence-based: Try Tiny, escalate if low confidence          │
│  • SLA-based: Route based on latency requirements                  │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Speculative Execution

Query: "Translate: Hello"
        │
        ├──▶ Small model (draft): "Bonjour" (5ms)
        │
        └──▶ Large model (verify): Check "Bonjour" (10ms parallel)
             │
             ├── Accept: Return immediately
             └── Reject: Generate with large model

Speedup: 2-3x when drafts are often accepted

Cascade Models

Input → ┌────────┐
        │ Filter │ ← Cheap filter (reject obvious negatives)
        └────────┘
             │ (candidates only)
             ▼
        ┌────────┐
        │ Stage 1│ ← Fast model (coarse ranking)
        └────────┘
             │ (top-100)
             ▼
        ┌────────┐
        │ Stage 2│ ← Accurate model (fine ranking)
        └────────┘
             │ (top-10)
             ▼
         Output

Benefit: 10x cheaper, similar accuracy

Optimization Checklist

Pre-Deployment

  • Profile baseline performance
  • Identify primary bottleneck (model, data, system)
  • Apply compiler optimizations (TensorRT, ONNX)
  • Evaluate quantization (INT8 usually safe)
  • Tune batch size for target throughput
  • Test accuracy after optimization

Deployment

  • Configure appropriate hardware
  • Enable caching where applicable
  • Set up monitoring (latency, throughput, errors)
  • Configure auto-scaling policies
  • Implement graceful degradation

Post-Deployment

  • Monitor p99 latency
  • Track accuracy metrics
  • Analyze cache hit rates
  • Review cost efficiency
  • Plan iterative improvements

Related Skills

  • llm-serving-patterns - LLM-specific serving optimization
  • ml-system-design - End-to-end ML pipeline design
  • quality-attributes-taxonomy - Performance as quality attribute
  • estimation-techniques - Capacity planning for ML systems

Version History

  • v1.0.0 (2025-12-26): Initial release - ML inference optimization patterns

Last Updated

Date: 2025-12-26

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Antigravity

28.52%
按下载量换算46

trae

22.25%
按下载量换算36

windsurf

16.2%
按下载量换算26

Claude Code

11.1%
按下载量换算18

Codex

6.71%
按下载量换算11

Gemini CLI

3.33%
按下载量换算5

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

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

安装前确认

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

来源信息

继续浏览同类 Skills