Claude Skill

cpp-hpc-optimization

Evidence-driven C++ high-performance computing design, profiling, and optimization across algorithmic time/space complexity, data layout, cache and memory behavior, numerics, SIMD, multicore scheduling, and CPU/accelerator pipelines. Use before designing or changing computation-i

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Download archibate-agent-skills-skills_cpp-hpc-optimization-0a4e08d.zip · 281 KB

Install

skills CLI npx skills add https://github.com/archibate/agent-skills/tree/master/skills/cpp-hpc-optimization
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install archibate-agent-skills@llmmart
Git git clone https://github.com/archibate/agent-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole archibate/agent-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

C++ HPC Optimization

Optimize the measured data path, not the code that merely looks low-level. Preserve a simple reference implementation and make every optimization earn its complexity with correctness evidence and a representative benchmark.

Non-negotiable rules

  1. Define the contract first. Record inputs, sizes, distributions, target hardware, accuracy, determinism, memory, latency, and throughput objectives.
  2. Pass the complexity gate. Compare the best practical algorithmic families for the actual size range before tuning constants inside one family.
  3. Profile before kernel redesign. Identify the hot path with end-to-end evidence.
  4. Keep an oracle. Retain a scalar or otherwise obviously-correct reference implementation and compare every optimized path against it.
  5. Model before tuning. Estimate useful operations, bytes transferred, working set, dependency depth, synchronization, and launch overhead.
  6. Change one axis at a time. Measure after each transformation and revert changes that do not win on the target workload.
  7. Never encode a benchmark accident as a law. Cache sizes, SIMD width, thread count, tile size, padding, and crossover thresholds are target- and workload-dependent.
  8. Make ISA requirements explicit. Use feature dispatch and a compatible fallback when targets vary, or a verified fixed ISA for controlled deployments. Both require tail handling and equivalence tests.

Workflow

1. Frame the performance contract

Write down:

  • the semantic result and accepted numerical error;
  • representative and adversarial input shapes and distributions;
  • steady-state throughput, single-item latency, tail latency, or deadline;
  • memory-footprint and allocation constraints;
  • target CPUs, accelerators, compilers, build flags, and deployment topology;
  • whether batching, reordering, nondeterministic reductions, or preprocessing are permitted.

Do not optimize an unspecified target. Throughput and latency often demand opposite choices: batching and deep queues improve throughput but add waiting.

2. Pass the algorithmic time/space complexity gate

Before applying cache, SIMD, threading, or instruction-level techniques:

  • identify lower bounds and the best mature practical algorithm families for the declared sizes, distributions, sparsity, dimensionality, accuracy, update/query ratio, and number of timesteps or solves;
  • compare total time, peak/live space, preprocessing, communication, numerical behavior, worst/expected cases, and implementation maturity;
  • benchmark crossover regions and retain a size/shape-dependent portfolio when different algorithms win in different regimes.

An asymptotically better method may lose at small n; an asymptotically worse regular kernel may exploit the target exceptionally well. Conversely, no amount of constant-factor kernel tuning rescues an avoidable complexity class at scale. Choose the industrially useful family for the declared range first, then use the rest of this skill to reduce its realized cost. Preserve the declared semantic or numerical contract; optimization need not be bit-exact when the contract permits an approximate, reordered, or mixed-precision algorithm.

3. Establish correctness and measurement baselines

  • Build a readable reference path before intrinsics, lossy precision, relaxed math, or concurrency.
  • Create correctness tests covering empty, tiny, tail, misaligned, extreme, NaN/Inf, sparse/dense, and aliasing cases that the contract permits.
  • Benchmark the actual hot operation with realistic data. Warm up, prevent dead-code elimination, report distribution rather than one lucky sample, and retain end-to-end measurements beside microbenchmarks.
  • Inspect generated code and compiler optimization remarks before assuming the compiler failed.

Read references/profiling-and-cost-model.md before profiling, benchmarking, or declaring a bottleneck.

4. Classify the limiting resource

Calculate at least an approximate per-item model:

  • useful operations and transcendental/divide cost;
  • compulsory input, output, metadata, and intermediate bytes;
  • working-set size at each reuse distance;
  • independent operations versus loop-carried dependency chains;
  • tasks, locks, atomics, barriers, launches, copies, and queue transitions;
  • scaling versus threads, vector width, batch size, and problem size.

Classify the current regime as memory-bandwidth, cache-capacity/latency, compute/issue, dependency-latency, synchronization, task-granularity, launch, or transfer bound. A kernel can move between regimes after each optimization.

5. Evaluate change scope and ROI

Record the currently authorized edit boundary, but do not mistake it for the root-cause boundary. When evidence places the limiting work upstream or in data representation, ownership, or construction, compare:

  • the best optimization inside the current boundary;
  • the smallest upstream, layout, index, or API change that removes the cause;
  • the practical blank-slate design, to expose the ceiling of both candidates.

For each candidate, estimate end-to-end speedup, complexity and crossover, memory, implementation and migration work, write amplification, invariant and test surface, and ongoing maintenance. If wider scope has credible net value, present the evidence and obtain user approval before expanding it. Keep the experiment reversible, measure the representative full workflow, and retain the wider change only when its observed performance and complexity benefits repay its lifecycle cost; otherwise revert it.

6. Apply transformations in economic order

Prefer the first measured transformation that attacks the current limit:

  1. Remove unnecessary work, copies, allocation, conversion, and materialization.
  2. Reduce footprint and improve data layout or traversal locality.
  3. Fuse passes or tile/block computation to reuse data before eviction.
  4. Expose compiler optimization by removing false alias/dependency barriers.
  5. Vectorize, using intrinsics only when generated code proves they are needed.
  6. Parallelize with enough work per task and no shared hot write locations.
  7. Batch, pipeline, or overlap copies and computation when latency can be hidden.
  8. Offload only when transfer, launch, and synchronization costs fit the model.

Load the relevant references before choosing:

  • references/data-layout-and-memory.md — DOD, AoS/SoA/AoSoA, packing, sparse data, locality, tiling, fusion, and Morton order.
  • references/allocation-and-memory-resources.md — measured allocation bottlenecks, preallocation, PMR, arenas, pools, TLS scratch, general-purpose allocators, NUMA, and allocator benchmarks.
  • references/ragged-topology.md — flattened variable-length arrays, offset encodings, sidecar topology, packed sparse sets, polygon-corner topology, aligned attributes, and scan-built output.
  • references/numerics-and-quantization.md — precision, FP16/BF16, shared exponent, quantization, accumulation, and numerical validation.
  • references/simd-and-compiler.md — auto-vectorization, dependencies, intrinsics, SIMD tricks, tails, and ISA dispatch.
  • references/parallelism-and-pipelines.md — thread degree, TLS reduction, false sharing, work stealing, queues, async launch, and pipelines.
  • references/accelerator-throughput.md — CPU/accelerator transfer, CUDA-style streams, occupancy, synchronization, and launch amortization.
  • references/hotpath-polymorphism.md — hot/cold boundaries, abstraction cost, and data-oriented polymorphism.

7. Validate and integrate

  • Compare every output with the reference under the declared error metric.
  • Run sanitizers and boundary tests before trusting benchmark results.
  • Measure the same workload, hardware state, compiler, and flags before/after.
  • Check performance across small, crossover, and large sizes; optimized kernels often lose below a threshold.
  • Preserve the readable fallback and dispatch outside the inner loop.
  • Record assumptions, selected thresholds, measured results, and rejected alternatives near the benchmark or design documentation.
  • Keep cold-path architecture maintainable. Do not spread kernel-specific data layout or ISA details across the rest of the system.

Relationship to C++ OOP design

Apply $cpp-oop-style to ownership, orchestration, I/O, error handling, and module boundaries. Inside a measured hot kernel, prefer flat data, value views, batch operations, static dispatch, and explicit SIMD when evidence requires it. Use its debug-instrumentation guidance for correctness and runtime diagnosis; this skill owns profiling, tracing, counters, and benchmarks used to locate or quantify a performance bottleneck.

The boundary should normally look like:

  • abstract behavior and resource ownership on the cold/control side;
  • data-only request/config/result types at the seam;
  • one dense concrete pool per hot subtype, with homogeneous spans or tiles entering the hot/data side;
  • dispatch once per batch, never once per element;
  • a reference kernel and one or more selected optimized implementations.

Read references/hotpath-polymorphism.md before removing abstractions or adding type tags. Virtual dispatch is rarely the largest cost by itself; the lost inlining, scattered objects, unpredictable branches, and pointer-chasing around it are often the actual problem.

Source material and provenance

Read references/parallel101-case-studies.md when looking for concrete lesson progressions or deeper examples from archibate's parallel101/course and parallel101/simdtutor repositories. Search the bundled offline corpus under references/parallel101/ before depending on a maintainer's checkout or the network. Use references/parallel101/provenance.tsv to recover the repository, author, source URL, commit, original path, teaching classification, license, and SHA-256 for every excerpt.

Treat the corpus as educational experiments, not production code. The case-study index marks outdated, unsafe, incomplete, or broken examples so their ideas can be learned without copying their defects. The skill and bundled corpus are licensed under CC BY-NC-SA 4.0; retain attribution and compatible terms when redistributing adaptations.

Files (agent-skills)
  • agents
    • openai.yaml 226 B
      Loading…
  • references
    • parallel101
      • course
        • 04
          • 3_pointers
            • 01_pointer_aliasing
              • main.cpp 64 B · in bundle
            • 02_restrict_pointer
              • main.cpp 97 B · in bundle
          • 5_loops
            • 01_worry_pointer_aliasing
              • main.cpp 102 B · in bundle
            • 02_no_pointer_aliasing
              • main.cpp 124 B · in bundle
            • 04_no_pointer_aliasing_ivdep
              • main.cpp 120 B · in bundle
            • 06_loop_with_external_call
              • main.cpp 156 B · in bundle
            • 07_loop_with_inlineable_call
              • main.cpp 159 B · in bundle
            • 08_loop_with_random_access
              • main.cpp 97 B · in bundle
            • 09_loop_with_skip_access
              • main.cpp 90 B · in bundle
            • 10_loop_with_ordered_access
              • main.cpp 86 B · in bundle
            • 11_loop_invariant_motion
              • main.cpp 149 B · in bundle
            • 12_loop_invariant_failed
              • main.cpp 147 B · in bundle
            • 13_loop_unrolling
              • main.cpp 106 B · in bundle
          • 6_structs
            • 01_vec2_simd_ok
              • main.cpp 146 B · in bundle
            • 02_vec3_simd_fail
              • main.cpp 159 B · in bundle
            • 03_vec3_with_padding_ok
              • main.cpp 180 B · in bundle
            • 04_vec3_with_alignas_ok
              • main.cpp 171 B · in bundle
            • 05_vec3_aos
              • main.cpp 159 B · in bundle
            • 06_vec3_soa
              • main.cpp 171 B · in bundle
            • 07_vec3_aosoa
              • main.cpp 234 B · in bundle
            • 08_benchmark
              • aos.cpp 219 B · in bundle
              • aosoa.cpp 320 B · in bundle
              • aos_aligned.cpp 248 B · in bundle
              • aos_parallel.cpp 253 B · in bundle
              • common.h 55 B · in bundle
              • main.cpp 1.1 KB · in bundle
              • profile.h 464 B · in bundle
              • soa.cpp 225 B · in bundle
              • soa_parallel.cpp 259 B · in bundle
              • soa_simd.cpp 247 B · in bundle
              • soa_size_t.cpp 259 B · in bundle
              • soa_unroll.cpp 347 B · in bundle
        • 05
          • 02_async
            • 01
              • main.cpp 735 B · in bundle
            • 02
              • main.cpp 866 B · in bundle
            • 03
              • main.cpp 1.1 KB · in bundle
            • 04
              • main.cpp 758 B · in bundle
            • 05
              • main.cpp 753 B · in bundle
            • 06
              • main.cpp 840 B · in bundle
        • 06
          • 02_reduce
            • 03
              • main.cpp 536 B · in bundle
            • 04
              • main.cpp 550 B · in bundle
            • 08
              • main.cpp 692 B · in bundle
          • 05_split
            • 01
              • main.cpp 565 B · in bundle
            • 02
              • main.cpp 563 B · in bundle
            • 03
              • main.cpp 723 B · in bundle
            • 04
              • main.cpp 677 B · in bundle
            • 05
              • main.cpp 659 B · in bundle
          • 07_filter
            • 01
              • main.cpp 332 B · in bundle
              • ticktock.h 472 B · in bundle
            • 02
              • main.cpp 533 B · in bundle
              • ticktock.h 472 B · in bundle
            • 03
              • main.cpp 716 B · in bundle
              • ticktock.h 472 B · in bundle
            • 04
              • main.cpp 710 B · in bundle
              • ticktock.h 472 B · in bundle
            • 05
              • main.cpp 727 B · in bundle
              • ticktock.h 472 B · in bundle
            • 06
              • main.cpp 753 B · in bundle
              • ticktock.h 472 B · in bundle
            • 07
              • main.cpp 786 B · in bundle
              • ticktock.h 472 B · in bundle
            • 08
              • main.cpp 847 B · in bundle
              • pod.h 1007 B · in bundle
              • ticktock.h 472 B · in bundle
            • 09
              • main.cpp 774 B · in bundle
              • ticktock.h 472 B · in bundle
            • 10
              • main.cpp 1.2 KB · in bundle
              • pod.h 1007 B · in bundle
              • ticktock.h 472 B · in bundle
          • 08_qsort
            • 07
              • main.cpp 1.1 KB · in bundle
            • 08
              • main.cpp 1.2 KB · in bundle
            • 09
              • main.cpp 407 B · in bundle
            • 10
              • main.cpp 783 B · in bundle
          • 09_pipeline
            • 01
              • main.cpp 1.2 KB · in bundle
            • 03
              • main.cpp 1.5 KB · in bundle
            • 05
              • main.cpp 2.2 KB · in bundle
        • 07
          • 01_bandwidth
            • 01
              • main.cpp 1021 B · in bundle
            • 02
              • main.cpp 730 B · in bundle
            • 03
              • main.cpp 840 B · in bundle
            • 04
              • main.cpp 1.9 KB · in bundle
            • 05
              • main.cpp 2 KB · in bundle
            • 06
              • main.cpp 1.9 KB · in bundle
            • 07
              • main.cpp 512 B · in bundle
          • 02_cache
            • 01
              • main.cpp 1.3 KB · in bundle
            • 02
              • main.cpp 2.1 KB · in bundle
            • 03
              • main.cpp 2 KB · in bundle
            • 04
              • main.cpp 1.6 KB · in bundle
              • pseudo.cpp 816 B · in bundle
          • 03_prefetch
            • 01
              • main.cpp 988 B · in bundle
            • 02
              • main.cpp 1.3 KB · in bundle
            • 03
              • main.cpp 1.9 KB · in bundle
            • 04
              • main.cpp 1.6 KB · in bundle
            • 05
              • main.cpp 1.2 KB · in bundle
            • 06
              • main.cpp 2.4 KB · in bundle
            • 07
              • main.cpp 1022 B · in bundle
          • 04_fusion
            • 00
              • main.cpp 909 B · in bundle
            • 01
              • main.cpp 969 B · in bundle
            • 02
              • main.cpp 986 B · in bundle
            • 03
              • main.cpp 1.6 KB · in bundle
            • 04
              • main.cpp 1.7 KB · in bundle
            • 05
              • main.cpp 1.8 KB · in bundle
          • 05_malloc
            • 15
              • main.cpp 548 B · in bundle
            • 16
              • main.cpp 587 B · in bundle
          • 06_ndarray
            • 01
              • alignalloc.h 4.3 KB · in bundle
              • main.cpp 1.6 KB · in bundle
            • 02
              • main.cpp 1.6 KB · in bundle
            • 03
              • main.cpp 1.9 KB · in bundle
              • ndarray.h 4.5 KB · in bundle
          • 08_matrix
            • 01
              • alignalloc.h 4.3 KB · in bundle
              • main.cpp 5.3 KB · in bundle
              • morton.h 2.1 KB · in bundle
              • ndarray.h 4.5 KB · in bundle
            • 02
              • main.cpp 1.6 KB · in bundle
            • 03
              • main.cpp 2.3 KB · in bundle
          • 09_multicore
            • 01
              • main.cpp 1 KB · in bundle
          • 10_rbgs
            • 01
              • main.cpp 1.9 KB · in bundle
        • 10
          • 00
            • 00.cpp 1 KB · in bundle
            • 03.cpp 1.6 KB · in bundle
            • 07.cpp 1.2 KB · in bundle
            • 08.cpp 1.3 KB · in bundle
            • 10.cpp 1.6 KB · in bundle
            • bate.h 851 B · in bundle
          • 01
            • 06.cpp 2.2 KB · in bundle
            • bate.h 851 B · in bundle
          • 04
            • 06.cpp 6.8 KB · in bundle
            • bate.h 869 B · in bundle
          • 05
            • 00.cpp 223 B · in bundle
            • 01.cpp 227 B · in bundle
            • 02.cpp 226 B · in bundle
            • 03.cpp 406 B · in bundle
            • 04.cpp 224 B · in bundle
            • bate.h 868 B · in bundle
          • 06
            • 03.cpp 1 KB · in bundle
            • 04.cpp 1.1 KB · in bundle
            • 05.cpp 1 KB · in bundle
            • 06.cpp 1.1 KB · in bundle
            • 07.cpp 1.1 KB · in bundle
            • bate.h 868 B · in bundle
        • 18
          • 00.cpp 3.5 KB · in bundle
          • 01.cpp 5 KB · in bundle
          • benchmark.hpp 2.7 KB · in bundle
        • slides
          • bench
            • BM_latency.csv 5.5 KB · in bundle
            • BM_struct.csv 5.5 KB · in bundle
            • main.cpp 345 B · in bundle
            • test.cpp 8 KB · in bundle
          • design
            • function2.md 14.9 KB
              Loading…
            • signal.md 6.2 KB
              Loading…
            • strict-aliasing.md 1.9 KB
              Loading…
            • virtual.md 31.3 KB
              Loading…
        • specifelse
          • benchtest
            • demo0.cpp 1.8 KB · in bundle
          • 0.cpp 708 B · in bundle
          • 1.cpp 92 B · in bundle
          • 2.cpp 133 B · in bundle
          • 3.cpp 145 B · in bundle
          • 4.cpp 1 KB · in bundle
          • 5.cpp 2.1 KB · in bundle
          • 6.cpp 1.6 KB · in bundle
          • randint.h 378 B · in bundle
          • ticktock.h 278 B · in bundle
        • README.md 3.5 KB
          Loading…
      • simdtutor
        • blas
          • dsdot.cpp 4.1 KB · in bundle
          • sdot.cpp 3.1 KB · in bundle
          • snrm2.cpp 2.8 KB · in bundle
        • customers
          • amgcg_vcycle_cuda
            • README.md 258 B
              Loading…
            • rec.txt 3.4 KB
              Loading…
            • vcycle.cu 21.7 KB · in bundle
          • issue4_getsubpixelvalue
            • main.cpp 9 KB · in bundle
            • old.cpp 3.3 KB · in bundle
          • parallel_multiply_uint8
            • fast_mask_lib.hpp 9.5 KB · in bundle
            • README.md 8.5 KB
              Loading…
        • foundation
          • cpp17pmrtest
            • filter.cpp 4.6 KB · in bundle
            • oldmain.cpp 3.7 KB · in bundle
          • cpplockfreequeue
            • affinity.h 402 B · in bundle
            • show_time.h 477 B · in bundle
            • spsc_ring.h 5.8 KB · in bundle
            • v10_local_variable_ring_queue.cpp 3.5 KB · in bundle
            • v11_ring_queue_template_class.cpp 3.5 KB · in bundle
            • v12_ring_queue_atomic_wait.cpp 4.4 KB · in bundle
            • v1_std_mt_queue.cpp 651 B · in bundle
            • v2_atomic_ring_queue.cpp 1.1 KB · in bundle
            • v3_atomic_acq_rel_ring_queue.cpp 1.3 KB · in bundle
            • v4_cache_align_ring_queue.cpp 1.4 KB · in bundle
            • v5_read_pos_cached_ring_queue.cpp 1.5 KB · in bundle
            • v6_write_pos_cached_ring_queue.cpp 1.6 KB · in bundle
            • v7_rw_pos_localize_ring_queue.cpp 1.7 KB · in bundle
            • v8_pointer_atomic_ring_queue.cpp 1.8 KB · in bundle
            • v9_do_while_ring_queue.cpp 1.8 KB · in bundle
          • moderncuda
            • cudapp.cuh 15.4 KB · in bundle
            • README.md 15.8 KB
              Loading…
          • radixsort
            • radix_sort.cpp 12.5 KB · in bundle
            • show_time.h 477 B · in bundle
          • dispatch_kernel.h 26.7 KB · in bundle
          • kernel_hashrng.h 22.3 KB · in bundle
          • kernel_rgba2rgb.h 3.8 KB · in bundle
          • ScopeProfiler.h 3.8 KB · in bundle
        • practices
          • dispatch.md 8.7 KB
            Loading…
          • u8rgba2rgb.md 5.7 KB
            Loading…
        • result
          • countp.cpp 4.3 KB · in bundle
          • fillsin.cpp 1.2 KB · in bundle
          • findp.cpp 2.4 KB · in bundle
          • rgba2rgb.cpp 12.7 KB · in bundle
          • saxpy.cpp 3.6 KB · in bundle
          • sum.cpp 1.7 KB · in bundle
        • source
          • countp.cpp 1.9 KB · in bundle
          • fillsin.cpp 3.5 KB · in bundle
          • filterp.cpp 3.5 KB · in bundle
          • findp.cpp 2.7 KB · in bundle
          • rgba2rgb.cpp 5.2 KB · in bundle
          • saxpy.cpp 2.4 KB · in bundle
          • sum.cpp 1.6 KB · in bundle
        • README.md 13.9 KB
          Loading…
      • provenance.tsv 59.1 KB · in bundle
    • accelerator-throughput.md 8.8 KB
      Loading…
    • allocation-and-memory-resources.md 18.2 KB
      Loading…
    • data-layout-and-memory.md 30.1 KB
      Loading…
    • hotpath-polymorphism.md 7.7 KB
      Loading…
    • numerics-and-quantization.md 10 KB
      Loading…
    • parallel101-case-studies.md 18.8 KB
      Loading…
    • parallelism-and-pipelines.md 19.7 KB
      Loading…
    • profiling-and-cost-model.md 13.2 KB
      Loading…
    • ragged-topology.md 10.1 KB
      Loading…
    • simd-and-compiler.md 26.8 KB
      Loading…
  • scripts
    • sync_parallel101_corpus.py 14 KB
      Loading…
  • LICENSE 20.4 KB · in bundle
  • SKILL.md 10.7 KB
    ---
    name: cpp-hpc-optimization
    description: >-
      Evidence-driven C++ high-performance computing design, profiling, and
      optimization across algorithmic time/space complexity, data layout, cache and
      memory behavior, numerics, SIMD, multicore scheduling, and CPU/accelerator
      pipelines. Use before designing or changing computation-intensive kernels,
      high-throughput data structures, performance-critical loops,
      SIMD/OpenMP/TBB/CUDA code, mixed-precision or sparse representations, or when
      investigating throughput, latency, scaling, cache, bandwidth,
      compiler-vectorization, or profiling problems.
    ---
    
    # C++ HPC Optimization
    
    Optimize the measured data path, not the code that merely looks low-level.
    Preserve a simple reference implementation and make every optimization earn its
    complexity with correctness evidence and a representative benchmark.
    
    ## Non-negotiable rules
    
    1. **Define the contract first.** Record inputs, sizes, distributions, target
       hardware, accuracy, determinism, memory, latency, and throughput objectives.
    2. **Pass the complexity gate.** Compare the best practical algorithmic families
       for the actual size range before tuning constants inside one family.
    3. **Profile before kernel redesign.** Identify the hot path with end-to-end evidence.
    4. **Keep an oracle.** Retain a scalar or otherwise obviously-correct reference
       implementation and compare every optimized path against it.
    5. **Model before tuning.** Estimate useful operations, bytes transferred,
       working set, dependency depth, synchronization, and launch overhead.
    6. **Change one axis at a time.** Measure after each transformation and revert
       changes that do not win on the target workload.
    7. **Never encode a benchmark accident as a law.** Cache sizes, SIMD width,
       thread count, tile size, padding, and crossover thresholds are target- and
       workload-dependent.
    8. **Make ISA requirements explicit.** Use feature dispatch and a compatible
       fallback when targets vary, or a verified fixed ISA for controlled deployments.
       Both require tail handling and equivalence tests.
    
    ## Workflow
    
    ### 1. Frame the performance contract
    
    Write down:
    
    - the semantic result and accepted numerical error;
    - representative and adversarial input shapes and distributions;
    - steady-state throughput, single-item latency, tail latency, or deadline;
    - memory-footprint and allocation constraints;
    - target CPUs, accelerators, compilers, build flags, and deployment topology;
    - whether batching, reordering, nondeterministic reductions, or preprocessing
      are permitted.
    
    Do not optimize an unspecified target. Throughput and latency often demand
    opposite choices: batching and deep queues improve throughput but add waiting.
    
    ### 2. Pass the algorithmic time/space complexity gate
    
    Before applying cache, SIMD, threading, or instruction-level techniques:
    
    - identify lower bounds and the best mature practical algorithm families for
      the declared sizes, distributions, sparsity, dimensionality, accuracy,
      update/query ratio, and number of timesteps or solves;
    - compare total time, peak/live space, preprocessing, communication, numerical
      behavior, worst/expected cases, and implementation maturity;
    - benchmark crossover regions and retain a size/shape-dependent portfolio when
      different algorithms win in different regimes.
    
    An asymptotically better method may lose at small `n`; an asymptotically worse
    regular kernel may exploit the target exceptionally well. Conversely, no amount
    of constant-factor kernel tuning rescues an avoidable complexity class at scale.
    Choose the industrially useful family for the declared range first, then use the
    rest of this skill to reduce its realized cost. Preserve the declared semantic or
    numerical contract; optimization need not be bit-exact when the contract permits
    an approximate, reordered, or mixed-precision algorithm.
    
    ### 3. Establish correctness and measurement baselines
    
    - Build a readable reference path before intrinsics, lossy precision, relaxed
      math, or concurrency.
    - Create correctness tests covering empty, tiny, tail, misaligned, extreme,
      NaN/Inf, sparse/dense, and aliasing cases that the contract permits.
    - Benchmark the actual hot operation with realistic data. Warm up, prevent
      dead-code elimination, report distribution rather than one lucky sample, and
      retain end-to-end measurements beside microbenchmarks.
    - Inspect generated code and compiler optimization remarks before assuming the
      compiler failed.
    
    Read `references/profiling-and-cost-model.md` before profiling, benchmarking,
    or declaring a bottleneck.
    
    ### 4. Classify the limiting resource
    
    Calculate at least an approximate per-item model:
    
    - useful operations and transcendental/divide cost;
    - compulsory input, output, metadata, and intermediate bytes;
    - working-set size at each reuse distance;
    - independent operations versus loop-carried dependency chains;
    - tasks, locks, atomics, barriers, launches, copies, and queue transitions;
    - scaling versus threads, vector width, batch size, and problem size.
    
    Classify the current regime as memory-bandwidth, cache-capacity/latency,
    compute/issue, dependency-latency, synchronization, task-granularity, launch, or
    transfer bound. A kernel can move between regimes after each optimization.
    
    ### 5. Evaluate change scope and ROI
    
    Record the currently authorized edit boundary, but do not mistake it for the
    root-cause boundary. When evidence places the limiting work upstream or in data
    representation, ownership, or construction, compare:
    
    - the best optimization inside the current boundary;
    - the smallest upstream, layout, index, or API change that removes the cause;
    - the practical blank-slate design, to expose the ceiling of both candidates.
    
    For each candidate, estimate end-to-end speedup, complexity and crossover,
    memory, implementation and migration work, write amplification, invariant and
    test surface, and ongoing maintenance. If wider scope has credible net value,
    present the evidence and obtain user approval before expanding it. Keep the
    experiment reversible, measure the representative full workflow, and retain the
    wider change only when its observed performance and complexity benefits repay
    its lifecycle cost; otherwise revert it.
    
    ### 6. Apply transformations in economic order
    
    Prefer the first measured transformation that attacks the current limit:
    
    1. Remove unnecessary work, copies, allocation, conversion, and materialization.
    2. Reduce footprint and improve data layout or traversal locality.
    3. Fuse passes or tile/block computation to reuse data before eviction.
    4. Expose compiler optimization by removing false alias/dependency barriers.
    5. Vectorize, using intrinsics only when generated code proves they are needed.
    6. Parallelize with enough work per task and no shared hot write locations.
    7. Batch, pipeline, or overlap copies and computation when latency can be hidden.
    8. Offload only when transfer, launch, and synchronization costs fit the model.
    
    Load the relevant references before choosing:
    
    - `references/data-layout-and-memory.md` — DOD, AoS/SoA/AoSoA, packing,
      sparse data, locality, tiling, fusion, and Morton order.
    - `references/allocation-and-memory-resources.md` — measured allocation
      bottlenecks, preallocation, PMR, arenas, pools, TLS scratch, general-purpose
      allocators, NUMA, and allocator benchmarks.
    - `references/ragged-topology.md` — flattened variable-length arrays, offset
      encodings, sidecar topology, packed sparse sets, polygon-corner topology,
      aligned attributes, and scan-built output.
    - `references/numerics-and-quantization.md` — precision, FP16/BF16, shared
      exponent, quantization, accumulation, and numerical validation.
    - `references/simd-and-compiler.md` — auto-vectorization, dependencies,
      intrinsics, SIMD tricks, tails, and ISA dispatch.
    - `references/parallelism-and-pipelines.md` — thread degree, TLS reduction,
      false sharing, work stealing, queues, async launch, and pipelines.
    - `references/accelerator-throughput.md` — CPU/accelerator transfer, CUDA-style
      streams, occupancy, synchronization, and launch amortization.
    - `references/hotpath-polymorphism.md` — hot/cold boundaries, abstraction cost,
      and data-oriented polymorphism.
    
    ### 7. Validate and integrate
    
    - Compare every output with the reference under the declared error metric.
    - Run sanitizers and boundary tests before trusting benchmark results.
    - Measure the same workload, hardware state, compiler, and flags before/after.
    - Check performance across small, crossover, and large sizes; optimized kernels
      often lose below a threshold.
    - Preserve the readable fallback and dispatch outside the inner loop.
    - Record assumptions, selected thresholds, measured results, and rejected
      alternatives near the benchmark or design documentation.
    - Keep cold-path architecture maintainable. Do not spread kernel-specific data
      layout or ISA details across the rest of the system.
    
    ## Relationship to C++ OOP design
    
    Apply `$cpp-oop-style` to ownership, orchestration, I/O, error handling, and
    module boundaries. Inside a measured hot kernel, prefer flat data, value views,
    batch operations, static dispatch, and explicit SIMD when evidence requires it.
    Use its debug-instrumentation guidance for correctness and runtime diagnosis;
    this skill owns profiling, tracing, counters, and benchmarks used to locate or
    quantify a performance bottleneck.
    
    The boundary should normally look like:
    
    - abstract behavior and resource ownership on the cold/control side;
    - data-only request/config/result types at the seam;
    - one dense concrete pool per hot subtype, with homogeneous spans or tiles
      entering the hot/data side;
    - dispatch once per batch, never once per element;
    - a reference kernel and one or more selected optimized implementations.
    
    Read `references/hotpath-polymorphism.md` before removing abstractions or adding
    type tags. Virtual dispatch is rarely the largest cost by itself; the lost
    inlining, scattered objects, unpredictable branches, and pointer-chasing around
    it are often the actual problem.
    
    ## Source material and provenance
    
    Read `references/parallel101-case-studies.md` when looking for concrete lesson
    progressions or deeper examples from archibate's `parallel101/course` and
    `parallel101/simdtutor` repositories. Search the bundled offline corpus under
    `references/parallel101/` before depending on a maintainer's checkout or the
    network. Use `references/parallel101/provenance.tsv` to recover the repository,
    author, source URL, commit, original path, teaching classification, license, and
    SHA-256 for every excerpt.
    
    Treat the corpus as educational experiments, not production code. The case-study
    index marks outdated, unsafe, incomplete, or broken examples so their ideas can
    be learned without copying their defects. The skill and bundled corpus are
    licensed under CC BY-NC-SA 4.0; retain attribution and compatible terms when
    redistributing adaptations.
    

Comments

Sign in to join the conversation.

No comments yet. Start the conversation.

Reviews (0)

No reviews yet.