named-einsum-and-packing
Use einops.einsum, pack, and unpack for named-axis contractions and reversible heterogeneous tensor packing.
- License 许可
- MIT
- 最近更新
- 2026-09-03
- Stars
- ★ 351
- Forks
- 27
01 前言 Front Matter
- name
- named-einsum-and-packing
- license
- MIT
- metadata
- { "disco-role": "operating" }
- description
- Use einops.einsum, pack, and unpack for named-axis contractions and reversible heterogeneous tensor packing.
- disable-model-invocation
- true
02 资源文件 5
- 参考文档references/api-reference.md12.0 KB
- 参考文档references/troubleshooting.md6.0 KB
- 参考文档references/workflows.md7.5 KB
- 脚本scripts/einsum_smoke.py5.8 KB
- 脚本scripts/packing_smoke.py9.2 KB
03 SKILL.md 正文
Named Einsum And Packing
Use this sub-skill when the task needs named-axis tensor contractions or
reversible packing of tensors with heterogeneous middle structure. It covers
einops.einsum, einops.pack, and einops.unpack as public runtime APIs.
Load When
- Translating NumPy/backend einsum formulas into readable named-axis patterns.
- Computing attention scores, dot products, linear projections, traces, diagonal reductions, or ellipsis-aware contractions.
- Packing class tokens, image tokens, text tokens, or other modalities into one sequence-like tensor and unpacking the processed result.
- Carrying packed-shape bookkeeping (
PS) through transformer/model flows. - Splitting one prediction tensor into multiple logical outputs with manual
packed_shapes. - Debugging failures involving
->, tensors-first call order, unsupported grouped einsum axes, invalid*packing patterns, badpacked_shapes, or-1inference.
Route Elsewhere
- Ordinary reshape, transpose, split, stack, reduce, repeat, pooling, or
dimension parsing recipes belong to sibling sub-skill
tensor-operations. - Framework layer abstractions such as
EinMixandeinops.layers.*belong to sibling sub-skillframework-integrations. - Repository development commands, native test selection, packaging, docs
builds, or source maintenance belong to sibling sub-skill
repo-development.
Public APIs
from einops import einsum, pack, unpack
einsum(*tensors_and_pattern)takes one or more tensors first and the pattern string last. This is the reverse ofnumpy.einsum(pattern, *tensors).pack(tensors, pattern)returns(packed_tensor, packed_shapes).unpack(tensor, packed_shapes, pattern)returns a list of tensors.
See references/api-reference.md for signatures, parameters, return contracts, limitations, and error behavior.
Golden Rules
- Always call
einsumaseinsum(tensor1, tensor2, ..., "axes -> axes"). A non-string last argument is a call-order bug. - Always include an explicit
->ineinsum; implicit-output NumPy-style shorthand is intentionally rejected. - Use semantic multi-letter axis names such as
batch,query,head, andchannel. Internally they are compacted to backend single-letter einsum symbols, but user code should stay named and readable. einsumsupports ellipsis and repeated axes on an input term for diagonal or trace-style operations. It does not support grouped axes like(h w), singleton(), or anonymous numeric axes like2.- Use
pack/unpack, not manual concatenate/slice/reshape, when tensors have heterogeneous axes in the packed position or when the inverse split must be carried safely through later code. - A packing pattern is not an arrow expression. It is a space-separated list of
axes with exactly one literal
*, for example"batch * channel". - Keep
packed_shapes(PS) next to the packed tensor. Treat it as part of the data contract, especially across model calls that change only non-packed axes such aschannel -> channel_out. - In manual
unpack, use at most one-1across the entirepacked_shapesargument, and validate round trips when shapes are computed dynamically. - Zero-length packed items are valid and should usually be preserved through
PSinstead of special-cased away.
Pattern Quick Reference
Named einsum
scores = einsum(
queries, keys,
"batch query head channel, batch key head channel -> batch head query key",
)
- Axes absent from the right side are summed over.
- Axes repeated within one input term select diagonals before summation.
- Ellipsis (
...) carries arbitrary leading, middle, or trailing dimensions.
Packing and unpacking
packed, ps = pack([class_token_bc, image_tokens_bhwc, text_tokens_btc], "batch * channel")
class_out, image_out, text_out = unpack(processed_packed, ps, "batch * channel_out")
- Axes before
*match leading axes of every input. - Axes after
*match trailing axes of every input. - Every remaining input axis is flattened into the packed axis, concatenated,
and recorded in the corresponding
PSentry. PSentries are shapes that replace*duringunpack;()means the item contributed one element with no explicit packed axes.
Workflow References
Use references/workflows.md for these recipes:
- Convert backend/NumPy attention or dot-product formulas to named
einsum. - Catch unsupported grouped-axis einsum and repair it with a separate reshape
step owned by
tensor-operations. - Pack class tokens and patch tokens for ViT-like flows.
- Pack multimodal token streams, including zero-length modalities.
- Split multi-output prediction tensors with manual
packed_shapes. - Auto-batch single examples and batches with
pack([x], "* ...")style flows. - Validate reversible pack/unpack round trips and
PSbookkeeping.
Use references/troubleshooting.md for the failure matrix and fixes for common error fragments.
Bundled Smoke Scripts
The scripts are deterministic, NumPy-only checks derived from public behavior covered by the repository tests and examples. They do not import repo tests or require a source checkout.
scripts/einsum_smoke.pychecks named einsum, attention, ellipsis, traces, and expected unsupported-syntax errors.scripts/packing_smoke.pychecks trivial packing, heterogeneous round trips, class-token and multimodal flows, multi-output unpacking, auto-batching, zero-length cases, and expected packing errors.
Run from the sub-skill directory or pass the script path explicitly:
python scripts/einsum_smoke.py --help
python scripts/einsum_smoke.py
python scripts/packing_smoke.py --help
python scripts/packing_smoke.py
Recovery Checklist
When a user reports a broken named-axis contraction or packing flow:
- Identify whether the operation is a contraction (
einsum) or reversible shape bookkeeping (pack/unpack). Do not solve a packing problem with a lossy manual slice unless reversibility is irrelevant. - Check API call order first: tensors before pattern for
einsum; sequence of tensors before pattern forpack; packed tensor,PS, then pattern forunpack. - Validate pattern family: arrow pattern for
einsum, one-star no-arrow pattern forpack/unpack. - For
einsum, remove unsupported groups, singletons, and anonymous axes by doing explicit reshapes or singleton insertion outsideeinsum. - For
pack/unpack, inspect thePSentries and the product they imply for the packed axis; then run a minimal round-trip assertion. - Reproduce with the bundled smoke script case nearest to the failure, then adapt its small deterministic arrays to the user's shapes.
04 同仓库更多 Skills
passnet-triton-opt
Make a single PassNet Triton kernel fast AND numerically faithful: performance model (when a replacement can win at all), block/grid/warp tuning, autotune policy, launch overhead, and per-op numeric recipes to pass the dtype baseline tolerances. Use when a pass matches and is correct but speedup below expected, or when correctness fails by small numeric margins.
passnet-solve
END-TO-END playbook for solving one PassNet sample: analyze the computation graphs, decide the optimization strategy (what to fuse, what to replace, what to leave alone), drive the iteration loop, and maximize the sample score. This is the ENTRY skill — invoke it first for any PassNet optimization task; it tells you when to use passnet-pattern-fusion, passnet-triton-opt and passnet-feedback.
passnet-skill
PassNet GPU kernel optimization via compiler passes. Design and implement Triton-based optimization passes, create pass files under ./pass_dir/, self-evaluate with pass_evaluator, and iterate to maximize GPU speedup.
passnet-pattern-fusion
Author PassNet pass files: write patterns that actually MATCH the FX graph, pick fusion regions (which ops to absorb into one Triton kernel), and structure multi-pass submissions with the mandatory shared-dispatch architecture. Use when creating or fixing pattern()/replacement_args()/replacement_func() files, when a pass "failed to match", or when deciding how to fuse multiple kernels/ops.
passnet-orchestrate
Round/batch planning and decision support for PassNet graph optimization. Use for multi-sample triage, worker allocation, eval-budget policy, and post-eval keep/revert decisions. For solving one concrete sample end to end, use passnet-solve as the entry skill; consult this skill only when you need broader planning or a specific decision gate.
passnet-feedback
Fast, deterministic feedback for PassNet work: pre-flight pattern/match verification WITHOUT burning a GPU evaluation, per-node bottleneck analysis of a sample's graphs, and eval-log parsing into per-variant status + estimated score + failure classification. Use BEFORE every GPU evaluation (check_pattern), at the START of a sample (analyze_graph), and AFTER every evaluation (parse_eval_log).