Skip to content

Optimize AMICATorchNG per-iteration cost (pow hot spot + CPU threading) #63

Closed

Description

@neuromechanist

Follow-up from the #59 benchmark. On the CPU float64 parity path, NG is ~3.2x slower than Fortran single-threaded and ~7.3x at 8 threads (Fortran even handicapped by Rosetta here). Two root causes, from a cProfile of a 20-iter fit (see #59):

1. pow is ~49% of runtime

2.55s of 5.15s is Tensor.pow, from the generalized-Gaussian |z|^rho (fractional exponent, single-threaded). It is evaluated separately in _log_pdf_and_deriv (core.py:94) and _score (core.py:159), so the density and its derivative each pay a fractional pow.

Proposals (all must stay bit-exact vs the Fortran z0/fp tests in test_ng_pdf_families.py):

  • Compute absz_pow = |z|**rho once and derive the score from it (fp ~ rho * absz_pow / z) instead of a second fractional pow.
  • Special-case rho == 2 (square) and rho == 1 (abs) to skip pow entirely for those PDF families.
  • Consider caching log|z| where |z|^rho = exp(rho*log|z|) is reused across pdf/score/rho-update.

2. NG does not parallelize on CPU

Going 1 -> 8 torch threads moves per-iter only 219 -> 204 ms (~7%), while Fortran OpenMP scales 68 -> 28 ms (~2.4x). The per-block Python loop dispatches many small elementwise kernels; intra-op threading cannot amortize that.

  • Investigate larger/vectorized block handling to give torch bigger ops to thread.
  • GPU (CUDA) is NG's intended fast path (float64 parallelizes far better); MPS cannot do float64. Quantify on a CUDA host via the Benchmark AMICATorchNG runtime vs Fortran binary #59 harness.

Acceptance

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions