Skip to content

Native Nat.pow still scales with the exponent #1708

Closed as not planned
Closed as not planned

Description

@oxura

On main e5527d5, an IO program compiled to C still evaluates Nat.pow through Base's recursive definition. The JS work in #1699/#1682 does not change this path. A large exponent spends a multiply and runtime call per step, even for bases 0 and 1.

The C-only patch uses checked repeated squaring. Base's definition and proof behavior are unchanged; multiplication still checks the 48-bit immediate limit, and the unused final square is skipped.

Real behavior proof: the shared fixture below returns checksum 10000 in both arms. Median wall time was 12.202 ms before and 0.891 ms after on this Linux x64 host. This is a bounded local measurement, not a general speed guarantee. Separate compiled C/JS programs cover zero, 3^7, 2^47, the largest immediate at powers 0 and 1, and two overflow boundaries. Native-only smoke inputs also accepted exponents 2^32 and 2^48-1; 2^(2^32) correctly stopped at the Nat wall.

Patch: oxura@ba5a8b1

Shared numeric reproducer and paired measurement driver

Save these as native-map-power.bend and measure.mjs. Build the same Bend file at main e5527d5 and at the patch commit, naming the binaries native-map-power-before and native-map-power-after. Run bun measure.mjs ./native-map-power-before ./native-map-power-after. The input comes from the environment, not a compile-time constant; every run checks an independent JS oracle. Each arm gets a warmup, then nine fresh-process runs in alternating order, one CPU thread, GPU off. The map-bit case is an unchanged control.

import Base

def powers(+n: Nat, +seed: U32, acc: U32) -> U32:
  match n:
    case 0n:
      acc
    case 1n+p:
      +u = U32.add(U32.from_nat(p), seed)
      a = U32.to_nat(U32.and(u, 1))
      b = Nat.add(256n, U32.to_nat(U32.mod(u, 128)))
      powers(p, seed, U32.add(acc, U32.from_nat(Nat.pow(a, b))))

def bit_result(pair: String & Bool) -> String & U32:
  (key, b) = pair
  (key, Bool.to_u32(b))

def bit_add(pair: String & U32, acc: U32) -> String & U32:
  (key, b) = pair
  (key, U32.add(acc, b))

def bits(+n: Nat, pair: String & U32, +seed: U32) -> String & U32:
  match n:
    case 0n:
      pair
    case 1n+p:
      match pair:
        case Tuple{key, acc}:
          +u = U32.add(U32.from_nat(p), seed)
          pos = Nat.add(Nat.mul(U32.to_nat(U32.mod(u, 257)), 33n), 32n)
          bits(p, bit_add(bit_result(Map.bit(key, pos)), acc), seed)

def widths(+n: Nat, +seed: U32, acc: U32) -> U32:
  match n:
    case 0n:
      acc
    case 1n+p:
      +u = U32.add(U32.mul(U32.from_nat(p), 2654435761), seed)
      fuel = U32.to_nat(U32.mod(U32.from_nat(p), 40))
      v = U32.from_nat(Map.msb.u(fuel, u))
      widths(p, seed, U32.add(acc, v))

def logs(+n: Nat, +seed: U32, acc: U32) -> U32:
  match n:
    case 0n:
      acc
    case 1n+p:
      u = U32.add(U32.mul(U32.from_nat(p), 2654435761), seed)
      logs(p, seed, U32.add(acc, U32.from_nat(U32.log2(u))))

def print_bits(pair: String & U32) -> IO(Unit):
  (key, total) = pair
  do IO<Unit>:
    u : Unit <- IO.print(U32.show(total))
    IO.print(key)

def work(kind: Nat, seed: U32) -> IO(Unit):
  match kind:
    case 0n:
      IO.print(U32.show(powers(20000n, seed, 0)))
    case 1n:
      print_bits(bits(1000n, (String.append(String.repeat("x", 256n), "q"), 0), seed))
    case 2n:
      IO.print(U32.show(widths(1000000n, seed, 0)))
    case 1n+rest:
      IO.print(U32.show(logs(1000000n, seed, 0)))

def parsed(m: Maybe<&2, Nat>) -> IO(Unit):
  match m:
    case None{}:
      IO.print("invalid input")
    case Some{n}:
      +n = n
      work(Nat.mod(n, 4n), U32.from_nat(Nat.div(n, 4n)))

def read_input(r: Result<&1, &1, U32 & String, String>) -> IO(Unit):
  match r:
    case Fail{error}:
      IO.print("missing input")
    case Done{value}:
      parsed(Nat.read(value))

def main() -> IO(Unit):
  do IO<Unit>:
    r : Result<&1, &1, U32 & String, String> <- IO.get_env("BEND_BENCH_INPUT")
    read_input(r)
import {spawnSync} from 'node:child_process';
import assert from 'node:assert/strict';
const paths=process.argv.slice(2),names=['power','map-bit','map-width','u32-log2'],seed=7;
const expected=[0,0,0,0];
for(let p=0;p<20000;p++){const u=(p+seed)>>>0;expected[0]=(expected[0]+Math.pow(u&1,256+u%128))>>>0;}
const key='x'.repeat(256)+'q';
for(let p=0;p<1000;p++)expected[1]+=key.charCodeAt(((p+seed)>>>0)%257)&1;
for(let p=0;p<1000000;p++){const x=(Math.imul(p,2654435761)+seed)>>>0;expected[2]=(expected[2]+Math.min(p%40,32-Math.clz32(x)))>>>0;}
for(let p=0;p<1000000;p++){const x=(Math.imul(p,2654435761)+seed)>>>0;expected[3]=(expected[3]+(x===0?0:31-Math.clz32(x)))>>>0;}
const result={};
for(let k=0;k<4;k++){
 const samples=[[],[]];
 const run=i=>{const t=performance.now();const r=spawnSync(paths[i],['--threads','1','--gpu','off'],{env:{...process.env,BEND_BENCH_INPUT:String(seed*4+k)},encoding:'utf8',timeout:30000});const elapsed=performance.now()-t;assert.equal(r.status,0,r.stderr);const lines=r.stdout.trim().split('\n');assert.equal(lines[0],String(expected[k]));if(k===1)assert.equal(lines[1],key);else assert.equal(lines.length,1);return elapsed;};
 for(let i=0;i<2;i++)run(i);
 for(let round=0;round<9;round++)for(const i of round%2?[1,0]:[0,1])samples[i].push(run(i));
 const beforeMs=[...samples[0]].sort((a,b)=>a-b)[4],afterMs=[...samples[1]].sort((a,b)=>a-b)[4];
 result[names[k]]={checksum:expected[k],beforeMs,afterMs,ratio:beforeMs/afterMs,samplesMs:samples};
}
console.log(JSON.stringify(result,null,2));

Activity

  1. Lorenzobattistela commented on Oct 19, 2026

    @Lorenzobattistela
    Collaborator

    Closing as won't-fix. Nat stops at 2^48, so for any base >= 2 Nat.pow overflows by exponent 47: Base's def already finishes in at most ~48 steps. The long runs only happen with base 0 or 1 and a huge exponent, which no real program computes, and nothing outside tests calls Nat.pow, so a C native would be extra code for no real gain. The Map.msb.u and U32.log2 natives from the same fixture went in through #1713. Thanks for the measurements!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions