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

debug-model — скилл для Claude Code: что делает и как установить

Протокол отладки модели MAX, которая запускается и выдаёт токены, но расходится с эталоном: сначала дампы тензоров, потом правки.

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

Что делает debug-model

Скилл нужен, когда модель MAX загружается, компилируется и отдаёт токены, но результат не сходится с эталоном: косинус логитов высокий, а argmax другой, или текст сначала связный, а дальше уезжает в мусор. Скалярные F.print такие баги почти не ловят, и каждая новая точка стоит полной перекомпиляции.

Порядок такой. Сначала прогон эталона на HF с тем же чекпойнтом и промптом, потом сборка компаратора: дампер HF, дампер MAX с точками в forward() и скрипт сравнения. Тензоры внутри forward() приводятся к FP32. Затем дамперы проверяются на модели, которую MAX уже отдаёт корректно (olmo3 или llama3_modulev3 с --prefer-module-v3): если там не cos ≈ 0.999, виноват компаратор, а не ваш порт.

Дальше по выводу компаратора выбирают ветку: искать разошедшийся слой или сразу сравнивать серв и пайплайн, когда сошлись все слои. Нужны окружение pixi с установленным MAX, доступ к Hugging Face Hub и GPU для дампа и серва. Падения при загрузке и недописанный модуль — не сюда, там import-model. Калибровку допусков на уже проверенной модели скилл тоже не покрывает.

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

  • найти первый слой, где порт расходится с эталоном на PyTorch
  • отличить сломанный компаратор от сломанной модели
  • проверить гипотезу на дампах, не тратя компиляцию
  • отделить баг модели от бага декод-состояния при серве
  • распутать наложенные ошибки, когда правка помогла, а проверка падает

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

  • Модель отдаёт связный текст несколько токенов, а потом мусор. Пройди по протоколу debug-model.
  • Логиты сходятся, а greedy-токены разные — собери компаратор дампов и найди первый расходящийся слой.
  • После апгрейда MAX косинус по слоям в норме, но генерация уходит в сторону. Что проверять первым?

Как установить debug-model

1Через Skills CLI (Vercel)

npx skills add modular/skills --skill debug-model -a claude-code

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

~/.claude/skills/debug-model/SKILL.md

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

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

Вопросы о debug-model

Как установить debug-model в Claude Code?

Выполните npx skills add modular/skills --skill debug-model -a claude-code. Файл скилла появится в ~/.claude/skills/debug-model/SKILL.md.

Что делает debug-model?

Ведёт отладку расхождений между моделью MAX и эталонной реализацией: строит компаратор тензорных дампов, проверяет гипотезы числами до перекомпиляции и бисектит серв против пайплайна.

Что нужно для работы скилла?

Окружение pixi с установленным MAX, доступ к Hugging Face Hub и GPU для дампа и серва. Без работающего эталона, который можно запустить и обвесить хуками, протокол не на что опереть.

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

SKILL.md · Apache-2.0
---
name: debug-model
description: >
  Debug a MAX model that loads, compiles, serves, and generates tokens but
  whose output disagrees with a reference implementation. Use whenever parity
  debugging stalls on scalar taps, the model returns gibberish or wrong greedy
  tokens, logit cosine is high but argmax differs, or generation is coherent then
  diverges. Applies during an architecture port, a quantization bring-up, a
  multi-GPU conversion, or after a MAX upgrade. Triggers on "parity failure", "silent
  corruption", "logits match but tokens diverge", "top-1 mismatch", "greedy
  divergence", and "model serves but generates garbage". Not for crashes on load
  or pre-serve scaffolding (use import-model). Mandates reference-vs-MAX
  tensor-dump comparators first, numerical verification of fixes before
  recompiling, and a serve-vs-pipeline bisect when dumps match but text diverges.
compatibility: Requires pixi env with MAX installed, network access to Hugging Face Hub, and a GPU for dumping and serving.
---

# Parity/coherence failure protocol

The model runs without errors but output is wrong. Scalar `F.print` taps hide
directional bugs, and each new tap costs a full recompile. Build a per-layer
tensor-dump comparator first. Every later check becomes a numpy read from disk.

**Use this skill when** MAX output disagrees with a PyTorch reference you can
run and hook. The primary case is a custom-architecture port that serves but
fails parity or coherence checks. The same protocol covers a quantized variant
of a working port, a multi-GPU conversion of a working single-GPU port, and a
regression after a MAX upgrade. It applies anywhere a trusted reference exists.

**Don't use this skill when:**

- The server crashes on load → fix config, weights, module (`import-model`)
- You haven't finished implementing the module → `import-model` Phase 2
- An already-verified model needs logit-comparison tolerances tuned → that's
  threshold calibration, which this skill doesn't cover

## References

| File                                                                      | Read when                                                       |
|---------------------------------------------------------------------------|-----------------------------------------------------------------|
| [comparator-build.md](references/comparator-build.md)                     | Building HF/MAX dumpers and the comparator                      |
| [comparator-output-patterns.md](references/comparator-output-patterns.md) | Interpreting comparator output, false cliffs, token-0 invariant |
| [agent-workflow.md](references/agent-workflow.md)                         | Dispatching parallel investigation agents                       |
| [stacked-failures.md](references/stacked-failures.md)                     | A fix helped but verification still fails                       |

For MAX's built-in runtime debugging options (NaN checks, source tracebacks,
op logging), see
[the MAX debugging tools](https://max.modular.com/develop/debugging/).
`max.nn.hooks.PrintHook` (covered in comparator-build.md) prints layer
inputs and outputs for quick triage.

## Protocol

### Step 0: Sanity-check HF

Run `model.generate(...)` on the same HF repo, prompt, and checkpoint. If HF is
incoherent, fix the tokenizer or chat template first. The MAX model isn't the
problem.

```bash
pixi run python -c "
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained('<repo>')
model = AutoModelForCausalLM.from_pretrained('<repo>', dtype=torch.float32, device_map='auto')
text = tok.apply_chat_template([{'role':'user','content':'Hello!'}], tokenize=False, add_generation_prompt=True)
out = model.generate(**tok(text, return_tensors='pt').to(model.device), max_new_tokens=32, do_sample=False)
print(tok.decode(out[0]))
"
```

### Step 1: Build the comparator

Follow [comparator-build.md](references/comparator-build.md). You need three
artifacts: HF dumper, MAX dumper (`forward()` taps + standalone runner),
comparator script. Cast dump tensors to FP32 inside the MAX `forward()`.

> **Guard: validate the dumpers before trusting them.** Run both dumpers on a
> ModuleV3 model that MAX already serves correctly, with the taps added to its
> `forward()`. Use `olmo3`, or `llama3_modulev3` served with
> `--prefer-module-v3`. Expect cos ≈ 0.999 at every layer, identical
> `prompt_tokens.npy` on both sides, and `post_embed` cos = 1.0. Anything less
> means the dumpers are broken. Fix them before reading anything into a
> comparison on your port.

### Step 2: Read comparator output, then branch

Follow
[comparator-output-patterns.md](references/comparator-output-patterns.md). Check
false cliffs (wrong `hidden_states` indexing, missing `attention_mask` on
decode-prefix dumps) before bisecting the model.

Choose the next step from the first comparator run that passes the guard:

- **Some layer diverges** → layer hunt. Continue with Steps 3 to 5.
- **Every layer matches (cos ≥ 0.99) but generation still diverges** → the
  model math is likely correct. Skip to Step 6. Don't bisect layers.
- **Pattern matches a false-cliff signature** → fix the dumper, re-dump,
  re-read. Don't debug the model against a broken comparator.

Compute per-token and per-dim cosine slices when global cos looks ambiguous:

```python
cos_per_token = [cos(h[t], m[t]) for t in range(h.shape[0])]
cos_per_dim = [cos(h[:, d], m[:, d]) for d in range(h.shape[1])]
```

High `max_diff` where HF spikes and MAX is flat usually means HF formed an
attention anchor your port didn't.

### Step 3: Dispatch investigation agents

Follow [agent-workflow.md](references/agent-workflow.md). One lead agent
analyzes dumps and ranks hypotheses with tensor evidence. Helpers run in
parallel (weight stats, code diff, kernel inspection, sub-tap prep). Don't
dispatch fix-attempt agents until the lead localizes.

### Step 4: Verify numerically before recompiling

For each hypothesis: read dump tensors, compute what the fix would produce,
compare to HF. Match → recompile. No match → next hypothesis.

### Step 5: Apply fix, re-dump, re-compare

One compile, one smoke, full comparator pass (cos > 0.99 all layers). If
verification still fails, see
[stacked-failures.md](references/stacked-failures.md).

### Step 6: Serve vs pipeline

When teacher-forced dumps at decode step K match HF but generated text diverges,
the model math is likely correct. Bisect before re-bisecting layers:

| Check                           | Pass                       | Fail →                                                 |
|---------------------------------|----------------------------|--------------------------------------------------------|
| Teacher-forced dump @ K         | cos ≥ 0.99, argmax matches | Steps 1 to 5 (model bug)                               |
| Incremental pipeline decode @ K | token K matches HF         | Decode-state bug (KV, conv cache)                      |
| Serve vs pipeline @ K           | match                      | Harness bug (tokenizer, chat template, token recovery) |

Build if missing: pipeline decode compare, incremental layer dump, serve
compare scripts. If teacher-forced and pipeline both pass but serve fails, don't
edit the model.

© modular · Apache-2.0 · modular/skills

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

Всё по теме «ИИ и ML» →
segment-anything-model Orchestra Research Скилл для работы с SAM: выделяет объекты на картинке по точке, рамке или маске и умеет находить все объекты сразу. CX Codex +1 985установок ML Model Training aj-geddes Скилл для обучения моделей машинного обучения: классификация, регрессия и кластеризация на scikit-learn, PyTorch и TensorFlow. CX Codex +1 515установок Model Hyperparameter Tuning aj-geddes Скилл для подбора гиперпараметров моделей: grid search, random search, байесовская оптимизация через Optuna. Пригодится, когда базовые настройки уже не тянут. CX Codex +1 494установок ml-model-training secondsky Скилл ведёт агента по полному циклу обучения модели: подготовка данных, разбивка, тренировка и оценка. Пригодится, когда нужно собрать классификатор или регрессию без забытых шагов. CX Codex +1 457установок safe-debug lllllllama Консервативная диагностика сбоев в deep learning исследованиях: локализует причину ошибки и готовит минимальный патч без несогласованных правок в коде. CX Codex +1 335 000установок debug-mantra thananon Задаёт порядок от воспроизведения сбоя до проверки гипотез и журнала экспериментов. Нужен при ошибках, журналах ошибок и трассировках стека. CX Codex +1 4 900установок

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

mojo-python-interop Скилл для агентов, которые пишут код на Mojo с вызовами Python: подсказывает актуальный синтаксис вместо устаревшего из обучающих данных. CX Codex +1 2 600установок mojo-gpu-fundamentals Инструкция для ИИ-агентов по низкоуровневой разработке на Mojo под GPU NVIDIA, AMD и Apple silicon. Избавляет модель от попыток вставлять синтаксис CUDA. CX Codex +1 2 600установок new-modular-project Создаёт и настраивает проекты на Mojo или MAX через менеджеры pixi либо uv. Скилл запрашивает только недостающие параметры и подключает каналы stable или nightly. CX Codex +1 2 400установок import-model Скилл ведёт агента через порт архитектуры из Hugging Face в MAX: разбор конфига, реализация слоёв, проверка против эталона. CX Codex +1 1 400установок profile-model Профилирует модели MAX, чтобы проверить загрузку GPU и найти самые долгие GPU-ядра. Нужен при медленном инференсе или разборе трассировки. CX Codex +1 1 200установок eval-model Гоняет текстовую модель за MAX по стандартным бенчмаркам и пишет воспроизводимые оценки по каждой задаче. Пригодится, когда надо сверить серверную модель с карточкой. CX Codex +1 981установок serve-model Скилл помогает поднять OpenAI-совместимый сервер для модели через max serve: от установки окружения до подбора флагов. CX Codex +1 949установок benchmark-model Гоняет нагрузку на запущенный max serve и выдаёт tokens/sec, TTFT и TPOT. Нужен, когда надо понять, сколько модель держит и где проседает latency. CX Codex +1 887установок

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

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