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

rocprofiler-pc-sampling — скилл для Claude Code: как настроить

Скилл rocprofiler-pc-sampling запускает профилирование приложений на AMD GPU через rocprofv3 с PC sampling и находит узкие места по коду и причины простоев вычислительных блоков.

MIT 592 установок ★ 510 обновлён 2026-10-24

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

Что делает rocprofiler-pc-sampling

Скилл помогает запустить rocprofv3 с флагом --pc-sampling-beta-enabled и проанализировать трассировки счётчика команд (Program Counter). Он настраивает стохастический метод или host_trap, привязывает вызовы ядер через --kernel-trace и сохраняет отчёт в JSON или CSV. Формат по умолчанию rocpd не поддерживает PC sampling, поэтому скилл переключает вывод вручную.

Для разбора результатов используется внутренний скрипт scripts/analyze_pc_sampling.py. Он выявляет горячие точки исходного кода и частые причины простоев, вроде задержек WAITCNT при операциях транспонирования.

Без рабочей установки ROCm и GPU с поддержкой PC sampling профилирование не запустится. Бинарник нужно собирать с отладочными символами и оптимизацией (-g -O3), иначе сопоставить замеры со строками кода не выйдет.

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

  • Найти горячие точки в коде ядер для AMD GPU
  • Выяснить причины простоев вычислений через анализ задержек
  • Настроить стохастический PC sampling в утилите rocprofv3
  • Сопоставить замеры счётчика команд со строками исходного кода

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

  • Сделай PC sampling для ./build/gpu_app через rocprofv3 и найди главные узкие места
  • Проанализируй причины простоев в ядре transpose_kernel по файлу results.json
  • Запусти стохастическое профилирование на AMD GPU с интервалом в 1048576 циклов

Как установить rocprofiler-pc-sampling

1Через Skills CLI (Vercel)

npx skills add amd/skills --skill rocprofiler-pc-sampling -a claude-code

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

~/.claude/skills/rocprofiler-pc-sampling/SKILL.md

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

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

Вопросы о rocprofiler-pc-sampling

Как установить rocprofiler-pc-sampling в Claude Code?

Выполните команду npx skills add amd/skills --skill rocprofiler-pc-sampling -a claude-code.

Что делает rocprofiler-pc-sampling?

Он конфигурирует запуск профилировщика rocprofv3 с семплированием счётчика команд и разбирает полученные отчёты скриптом scripts/analyze_pc_sampling.py.

Какой формат вывода поддерживает PC sampling?

Нужно указывать json или csv. Стандартный для rocprofv3 формат rocpd вывод PC sampling сейчас не поддерживает.

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

SKILL.md · MIT
---
name: rocprofiler-pc-sampling
description: Profiles a target application using rocprofv3 with program counter sampling enabled and then analyzes the results. Use when the user has a program that runs on an AMD GPU and asks to perform PC sampling, to determine the runtime performance characteristics of their application, to determine stall reasons, or to determine hotspots in the code.
---

# PC Sampling

## Prerequisites

- The system must have a ROCm installation and an accessible AMD GPU; that is, `amd-smi` should return at least one valid device.
- The GPU must support PC sampling. Available PC sampling configurations can be determined via `rocprofv3-avail info --pc-sampling` or `rocprofv3 -L`. Your sampling method and interval must align with the outputs of this command. Also pay attention to any flags reported for a given configuration; at time of writing, stochastic sampling intervals must be powers of two.
- The application should be built with debug symbols AND optimization flags (e.g. `-g -O3`) in order to get source line attribution and a representative execution profile.

## How to use PC Sampling

To run rocprofv3 with PC sampling:

- explicitly enable pc sampling with the flag `--pc-sampling-beta-enabled`.
- specify the pc sampling method with `--pc-sampling-method`: `host_trap` or `stochastic`
- specify the interval unit for the sampling with `--pc-sampling-unit`: `time` for host_trap and `cycles` for stochastic
- specify the sampling interval with `--pc-sampling-interval`: an integer representing microseconds if you specified `time` or cycles if you specified `cycles`.
- add the `--kernel-trace` flag to track kernel launches for attribution
- specify either the `json` or `csv` output format with `--output-format`; the default output format, `rocpd`, does not currently support PC sampling output.

A typical command will look like the following:

```bash
rocprofv3 \
  --pc-sampling-beta-enabled \
  --pc-sampling-method stochastic \
  --pc-sampling-unit cycles \
  --pc-sampling-interval 1048576 \
  --kernel-trace \
  --output-format json \
  -- <target app>
```

### PC Sampling Outputs

Output-related options:

- `-d <dir>`: output location (default: `%cwd%`)
- `-o <prefix>`: name prefix (default: `%hostname%/%pid%`)
- `--output-format csv,json`: emit both formats

Default path pattern: `<output_dir>/<output_prefix>_<name>.<ext>` where prefix is `%hostname%/%pid%` unless overridden.

#### Possible output files

| File | Format | Contents |
|-----|-----|-----|
| `*_pc_sampling_stochastic.csv` or `*_pc_sampling_host_trap.csv` | CSV | Flat sample records; one row per sample |
| `*_agent_info.csv` | CSV | GPU/CPU agent metadata (**not** samples) |
| `*_kernel_trace.csv` | CSV | Kernel dispatch records (with `--kernel-trace`) |
| `*_results.json` | JSON | All data in one file |

### PC Sampling Guidance

There are two types of PC sampling: host-trap and stochastic. Stochastic requires hardware support and is available on fewer GPUs, but provides more information.

The default output format, rocpd, does not currently support pc sampling, so you must explicitly specify json (preferred) or csv. json outputs contain more information.

- Prefer stochastic sampling unless the sampling interval needs to be larger than what stochastic can support.
- Prefer the json output format since it will carry richer information when using stochastic sampling.
- Prefer larger stochastic sampling intervals (2^18^-2^20^; often the maximum) unless the workload is short enough that this does not produce sufficient samples. Shorter intervals will quickly produce huge amounts of data.
- Prefer host trap intervals on the order of 1000 microseconds, decreasing if needed.

## Analyzing PC Sampling Results

Inside this skill's folder is an analysis script: scripts/analyze_pc_sampling.py. When passed the output sample file (.json or .csv) it will report the top sample locations and top stall reasons. You may also filter results to a particular kernel -with `--kernel <kernel name>`.

Run the included python script to perform basic analysis of the output files. Use its output to analyze the user's code, explain its performance, and help give specific and relevant suggestions for improvements. Inform the user of hot spots, the causes of the hotspots (if available), and possible improvements if any. If there are no notable potential improvements, briefly explain why. For example, transpose operations are heavily memory bound and a profile of a well-written transpose kernel will exhibit large amounts of WAITCNT stalls. This is inherent from the task itself and is not *necessarily* a failing of the kernel. However, a naive transpose kernel may exhibit scattered reads or writes, causing far more memory traffic and thus WAITCNT stalls than is necessary.

## Procedure Checklist

1. ensure the prerequisites defined above are met
2. if there is not an up-to-date build of the target application with debug information, build it
3. profile the application with rocprofv3 using pc sampling settings as directed above
4. run this skill's included analysis script on the profiling outputs
5. check that the run was successful and produced a non-trivial number of samples
6. use the output of the script to provide analysis of their code's behavior and specific guidance on possible improvements

## Misc. Tips

Tiny workloads may produce too few samples. Ensure the workload is large enough to get a representative sample count. If source code is available and the workload is too small, consider modifying the code to invoke the kernel multiple times, and then restoring it to its original state after the profiling run.

Host-trap sampling can have an instruction "skid" of one or two instructions; if sample attribution does not make sense, look at the surrounding instructions and branch targets.

A brief overview of stall types and their causes is available in this skill's resources/stall-reasons.md.

The rocm-systems repository has several PC sampling documentation files in this folder: projects/rocprofiler-sdk/source/docs/how-to/. You may also access them here: https://rocm.docs.amd.com/projects/rocprofiler-sdk/en/develop/how-to/cdna3-cdna4-pc-sampling.html

Only one PC sampling configuration can be used at a time, so if exactly one valid configuration is reported then PC sampling is probably being actively used by another process. If this happens, report it to the user and inform them that results may be affected.

© amd · MIT · amd/skills

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

Все скиллы по теме «Код-ревью и рефакторинг» →
hip-rocm mohitmishra786 Скилл hip-rocm для Claude Code помогает писать HIP-ядра и переносить CUDA-код на AMD GPU. Он включается при запросах о HIP, ROCm, HIPIFY и профилировании. CX Codex +1 364установок style-sampling heygen-com Скилл style-sampling для Claude Code создаёт выпуск видео в одном из пяти заданных стилей на тему пользователя. Для неизвестного стиля он предлагает пересобрать видео по кадрам или взять его визуальный язык за основу. CX Codex +1 174 100установок linux-nvidia-cuda-python-cursorrules-prompt-file PatrickJS Правило linux-nvidia-cuda-python-cursorrules-prompt-file настраивает поведение ассистента Cursor для проекта квантования моделей Hugging Face на Linux-серверах с видеокартами Nvidia или AMD. CX Codex +1 ★ 41 178звёзд репо golang-performance samber Скилл golang-performance помогает находить и устранять узкие места в Go-коде: сокращает аллокации памяти, оптимизирует горячие циклы и проверяет результаты замеров. CX Codex +1 44 500установок python-performance-optimization Seth Hobson Скилл python-performance-optimization помогает профилировать Python-код, находить узкие места CPU и памяти. Подходит, когда приложение медленно отвечает или тратит слишком много ресурсов. CX Codex +1 35 675установок react-native-best-practices callstackincubator Скилл react-native-best-practices передаёт агенту правила оптимизации React Native на базе опыта Callstack: от профилирования FPS и TTI до чистки бандла. Помогает устранить лаги анимаций и утечки памяти. CX Codex +1 32 700установок

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

Весь набор →
local-ai-app-integration Скилл local-ai-app-integration для Claude Code и Codex. Переводит запросы из облачных API в локальный процесс Embeddable Lemonade, встраивая автономные модели в приложение на Windows или Linux. CX Codex +1 1 300установок hyperloom-workload-optimizer Скилл hyperloom-workload-optimizer для Claude Code устанавливает Hyperloom на хост с AMD Instinct и запускает многоагентную оптимизацию пропускной способности LLM на MI300X, MI325X или MI355X. CX Codex +1 1 200установок quark-install Скилл quark-install для Claude Code и Codex: ставит и проверяет AMD Quark в выбранном окружении Python, подбирая PyTorch под имеющийся ускоритель. Устраняет падение импорта quark и ошибки компиляции ядра. CX Codex +1 966установок quark-torch-llm-ptq Скилл quark-torch-llm-ptq ведёт модель на PyTorch или Hugging Face через посттренировочное квантование в AMD Quark: анализ, план, манифест, запуск. CX Codex +1 965установок flydsl-kernel-authoring Скилл flydsl-kernel-authoring для Claude Code и Cursor выступает справочником по написанию и проверке GPU-ядер FlyDSL на графических процессорах AMD. CX Codex +1 437установок flydsl-kernel-trace-analysis Скилл flydsl-kernel-trace-analysis для Claude Code собирает и разбирает трассы GPU-ядер, чтобы найти задержки исполнения. Запускается для профилирования команды или анализа уже готовой папки с трассой. CX Codex +1 436установок rocprofiler-systems-choosing-a-profiling-preset Скилл rocprofiler-systems-choosing-a-profiling-preset для Claude Code подбирает профиль запуска rocprofiler-systems под тип работы и цель измерения. Срабатывает на вопрос о выборе профиля или запуск без --preset. CX Codex +1 266установок rocprofiler-systems-discovering-profiling-options Скилл rocprofiler-systems-discovering-profiling-options для Claude Code подбирает команду для поиска настроек и возможностей профилирования ROCPROFSYS. CX Codex +1 266установок

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

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