К основному содержанию
скилл CX Codex

magpie-kernel-evaluator — скилл для Claude Code: бенчмарк

Гоняет бенчмарки LLM-инференса через Magpie, разбирает трейсы в TraceLens и ведёт от узкого ядра до проверенного варианта.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add amd/skills --skill magpie-kernel-evaluator -a claude-code
Открыть на GitHub

Что делает magpie-kernel-evaluator

Скилл закрывает три связанные задачи: замерить инференс-нагрузку и снять трейсы, сравнить GPU-ядра по корректности и скорости, провести цикл оптимизации от найденного узкого места до исходника и повторного бенчмарка. Поддерживаются публичные типы ядер hip, cuda, pytorch и triton, а для инференса заявлены vllm, sglang и atom в режимах local и docker; распределённый запуск идёт через YAML и примеры с Ray.

Сам скилл приложение Magpie не ставит. Перед первой нагрузкой проверяется magpie --help в нужном окружении с Python 3.10+, при отсутствии — установка пакета из git-репозитория. ROCm, профилировщики и веса моделей пакет не приносит, поэтому без них бенчмарк не пойдёт. Версии ROCm и железа, которых нет в матрице совместимости репозитория, остаются непроверенными до теста.

Успешный запуск ядра ещё не значит корректный результат: для PyTorch без тесткейса встроенная проверка смотрит только на конечность значений, так что численного совпадения между вариантами она не доказывает. Профилирование искажает латентность, поэтому чистый базовый прогон с ним не совмещают. Отчёты TraceLens ложатся в tracelens/ рабочей папки бенчмарка — компактные *_kernel_roofline_simple.csv открывают первыми и ранжируют по kernel_time_ms_sum или time_pct.

Какие задачи решает

  • снять пропускную способность и задержки инференса vLLM или SGLang
  • разложить трейс на стадии prefill и decode с roofline-отчётом
  • найти в профиле самые дорогие ядра и связать их с исходником
  • сравнить HIP- или Triton-варианты ядра и выбрать базовый
  • проверить корректность оптимизированного ядра до замеров скорости

Примеры запросов агенту

  • Сними бенчмарк по benchmark.yaml и покажи TTFT и TPOT
  • Разбери трейс из tracelens/ и назови ядра, которые упираются в roofline
  • Сравни два варианта ядра attention.hip с общим тесткейсом

Как установить magpie-kernel-evaluator

1Через Skills CLI (Vercel)

npx skills add amd/skills --skill magpie-kernel-evaluator -a claude-code

2Вручную: положить файлы

~/.claude/skills/magpie-kernel-evaluator/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/magpie-kernel-evaluator/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о magpie-kernel-evaluator

Как установить magpie-kernel-evaluator в Claude Code?

Выполните npx skills add amd/skills --skill magpie-kernel-evaluator -a claude-code, файл скилла окажется по пути ~/.claude/skills/magpie-kernel-evaluator/SKILL.md. Само приложение Magpie ставится отдельно: python -m pip install git+https://github.com/AMD-AGI/Magpie.git.

Что делает magpie-kernel-evaluator?

Замеряет инференс-нагрузки, разбирает torch-трейсы через TraceLens на стадии и roofline, а также анализирует и сравнивает ядра HIP, CUDA, PyTorch и Triton.

Нужен ли тесткейс для сравнения ядер?

Для приёма результата по корректности — да. У PyTorch без тесткейса встроенная проверка подтверждает лишь конечность чисел, а не равенство вариантов.

Исходный текст

SKILL.md · MIT
---
name: magpie-kernel-evaluator
description: Benchmarks LLM inference and drives GPU kernel optimization with Magpie. Use when the user wants to benchmark vLLM, SGLang, or Atom; capture torch traces; post-process inference traces with TraceLens into prefill/decode and roofline reports; identify top bottleneck kernels or map profiler names to source; analyze or compare HIP, CUDA, PyTorch, or Triton kernels; validate and rank optimized variants; run local, container, or Ray workloads; or mentions Magpie, TraceLens, gap analysis, TTFT, TPOT, kernel evaluation, or AMD GPU optimization.
---

# Magpie

Use Magpie for three connected jobs:

1. Benchmark an inference workload and collect throughput, latency, and traces.
2. Analyze or compare GPU kernels for correctness and performance.
3. Drive an optimization loop from a benchmark bottleneck to source, candidate kernels, and end-to-end validation.

Describe only capabilities supported by the checked-out Magpie version. Do not infer support for an unverified ROCm, GPU, framework, or experimental integration.

## Choose the workflow

| User goal | Workflow |
|---|---|
| Evaluate one implementation | `analyze` |
| Rank two or more implementations | `compare` |
| Measure model-serving performance | `benchmark` |
| Find expensive kernels in existing traces | standalone gap analysis |
| Explain a profiled inference workload | benchmark → TraceLens post-processing → stage/roofline review |
| Optimize an end-to-end workload | benchmark → TraceLens/gap analysis → source mapping → analyze/compare → re-benchmark |

Use a YAML config for reproducible or multi-step work. Use inline CLI arguments for small exploratory runs.

## Preflight

Installing this skill does not install the Magpie application (`magpie-eval`). For a preparation-only request, read the supplied fixtures and [reference.md](reference.md), write the requested plan or configuration, and identify commands that remain unverified. Do not install packages or execute a workload when the user forbids it; a missing Magpie installation does not prevent preparing a plan.

Before executing a Magpie workload:

1. Check `magpie --help` in the intended Python environment (Python 3.10+). If the command is missing, try `python -m Magpie --help` in that same environment; a working module entry point can be used instead of the CLI. `No module named Magpie` means the application is not installed in that environment. For errors inside an installed Magpie package, diagnose the reported import or dependency failure instead.
2. If Magpie is not installed, install it in the intended environment before continuing:

   ```bash
   python -m pip install git+https://github.com/AMD-AGI/Magpie.git
   ```

   For an existing Magpie source checkout, use `python -m pip install -e /path/to/Magpie` instead. The installed skill folder and a testcase workspace are not Magpie source checkouts. Re-run `magpie --help` or `python -m Magpie --help` to verify the installation; if it fails, report the error before attempting a workload.
3. Inspect the installed interface for the selected workflow (substitute `python -m Magpie` if using the module entry point):

   ```bash
   magpie --help
   magpie analyze --help
   magpie compare --help
   magpie benchmark --help
   magpie --gpu-info
   ```

4. Check required tools, model access, GPU visibility, writable output space, and container or Ray access as applicable. Installing the Python package does not install ROCm/CUDA, profilers, or model weights.
5. Read the repository compatibility matrix before making version claims. Treat ROCm or hardware not listed there as unverified until tested.
6. Record the exact config, model revision, image, environment variables, GPU allocation, and Magpie commit for benchmark comparisons.

## Analyze a kernel

Prefer a config when correctness or profiler settings matter:

```bash
magpie analyze --kernel-config path/to/kernel.yaml
```

For a quick single-kernel run:

```bash
magpie analyze path/to/kernel.hip --type hip --testcase "./run_test.sh"
```

Supported public kernel types are `hip`, `cuda`, `pytorch`, and `triton`. Use `--no-perf` only when the user wants correctness or execution validation without profiling.

Do not equate successful execution with numerical correctness. Supply a representative testcase whenever an optimized result will be accepted or rejected.

## Compare kernel variants

Compare at least two implementations and identify the baseline explicitly:

```bash
magpie compare --kernel-config path/to/compare.yaml
```

Keep inputs, tolerances, warmup, iteration count, GPU allocation, and profiler settings identical across candidates. Reject candidates that fail correctness before considering performance rankings.

For PyTorch without a testcase, Magpie's built-in check only verifies that each result is finite; it does not prove numerical equivalence between variants. Require a testcase for numerical validation.

## Benchmark inference

Prefer a checked-in benchmark config:

```bash
magpie benchmark --benchmark-config path/to/benchmark.yaml
```

The stable public CLI supports `vllm`, `sglang`, and `atom`. It supports direct `docker` and `local` run modes; use YAML configuration and the repository's Ray examples for distributed execution. Do not advertise integrations that exist only in internal enums or partial code paths as stable.

Enable profiling deliberately: profiler runs perturb latency and should not replace a clean baseline. Compare throughput, completed requests, TTFT, TPOT, ITL, and end-to-end latency using equivalent workloads.

## Post-process traces with TraceLens

Enable TraceLens in the profiled benchmark YAML; torch traces are its required input:

```yaml
benchmark:
  profiler:
    torch_profiler:
      enabled: true
    tracelens:
      enabled: true
      analysis_mode: inference
      analysis_stages: all
      export_format: csv
```

Use `analysis_mode: inference` for vLLM/SGLang. It splits the rank-0 trace into `prefilldecode`, `decode`, and `prefill` stages when available, runs TraceLens post-processing, and writes full stage reports plus compact `*_kernel_roofline_simple.csv` files under the benchmark workspace's `tracelens/` directory. For direct PyTorch trace reporting, use `analysis_mode: pytorch`.

Open the compact roofline CSVs first. Rank rows by `kernel_time_ms_sum` or `time_pct`; then use `roofline_bound`, arithmetic intensity, achieved TFLOP/s or TB/s, and `pct_roofline_mean` to form an optimization hypothesis. Confirm `benchmark_report.json.tracelens_analysis` has outputs and no error before treating post-processing as successful. Use `analysis_mode: pytorch` when the task specifically needs the legacy direct single-rank or multi-rank collective reports.

Magpie's integrated TraceLens stage produces CSV/Excel analysis artifacts, not an agent-written `analysis.md`. If the user requests a prioritized agentic report, pass the captured trace to the separate `tracelens-analysis-orchestrator` skill when installed; keep that result distinct from Magpie's benchmark report.

## Analyze existing traces and find source

Run standalone gap analysis with `--trace-dir` directly on `benchmark`:

```bash
magpie benchmark \
  --trace-dir path/to/torch_trace \
  --top-k 20 \
  --find-kernel-sources \
  --kernel-source-repos path/to/repository
```

Do not insert a `gap-analysis` positional token; it is not a CLI subcommand. Inspect the generated aggregate and per-rank CSVs, and preserve source-mapping confidence rather than assuming every normalized kernel name maps uniquely.

## Drive the optimization loop

1. Run an unprofiled baseline benchmark and save its config and report.
2. Repeat with torch profiling and TraceLens inference post-processing enabled.
3. Review stage-level TraceLens roofline summaries to classify dominant operations and likely compute, memory, or communication limits.
4. Run gap analysis over the representative steady-state window to rank concrete kernels.
5. Select bottlenecks by total contribution, not only single-dispatch duration.
6. Map the selected kernel to source and an executable testcase.
7. Generate isolated candidate implementations; preserve the baseline.
8. Use `analyze` for iteration, then `compare` with correctness gates to rank candidates.
9. Re-run the original unprofiled benchmark with the winning candidate and the same workload. Report both kernel-level and end-to-end changes, including regressions.

Stop before claiming success if correctness is unproven, the benchmark inputs changed, the source mapping is uncertain, or the end-to-end improvement is within run-to-run noise.

## Use MCP tools when available

Prefer Magpie MCP tools for structured agent workflows such as hardware inspection, kernel discovery, config generation, analyze/compare, optimization suggestions, result lookup, report comparison, Ray job management, and benchmark batches.

Do not pass a CLI `analyze_report.json` wrapper directly to an MCP tool that expects one result object's `performance_state` and `performance_result`. Do not assume every CLI option exists in MCP; kernel-source enrichment is currently exposed by the CLI gap-analysis path.

## Additional resources

- Full CLI reference: [reference.md](reference.md)
- Copy-paste command examples: [examples.md](examples.md)

© amd · MIT · amd/skills

Похожие скиллы

Всё по теме «ИИ и ML» →
skill-creator официальный anthropics Помогает создать новый скилл, доработать существующий и проверить результат через тестовые промпты и оценки. 414 180установок writing-for-agents Matt Pocock Помогает писать скиллы и документы с инструкциями для агентов. Пригодится при правках AGENTS.md, CLAUDE.md и связанных справочных файлов. 466 719установок media-use heygen-com Находит и генерирует ассеты для видео в HyperFrames — музыку, дикторский голос, аватары и эффекты. Сохраняет всё локально в assets. CX Codex +1 1 100 000установок mcp-builder официальный anthropics Скилл проводит через создание MCP-сервера на TypeScript или Python: от изучения протокола до тестов и оценки качества. 130 949установок subagent-driven-development Jesse Vincent Скилл выполняет план через отдельных субагентов для каждой задачи и проверяет результат после каждого шага. Подходит для независимых задач в одной сессии. CX Codex 237 746установок orchestration stablyai Координирует воркеров Orca через DAG задач, циклы супервизора и цепочки сообщений. Пригодится для распределения сложной работы между агентами. CX Codex +1 349 800установок

Из того же набора11

local-ai-use Мета-скилл перенастраивает агента так, чтобы генерация изображений, озвучка и расшифровка аудио шли через локальный Lemonade Server, а не через платный API. CX Codex +1 1 100установок local-ai-app-integration Переводит клиентские запросы из облачных API в локальный процесс Embeddable Lemonade. Пригодится, когда нужно встроить автономные модели в готовое приложение на Windows или Linux. CX Codex +1 895установок tracelens-analysis-orchestrator Скилл ведёт агентный разбор трейсов PyTorch Profiler через TraceLens: готовит отчёты, запускает субагентов и собирает analysis.md. CX Codex +1 877установок serving-llms-on-instinct Разворачивает vLLM-эндпоинт на GPU AMD Instinct: определяет железо, проверяет окружение, собирает Docker-команду и запускает модель. CX Codex +1 876установок serving-llms-on-epyc Разворачивает эндпоинт vLLM с бэкендом zentorch на процессорах AMD EPYC в Docker, Podman или conda. Пригодится для инференса LLM на серверных CPU без привязки к GPU. CX Codex +1 817установок lemonade-router-builder Скилл превращает словесные инструкции в валидный JSON-конфиг collection.router для Lemonade. Он нужен для распределения запросов между локальными и облачными моделями. CX Codex +1 807установок hyperloom-workload-optimizer Ставит Hyperloom на хост с AMD Instinct и запускает многоагентную оптимизацию пропускной способности LLM. Нужен, когда модель на MI300X, MI325X или MI355X должна отдавать больше токенов в секунду. CX Codex +1 783установок quark-install Ставит и проверяет AMD Quark в выбранном окружении Python, подбирая PyTorch под имеющийся ускоритель. Пригодится, когда импорт quark падает или ядро не компилируется. CX Codex +1 526установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой