vectorization skill
✓ 인증됨TensorPrimitives, hardware intrinsics, vector type을 사용하여 .NET에서 SIMD 최적화 코드를 설계, 구현 및 검토합니다.
- GitHub 스타
- 5,942
- 파일
- 1
- 마지막 커밋
- 2026년 11월 11일
- 라이선스
- MIT
- 허용된 도구
- —
vectorization skill은 무엇을 하나요?
vectorization은(는) agent skill입니다. TensorPrimitives, hardware intrinsics, vector type을 사용하여 .NET에서 SIMD 최적화 코드를 설계, 구현 및 검토합니다.
skill의 SKILL.md에서 생성된 요약입니다.
vectorization skill 정보
고성능 .NET 애플리케이션을 개발하는 개발자는 이 SKILL을 사용하여 SIMD 최적화 코드를 설계, 구현 및 검토합니다. TensorPrimitives, hardware intrinsics, 그리고 Vector128, Vector256, Vector512와 같은 다양한 vector type을 사용하여 스칼라 루프를 벡터화된 연산으로 변환하는 데 중점을 둡니다. 이 SKILL은 엄격한 메모리 안전성을 유지하고 기존 스칼라 계약을 보존하면서 계산 처리량을 향상시켜야 하는 엔지니어를 대상으로 합니다.
에이전트가 이 SKILL을 로드하면 이식 가능하고 하드웨어 가속이 적용된 코드를 작성하기 위한 의사 결정 규칙과 검증 체크리스트를 제공합니다. 기존 프레임워크 가속을 불필요하게 건너뛰지 않도록, 수동 구현으로 넘어가기 전에 사용 가능한 가장 높은 수준의 API를 선택하도록 사용자를 안내합니다. 이 프로세스는 BenchmarkDotNet을 사용하여 새로운 구현을 스칼라 베이스라인과 비교하고, 다양한 아키텍처 및 입력 길이에 대해 정확성을 검증하는 방식에 의존합니다. 적절한 tail handling, 소규모 입력용 헬퍼, 플랫폼별 가드(guard)를 포함하는 최적화된 코드 구조를 생성합니다.
agent가 수행할 수 있는 작업
- 1스칼라 루프 벡터화TensorPrimitives 또는 hardware intrinsics를 사용하여 기존 스칼라 루프를 SIMD 최적화 버전으로 변환합니다.
- 2SIMD 코드 정확성 검토기존 벡터화 구현의 메모리 안전성, tail handling 및 계약 등가성을 감사합니다.
- 3성능 향상 검증벤치마킹 도구를 사용하여 Vector512와 같은 더 넓은 벡터 경로를 추가하는 복잡성의 타당성을 검토합니다.
- 4플랫폼 이식성 보장하드웨어 지원이 없는 경우 스칼라 동작으로 대체되는 크로스 플랫폼 벡터 연산을 구현합니다.
skill의 SKILL.md를 기반으로 작성되었습니다. 모든 사용 사례는 해당 문서의 인용구와 대조 확인되었습니다.
vectorization skill 설치 방법
각 명령은 skill 폴더를 클라이언트의 skills 디렉터리에 복사합니다. 클라이언트를 재시작하거나 새 세션을 시작하여 로드하세요.플러그인에 vectorization skill 설치
/plugin marketplace add dotnet/skills /plugin install dotnet-advanced@dotnet-agent-skills
Claude Code에 vectorization skill 설치
~/.claude/skills/vectorization/SKILL.md
$ npx degit dotnet/skills/plugins/dotnet-advanced/skills/vectorization ~/.claude/skills/vectorizationClaude Code (project)에 vectorization skill 설치
.claude/skills/vectorization/SKILL.md
$ npx degit dotnet/skills/plugins/dotnet-advanced/skills/vectorization .claude/skills/vectorizationCodex에 vectorization skill 설치
~/.agents/skills/vectorization/SKILL.md
$ npx degit dotnet/skills/plugins/dotnet-advanced/skills/vectorization ~/.agents/skills/vectorizationGemini CLI에 vectorization skill 설치
~/.gemini/skills/vectorization/SKILL.md
$ npx degit dotnet/skills/plugins/dotnet-advanced/skills/vectorization ~/.gemini/skills/vectorizationClaude.ai에 vectorization skill 설치
npx degit dotnet/skills/plugins/dotnet-advanced/skills/vectorization vectorization && zip -r vectorization.zip vectorization # claude.ai → Customize → Skills → + → Create skill → Upload a skill → vectorization.zip
자동 검사
2026년 11월 14일에 실행됨전체 보고서 →자동 검사를 통과했습니다. 보안 감사는 아닙니다. 에이전트가 실행하기 전에 스크립트를 읽어 보세요. 검사 방식
- 소스 저장소 연결 및 접근 가능dotnet/skills/plugins/dotnet-advanced/skills/vectorization is public and reachablegithub.com/dotnet/skills/tree/HEAD/plugins/dotnet-advanced/s ↗통과
- 오픈 소스 라이선스 (OSI)MITspdx.org/licenses/MIT.html ↗통과
- 최근 1년 내 커밋 또는 릴리스Last commit 2026-11-11github.com/dotnet/skills/commits ↗통과
- 스크립트에 다운로드 후 실행이나 자격 증명 탈취가 없음No scripts in the skill folder통과
- SKILL.md에 숨겨진 지침 없음No override phrases, safeguard switches, credential requests or hidden charactersgithub.com/dotnet/skills/blob/HEAD/plugins/dotnet-advanced/s ↗통과
- 사전 허용 도구가 제한됨No pre-approved tools; the agent asks before using onegithub.com/dotnet/skills/blob/HEAD/plugins/dotnet-advanced/s ↗통과
SKILL.md
GitHub에서 보기.NET SIMD vectorization
Produce a portable optimization that preserves the scalar contract, remains memory-safe at every length, and earns its complexity with measured results. Read the official SIMD and hardware-intrinsics guidance first and follow its comprehensive implementation templates. In particular, use its self-contained per-width dispatch, dedicated small-input handling, loop, and remainder shapes rather than reducing them to a chain of width checks. This skill supplies the decision rules and validation checks to apply while changing real code.
Inputs and prerequisites
Discover these from the repository before asking the user:
| Input | Required | What to establish |
|---|---|---|
| Scalar implementation and tests | Yes | Existing contract, representative call sites, and supported overlap |
| Target frameworks and platforms | Yes | Available SIMD APIs and architectures that must behave consistently |
| Build and test workflow | Yes | The repository's normal commands and how to launch separate test processes |
| Representative workload or benchmark | For optimization | Typical input sizes and the baseline to beat |
Do not add a package merely because an API exists there. First check the target framework and the project's existing dependency/versioning policy.
Core rules
- Use the highest-level API that matches the contract, then stop.
Span<T>andstringoperations,TensorPrimitives, and tensor types already accelerate many operations. LINQ reductions such asSum,Min,Max, andAveragecan also accelerate when the source exposes its underlying span. Verify empty-input and floating-point behavior rather than assuming similarly named operations are interchangeable. Once an existing API preserves the contract, use it instead of continuing into handwritten SIMD. Before writing an explicit loop, name the framework APIs considered and why none applies. Fixed-shapeSystem.Numericstypes remain appropriate for graphics and similar domains. - Start new explicit SIMD loops with
Vector128<T>. It is accelerated across the broadest hardware set. Add wider fixed-width paths only when measurements justify them. - Keep platforms consistent. Prefer cross-platform operations on the fixed-width vector types;
they lower to the appropriate target instructions. For example,
(vector & mask) == Vector128<byte>.Zerobecomespteston x86/x64. Use architecture-specific intrinsics only for a measured gap, guard them withIsSupported, and retain equivalent portable or scalar behavior. - Read
IsHardwareAccelerated,IsSupported, andCountdirectly. The JIT treats them as constants, so caching them adds no value and obscures which branches disappear. - Prefer operators where they are clear. Parenthesize expressions that mix bitwise and comparison operators so precedence is explicit.
If the task is review-only, do not rewrite the code. Report correctness and memory-safety defects before performance opportunities.
Authoring checklist
- Contract: identify behavior for empty and short inputs, overlap, overflow, NaN, signed zero, ordering, and exceptions before changing the implementation.
- Framework gate: inspect the target framework and existing package references, then compile or probe the highest-level candidate API with the required edge cases. A small contract adapter, such as preserving special empty-input behavior, does not justify reimplementing the operation. If the API preserves the contract, use it and stop; do not claim it is unavailable without checking.
- Structure: for new explicit SIMD, implement
Vector128<T>and scalar first. Only after measurements justify wider paths, checkVector512<T>, thenVector256<T>, optionalVector<T>,Vector128<T>, and finally scalar. Omit paths the implementation does not need. Each outer fixed-width guard checks only itsIsHardwareAcceleratedproperty and, for generic element types,IsSupported. Inside that block, run the width-specific helper when the input has at leastCountelements; otherwise run a dedicated small-input helper, then return. Do not put the length check in the outer guard and fall through to repeat dispatch at narrower widths. Keeping each supported-width block self-contained lets the JIT remove unsupported blocks and avoids redundant work on common small inputs. - Loads and stores: prefer span-based
Vector128.Create(span)andCopyTo; the JIT keeps them efficient and they require no pinning or reference arithmetic. Unsafe loads and stores are largely unnecessary. When a path genuinely must walk a buffer by managed reference, use the element-offsetLoadUnsafe(ref T, nuint)andStoreUnsafeoverloads rather than pointers or manually advanced references. - Empty inputs: in a reference-based path, obtain the starting reference with
MemoryMarshal.GetReference(span)orMemoryMarshal.GetArrayDataReference(array), not by indexing element0. - Unsupported element types: the fixed-width vectors support primitive numeric element types,
not
charorbool. Reinterpret withMemoryMarshal.CastorAs<TFrom, TTo>; reinterpretation changes only the type, not the bits. Keep Boolean data as0or1and characters as valid UTF-16, normalizing results before storing when necessary. - Offsets: prove the input contains a full vector before subtracting
Countor converting an index tonuint; otherwise a negative value becomes a huge unsigned offset. - Managed references: do not form references before the start or past the end of a span, including a one-past-end reference. The runtime permits a non-dereferenced managed pointer exactly one past an object or array, but this guidance intentionally prohibits the pattern because it is fragile and easy to misuse. Keep the base reference in range and express traversal with an element offset.
- Remainders: cover every length, including
0,Count - 1,Count,Count + 1, and nonmultiples of each width. Once the input contains a full vector, keep the tail vectorized by reprocessing the last full vector. An idempotent operation can fold that overlap in directly. A non-idempotent operation must useConditionalSelectto replace repeated lanes with the operation's identity before folding them in. This is the JIT-recognized general pattern; it can reduce a zero-identity selection to a bitwise mask while retaining broader optimization opportunities. For in-place transforms, preserve the original tail values before overlapping stores and write only valid results. - Buffer overlap: choose a traversal direction or staging strategy that prevents stores from corrupting values not yet loaded.
- Numeric behavior: account for floating-point reassociation, NaN and signed-zero semantics,
checked or unchecked integer overflow, and endianness where the algorithm depends on byte order.
NativeandEstimateoperations can intentionally relax precision or IEEE edge-case behavior; use them only when the contract permits it and measurements justify them.
The official guidance contains the complete dispatch, small-input, unrolling, and remainder
templates; use those for the full implementation. The following excerpt illustrates only the inner
safe Vector128<T> loop for an in-place elementwise transform, after its self-contained dispatch
block has established at least one full vector. Transform represents the operation being
implemented:
Span<int> tail = data.Slice(data.Length - Vector128<int>.Count);
Vector128<int> end = Vector128.Create<int>(tail);
Span<int> remaining = data;
while (remaining.Length >= Vector128<int>.Count)
{
Vector128<int> values = Vector128.Create<int>(remaining);
Transform(values).CopyTo(remaining);
remaining = remaining.Slice(Vector128<int>.Count);
}
if (!remaining.IsEmpty)
{
Transform(end).CopyTo(tail);
}
The early end load preserves original values before overlapping stores. For a read-only reduction,
load the same final span after the main loop and use ConditionalSelect to replace already-processed
lanes with the operation's identity. Do not substitute LoadUnsafe/StoreUnsafe or a scalar
epilogue merely to avoid span bounds checks.
Testing checklist
- Compare the optimized implementation with the scalar contract across boundary lengths, randomized values, empty inputs, supported overlap, and numeric edge cases. Cover every implemented width and the scalar path with inputs both large enough and too small to benefit.
- Exercise every implemented width and the scalar fallback in separate processes. On x86/x64
CoreCLR,
DOTNET_EnableAVX2=0disables AVX2 andDOTNET_EnableHWIntrinsic=0disables hardware intrinsics. Use the repository's normal test command and do not change these process-wide settings inside a unit test. These settings do not change code already compiled as ReadyToRun or ahead of time, so confirm the target code is JIT-compiled when using them to force a path. - For unsafe loads and stores, use guard-page or equivalent boundary tests when available. Put the inaccessible page after the buffer for forward iteration and before it for backwards iteration, and include nonmultiple lengths. An ordinary array allocation does not reliably expose an out-of-bounds read.
Benchmarking
Use BenchmarkDotNet to measure representative small and large inputs before keeping the added
complexity. Compare scalar, Vector128<T>, and each wider implemented path in the same run. Small
inputs can be slower because setup dominates, and speedups are rarely the theoretical vector-width
multiple because memory throughput, alignment, and latency still apply. Report throughput or time
with noise context and, when relevant, generated code size or instruction counts. Control allocation
alignment for stable measurements or randomize it to observe the distribution. A wider vector is
not automatically faster.
If the project cannot target the required framework, run the relevant architecture, or execute the fallback configuration, state exactly which path remains unverified. Do not claim success from a default-hardware test alone.
Completion contract
- Authoring: leave the scalar contract covered by tests; identify the framework or SIMD layer selected; report measurements for the representative workload; name any architecture or fallback path that could not be exercised.
- Review: report only concrete findings, ordered by correctness, memory safety, portability, tests, then performance evidence. If none remain, say so directly.
- Do not call an optimization complete when it only builds, only passes on the current machine, or has no comparison against the scalar baseline.
Review checklist
Review in this order:
- Scalar-contract equivalence, including signed zero, NaN, overflow, and relevant endianness
- Reuse of an existing accelerated framework API
- Tail correctness for idempotent versus non-idempotent work
- Memory safety, unsigned offset arithmetic, empty inputs, and overlapping buffers
- Portable dispatch and behaviorally equivalent fallbacks
- Tests that force each width and the scalar path
- Benchmarks that justify explicit SIMD and additional widths
이 스킬의 파일
1vectorization skill 질문
Claude Code에 vectorization skill을 어떻게 설치하나요?
npx degit dotnet/skills/plugins/dotnet-advanced/skills/vectorization ~/.claude/skills/vectorization를 실행합니다. Claude Code는 ~/.claude/skills(모든 프로젝트) 또는 .claude/skills(한 프로젝트)에서 skills를 로드하며, 설명이 작업과 일치할 때 skill을 사용합니다.
vectorization skill을 사용할 수 있는 클라이언트는 무엇인가요?
Agent Skills 형식을 읽는 모든 클라이언트(Claude Code, Codex, Gemini CLI, claude.ai(ZIP으로 업로드))가 사용할 수 있습니다. skill 내 스크립트는 클라이언트가 코드 실행을 허용하는 경우에만 실행됩니다.
.NET에서 루프를 최적화할 때 무엇을 가장 먼저 사용해야 하나요?
명시적인 SIMD 루프를 작성하기 전에 Span<T>, 문자열 작업 또는 TensorPrimitives와 같이 계약에 부합하는 가장 높은 수준의 API를 사용하십시오.
새로운 명시적 SIMD 루프를 어떻게 작성하기 시작해야 하나요?
가장 폭넓은 하드웨어 세트에서 가속되는 Vector128<T>로 시작하고, 측정 결과가 정당화되는 경우에만 더 넓은 경로를 추가하십시오.
테스트에서 다양한 하드웨어 명령어 세트를 어떻게 테스트하나요?
별도의 테스트 프로세스에서 DOTNET_EnableAVX2=0 또는 DOTNET_EnableHWIntrinsic=0과 같은 환경 변수를 사용하여 특정 기능을 비활성화하십시오.