Repository navigation
feat(ops)!: exact (erf) GELU and erf op (#1342, part 1) - #1344
Merged
michalharakal merged 2 commits intoOct 14, 2026
Merged
michalharakal merged 2 commits into
michalharakal merged 2 commits into
Conversation
…lopers#1342, part 1) Encoder checkpoints trained with hidden_act = "gelu" (BERT-class, Laya) use the exact 0.5·x·(1 + erf(x/√2)); the engine only had the tanh approximation, and no erf at all. The two differ by up to 4.7e-4 near |x| ≈ 2.7, which the Laya decision head turns into a 7.5e-4 drift against a 5e-5 parity gate. Op surface - TensorOps.erf(tensor); TensorOps.gelu(tensor, approximate: Boolean = true). The default is the tanh form, byte-for-byte unchanged; approximate = false selects the exact form. Tensor extensions, VoidTensorOps, GELU(approximate) module, Java TensorJavaOps.gelu(a, approximate)/erf(a) and SequentialModelBuilder.gelu(approximate), ground-truth OperationParams. - KSP: gelu and erf join the unary list in MethodAnalyzer so the tracing wrapper records the approximate flag next to the shape attributes; the name-keyed default tables of the network and graph DSL generators learn `approximate -> true` (KSP cannot read declared defaults). CPU - ErfKernel: Abramowitz–Stegun 7.1.26 in double (|err| < 1.5e-7), the same expression order as the Laya host workaround, origin pinned to signed zero; single-precision variants for the SIMD tail. - DefaultCpuOps.gelu(approximate) / erf with the FP32 fast path; DefaultCpuOpsJvm lane kernels over VectorOperators.EXP with a scalar tail of identical operation order (parity ≤ 1e-6 across SPECIES±1 tails). Fixes the literal "${tensor.dtype}" in gelu's error message; drops the stale @inprogress. Metadata through the compiled path - GeluOperation(parameters["approximate"]) and ErfOperation; the legacy RecordingTensorOpsDecorator records both (gelu used to be delegated unrecorded, so compiled graphs never saw it); ComputeGraphExecutor dispatches on the flag; geluBackward picks the exact derivative Φ(x) + x·φ(x) from it; new erfBackward registered for autodiff coverage. - StableHLO: erf lowers to `chlo.erf %x : T -> T`, exact GELU to 0.5·x·(1 + chlo.erf(x·√½)). GeluLowering emits both chains through an HloEmitter seam (ContextEmitter today) so part 2 can reuse the builder for a stablehlo.composite decomposition. Tests: CPU erf table / oddness / exact-vs-host bit equality / default unchanged / exact-vs-tanh band 4.5e-4..5.0e-4; JVM vector parity; GeluExactRecordingTest (flag on trace and node, DIRECT vs OPTIMIZED ≤ 1e-6); exact-gelu and erf finite-difference gradients; recorder test; HLO exact and erf lowering tests; generated DSL gelu(approximate = false) in the network builder coverage test. API dumps and operator docs regenerated. BREAKING CHANGE: TensorOps.gelu gained the approximate parameter — interface implementors must update the override (callers keep compiling through the default). In the generated network DSL a positional gelu("name") becomes gelu(id = "name"), matching leakyRelu(slope, id).
…/gelu tests JS and Wasm evaluate Float in double precision, so the exact-GELU host comparison allows one ulp instead of bit equality, and the unsupported-dtype check matches the dtype name rather than the JVM KClass rendering.
8 tasks
michalharakal
merged commit Oct 14, 2026
c1a4d4d
into
SKaiNET-developers:develop
27 of 29 checks passed
This was referenced Oct 14, 2026
Merged
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Part 1 of #1342:
erfas a first-class op and an exact GELU, carried as op metadata so DIRECT, OPTIMIZED and the StableHLO export all see the same choice.TensorOps.erf(tensor)andgelu(tensor, approximate: Boolean = true). The default stays the tanh form, byte-for-byte, so no existing model changes numerically;approximate = falseis0.5·x·(1 + erf(x/√2)), the form BERT-class encoders and the Laya decision models were trained with. Measured on the kernel: the two differ by at most 4.73e-4 at |x| ≈ 2.70 (the issue's "≈ 2e-3" was an overestimate; the test pins the real band).ErfKernel(Abramowitz–Stegun 7.1.26 in double, |err| < 1.5e-7, the same expression order as the Laya host workaround so the scalar path reproduces it bit-for-bit) plus a JVM Vector API lane kernel (VectorOperators.EXP+ Horner) with a single-precision scalar tail of identical operation order; scalar-vs-vector parity ≤ 1e-6 across SPECIES±1 tails. Drive-by:DefaultCpuOps.geluprinted a literal${tensor.dtype}in its error message; the stale@InProgress(... task-ops.md)reference is gone.GeluOperation(parameters["approximate"])/ErfOperationinTensorOperations.kt; the KSP tracing wrapper recordsapproximatenext to the shape attributes (gelu/erf joined the unary list inMethodAnalyzer), soTraceToGraphBuilderputs it on the node;ComputeGraphExecutordispatches on it;geluBackwardpicks the exact derivativeΦ(x) + x·φ(x)from it; newerfBackward. The legacyRecordingTensorOpsDecoratornow records gelu/erf instead of delegating them unrecorded (before this PR a compiled graph never saw GELU at all).erf→chlo.erf %x : T -> T(CHLO unary assembly); exact GELU →0.5·x·(1 + chlo.erf(x·√½)). OneGeluLoweringbuilder emits both the tanh chain (unchanged text) and the exact chain through anHloEmitterseam, so part 2 can wrap the same builder into astablehlo.compositedecomposition without a second copy of the formula.network {}getsgelu(approximate: Boolean = true, id)anderf(id)(the KSP default tables are name-keyed —approximatewas added to both generators);GELU(name, approximate)module; JavaTensorJavaOps.gelu(a, approximate)/erf(a),SequentialModelBuilder.gelu(approximate); ground-truthOperationParams.approximate.Breaking
TensorOps.gelugained a parameter: implementors of the interface must update the override (callers are source-compatible through the default). In the generated network DSL the activation convention puts parameters beforeid, so a positionalgelu("name")becomesgelu(id = "name")(same asleakyRelu(slope, id)).Test plan
skainet-backend-cpu: erf reference table (2e-7), oddness/saturation, exact gelu bit-equal to the host formula, default byte-identical to the old tanh path, exact-vs-tanh band 4.5e-4..5.0e-4 at |x| ∈ [2.5, 2.9], Int32 rejection; JVMerf_and_exact_gelu_match_scalar_reference_with_tailsskainet-compile-dag:GeluExactRecordingTest(flag on trace and node, DIRECT vs OPTIMIZED replay ≤ 1e-6), exact-gelu and erf finite-difference gradients,AutodiffCoverageTest(erf rule registered)skainet-compile-core: legacy recorder recordsGeluOperation(approximate)/ErfOperationskainet-compile-hlo:testGeluOperationunchanged,testGeluExactOperation,testErfOperationLowersToChlo, approximate=true equals defaultskainet-lang-core: generated DSLgelu(approximate = false, id = …)compiles and builds; KSP processor testsapiDump,generateDocs,scripts/pr-gate.sh --quickPart 2 (composite emission behind
OpGranularityPolicy, explicit exact→tanh legalization pass,@Loweringmatrix column) follows in a separate PR, as laid out in #1342.