К основному содержанию
скилл CX Codex официальный · GitHub

embedding-anisotropy-check — скилл для GitHub Copilot

Скилл embedding-anisotropy-check для GitHub Copilot вычисляет анизотропию эмбеддингов и находит базовый уровень сходства для несвязанных пар. Запускается перед оценкой моделей, слоёв или качества ретривера.

MIT ★ 41 430 обновлён 2026-10-23

Установить в GitHub Copilot · GitHub CLI Все способы и платформы ↓
gh skill install github/awesome-copilot skills/embedding-anisotropy-check
Открыть на GitHub

Что делает embedding-anisotropy-check

Скилл проверяет распределение векторов перед публикацией косинусного сходства. Большинство энкодеров предложений и слоёв трансформеров сдвигают скрытые состояния в одну общую сторону, из-за чего косинус между несвязанными текстами нередко достигает 0.6 или 0.9. Инструмент центрирует векторы по среднему значению генеральной совокупности и сопоставляет сходство пар с базовым уровнем случайных перестановок.

Внутрь входит скрипт scripts/anisotropy_check.py, принимающий массивы A.npy и B.npy размерности (n, d). Скрипт поддерживает расчёт общего среднего флагом --shared, а также центрирование по отдельным обучающим выборкам через --fit-a и --fit-b. В отчёте выводятся анизотропия, показатели до и после центрирования, а также метрика partner_ranked_first.

Для двух независимо обученных моделей без явного выравнивания скилл не подходит. Сначала нужно выполнить ортогональное преобразование Прокруста. Для работы скрипта требуется Python 3.9+ и пакет numpy.

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

  • рассчитать базовый уровень косинусного сходства для несвязанных пар
  • измерить анизотропию векторов в скрытых слоях трансформера
  • центрировать эмбеддинги по среднему вектору обучающей выборки
  • проверить смещение представлений при квантовании модели в 4 бита

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

  • Проверь сходство эмбеддингов в A.npy и B.npy с учётом базового уровня
  • Оцени анизотропию представлений после квантования модели в 4 бита
  • Сравни представления между слоями трансформера через anisotropy_check.py

Как установить embedding-anisotropy-check

1GitHub CLI

gh skill install github/awesome-copilot skills/embedding-anisotropy-check

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

.github/skills/embedding-anisotropy-check/SKILL.md

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

Вопросы об embedding-anisotropy-check

Как установить embedding-anisotropy-check в GitHub Copilot?

Выполните команду gh skill install github/awesome-copilot skills/embedding-anisotropy-check в терминале.

Зачем нужен embedding-anisotropy-check?

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

Что нужно для работы embedding-anisotropy-check?

Требуются Python версии 3.9 или выше и библиотека numpy. Для запуска тестового примера из репозитория также понадобятся datasets, sentence-transformers и torch.

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

SKILL.md · MIT
---
name: embedding-anisotropy-check
description: 'Use before reporting any cosine similarity computed over embeddings or transformer hidden states, whether the agent computed the vectors or loaded them. Measures the anisotropy of each side, centres by the population mean, and scores matched pairs against a permuted floor taken from the same comparison. Use when comparing one model''s embeddings across precisions, runtimes or layers, when evaluating retrieval, probes or adapters, or before calling a similarity high, two conditions in agreement, or a small gap a null.'
license: MIT
compatibility: Python 3.9+ with numpy
---

# Embedding anisotropy check

Raw cosine between embeddings is rarely centred on zero. Most sentence encoders and most hidden-state layers place
every vector near one shared direction, so two unrelated inputs can score 0.6, 0.9 or 0.99. A matched pair at 0.9 is
then not evidence of anything by itself, and a gap of 0.01 between two conditions can be the whole signal or none of
it. This skill makes every such comparison carry its own floor.

## How an agent reaches this skill

The agent does not vectorise anything here. The skill applies at the point where the agent is about to report a cosine
number, whoever produced the vectors:

- **The agent wrote the evaluation.** A request such as "write a retrieval eval for our index" or "check that the 4-bit
  export of this encoder still matches bf16" ends in a script that prints a mean cosine. Before the agent says
  "0.91, the export is fine", it runs the same model's unrelated pairs through the script and reports the floor beside
  the matched figure.
- **The vectors already exist in the workspace.** An `embeddings.npy`, a probe or adapter evaluated on saved hidden
  states, a vector-store dump. Asked "are these two layers encoding the same thing" or "did the fine-tune move the
  representations", the agent loads the arrays and runs the check before answering.
- **A claim is being written.** The agent is drafting a README, a PR description or a results table that calls a
  similarity high, says two conditions agree, or calls a small difference a null. The number in that sentence is the
  trigger.

## When to use this skill

- The same inputs under one model at two precisions (bf16 against 4-bit), in two runtimes, or at two nearby layers,
  which share one coordinate space.
- Query and passage, image and caption, or any other paired evaluation inside one embedding space.
- Any sentence claiming that a similarity is high, that two conditions agree, or that a small difference is a null.

Not for two independently trained models as they stand. A rotation of one model's space keeps its geometry and changes
every cosine against the other model, and centring does not align the two bases. Fit an explicit map first, for
example orthogonal Procrustes on a train split of paired rows, and compare the mapped rows; or compare each model's
own within-space similarities instead.

## Procedure

1. Save the compared rows as two `.npy` arrays of shape `(n, d)`, row `i` of A paired with row `i` of B.
2. Choose where the means come from. The best source is a train split from the same domain, model and modality as the
   compared rows. A mean fitted on another domain mis-centres: it can leave part of the shared direction in place,
   remove too much of it, or add a direction of its own, and what it leaves then looks like an effect of whatever
   differs between the domains.
3. Run the bundled script:

   ```bash
   python scripts/anisotropy_check.py A.npy B.npy --fit-a trainA.npy --fit-b trainB.npy
   ```

   Pass `--shared` when A and B come from one model and one population, so that both sides are centred by one mean.
   Without `--fit-a` and `--fit-b` the means are fitted on the compared rows themselves, and the output's `means`
   field says, for each side, which rows its mean came from.
4. Report, side by side: the anisotropy of each side, matched against floor before centring, matched against floor
   after centring, and `partner_ranked_first` against its chance rate `1/n`.

## Reading the output

- `anisotropy` is the mean cosine between different rows of one side. For large `n` it is close to the squared length
  of the mean of the unit rows, so it measures how much the rows share one common direction, which is what centring
  removes. It does not detect every departure from isotropy: rows spread along one axis in both directions score near
  0 and still give raw cosines of +1 and -1. A value near 0 says there is little within-side mean direction to remove,
  not that raw cosine can be read without its floor. Above about 0.3, rows within that side cluster strongly around a
  mean direction (the script adds a warning); check `raw.floor` to see how much of that direction is shared across
  sides, and report both the raw and centred matched-versus-floor readings (centring changes the scoring function and
  does not replace evaluating an index that searches by raw cosine).
- `raw.floor` is what an unrelated pair scores in this comparison. A matched cosine means something only through its
  distance from this floor.
- `centred.gap_over_floor_sd` and `centred.cohens_d` say whether matched pairs separate from unrelated ones at all.
  When unrelated pairs all score the same, the floor has no spread and `gap_over_floor_sd` is `null`: the gap cannot
  be expressed in floor standard deviations, and the plain `gap` is the figure to read.
- `partner_ranked_first` is the retrieval view of the same pairs. Centring can move a ranking either way, so report it
  both ways rather than assuming it transfers.

## Rules that go with the numbers

- Average the signed difference across seeds or items, then take its absolute value. Averaging absolute differences
  is biased upward, and the bias is greatest when the gap is small relative to its noise.
- Give a gap with its spread and the smallest effect the test could have detected. An underpowered comparison is not
  a refutation, and the report should say which of the two it is.
- Put the floor from the same comparison beside every result. A floor copied from another run, model or domain does
  not correct this one.

## Example

bge-small-en-v1.5 on the first 100 documents of `mteb/scifact`'s corpus, each split into its first and second half at
the middle sentence boundary, with the halves of one abstract as the matched pair and one mean shared by both sides
(`--shared`). `scripts/example_scifact_halves.py` rebuilds it: it pins the corpus at revision `cf10ab6` and the model
at `5c38ec7`, states the sentence split, and needs `datasets` and `sentence-transformers` besides numpy. With datasets
5.0.1, sentence-transformers 6.0.1, torch 2.13.0 and numpy 2.5.1 it gives (rounded to four decimal places):

| | matched | floor (unrelated halves) | gap over floor sd |
| --- | ---: | ---: | ---: |
| raw cosine | 0.8636 | 0.6024 | 4.38 |
| centred cosine | 0.6487 | -0.0131 | 5.87 |

The anisotropy is 0.5956 and 0.6148, and here the two sides share one space, so before centring an unrelated half
already scores 70% of what the matching half scores. Both spaces separate matched from unrelated halves (4.38 floor sd
raw and 5.87 centred) and put the partner first for most abstracts (97 and 98 of 100), while centring removes the
0.6024 baseline offset.

© github · MIT · github/awesome-copilot

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

Все скиллы по теме «ИИ и ML» →
embedding-strategies Seth Hobson Скилл embedding-strategies помогает выбирать модели эмбеддингов, настраивать чанкинг и проверять качество в semantic search и RAG. CX Codex +1 11 391установок embedding-pipeline-builder patricio0312rev Скилл embedding-pipeline-builder для Claude Code собирает пайплайны эмбеддингов документов: загрузку, очистку, чанкинг, индексацию и настройку поиска. Поддерживает RAG и семантическую индексацию. CX Codex +1 259установок dspy-embedding-retrieval OmidZamani Скилл dspy-embedding-retrieval для Claude Code настраивает семантический поиск по текстовому корпусу через DSPy, эмбеддинги и FAISS. Выполняет retrieval для RAG. CX Codex +1 ★ 125звёзд репо nlp-engineer rohitg00 Субагент nlp-engineer для разработки NLP-систем: классификация, NER, эмбеддинги и файн-тюнинг трансформеров. Выбирает классические методы или нейросети по требованиям точности и ресурсам. CX Codex ★ 2 858звёзд репо matplotlib K-Dense-AI Скилл для построения и тонкой настройки научных графиков на Matplotlib: от отдельных осей до многопанельных фигур и экспорта в PNG, PDF и SVG. CX Codex +1 2 500установок exploratory-data-analysis K-Dense-AI Скилл exploratory-data-analysis проводит локальный первичный анализ научных файлов: таблиц, массивов NumPy и HDF5. Скилл готовит отчёты без выхода в сеть и защищает систему от исполнения непроверенного кода. CX Codex +1 2 400установок

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

Весь набор →
logicapps-custom-code-net10-migration Скилл logicapps-custom-code-net10-migration для GitHub Copilot переводит проекты кастомного кода Azure Logic Apps Standard с .NET 8 на .NET 10. Настраивает конфигурацию проектов, сборку и локальную отладку в VS Code. CX Codex +1 ★ 41 430звёзд репо lightweight-charts-react-components Скилл lightweight-charts-react-components для GitHub Copilot помогает добавлять и чинить финансовые графики на React с lightweight-charts. Включается по запросу о TradingView-графиках, пакетах lightweight-charts или их возможностях. CX Codex +1 ★ 41 430звёзд репо globestudio Генерирует точечные карты мира и трёхмерные анимированные глобусы через веб-сервис Globestudio. Создаёт ссылки с JSON-конфигурацией и код для встраивания на сайт. CX Codex +1 ★ 41 430звёзд репо foundry-agentic-loop Скилл foundry-agentic-loop для GitHub Copilot координирует создание агентных решений на Microsoft Foundry и Azure. Запускает прототипирование, разработку по спецификации или улучшение скилла по результатам прошлых запусков. CX Codex +1 ★ 41 430звёзд репо diagnose-ci-gate Скилл diagnose-ci-gate для GitHub Copilot разбирает падение обязательной CI-проверки. Сопоставляет ошибку с базовой веткой и текущими изменениями, затем рекомендует одно действие. CX Codex +1 ★ 41 430звёзд репо caption-qa Скилл caption-qa для GitHub Copilot и других ИИ-платформ, который проверяет файлы .srt и .vtt на соответствие стандартам Netflix, BBC и DCMP. Исправляет ошибки длительности и форматирования, пересчитывая тайминги без изменения текста. CX Codex +1 ★ 41 430звёзд репо azure-logic-apps-standard-cli Скилл azure-logic-apps-standard-cli для GitHub Copilot управляет проектами Azure Logic Apps Standard через расширение Azure CLI. Он помогает создавать и проверять рабочие процессы, запускать тесты и готовить проекты к развёртыванию. CX Codex +1 ★ 41 430звёзд репо adobe-illustrator-integrations Скилл adobe-illustrator-integrations для GitHub Copilot и Claude Code по созданию и отладке расширений, плагинов и MCP-серверов для Adobe Illustrator. Ускоряет автоматизацию задач через скрипты и внешние инструменты. CX Codex +1 ★ 41 430звёзд репо

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

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