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

preference-optimization — скилл для Claude Code: что делает

Помогает выбрать и настроить метод выравнивания LLM: DPO, ORPO, KTO или SimPO. Пригодится при наличии пар предпочтений или бинарных оценок пользователей.

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add wshobson/agents
/plugin install llm-finetuning@claude-code-workflows
Открыть на GitHub

Что делает preference-optimization

Скилл определяет подходящий метод выравнивания и формирует точные параметры для TRL и Unsloth. Базовый вариант по умолчанию — DPO с β=0.1 и скоростью обучения 5e-7–1e-6. Если видеопамяти GPU не хватает на отдельную референсную модель, скилл переключает пайплайн на ORPO. Для непарных сигналов вроде лайков и дизлайков выбирается KTO, а SimPO рекомендуется только при борьбе с раздуванием ответов и наличии ресурсов на подбор параметров.

Логика выбора опирается на исследование arXiv 2603.19335 по итогам 240 прогонов на H100. Смена функции потерь даёт всего около 1 процентного пункта разницы, тогда как масштаб модели — около 50. Из 20 вариантов DPO ни один не превзошёл базовую версию на целевом масштабе. Поэтому скилл исключает долгие тесты редких модификаций и предлагает собирать пары по порогу μ−2σ от распределения наград вместо крайнего минимума.

Для рабочих пайплайнов описан итеративный цикл on-policy DPO: модель генерирует ответы, получает оценки и служит базой для следующего шага. Ставьте скилл, если настраиваете обучение предпочтениям после SFT. Классический PPO с отдельной моделью наград скилл не использует, считая его устаревшим для прикладных задач.

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

  • подобрать алгоритм выравнивания под формат разметки
  • сгенерировать параметры DPO, ORPO, KTO или SimPO для TRL
  • установить корректный шаг обучения ниже уровня SFT
  • составить пары предпочтений по формуле μ−2σ наград
  • выстроить итеративный цикл дообучения on-policy DPO

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

  • У нас есть чекпоинт после SFT и лайки с дизлайками пользователей, какой метод применить?
  • Ответы DPO получаются слишком длинными, помоги настроить SimPO и сетку параметров
  • Собери пары chosen и rejected из трейсов одного задания

Как установить preference-optimization

1Через маркетплейс плагинов

/plugin marketplace add wshobson/agents
/plugin install llm-finetuning@claude-code-workflows

Команда ставит плагин llm-finetuning целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add wshobson/agents --skill preference-optimization -a claude-code

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

~/.claude/skills/preference-optimization/SKILL.md

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

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

Весь набор →
typescript-advanced-types Seth Hobson Помогает агенту писать сложную типизацию TypeScript: generics, conditional types и преобразования типов. Нужен для библиотек, API-клиентов и строгих конфигураций. Claude Code CX Codex Cursor 92 169установок tailwind-design-system Seth Hobson Помогает строить дизайн-системы на Tailwind CSS v4. Пригодится для библиотеки компонентов или унификации интерфейса в проекте. Claude Code CX Codex Cursor 70 180установок brand-landingpage Travis D. Elliott Скилл проводит интервью о продукте и визуальном стиле, затем помогает создать лендинг через Stitch. Подойдёт, если у проекта пока нет готового дизайна. Claude Code CX Codex Cursor 39 476установок python-testing-patterns Seth Hobson Скилл помогает писать тесты Python с pytest, фикстурами и моками. Подходит для настройки тестового набора и отладки падающих проверок. Claude Code CX Codex Cursor 36 943установок python-performance-optimization Seth Hobson Скилл помогает профилировать Python-код, находить узкие места CPU и памяти. Подходит, когда приложение медленно отвечает или тратит слишком много ресурсов. Claude Code CX Codex Cursor 35 675установок nextjs-app-router-patterns Seth Hobson Помогает строить приложения на Next.js App Router: выбирать режим рендеринга, организовывать маршруты и получать данные. Подойдёт при миграции с Pages Router или работе с Server Components. Claude Code CX Codex Cursor 32 529установок api-design-principles Seth Hobson Скилл помогает проектировать и проверять REST- и GraphQL API. Пригодится при подготовке спецификации, пересмотре существующего API или согласовании стандартов команды. Claude Code CX Codex Cursor 30 348установок code-review-excellence Seth Hobson Скилл помогает разбирать pull request по этапам, находить ошибки и давать конкретную обратную связь. Подойдёт для ревью кода и настройки командных стандартов. Claude Code CX Codex Cursor 30 193установок

Похожие

phoenix-tracing официальный [email protected] Скилл помогает добавить OpenInference-трассировку к LLM-приложению и разбирать данные в Phoenix. Пригодится для настройки трасс, пользовательских спанов и подготовки к продакшену. GitHub Copilot 1 000установок phoenix-evals официальный [email protected] Скилл помогает создавать и запускать оценщики для AI- и LLM-приложений с Phoenix. Пригодится для разбора ошибок, проверки RAG и оценки качества моделей. GitHub Copilot 1 000установок phoenix-cli официальный arize-ai Скилл для GitHub Copilot, который через Phoenix CLI достаёт трейсы, спаны и сессии, помогает найти причины сбоев LLM-приложений и собрать таксономию ошибок. GitHub Copilot 1 000установок gke-ai-troubleshooting-node-unresponsive-timeout официальный google Находит причины зависания GPU и TPU нод в GKE со статусом NodeStatusUnknown. Помогает, когда от ноды перестали приходить хартбиты, а поды зависли в Terminating. Claude Code Gemini CLI CX Codex 810установок skill-creator официальный anthropics Помогает создать новый скилл, доработать существующий и проверить результат через тестовые промпты и оценки. Claude Code Claude.ai 414 180установок writing-for-agents Matt Pocock Помогает писать скиллы и документы с инструкциями для агентов. Пригодится при правках AGENTS.md, CLAUDE.md и связанных справочных файлов. Claude Code 466 719установок media-use heygen-com Находит и генерирует ассеты для видео в HyperFrames — музыку, дикторский голос, аватары и эффекты. Сохраняет всё локально в assets. Claude Code CX Codex Cursor +1 1 100 000установок mcp-builder официальный anthropics Скилл проводит через создание MCP-сервера на TypeScript или Python: от изучения протокола до тестов и оценки качества. Claude Code Claude.ai 130 949установок

Вопросы о preference-optimization

Как установить preference-optimization в Claude Code?

Выполните команду npx skills add wshobson/agents --skill preference-optimization -a claude-code. Также доступна установка через /plugin install llm-finetuning@claude-code-workflows.

Что делает preference-optimization?

Скилл сопоставляет доступные данные с алгоритмами DPO, ORPO, KTO или SimPO и отдаёт готовые аргументы для конфигов обучения.

Почему нельзя использовать learning rate из этапа SFT?

Для DPO требуется меньший шаг обучения — от 5e-7 до 1e-6 на 1–2 эпохи. Перенос высокого LR из этапа SFT приводит к нестабильности и считается частой ошибкой настройки.

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

SKILL.md · MIT
---
name: preference-optimization
description: Align a fine-tuned model with preference data using DPO, ORPO, KTO, or SimPO. Use when preference pairs or thumbs-up/down feedback exist, when choosing between preference-optimization methods, or when a DPO run needs hyperparameters or debugging.
---

# Preference Optimization

This skill assumes `finetuning-method-selection`
already routed here because the data shape is
preference pairs or unpaired thumbs-up/down
feedback, not demonstrations (that's
`lora-qlora-recipes`) or a verifiable reward
signal (that's `grpo-rlvr-training`). What
follows is method selection among the DPO family,
the evidence for how much that selection actually
matters, the production training pattern, and how
to build the pairs in the first place.

**Input:** a routing decision (preference
optimization) plus preference pairs or unpaired
feedback, usually from an SFT checkpoint.
**Output format:** a validated method choice plus
a config — the kwarg values in
`references/method-configs.md`, not free-form
advice — that `llm-finetuning-training-engineer`
consumes directly.

## Method Selection

| Data shape | Method | Key parameters |
|---|---|---|
| Preference pairs, default case | **DPO** | β=0.1, LR 5e-7–1e-6, 1–2 epochs |
| Memory-bound or no SFT checkpoint | **ORPO** | reference-free, fused SFT+preference in one loss |
| Unpaired thumbs-up/down | **KTO** | binary label per example, no pairing needed |
| Length bias observed, sweep budget available | **SimPO** | reference-free; see sweep grid below |

- **DPO is the safe default.** Use β=0.1 and a
  learning rate of 5e-7 to 1e-6 for 1–2 epochs.
  This LR is *lower* than the SFT LR that produced
  the checkpoint being aligned — porting an SFT-
  scale LR into a DPO run is the most common
  misconfiguration here, not an edge case.
- **ORPO** routes in when memory is the
  constraint, or when there's no separate SFT
  checkpoint to start from — it's reference-free
  and fuses the SFT and preference objectives into
  one loss, skipping the separate SFT pass and the
  reference-model memory cost DPO carries.
- **KTO** routes in when feedback is unpaired
  binary signal (thumbs-up/down) rather than
  matched preference pairs — don't force unpaired
  feedback into synthetic pairs to use DPO instead.
- **SimPO** fixes DPO's length bias but only pays
  off with disciplined sweeping — its published
  gains are a ceiling reported under a tuned sweep,
  not a baseline any single config will reproduce.
  Route here only when there's sweep budget; use
  DPO instead if there isn't.
- **Classic RLHF (reward model + PPO) is retired**
  outside frontier labs. Don't reach for it in a
  production pipeline — every method above is
  cheaper and better-supported for the same data
  shapes.

### Worked Examples

- *"We have an SFT checkpoint and clean paired
  preference data, no length-bias complaints yet."*
  → default case → **DPO** at β=0.1.
- *"Reviewers click thumbs-up/down per response;
  nothing is paired."* → unpaired signal →
  **KTO**, not DPO — don't synthesize pairs to
  force DPO onto unpaired data.
- *"GPU budget doesn't cover a separate SFT pass
  plus a DPO reference model."* → memory-bound,
  no separate checkpoint → **ORPO**.
- *"DPO output favors longer answers regardless of
  quality, and there's time to run a sweep."* →
  length bias plus sweep budget → **SimPO**. Skip
  it if the sweep budget isn't actually there.

## The Low-Leverage Truth

A 2026 240-H100-run study (arXiv 2603.19335) is
the load-bearing evidence behind the table above:
**loss-function choice is worth roughly 1
percentage point of leverage, model scale is
worth roughly 50.** Zero of 20 DPO variants tested
beat vanilla DPO. Rankings also **invert with
scale** — a variant that wins in a small pilot can
lose at deployment size.

Two practical consequences:

- Don't spend a routing decision agonizing over
  DPO-variant bake-offs. The table above is
  sufficient; deeper variant selection is
  low-leverage compared to data quality and scale.
- **Validate at deployment scale before trusting a
  ranking.** A method comparison run on a small
  pilot model doesn't transfer to the production
  size class — re-check the winner once scale
  changes.

This is also why the Method Selection table above
is deliberately short: it encodes the ~1pp lever,
not a ranking of DPO variants that the same study
shows doesn't hold up across scale. Treat any
variant-selection advice that isn't in that table
— including advice that claims a specific variant
"wins" — as unproven until it's been validated at
the target deployment size.

## Production Pattern: Iterative On-Policy DPO

A single offline DPO pass on a static preference
dataset is a starting point, not the production
pattern. The policy drifts away from the
distribution the pairs were sampled from as
training proceeds, and a static dataset goes stale
against that drift. Production pipelines run DPO
iteratively and on-policy instead:

1. Sample completions from the current policy
   checkpoint.
2. Score or rank the completions (reward model,
   judge, or task grader).
3. Run a DPO pass using the current checkpoint as
   the reference model.
4. The resulting checkpoint becomes both the new
   policy *and* the new reference for the next
   round.

Repeat. Each round's reference model is the prior
round's output, not a fixed initial checkpoint —
that's what keeps the preference signal on-policy
instead of scoring against an increasingly stale
distribution.

A single-pass DPO run is still a reasonable first
iteration — it just isn't the whole pipeline. Plan
for at least one more round once the first
checkpoint exists, rather than treating pass one
as the finished artifact.

## Pair Construction

Build DPO/ORPO pairs from **same-task
passing-vs-failing trajectories** — two attempts
at the same underlying task, not unrelated
best-and-worst examples pulled from different
tasks. Within that trajectory set, select the
rejected member at **μ−2σ of the reward
distribution, never the minimum**. Naive
best-vs-worst pair construction (max reward vs.
absolute minimum) degrades as scale increases; the
μ−2σ selection is more robust to the same scale
sensitivity the low-leverage study surfaced above.

```
sorted_by_reward = sort(trajectories, key=reward)
chosen   = sorted_by_reward[-1]                # highest reward
mu, sigma = mean(rewards), stdev(rewards)
rejected = closest(sorted_by_reward, mu - 2 * sigma)
# NOT sorted_by_reward[0] — the absolute minimum
# is the naive best-vs-worst construction that
# degrades as scale increases.
```

For the mechanics of turning graded traces into
these pairs — including rejection sampling and
judge-scored delta selection — see
`trace-to-training-data`.

## References

Complete TRL config blocks per method —
`DPOConfig`, `ORPOConfig`, `KTOConfig`, and the
SimPO sweep grid — plus Unsloth wrappers and a
catastrophic-forgetting note live in
`references/method-configs.md`. Those configs use
the same current-TRL API conventions established
in `lora-qlora-recipes`'s
`references/unsloth-trl-mapping.md`
(`processing_class`, not `tokenizer=`).

`references/method-configs.md` also carries the
catastrophic-forgetting note: a too-high learning
rate is the usual cause when a preference-tuned
checkpoint loses general capability, and the fix
is almost always to drop the LR toward the low end
of the range in the Method Selection table above
before reaching for any other remediation.

Related skills: `finetuning-method-selection`
routes here once preference pairs or unpaired
feedback exist; `lora-qlora-recipes` produces the
SFT checkpoint DPO/KTO/SimPO align (ORPO's
fused path can skip it); `trace-to-training-data`
converts passing/failing trajectories into the
pairs this skill's Pair Construction section
consumes.

© Seth Hobson · MIT · wshobson/agents

Смотрите также

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

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