nemo-mbridge-perf-hierarchical-context-parallel — скилл Claude Code
Скилл настраивает иерархический контекстный параллелизм в Megatron-Bridge. Помогает масштабировать обучение длинных последовательностей при нехватке KV-голов.
npx skills add NVIDIA/skills --skill nemo-mbridge-perf-hierarchical-context-parallel -a claude-codeЧто делает nemo-mbridge-perf-hierarchical-context-parallel
Инструкция объясняет, как включить комбинированную схему a2a+p2p с параметром hierarchical_context_parallel_sizes и связать уровни коммуникации. Она описывает создание групп процессов через MPU и передачу их в Transformer Engine.
Для работы обязателен Transformer Engine версии не ниже 1.12.0. Длина последовательности seq_length должна делиться на удвоенный размер context_parallel_size. Вдобавок в Megatron-Bridge поддерживается только MPU: если задать флаг use_decentralized_pg=True, многоуровневые группы не создадутся, а фреймворк вернётся к плоскому CP.
В старых версиях MCore пропуск параметров приводил к тихому отключению обмена данными и фиктивному росту скорости со сломанными градиентами. Скилл даёт команду тестового запуска на четырёх GPU и критерии проверки по логам: в выводе должны появиться группы HIERARCHICAL_CONTEXT_PARALLEL_GROUPS.
Какие задачи решает
- настроить схему коммуникации a2a+p2p в Megatron-Bridge
- масштабировать контекстный параллелизм за пределы числа KV-голов
- проверить создание групп HIERARCHICAL_CONTEXT_PARALLEL_GROUPS по логам
- устранить скрытые ошибки градиентов из-за неверной конфигурации CP
Примеры запросов агенту
- Настрой иерархический параллелизм контекста в Megatron-Bridge для четырёх видеокарт.
- Проверь распределённую конфигурацию и найди причину ошибки в режиме a2a+p2p.
- Покажи команду запуска рецепта для проверки многоуровневого контекстного параллелизма.
Как установить nemo-mbridge-perf-hierarchical-context-parallel
1Через Skills CLI (Vercel)
npx skills add NVIDIA/skills --skill nemo-mbridge-perf-hierarchical-context-parallel -a claude-code2Вручную: положить файлы
~/.claude/skills/nemo-mbridge-perf-hierarchical-context-parallel/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/nemo-mbridge-perf-hierarchical-context-parallel/
1Через Skills CLI (Vercel)
npx skills add NVIDIA/skills --skill nemo-mbridge-perf-hierarchical-context-parallel -a codex2Вручную: положить файлы
.agents/skills/nemo-mbridge-perf-hierarchical-context-parallel/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add NVIDIA/skills --skill nemo-mbridge-perf-hierarchical-context-parallel -a cursor2Вручную: положить файлы
.cursor/skills/nemo-mbridge-perf-hierarchical-context-parallel/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install NVIDIA/skills nemo-mbridge-perf-hierarchical-context-parallel2Вручную: положить файлы
.github/skills/nemo-mbridge-perf-hierarchical-context-parallel/SKILL.md1Через Skills CLI (Vercel)
npx skills add NVIDIA/skills --skill nemo-mbridge-perf-hierarchical-context-parallel -a gemini-cli2Командой платформы
gemini skills install https://github.com/NVIDIA/skills --path skills/nemo-mbridge-perf-hierarchical-context-parallelВручную: положить файлы
.devin/skills/nemo-mbridge-perf-hierarchical-context-parallel/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add NVIDIA/skills --skill nemo-mbridge-perf-hierarchical-context-parallel -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о nemo-mbridge-perf-hierarchical-context-parallel
Как установить nemo-mbridge-perf-hierarchical-context-parallel в Claude Code?
Выполните команду npx skills add NVIDIA/skills --skill nemo-mbridge-perf-hierarchical-context-parallel -a claude-code.
Зачем нужен иерархический контекстный параллелизм?
Он делит обработку длинной последовательности между GPU, когда размер CP превышает число голов ключей и значений. Схема a2a+p2p объединяет передачу данных внутри узла и между узлами во вложенные группы.
Какие системные требования нужны для работы?
Требуется Transformer Engine версии 1.12.0 или новее. Параметр use_decentralized_pg должен быть выключен, а произведение чисел в hierarchical_context_parallel_sizes обязано строго равняться context_parallel_size.
Исходный текст
SKILL.md · Apache-2.0
---
name: nemo-mbridge-perf-hierarchical-context-parallel
description: Operational guide for enabling hierarchical context parallelism in Megatron-Bridge, including config knobs, code anchors, pitfalls, and verification.
license: Apache-2.0
when_to_use: Scaling context parallelism beyond KV heads, or investigating a commit that changed CP config and caused OOM or a regression; 'hierarchical_context_parallel_sizes', 'a2a+p2p', 'hierarchical CP', 'CP beyond KV heads', 'multi-level CP'.
---
# Hierarchical Context Parallel Skill
This skill covers hierarchical context parallelism: nested context-parallel process
groups used by `cp_comm_type="a2a+p2p"` and configured with
`hierarchical_context_parallel_sizes`.
For what hierarchical CP is, when to use it, and the decision tree
(`a2a+p2p` vs pure `a2a` vs `p2p`), see:
- @docs/training/hierarchical-context-parallel.md
- @skills/nemo-mbridge-perf-hierarchical-context-parallel/card.yaml
## Enablement
Minimal Bridge override:
```python
cfg.model.context_parallel_size = 4
cfg.model.cp_comm_type = "a2a+p2p"
cfg.model.hierarchical_context_parallel_sizes = [2, 2]
cfg.dist.use_decentralized_pg = False
```
Required constraints:
- `prod(hierarchical_context_parallel_sizes) == context_parallel_size`
- `seq_length % (2 * context_parallel_size) == 0`
- Transformer Engine `>= 1.12.0`
## Code Anchors
Upstream config and validation:
```45:54:3rdparty/Megatron-LM/megatron/core/model_parallel_config.py
context_parallel_size: int = 1
"""Splits network input along sequence dimension across GPU ranks."""
hierarchical_context_parallel_sizes: Optional[list[int]] = None
"""Degrees of the hierarchical context parallelism. Users should provide a list to specify
the sizes for different levels. Taking the a2a+p2p cp comm type as example, it contains
groups of two levels, so the first value of the list indicates the group size of the a2a
communication type, and the second value indicates the group size of the p2p communication
type.
"""
```
```428:433:3rdparty/Megatron-LM/megatron/training/arguments.py
if args.hierarchical_context_parallel_sizes:
from numpy import prod
assert args.context_parallel_size == prod(args.hierarchical_context_parallel_sizes)
if "a2a+p2p" in args.cp_comm_type:
assert args.hierarchical_context_parallel_sizes is not None, \
"--hierarchical-context-parallel-sizes must be set when a2a+p2p is used in cp comm"
```
Bridge MPU path:
```613:648:src/megatron/bridge/training/initialize.py
parallel_state.initialize_model_parallel(
...
context_parallel_size=model_config.context_parallel_size,
hierarchical_context_parallel_sizes=model_config.hierarchical_context_parallel_sizes,
...
)
...
return ProcessGroupCollection.use_mpu_process_groups()
```
Bridge decentralized-PG path:
```503:524:src/megatron/bridge/training/initialize.py
pg_collection = ProcessGroupCollection(
...
cp=cp_pg,
tp_cp=tp_cp_pg,
hcp=None,
ep=ep_pg,
...
)
```
## Implementation Map
The code anchors above show the config declarations and argument validation.
### Validation (MCore)
`TransformerConfig.__post_init__` enforces that `a2a+p2p` requires HCP sizes and the product matches CP.
### Process group creation
`parallel_state.initialize_model_parallel` creates hierarchical CP sub-groups
when HCP sizes are provided via `create_hierarchical_groups`. Bridge currently
gets those groups through the MPU-backed `ProcessGroupCollection`.
### TE integration
`TEDotProductAttention` passes the hierarchical groups to Transformer Engine
when `a2a+p2p` is used. Requires **Transformer Engine >= 1.12.0**.
## Pitfalls
1. **Bridge HCP is MPU-only today**: If `use_decentralized_pg=True`, Bridge initializes flat CP groups and leaves HCP unset.
2. **No checked-in Bridge recipe** currently exercises HCP directly.
3. **Single-GPU load helpers** clear `hierarchical_context_parallel_sizes`.
4. **Silent broken training on old stacks**: If you use `a2a+p2p` without setting `hierarchical_context_parallel_sizes`, MCore now asserts. Older versions would silently disable CP communication, so each rank attended only to its local chunk and produced artificially high throughput with broken gradients.
5. **Product must match**: `prod(hierarchical_context_parallel_sizes)` must exactly equal `context_parallel_size`. A mismatch triggers an assertion.
6. **Verify in logs**: Look for the process group initialization output. You should see `HIERARCHICAL_CONTEXT_PARALLEL_GROUPS` being created. If you only see `CONTEXT_PARALLEL_GROUP`, HCP is not active.
## Verification
No dedicated Bridge end-to-end test exists yet for HCP (see @skills/nemo-mbridge-perf-hierarchical-context-parallel/card.yaml
`follow_up_validation`). Use the existing unit tests and log inspection instead.
Run the decentralized-PG unit test to confirm the flat-CP behavior is preserved:
```bash
uv run python -m pytest tests/unit_tests/training/test_decentralized_pg.py -q
```
For a manual smoke check, launch a 4-GPU run with a small recipe and
`cp_comm_type=a2a+p2p` plus `hierarchical_context_parallel_sizes=[2,2]`:
```bash
CUDA_VISIBLE_DEVICES=0,1,2,3 uv run python -m torch.distributed.run --nproc_per_node=4 \
scripts/training/run_recipe.py \
--recipe llama32_1b_pretrain_config \
model.context_parallel_size=4 \
model.cp_comm_type=a2a+p2p \
"model.hierarchical_context_parallel_sizes=[2,2]" \
train.train_iters=2
```
Success criteria:
- Logs show `HIERARCHICAL_CONTEXT_PARALLEL_GROUPS` being created
- Training completes at least one step without error
- If you only see `CONTEXT_PARALLEL_GROUP`, HCP is not active
© NVIDIA · Apache-2.0 · NVIDIA/skills