scrub-issue

pytorch/pytorch

Получение, анализ, воспроизведение и минимизация воспроизведений GitHub-issue. Используйте для проверки воспроизводимости issue, минимизации репро, анализа баг-репортов и триажа на воспроизводимость.

Звёзды105 793
Авторpytorch
Установок133

Установка

SKILL.md

Minimize Issue Reproduction

Fetch a GitHub issue, evaluate whether it has a reasonable repro, check if it still reproduces, and systematically minimize the repro to the smallest possible self-contained script.

Tools

Assume the current environment is correct and run python directly. Only use conda run -n <env> for version bisection (step 5a) where you need to temporarily use a different environment. Use the Bash tool's timeout parameter to enforce timeouts when running repro scripts.

  • gh issue view <NUMBER> --repo pytorch/pytorch to fetch the issue body
  • gh issue view --comments <NUMBER> --repo pytorch/pytorch to fetch comments
  • python <script> to run repro scripts
  • gh issue comment <NUMBER> --repo pytorch/pytorch --body <BODY> to comment
  • gh issue edit <NUMBER> --repo pytorch/pytorch --add-label <LABEL> to add labels

Multiple gh issue edit flags can be combined in a single command (e.g. --add-label "bug,help wanted" --add-assignee "@me"). Prefer batching edits into one command to minimize API calls and reduce the chance of auto-subscribing to notifications.

Preserving notification subscription state

Modifying an issue (commenting, adding labels) auto-subscribes you to notifications. Use tools/stale_issues.py to save and restore subscription state:

  1. Before the first modification, save the current state. This can be run in parallel with fetching the issue body/comments, but it must complete before any gh issue edit, gh issue comment, or gh issue close command is executed:<!-- -->
    python tools/stale_issues.py subscription save <NUMBER>
    
  2. After the last modification, restore the saved state — unless the issue was closed (via gh issue close), in which case skip the restore so the user stays subscribed to follow any responses to the closure. The restore must be the very last GitHub API call — do not run it in the background or in parallel with any gh issue edit or gh issue comment commands:<!-- -->
    python tools/stale_issues.py subscription restore <NUMBER>
    

If either the save or restore command fails, warn the user and continue without the save/restore mechanism.

Important: Never run gh issue edit, gh issue comment, gh issue close, or subscription save/restore commands in the background. These must all run in the foreground so their completion can be verified before proceeding. If commenting or editing fails because the issue is locked, report this to the user and skip the modification.

Security review checklist

Before running any repro code, check for the following concerns:

  • Network requests to untrusted URLs (requests, urllib, curl, wget)
  • File operations outside /tmp/
  • Shell command execution (os.system, subprocess, eval, exec) — but subprocess used to launch torchrun or mp.spawn for distributed repros is expected and not a concern
  • Downloading or loading external files (model weights, pickled objects, data files) — especially torch.load on untrusted .pt/.pth files
  • Obfuscated code (base64-encoded strings, encoded bytes, unusual escapes)
  • Package installation (pip install, conda install)
  • Environment variable manipulation that could affect the host system — but setting MASTER_ADDR, MASTER_PORT, RANK, WORLD_SIZE, CUDA_VISIBLE_DEVICES, or other standard PyTorch/CUDA env vars is expected and not a concern

If any of these are present, explain the concern to the user and ask whether to proceed, skip, or modify the repro to remove the risky parts. If the user chooses to skip, still refresh the triaged label timestamp (remove and re-add, or just add if not present) before reporting that the analysis is finished.

Even if the repro passes the checklist above, check whether the author of the repro code is a PyTorch collaborator by running python tools/stale_issues.py collaborator-check <username>. If the command exits with a non-zero status (user is not a collaborator), show the repro code to the user and ask them to verify it is safe to run before executing it.

Steps

1) Fetch the issue

Fetch the issue body and comments in parallel. Identify the reported repro script and error. If multiple repros are present, prefer the most recent one from the original poster. If a commenter has posted a strictly shorter and more self-contained repro that doesn't require additional context from the issue description, prefer that one. Note which repro you selected. If the repro code is only present in screenshots or images rather than copyable text, stop and report this to the user.

2) Check if the issue is actionable

Before investing effort in reproduction, check whether the issue is actionable. Do not proceed to later steps if any of the following apply:

  • Already closed or resolved in comments. Report to the user and stop. Do not modify labels on closed issues.
  • Duplicate of another issue (linked or obviously the same bug)
  • Not a bug report (feature request, question, discussion, refactoring / code cleanup task). If the issue is a feature request and doesn't already have the feature label, add it via gh issue edit. If the issue is a better-engineering / refactoring task and doesn't already have the better-engineering label, add it via gh issue edit. If the issue includes a repro script that demonstrates the current behavior, apply the security review checklist first, then run it to verify the behavior persists. If the repro needed to be modernized (e.g. updated imports for renamed APIs), or if you verified that the behavior still persists, comment on the issue with the findings and updated repro. After adding any applicable labels (and optionally running/commenting on a repro), report the analysis to the user and do not proceed to later steps.
  • Tracking/meta issue (umbrella issue tracking multiple bugs, burn-down lists, improvement proposals without a specific repro). If the issue doesn't already have the tracker label, add it via gh issue edit. Then stop and report to the user.
  • Requires unavailable hardware (specific GPU models, TPUs, multi-node) with no path to simplify. Note: CUDA is available on the current machine, so single-GPU CUDA repros can be run directly.

For non-actionable issues that are old (more than ~1 year), have no assignees, no recent progress, and are underspecified or lack concrete motivation, suggest closing them as "not planned" (gh issue close --reason "not planned") with a comment explaining the rationale. Ask the user before closing.

If the issue is not actionable and no GitHub-visible modification was made (no label added, no comment posted — saving subscription state does not count), refresh the triaged label to update the issue's "last updated" timestamp. A single gh issue edit with both --remove-label and --add-label doesn't work because the remove and add cancel each other out. Instead, chain both edits in a single Bash tool call: gh issue edit ... --remove-label triaged && gh issue edit ... --add-label triaged. If the issue doesn't have the triaged label, just add it.

Then summarize why the issue is not actionable. If a label or other update was made, just report that the analysis is finished. Only ask the user how to proceed if no update was made and the situation is ambiguous. Always ask the user before closing an issue.

3) Analyze the repro

Evaluate whether the issue has a reasonable repro:

  • Is there a code snippet that can be run?
  • Are the dependencies available (CUDA, distributed, specific hardware)? Note: torch.distributed repros often don't require special hardware — they can be launched with torchrun --nproc_per_node=1 or mp.spawn on a single machine.
  • Is the expected error described?
  • Is the repro self-contained or does it need external data/models?

If there is no repro code at all, or the issue is missing critical info (no error message, no description of expected vs actual behavior), add the needs reproduction label (if not already present) via gh issue edit, then stop and report to the user. Do not attempt to write a repro from the description without being asked.

Conversely, if the issue already has the needs reproduction label but does have a valid repro, remove the label via gh issue edit --remove-label "needs reproduction".

Apply the security review checklist (see above) to the repro before running it.

If the repro requires third-party packages that are not installed (e.g. transformers, torchvision, numpy), stop and ask the user how to proceed rather than installing them yourself.

Summarize your assessment before proceeding.

4) Check for recent verification

If a comment from the last six months already confirms the issue still reproduces (with a matching error and a reasonable repro), stop and ask the user whether they want to re-verify or skip ahead to minimization.

5) Check if it still reproduces

Extract the repro code into a temporary file under /tmp/ and run it with a timeout of 120 seconds. For repros involving torch.compile that call compile multiple times in the same process, add torch._dynamo.reset() between invocations to reset in-memory Dynamo state. This is unnecessary for scripts that compile once and exit.

If the script times out, consider whether a hang is the reported bug or an unrelated issue, and report to the user.

Record the PyTorch version before running (python -c "import torch; print(torch.__version__)") for inclusion in the report.

Check both the exit code and output to determine the result. An exit code > 128 indicates the process was killed by a signal (e.g. segfault = 139, OOM kill = 137) — this is a valid crash reproduction even without a Python traceback. If the repro crashes with a CUDA out-of-memory error and OOM is not the reported bug, try reducing tensor sizes before concluding it doesn't reproduce. For correctness bugs (wrong numerical results rather than crashes), the repro should include an assertion that fails when the bug is present. If the original repro only prints output without asserting, add a simple assertion based on the expected behavior described in the issue (e.g. assert torch.allclose(actual, expected)) so the repro has a clear pass/fail signal.

If the result is inconsistent across runs, run 3-5 times to assess flakiness. For non-deterministic bugs, try setting PYTHONHASHSEED=0 and a fixed torch.manual_seed to stabilize reproduction. Report the success/failure ratio to the user. Flaky repros are still valid bugs — note the flakiness in the issue comment (step 8) and include the success/failure ratio.

Three possible outcomes (to determine which outcome applies, match on the exception class and a distinctive substring of the error message — the substring should be specific enough to identify the bug, e.g. RuntimeError: expected scalar type Float rather than just RuntimeError):

  • Same error as reported: the bug still reproduces. Continue to step 6.
  • No error (passes): the bug may have been fixed. Try to identify the fixing PR (see step 5a), then report to the user. The issue will be closed in step 8.
  • Different error: distinguish between setup issues (missing import, renamed API) that can be fixed and genuinely different bugs. If the error is due to API changes between the reported version and the current version (renamed functions, moved modules, changed signatures), adapt the repro to use the current API while preserving the original intent. If the error is unclear, consider re-running with TORCH_LOGS=+dynamo or other relevant logging flags for more diagnostic output. Report genuinely different errors to the user.

5a) Identify when and how it was fixed

When the bug no longer reproduces, try to determine which version fixed it and which PR introduced the fix.

Version bisection: Check if conda environments named pytorch-<version> (e.g. pytorch-2.6, pytorch-2.8) are available (conda env list | grep pytorch-). If they exist, binary-search across them to find the first version where the bug is fixed. Run from /tmp in a subshell and clear PYTHONPATH to avoid picking up the local source tree (which would cause torch._C import errors): (cd /tmp && PYTHONPATH= conda run -n pytorch-<version> python /tmp/repro_....py). To speed up bisection, pick 2-3 evenly-spaced probe points from the candidate range and test them in parallel each round (e.g. if candidates are 2.2 through 2.8, test 2.4 and 2.6 simultaneously to split the range into thirds). If no versioned conda environments are available, skip bisection and just report that the bug no longer reproduces on the current version.

PR identification: Try to find the specific PR that fixed the bug. Use version control blame on the relevant fix code to find the changeset, then look up the commit message for the PR number (format (#NNNNN)). В качестве альтернативы можно поискать в истории системы контроля версий коммиты, затрагивающие соответствующий файл, по связанному ключевому слову. Если это не даёт быстрого и ясного ответа, просто укажи версию — не трать дополнительное время на поиск PR.

6) Минимизируй воспроизведение

Сохрани исходное рабочее воспроизведение в /tmp/repro_<issue_number>_original.py перед внесением любых изменений.

Сначала оцени, является ли воспроизведение уже достаточно минимальным. Минимизируй только если в воспроизведении есть существенная избыточная сложность (большие модели, неиспользуемые ветки кода, ненужные зависимости и т. п.). При оценке сложности не учитывай неустранимый шаблонный код — например, определение подкласса тензора, содержащее только обязательные dunder-методы (__new__, __init__, __torch_dispatch__, __tensor_flatten__, __tensor_unflatten__), не подлежит сокращению, даже если оно занимает 20+ строк. Сосредоточься на том, можно ли осмысленно уменьшить сложность кода-триггера и модели/настройки. Если единственные возможные «упрощения» косметические (встраивание переменных, удаление __repr__), пропусти минимизацию.

Систематически сокращай воспроизведение, проверяя, вызывает ли каждое упрощение ту же ошибку. Во время минимизации используй более короткий таймаут (30–60 секунд), поскольку упрощённые воспроизведения должны выполняться быстрее. Запускай несколько кандидатов на упрощение параллельно, когда они независимы (то есть изменяют непересекающиеся части кода и ни один не зависит от того, что удаляет другой).

Стратегии сокращения (применяй примерно в таком порядке):

  1. Удали ненужные импорты и настройку (распределённая инициализация, переменные окружения, логирование)
  2. Уменьши модель (замени большие модули минимальными эквивалентами)
  3. Удали обёртку класса/модуля если достаточно голой функции
  4. Уменьши размеры тензоров (большие размерности → маленькие, например 4 или 8)
  5. Удали требования к устройству/dtype (сначала попробуй CPU и float32)
  6. Упрости вычисление (замени сложные операции минимальными, которые всё ещё вызывают баг)
  7. Удали ненужный поток управления (ветвления, циклы, условия)
  8. Попробуй более простые бэкенды (e.g. aot_eager вместо inductor), если баг не специфичен для бэкенда

После каждого раунда проверяй, что ошибка всё ещё воспроизводится — тот же класс исключения и характерная подстрока сообщения об ошибке, как описано в шаге 5 (незначительные различия в трассировке допустимы). Для багов корректности сохраняй утверждение, демонстрирующее неверный результат, и проверяй, что оно по-прежнему показывает то же некорректное поведение. При объединении нескольких успешных параллельных упрощений проверяй, что объединённый результат всё ещё воспроизводится, поскольку независимые упрощения могут взаимодействовать. Прекращай минимизацию, когда воспроизведение занимает менее ~20 строк непустого кода без учёта импортов, или когда два последовательных раунда (где раунд — это один полный проход по применимым стратегиям сокращения) не приводят к дальнейшему упрощению.

7) Примени тривиальные исправления

Если анализ выявляет тривиальное исправление (например, удаление устаревшей xfailIfTorchDynamo or expectedFailure аннотации из теста, поскольку основная проблема исправлена), сообщи об исправлении пользователю и спроси, применять ли его. Не изменяй исходные файлы без одобрения пользователя. В шаге 8 упомяни исправление независимо от того, было ли оно применено или отклонено.

8) Сообщи о результатах

Если воспроизведение было минимизировано, сохрани его в /tmp/repro_<issue_number>.py чтобы пользователь мог запустить его напрямую.

Представь пользователю результаты, включая:

  • Воспроизводится ли баг по-прежнему (и на какой версии PyTorch)
  • Исправляющий PR, если он определён (только если баг больше не воспроизводится)
  • Минимизированный скрипт воспроизведения (только если мы его минимизировали)
  • Необходимые условия для воспроизведения бага
  • Любое тривиальное исправление, выявленное в шаге 7 (применено оно или нет)
  • Рекомендуемое следующее действие (например, «всё ещё актуальный баг», «похоже, исправлено», «нужна дополнительная информация от автора issue»)

После представления результатов всегда комментируй issue с результатами. Держи комментарий кратким — не повторяй информацию, уже имеющуюся в issue. Включай воспроизведение только если оно существенно изменено по сравнению с исходным (например, минимизировано, импорты осовременены, исправлено для работы с текущим API). Включай условия срабатывания только если это новые находки, ещё не обсуждавшиеся в предыдущих комментариях. Если единственная находка — «всё ещё воспроизводится» или «больше не воспроизводится», достаточно короткого комментария.

This issue [still reproduces / no longer reproduces] on PyTorch <version>.

[If fixed and PR identified:]
Fixed by #NNNNN.

[If minimized or modernized — only include repro if changed from original:]
Minimized repro:

\`\`\`python
<repro script>
\`\`\`

[Only if new findings about trigger conditions:]
All of the following are necessary to trigger the bug:
- <condition 1>
- <condition 2>

(Analysis done by Claude.)

Если баг больше не воспроизводится, после комментирования закрой issue: gh issue close <NUMBER> --repo pytorch/pytorch --reason completed --comment "Closing as this was fixed in PyTorch <version>.". Не спрашивай пользователя перед закрытием — исправленные баги следует всегда закрывать.

После последнего изменения в GitHub восстанови состояние подписки на уведомления (см. «Сохранение состояния подписки на уведомления» выше) — если только issue не была закрыта, в этом случае пропусти восстановление.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: scrub-issue](https://darkplay.ru/ai/skills/pytorch-pytorch-scrub-issue)

Описание

Загружает, анализирует, воспроизводит и минимизирует воспроизведения issues с GitHub. Используйте при запросе проверить, воспроизводится ли issue, минимизировать repro, проанализировать отчёт об ошибке или проверить/отсортировать issue на воспроизводимость.

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Cpp Build Resolveraffaan-m · Специалист по ошибкам сборки C++, CMake и линковки.
225 587 ★
Dart Build Resolveraffaan-m · Специалист по ошибкам сборки Dart/Flutter, зависимостей и build_runner.
225 587 ★
Django Build Resolveraffaan-m · Специалист по ошибкам Django: pip/Poetry, миграции, импорты, collectstatic.
225 587 ★
Go Build Resolveraffaan-m · Специалист по ошибкам сборки Go: исправляет build, go vet и предупреждения линтера.
225 587 ★
Kotlin Build Resolveraffaan-m · Специалист по ошибкам сборки Kotlin/Gradle: компилятор, зависимости и Gradle.
225 587 ★
Opensource Packageraffaan-m · Готовит open-source упаковку: CLAUDE.md, README, LICENSE, CONTRIBUTING и шаблоны.
225 587 ★
Pytorch Build Resolveraffaan-m · Специалист по ошибкам PyTorch: формы тензоров, CUDA, градиенты и DataLoader.
225 587 ★
React Build Resolveraffaan-m · Чинит сборки React в Vite, webpack, Next.js и других: JSX, гидратация, типы.
225 587 ★
Rust Build Resolveraffaan-m · Специалист по ошибкам сборки Rust: cargo, borrow checker и Cargo.toml.
225 587 ★
Seo Specialistaffaan-m · SEO-специалист: технический аудит, оптимизация страниц, структурированные данные, Core…
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8