Write numerically stable kernel

From wenyi-li/awesome-agent-kernel-skills · View interactive version

Write numerically stable kernel is an AI agent skill from the GitHub repository wenyi-li/awesome-agent-kernel-skills. Guide the agent through identifying numerical instability risks in a kernel's computation path and applying the correct stabilization strategy for each risk class.

How to use this skill

Skill file

Skill: Write a Numerically Stable Kernel

Purpose

Guide the agent through identifying numerical instability risks in a kernel's computation path and applying the correct stabilization strategy for each risk class.

Use this when

Do not use this when

Inputs the agent should gather first

Required reasoning process

  1. Enumerate all accumulation and reduction paths. Walk through the kernel's computation and list every place where values are summed, multiplied, or combined iteratively. Each is a candidate for precision loss.
  1. Classify each risk. Apply the following classification:
  1. Choose mitigation for each risk. Apply the correct strategy, not a generic "use fp32" instruction:
  1. Write the stabilized formulation explicitly. Do not write pseudocode — write the exact mathematical expressions that will appear in the kernel, annotated with dtypes at each step.
  1. Identify whether the stabilization requires additional kernel passes. The log-sum-exp trick and stable softmax both require computing the maximum before the sum, which means either a two-pass design or an online algorithm. State this explicitly in the design.
  1. Verify with a double-precision reference. Numerical stability can only be confirmed by comparing to a higher-precision reference, not by comparing two fp16 implementations against each other.

Kernel design rules

Correctness requirements

Performance requirements

Output format

The agent should produce:

  1. Risk classification table: a table listing each identified risk (catastrophic cancellation, overflow, underflow, accumulation error, inf propagation), where in the kernel it occurs, and which mitigation is applied.
  2. Stabilized mathematical formulation: the exact formulas to be implemented, with dtypes annotated at each step, written before any code.
  3. Kernel implementation: complete, compilable code implementing the stabilized formulation.
  4. Reference comparison test: a test that computes the same operation in fp64 on CPU and compares to the kernel output using appropriate tolerances. The test must include at least one adversarial input case.
  5. Performance cost statement: a brief explicit statement of what the stabilization costs (extra passes, registers, arithmetic) relative to the naive implementation.

Common failure modes

Review checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.